[{"prompt": " import msgpack WORKER_STATUS = \"\" WORKER_HALT = \"\" WORKER_LAST_ACTION = \"\" class ServiceMessage ( object ) : @ staticmethod ", "answer": "def dumps ( data ) :"}, {"prompt": " import sys import os import os . path as P from fabric . api import * sys . path . append ( P . abspath ( P . join ( P . dirname ( __file__ ) , '' ) ) ) import venv local = venv . local clean = venv . clean init = venv . init def test ( k = None ) : \"\"\"\"\"\" venv . install ( '' ) py_test = venv . get_script ( '' ) test_script = P . join ( '' , '' , '' ) if not P . exists ( '' ) : ", "answer": "os . mkdir ( '' )"}, {"prompt": " \"\"\"\"\"\" from agents . ec2_agent import EC2Agent from boto . exception import EC2ResponseError import boto import os from urlparse import urlparse from utils import utils __author__ = '' __email__ = '' class OpenStackAgent ( EC2Agent ) : \"\"\"\"\"\" DEFAULT_REGION = \"\" def configure_instance_security ( self , parameters ) : \"\"\"\"\"\" keyname = parameters [ self . PARAM_KEYNAME ] group = parameters [ self . PARAM_GROUP ] key_path = '' . format ( utils . KEY_DIRECTORY , keyname ) ssh_key = os . path . abspath ( key_path ) utils . log ( '' '' . format ( ssh_key ) ) if os . path . exists ( ssh_key ) : utils . log ( '' '' ) return False try : conn = self . open_connection ( parameters ) key_pair = conn . get_key_pair ( keyname ) if key_pair is None : utils . log ( '' . format ( keyname ) ) key_pair = conn . create_key_pair ( keyname ) utils . write_key_file ( ssh_key , key_pair . material ) security_groups = conn . get_all_security_groups ( ) group_exists = False for security_group in security_groups : if security_group . name == group : group_exists = True break if not group_exists : utils . log ( '' . format ( group ) ) conn . create_security_group ( group , '' ) conn . authorize_security_group ( group , from_port = , to_port = , ip_protocol = '' ) conn . authorize_security_group ( group , from_port = , to_port = , ip_protocol = '' ) conn . authorize_security_group ( group , from_port = - , to_port = - , ip_protocol = '' , cidr_ip = '' ) return True except EC2ResponseError as exception : self . handle_failure ( '' '' . format ( exception . error_message ) ) except Exception as exception : self . handle_failure ( '' '' . format ( exception . message ) ) def run_instances ( self , count , parameters , security_configured ) : \"\"\"\"\"\" if parameters [ self . PARAM_SPOT ] == \"\" : parameters [ self . PARAM_SPOT ] = '' utils . log ( \"\" ) super . run_instances ( self , count , parameters , security_configured ) def open_connection ( self , parameters ) : \"\"\"\"\"\" credentials = parameters [ self . PARAM_CREDENTIALS ] region_str = self . DEFAULT_REGION access_key = str ( credentials [ '' ] ) secret_key = str ( credentials [ '' ] ) ec2_url = str ( credentials [ '' ] ) result = urlparse ( ec2_url ) ", "answer": "if result . port is None or result . hostname is None or result . path is None :"}, {"prompt": " import tornado . ioloop import tornado . web import json class TextHandler ( tornado . web . RequestHandler ) : def get ( self ) : self . write ( '' ) application = tornado . web . Application ( [ ( r\"\" , TextHandler ) , ] ) if __name__ == \"\" : ", "answer": "application . listen ( )"}, {"prompt": " import abc from neutron_lib import constants from neutron_lib import exceptions from oslo_log import log as logging import webob . exc from neutron . _i18n import _ , _LE from neutron . api import extensions from neutron . api . v2 import base from neutron . api . v2 import resource from neutron . common import rpc as n_rpc from neutron . extensions import agent from neutron import manager from neutron . plugins . common import constants as service_constants from neutron import policy from neutron import wsgi LOG = logging . getLogger ( __name__ ) L3_ROUTER = '' L3_ROUTERS = L3_ROUTER + '' L3_AGENT = '' L3_AGENTS = L3_AGENT + '' ", "answer": "class RouterSchedulerController ( wsgi . Controller ) :"}, {"prompt": " from twisted . trial import unittest from twisted . internet import defer from nodeset . core import config from nodeset . common . twistedapi import NodeSetAppOptions class ConfigurationTest ( unittest . TestCase ) : def setUp ( self ) : cfg = NodeSetAppOptions ( ) cfg . parseOptions ( [ '' , '' , '' , '' , '' ] ) self . config = config . Configurator ( ) self . config . _config = cfg def testListenParam ( self ) : self . assertTrue ( self . config [ '' ] == '' ) def testDispatcherParam ( self ) : self . assertTrue ( self . config [ '' ] == '' ) def testAnotherInstance ( self ) : c = config . Configurator ( ) self . assertTrue ( c [ '' ] == '' ) def testUpdate ( self ) : self . config [ '' ] = '' self . assertTrue ( self . config [ '' ] == '' ) def testAnotherRoutine ( self ) : def anotherRoutine ( d ) : c = config . Configurator ( ) self . assertTrue ( c [ '' ] == '' ) ", "answer": "self . config [ '' ] = ''"}, {"prompt": " import logging import re from django . conf import settings from django . core import mail from common import api from common import clean from common import exception from common import profile from common import sms as sms_service from common import util from common . protocol import sms from common . test import base from common . test import util as test_util class SmsTest ( base . FixturesTestCase ) : sender = '' target = settings . SMS_TARGET def setUp ( self ) : super ( SmsTest , self ) . setUp ( ) self . service = sms_service . SmsService ( sms . SmsConnection ( ) ) self . service . init_handlers ( ) def receive ( self , message , sender = None , target = None ) : if sender is None : sender = self . sender if target is None : target = self . target self . service . handle_message ( sender , target , message ) self . exhaust_queue_any ( ) outbox = sms . outbox [ : ] sms . outbox = [ ] return outbox def assertOutboxContains ( self , outbox , pattern , sender = None ) : if sender is None : sender = self . sender if type ( pattern ) is type ( '' ) : pattern = re . compile ( pattern ) for mobile , message in outbox : if mobile == sender and pattern . search ( message ) : return True self . fail ( '' % ( pattern . pattern , outbox ) ) def sign_in ( self , nick , sender = None ) : password = self . passwords [ clean . nick ( nick ) ] r = self . receive ( '' % ( nick , password ) , sender = sender ) return r def test_sign_in ( self ) : nick = '' password = self . passwords [ clean . nick ( nick ) ] r = self . receive ( '' % ( nick , password ) ) self . assertOutboxContains ( r , '' % ( util . get_metadata ( '' ) , nick ) ) def test_sign_on ( self ) : self . sign_in ( '' ) r = self . receive ( '' ) self . assertOutboxContains ( r , sms_service . HELP_SIGNED_OUT ) r = self . receive ( '' ) self . assertOutboxContains ( r , sms_service . HELP_SIGN_IN ) def test_post_and_reply ( self ) : unpop = '' r = self . sign_in ( '' , sender = unpop ) r = self . receive ( '' , sender = unpop ) r = self . sign_in ( '' ) r = self . receive ( '' ) r = self . receive ( '' ) self . assertOutboxContains ( r , '' , sender = unpop ) r = self . receive ( '' , sender = unpop ) self . assertOutboxContains ( r , '' ) def test_whitelist ( self ) : o = test_util . override ( SMS_MT_WHITELIST = re . compile ( '' ) ) def _all_blocked ( ) : r = self . sign_in ( '' ) self . assertRaises ( exception . ServiceError , _all_blocked ) r = self . sign_in ( '' , '' ) ", "answer": "self . assert_ ( r )"}, {"prompt": " from __future__ import absolute_import import re import copy import xml . etree . ElementTree as ET from svtplay_dl . service import Service , OpenGraphThumbMixin from svtplay_dl . utils import is_py2_old from svtplay_dl . error import ServiceError from svtplay_dl . fetcher . rtmp import RTMP class Qbrick ( Service , OpenGraphThumbMixin ) : supported_domains = [ '' ] def get ( self ) : data = self . get_urldata ( ) if self . exclude ( self . options ) : yield ServiceError ( \"\" ) return if re . findall ( r\"\" , self . url ) : match = re . search ( \"\" , data ) if not match : yield ServiceError ( \"\" % self . url ) return data = self . http . request ( \"\" , match . group ( ) ) . content match = re . search ( r\"\" , data ) ", "answer": "if not match :"}, {"prompt": " \"\"\"\"\"\" import warnings warnings . warn ( \"\" \"\" , DeprecationWarning , stacklevel = ) import itertools , sys , commands , os . path from twisted . python import reflect , util , usage from twisted . application . service import IServiceMaker class MyOptions ( usage . Options ) : \"\"\"\"\"\" longdesc = \"\" synopsis = \"\" optFlags = [ [ \"\" , \"\" , '' '' '' ] ] optParameters = [ [ \"\" , \"\" , None , \"\" ] ] def postOptions ( self ) : if self [ '' ] and self [ '' ] : raise usage . UsageError , \"\" \"\" if not self [ '' ] and not self [ '' ] : raise usage . UsageError , \"\" if self [ '' ] and not os . path . isdir ( self [ '' ] ) : raise usage . UsageError , \"\" % self [ '' ] class Builder : def __init__ ( self , cmd_name , options , file ) : \"\"\"\"\"\" self . cmd_name = cmd_name self . options = options self . file = file def write ( self ) : \"\"\"\"\"\" self . file . write ( '' % ( self . cmd_name , ) ) gen = ArgumentsGenerator ( self . cmd_name , self . options , self . file ) gen . write ( ) class SubcommandBuilder ( Builder ) : \"\"\"\"\"\" interface = None subcmdLabel = None def write ( self ) : \"\"\"\"\"\" self . file . write ( '' % ( self . cmd_name , ) ) self . file . write ( '' ) from twisted import plugin as newplugin plugins = newplugin . getPlugins ( self . interface ) for p in plugins : self . file . write ( '' % ( p . tapname , p . description ) ) self . file . write ( \"\" ) self . options . __class__ . zsh_extras = [ '' ] gen = ArgumentsGenerator ( self . cmd_name , self . options , self . file ) gen . write ( ) self . file . write ( \"\"\"\"\"\" % ( self . subcmdLabel , ) ) plugins = newplugin . getPlugins ( self . interface ) for p in plugins : self . file . write ( p . tapname + \"\" ) gen = ArgumentsGenerator ( p . tapname , p . options ( ) , self . file ) gen . write ( ) self . file . write ( \"\" ) self . file . write ( \"\" \"\" ) class MktapBuilder ( SubcommandBuilder ) : \"\"\"\"\"\" interface = IServiceMaker subcmdLabel = '' class TwistdBuilder ( SubcommandBuilder ) : \"\"\"\"\"\" interface = IServiceMaker subcmdLabel = '' class ArgumentsGenerator : \"\"\"\"\"\" def __init__ ( self , cmd_name , options , file ) : \"\"\"\"\"\" self . cmd_name = cmd_name self . options = options self . file = file self . altArgDescr = { } self . actionDescr = { } self . multiUse = [ ] self . mutuallyExclusive = [ ] self . actions = { } self . extras = [ ] aCL = reflect . accumulateClassList aCD = reflect . accumulateClassDict aCD ( options . __class__ , '' , self . altArgDescr ) aCD ( options . __class__ , '' , self . actionDescr ) aCL ( options . __class__ , '' , self . multiUse ) aCL ( options . __class__ , '' , self . mutuallyExclusive ) aCD ( options . __class__ , '' , self . actions ) aCL ( options . __class__ , '' , self . extras ) optFlags = [ ] optParams = [ ] aCL ( options . __class__ , '' , optFlags ) aCL ( options . __class__ , '' , optParams ) for i , optList in enumerate ( optFlags ) : if len ( optList ) != : optFlags [ i ] = util . padTo ( , optList ) for i , optList in enumerate ( optParams ) : if len ( optList ) != : optParams [ i ] = util . padTo ( , optList ) self . optFlags = optFlags self . optParams = optParams optParams_d = { } for optList in optParams : optParams_d [ optList [ ] ] = optList [ : ] self . optParams_d = optParams_d optFlags_d = { } for optList in optFlags : optFlags_d [ optList [ ] ] = optList [ : ] self . optFlags_d = optFlags_d optAll_d = { } optAll_d . update ( optParams_d ) optAll_d . update ( optFlags_d ) self . optAll_d = optAll_d ", "answer": "self . addAdditionalOptions ( )"}, {"prompt": " from __future__ import with_statement import sys from optparse import OptionParser from squawk . query import Query from squawk . output import output_formats from squawk . parsers import parsers from squawk . sql import sql_parser def get_table_names ( tokens ) : if not isinstance ( tokens . tables [ ] [ ] , basestring ) : return get_table_names ( tokens . tables [ ] [ ] ) return [ tokens . tables [ ] [ ] ] class Combiner ( object ) : def __init__ ( self , files , parser_class ) : self . files = files self . parser_class = parser_class self . index = self . next_file ( ) def next_file ( self ) : if self . index >= len ( self . files ) : raise StopIteration ( ) fname = self . files [ self . index ] self . parser = self . parser_class ( sys . stdin if fname == '' else open ( fname , \"\" ) ) self . parser_iter = iter ( self . parser ) self . columns = self . parser . columns self . index += def __iter__ ( self ) : return self def next ( self ) : while True : try : row = self . parser_iter . next ( ) except StopIteration : self . next_file ( ) else : return row def build_opt_parser ( ) : parser = OptionParser ( ) parser . add_option ( \"\" , \"\" , dest = \"\" , help = \"\" ) parser . add_option ( \"\" , \"\" , dest = \"\" , default = \"\" , help = \"\" , metavar = \"\" ) return parser def main ( ) : parser = build_opt_parser ( ) ( options , args ) = parser . parse_args ( ) sql = '' . join ( args ) . strip ( ) if not sql : print \"\" return files = get_table_names ( sql_parser . parseString ( sql ) ) parser_name = options . parser if parser_name : parser = parsers [ parser_name ] else : fn = files [ ] if fn . rsplit ( '' , ) [ - ] == '' : parser = parsers [ '' ] elif fn . endswith ( '' ) : parser = parsers [ '' ] else : sys . stderr . write ( \"\" ) sys . exit ( ) source = Combiner ( files , parser ) ", "answer": "query = Query ( sql )"}, {"prompt": " \"\"\"\"\"\" import httplib import logging import os import unittest import sys import threading from django import http from django import test from django . test import client from django . conf import settings from google . appengine . tools import dev_appserver from google . appengine . tools import dev_appserver_login PORT = ROOT_PATH = os . path . dirname ( os . path . dirname ( os . path . dirname ( __file__ ) ) ) APP_ID = '' LOGIN_URL = '' def start_server ( root_path = ROOT_PATH , port = PORT , app_id = APP_ID ) : dev_appserver . ApplicationLoggingHandler . InitializeTemplates ( '' , '' , '' , '' ) dev_appserver . SetupStubs ( app_id , login_url = LOGIN_URL , datastore_path = '' , history_path = '' , clear_datastore = False ) server = dev_appserver . CreateServer ( ROOT_PATH , LOGIN_URL , port , '' ) server_thread = threading . Thread ( target = server . serve_forever ) server_thread . setDaemon ( True ) server_thread . start ( ) return port def RetrieveURL ( method , host_port , relative_url , user_info = None , body = None , extra_headers = [ ] ) : \"\"\"\"\"\" url_host = '' % host_port logging . info ( '' , url_host ) try : connection = httplib . HTTPConnection ( url_host ) logging . info ( '' , method , relative_url ) try : connection . putrequest ( method , relative_url ) if user_info is not None : email , admin = user_info auth_string = '' % ( dev_appserver_login . COOKIE_NAME , dev_appserver_login . CreateCookieData ( email , admin ) ) logging . info ( '' , auth_string ) connection . putheader ( '' , auth_string ) if body is not None : connection . putheader ( '' , len ( body ) ) for key , value in extra_headers : logging . info ( '' , str ( key ) , str ( value ) ) connection . putheader ( str ( key ) , str ( value ) ) connection . endheaders ( ) if body is not None : connection . send ( body ) response = connection . getresponse ( ) status = response . status content = response . read ( ) headers = dict ( response . getheaders ( ) ) logging . info ( '' , status , content ) return status , content , headers finally : connection . close ( ) except ( IOError , httplib . HTTPException , socket . error ) , e : logging . error ( '' , e ) raise e ", "answer": "class AppEngineClientHandler ( client . ClientHandler ) :"}, {"prompt": " import fnmatch import logging import getpass import boto import sys from cactus . s3 . utils import fileList import re import os import paramiko import yaml from . import BaseTask from cactus . s3 . file import File from paramiko import SFTPClient from cactus . utils import to_unix_path class DeployTask ( BaseTask ) : \"\"\"\"\"\" local_settings = { } config = { } helptext_short = \"\" \"\" @ classmethod def conf ( cls , key , default = None ) : return cls . local_settings . get ( key , cls . config . get ( key , default ) ) @ classmethod def run ( cls , * args , ** kwargs ) : if len ( args ) > : print cls . usage ( ) return do_build = True run_tests = False target = \"\" for arg in args : m1 = re . match ( r'' , arg , re . I ) m2 = re . match ( r'' , arg , re . I ) if m1 : do_build = m1 . group ( ) . lower ( ) == \"\" elif m2 : run_tests = m2 . group ( ) . lower ( ) == \"\" else : target = arg try : cls . local_settings = yaml . load ( open ( os . path . join ( os . getcwd ( ) , \"\" ) , '' ) ) . get ( target ) except Exception , e : cls . local_settings = { } logging . warn ( \"\" . format ( e ) ) from cactus import site as cactus_site site = cactus_site . Site ( os . getcwd ( ) ) site . verify ( ) cls . config = site . config . get ( \"\" ) . get ( target , \"\" ) deployment_type = cls . conf ( \"\" , \"\" ) discard_files = cls . conf ( \"\" , [ ] ) def createSSHClient ( server , port = , user = None , password = None , privkey = None ) : client = paramiko . SSHClient ( ) client . load_system_host_keys ( ) client . set_missing_host_key_policy ( paramiko . AutoAddPolicy ( ) ) client . connect ( server , port = port , username = user , password = password , key_filename = privkey , ) return client if do_build or run_tests : print \"\" site . build ( dist = True ) site . call_plugin_method ( \"\" ) if run_tests : if not site . run_tests ( ) : logging . error ( \"\" ) return print u\"\" . format ( target ) if deployment_type == \"\" : host = cls . conf ( \"\" ) port = int ( cls . conf ( \"\" , ) ) print \"\" . format ( host ) auth_type = cls . conf ( \"\" , \"\" ) try : from win32com . shell import shellcon , shell homedir = shell . SHGetFolderPath ( , shellcon . CSIDL_APPDATA , , ) except ImportError : homedir = os . path . expanduser ( \"\" ) if auth_type == \"\" : try : ssh = createSSHClient ( host , port = port , user = cls . conf ( \"\" ) , privkey = cls . conf ( \"\" , \"\" ) . format ( home = homedir ) , ) except paramiko . PasswordRequiredException : ssh = createSSHClient ( host , port = port , user = cls . conf ( \"\" ) , privkey = cls . conf ( \"\" , \"\" ) . format ( home = homedir ) , password = getpass . getpass ( prompt = \"\" ) , ) else : user = cls . conf ( \"\" ) if not user : user = raw_input ( \"\" ) ssh = createSSHClient ( host , port = port , user = user , password = getpass . getpass ( prompt = \"\" ) ) scp = SFTPClient . from_transport ( ssh . get_transport ( ) ) dist_dir = os . path . abspath ( site . paths [ '' ] ) remote_base = cls . conf ( \"\" ) for ( path , dirs , files ) in os . walk ( dist_dir ) : remote_path = path . replace ( dist_dir , '' ) remote_path = re . sub ( r'' , '' , remote_path ) remote_path = re . sub ( r'' , '' , remote_path ) for d in dirs : rdir = to_unix_path ( os . path . join ( remote_base , remote_path , d ) ) try : scp . stat ( rdir ) except IOError : scp . mkdir ( rdir ) for f in files : src = os . path . abspath ( os . path . join ( path , f ) ) dest = to_unix_path ( os . path . join ( remote_base , remote_path , f ) ) discard = False for pattern in discard_files : d = \"\" . format ( pattern ) if fnmatch . fnmatch ( dest , d ) : discard = True if not discard : logging . info ( \"\" . format ( src , dest ) ) scp . put ( src , dest ) else : logging . info ( \"\" . format ( src ) ) site . call_plugin_method ( \"\" ) elif deployment_type == \"\" : key = cls . conf ( \"\" ) ", "answer": "secret = cls . conf ( \"\" )"}, {"prompt": " \"\"\"\"\"\" from cloudcafe . networking . lbaas . common . behaviors import BaseLoadBalancersBehaviors class ListenerBehaviors ( BaseLoadBalancersBehaviors ) : OBJECT_MODEL = '' def __init__ ( self , listeners_client , config ) : super ( ListenerBehaviors , self ) . __init__ ( ", "answer": "lbaas_client_type = listeners_client , config = config )"}, {"prompt": " import logging import time from apns_proxy_client import APNSProxyClient valid_token = \"\" def main ( ) : ", "answer": "client = APNSProxyClient ( host = \"\" , port = , application_id = \"\" )"}, {"prompt": " from struct import calcsize from ryu . ofproto . ofproto_common import OFP_HEADER_SIZE NXAST_RESUBMIT = NXAST_SET_TUNNEL = NXAST_DROP_SPOOFED_ARP__OBSOLETE = NXAST_SET_QUEUE = NXAST_POP_QUEUE = NXAST_REG_MOVE = NXAST_REG_LOAD = NXAST_NOTE = NXAST_SET_TUNNEL64 = NXAST_MULTIPATH = NXAST_AUTOPATH = NXAST_BUNDLE = NXAST_BUNDLE_LOAD = NXAST_RESUBMIT_TABLE = NXAST_OUTPUT_REG = NXAST_LEARN = NXAST_EXIT = NXAST_DEC_TTL = NXAST_FIN_TIMEOUT = NXAST_CONTROLLER = NXAST_CONJUNCTION = NXAST_CT = NXAST_NAT = NX_ACTION_RESUBMIT_PACK_STR = '' NX_ACTION_RESUBMIT_SIZE = assert calcsize ( NX_ACTION_RESUBMIT_PACK_STR ) == NX_ACTION_RESUBMIT_SIZE NX_ACTION_SET_TUNNEL_PACK_STR = '' NX_ACTION_SET_TUNNEL_SIZE = assert calcsize ( NX_ACTION_SET_TUNNEL_PACK_STR ) == NX_ACTION_SET_TUNNEL_SIZE NX_ACTION_SET_QUEUE_PACK_STR = '' NX_ACTION_SET_QUEUE_SIZE = assert calcsize ( NX_ACTION_SET_QUEUE_PACK_STR ) == NX_ACTION_SET_QUEUE_SIZE NX_ACTION_POP_QUEUE_PACK_STR = '' NX_ACTION_POP_QUEUE_SIZE = assert calcsize ( NX_ACTION_POP_QUEUE_PACK_STR ) == NX_ACTION_POP_QUEUE_SIZE NX_ACTION_REG_MOVE_PACK_STR = '' NX_ACTION_REG_MOVE_SIZE = assert calcsize ( NX_ACTION_REG_MOVE_PACK_STR ) == NX_ACTION_REG_MOVE_SIZE NX_ACTION_REG_LOAD_PACK_STR = '' NX_ACTION_REG_LOAD_SIZE = assert calcsize ( NX_ACTION_REG_LOAD_PACK_STR ) == NX_ACTION_REG_LOAD_SIZE NX_ACTION_SET_TUNNEL64_PACK_STR = '' NX_ACTION_SET_TUNNEL64_SIZE = assert calcsize ( NX_ACTION_SET_TUNNEL64_PACK_STR ) == NX_ACTION_SET_TUNNEL64_SIZE NX_ACTION_MULTIPATH_PACK_STR = '' NX_ACTION_MULTIPATH_SIZE = assert calcsize ( NX_ACTION_MULTIPATH_PACK_STR ) == NX_ACTION_MULTIPATH_SIZE NX_ACTION_NOTE_PACK_STR = '' NX_ACTION_NOTE_SIZE = assert calcsize ( NX_ACTION_NOTE_PACK_STR ) == NX_ACTION_NOTE_SIZE NX_ACTION_BUNDLE_PACK_STR = '' NX_ACTION_BUNDLE_SIZE = assert calcsize ( NX_ACTION_BUNDLE_PACK_STR ) == NX_ACTION_BUNDLE_SIZE NX_ACTION_AUTOPATH_PACK_STR = '' NX_ACTION_AUTOPATH_SIZE = assert calcsize ( NX_ACTION_AUTOPATH_PACK_STR ) == NX_ACTION_AUTOPATH_SIZE NX_ACTION_OUTPUT_REG_PACK_STR = '' NX_ACTION_OUTPUT_REG_SIZE = assert calcsize ( NX_ACTION_OUTPUT_REG_PACK_STR ) == NX_ACTION_OUTPUT_REG_SIZE NX_ACTION_LEARN_PACK_STR = '' NX_ACTION_LEARN_SIZE = assert calcsize ( NX_ACTION_LEARN_PACK_STR ) == NX_ACTION_LEARN_SIZE NX_ACTION_CONTROLLER_PACK_STR = '' NX_ACTION_CONTROLLER_SIZE = assert calcsize ( NX_ACTION_CONTROLLER_PACK_STR ) == NX_ACTION_CONTROLLER_SIZE NX_ACTION_FIN_TIMEOUT_PACK_STR = '' NX_ACTION_FIN_TIMEOUT_SIZE = assert calcsize ( NX_ACTION_FIN_TIMEOUT_PACK_STR ) == NX_ACTION_FIN_TIMEOUT_SIZE NX_ACTION_HEADER_PACK_STR = '' NX_ACTION_HEADER_SIZE = assert calcsize ( NX_ACTION_HEADER_PACK_STR ) == NX_ACTION_HEADER_SIZE NXT_ROLE_REQUEST = NXT_ROLE_REPLY = NXT_SET_FLOW_FORMAT = NXT_FLOW_MOD = NXT_FLOW_REMOVED = NXT_FLOW_MOD_TABLE_ID = NXT_SET_PACKET_IN_FORMAT = NXT_PACKET_IN = NXT_FLOW_AGE = NXT_SET_ASYNC_CONFIG = NXT_SET_CONTROLLER_ID = NX_ROLE_OTHER = NX_ROLE_MASTER = NX_ROLE_SLAVE = NXFF_OPENFLOW10 = NXFF_NXM = NXPIF_OPENFLOW10 = NXPIF_NXM = NXST_FLOW = NXST_AGGREGATE = NXST_FLOW_MONITOR = NICIRA_HEADER_PACK_STR = '' NICIRA_HEADER_SIZE = assert ( calcsize ( NICIRA_HEADER_PACK_STR ) + OFP_HEADER_SIZE == NICIRA_HEADER_SIZE ) NX_ROLE_PACK_STR = '' NX_ROLE_SIZE = assert ( calcsize ( NX_ROLE_PACK_STR ) + NICIRA_HEADER_SIZE == NX_ROLE_SIZE ) NX_FLOW_MOD_PACK_STR = '' NX_FLOW_MOD_SIZE = assert ( calcsize ( NX_FLOW_MOD_PACK_STR ) + NICIRA_HEADER_SIZE == NX_FLOW_MOD_SIZE ) NX_SET_FLOW_FORMAT_PACK_STR = '' NX_SET_FLOW_FORMAT_SIZE = assert ( calcsize ( NX_SET_FLOW_FORMAT_PACK_STR ) + NICIRA_HEADER_SIZE == NX_SET_FLOW_FORMAT_SIZE ) NX_FLOW_REMOVED_PACK_STR = '' NX_FLOW_REMOVED_SIZE = assert ( calcsize ( NX_FLOW_REMOVED_PACK_STR ) + NICIRA_HEADER_SIZE == NX_FLOW_REMOVED_SIZE ) NX_FLOW_MOD_TABLE_ID_PACK_STR = '' NX_FLOW_MOD_TABLE_ID_SIZE = assert ( calcsize ( NX_FLOW_MOD_TABLE_ID_PACK_STR ) + NICIRA_HEADER_SIZE == NX_FLOW_MOD_TABLE_ID_SIZE ) NX_SET_PACKET_IN_FORMAT_PACK_STR = '' NX_SET_PACKET_IN_FORMAT_SIZE = assert ( calcsize ( NX_SET_PACKET_IN_FORMAT_PACK_STR ) + NICIRA_HEADER_SIZE == NX_SET_PACKET_IN_FORMAT_SIZE ) NX_PACKET_IN_PACK_STR = '' NX_PACKET_IN_SIZE = assert ( calcsize ( NX_PACKET_IN_PACK_STR ) + NICIRA_HEADER_SIZE == NX_PACKET_IN_SIZE ) NX_ASYNC_CONFIG_PACK_STR = '' NX_ASYNC_CONFIG_SIZE = assert ( calcsize ( NX_ASYNC_CONFIG_PACK_STR ) + NICIRA_HEADER_SIZE == NX_ASYNC_CONFIG_SIZE ) NX_CONTROLLER_ID_PACK_STR = '' NX_CONTROLLER_ID_SIZE = assert ( calcsize ( NX_CONTROLLER_ID_PACK_STR ) + NICIRA_HEADER_SIZE == NX_CONTROLLER_ID_SIZE ) NX_STATS_MSG_PACK_STR = '' NX_STATS_MSG0_SIZE = assert calcsize ( NX_STATS_MSG_PACK_STR ) == NX_STATS_MSG0_SIZE NX_STATS_MSG_SIZE = _OFP_VENDOR_STATS_MSG_SIZE = assert ( calcsize ( NX_STATS_MSG_PACK_STR ) + _OFP_VENDOR_STATS_MSG_SIZE == NX_STATS_MSG_SIZE ) NX_FLOW_STATS_REQUEST_PACK_STR = '' NX_FLOW_STATS_REQUEST_SIZE = assert ( calcsize ( NX_FLOW_STATS_REQUEST_PACK_STR ) == NX_FLOW_STATS_REQUEST_SIZE ) NX_FLOW_STATS_PACK_STR = '' NX_FLOW_STATS_SIZE = assert calcsize ( NX_FLOW_STATS_PACK_STR ) == NX_FLOW_STATS_SIZE NX_AGGREGATE_STATS_REQUEST_PACK_STR = '' NX_AGGREGATE_STATS_REQUEST_SIZE = assert ( calcsize ( NX_AGGREGATE_STATS_REQUEST_PACK_STR ) == NX_AGGREGATE_STATS_REQUEST_SIZE ) NX_AGGREGATE_STATS_REPLY_PACK_STR = '' NX_AGGREGATE_STATS_REPLY_SIZE = assert ( calcsize ( NX_AGGREGATE_STATS_REPLY_PACK_STR ) == NX_AGGREGATE_STATS_REPLY_SIZE ) NX_HASH_FIELDS_ETH_SRC = NX_HASH_FIELDS_SYMMETRIC_L4 = NX_MP_ALG_MODULO_N = NX_MP_ALG_HASH_THRESHOLD = NX_MP_ALG_HRW = NX_MP_ALG_ITER_HASH = NX_BD_ALG_ACTIVE_BACKUP = NX_BD_ALG_HRW = NX_LEARN_N_BITS_MASK = NX_LEARN_SRC_FIELD = << NX_LEARN_SRC_IMMEDIATE = << NX_LEARN_SRC_MASK = << NX_LEARN_DST_MATCH = << NX_LEARN_DST_LOAD = << NX_LEARN_DST_OUTPUT = << NX_LEARN_DST_RESERVED = << NX_LEARN_DST_MASK = << NX_NAT_RANGE_IPV4_MIN = << NX_NAT_RANGE_IPV4_MAX = << NX_NAT_RANGE_IPV6_MIN = << ", "answer": "NX_NAT_RANGE_IPV6_MAX = << "}, {"prompt": " patched = { } def patch ( namespace , name , value ) : \"\"\"\"\"\" nref = ( namespace , name ) orig = getattr ( namespace , name ) patched . setdefault ( nref , [ ] ) . append ( orig ) setattr ( namespace , name , value ) return orig def revert ( namespace , name ) : \"\"\"\"\"\" nref = ( namespace , name ) if nref not in patched or not patched [ nref ] : ", "answer": "raise ValueError , \"\" % nref"}, {"prompt": " import pyjd from pyjamas import Window from pyjamas . ui . Tree import Tree from pyjamas . ui . TreeItem import TreeItem from pyjamas . ui . CheckBox import CheckBox from pyjamas . ui . RootPanel import RootPanel def onCb1 ( sender ) : Window . alert ( '' + str ( sender ) + str ( sender . isChecked ( ) ) ) def onCb2 ( sender ) : Window . alert ( '' + str ( sender ) + str ( sender . isChecked ( ) ) ) def main ( ) : root = RootPanel ( ) tree = Tree ( ) cb1 = CheckBox ( '' ) cb1 . addClickListener ( onCb1 ) root . add ( cb1 ) cb2 = CheckBox ( '' ) cb2 . addClickListener ( onCb2 ) item = TreeItem ( cb2 ) ", "answer": "tree . addItem ( item )"}, {"prompt": " \"\"\"\"\"\" import os import sys from django . core . wsgi import get_wsgi_application sys . path . insert ( ", "answer": " ,"}, {"prompt": " import os from flask import ( Flask , redirect , url_for , session , request , render_template , g ) from flask . ext . login import ( LoginManager , login_required , login_user , logout_user , current_user ) from flask . ext . sqlalchemy import SQLAlchemy from flask_oauth import OAuth FACEBOOK_APP_ID = os . environ [ '' ] FACEBOOK_APP_SECRET = os . environ [ '' ] app = Flask ( __name__ ) app . debug = True app . secret_key = os . environ [ '' ] app . config [ '' ] = '' db = SQLAlchemy ( app ) class User ( db . Model ) : id = db . Column ( db . Integer , primary_key = True ) social_id = db . Column ( db . Integer , unique = True ) name = db . Column ( db . String , nullable = False ) email = db . Column ( db . String , nullable = True ) def __init__ ( self , name , social_id , email = None ) : self . name = name self . social_id = social_id self . email = email def is_authenticated ( self ) : return True def is_active ( self ) : return True def is_anonymous ( self ) : return False def get_id ( self ) : return unicode ( self . id ) def __repr__ ( self ) : return \"\" % ( self . name ) ", "answer": "oauth = OAuth ( )"}, {"prompt": " from qiniu import Auth , put_file , etag , urlsafe_base64_encode import qiniu . config access_key = '' secret_key = '' q = Auth ( access_key , secret_key ) bucket_name = '' ", "answer": "key = '' ;"}, {"prompt": " import numpy as n import os from time import time , asctime , localtime , strftime from numpy . random import randn , rand from numpy import s_ , dot , tile , zeros , ones , zeros_like , array , ones_like from util import * from data import * from options import * from math import ceil , floor , sqrt from data import DataProvider , dp_types import sys import shutil import platform from os import linesep as NL class ModelStateException ( Exception ) : pass class IGPUModel : def __init__ ( self , model_name , op , load_dic , filename_options = None , dp_params = { } ) : self . model_name = model_name self . op = op self . options = op . options self . load_dic = load_dic self . filename_options = filename_options self . dp_params = dp_params self . get_gpus ( ) self . fill_excused_options ( ) self . img_size = self . img_channels = self . img_rs = for o in op . get_options_list ( ) : setattr ( self , o . name , o . value ) if load_dic : self . model_state = load_dic [ \"\" ] self . save_file = self . options [ \"\" ] . value if not os . path . isdir ( self . save_file ) : self . save_file = os . path . dirname ( self . save_file ) ( pdir , self . save_file ) = os . path . split ( self . save_file ) if ( len ( self . save_file ) == ) : ( pdir , self . save_file ) = os . path . split ( pdir ) if ( os . path . samefile ( pdir , self . save_path ) ) : print \"\" , pdir print \"\" , self . save_path else : self . model_state = { } if self . model_file : self . save_file = self . model_file else : if filename_options is not None : self . save_file = model_name + \"\" + '' . join ( [ '' % ( char , self . options [ opt ] . get_str_value ( ) ) for opt , char in filename_options ] ) + '' + strftime ( '' ) self . model_state [ \"\" ] = [ ] self . model_state [ \"\" ] = [ ] self . model_state [ \"\" ] = self . model_state [ \"\" ] = self . train_batch_range [ ] self . init_data_providers ( ) if load_dic : self . train_data_provider . advance_batch ( ) try : self . init_model_state ( ) except ModelStateException , e : print e sys . exit ( ) for var , val in self . model_state . iteritems ( ) : setattr ( self , var , val ) self . import_model ( ) self . init_model_lib ( ) def import_model ( self ) : print \"\" print \"\" % ( '' + self . model_name ) self . libmodel = __import__ ( '' + self . model_name ) def fill_excused_options ( self ) : pass def init_data_providers ( self ) : self . dp_params [ '' ] = self try : self . test_data_provider = DataProvider . get_instance ( self . data_path , self . img_size , self . img_channels , self . test_batch_range , type = self . dp_type , dp_params = self . dp_params , test = True ) self . train_data_provider = DataProvider . get_instance ( self . data_path , self . img_size , self . img_channels , self . train_batch_range , self . model_state [ \"\" ] , self . model_state [ \"\" ] , type = self . dp_type , dp_params = self . dp_params , test = False ) except DataProviderException , e : print \"\" % e self . print_data_providers ( ) sys . exit ( ) def init_model_state ( self ) : pass def init_model_lib ( self ) : pass def start ( self ) : if self . test_only : self . test_outputs += [ self . get_test_error ( ) ] self . print_test_results ( ) sys . exit ( ) self . train ( ) def scale_learningRate ( self , eps ) : self . libmodel . scaleModelEps ( eps ) ; def reset_modelMom ( self ) : self . libmodel . resetModelMom ( ) ; def train ( self ) : print \"\" print \"\" , self . scale_rate print \"\" , self . reset_mom print \"\" , self . img_rs print \"\" self . scale_learningRate ( self . scale_rate ) if self . reset_mom : self . reset_modelMom ( ) print \"\" print \"\" % self . model_name self . op . print_values ( ) print \"\" self . print_model_state ( ) print \"\" % \"\" . join ( \"\" % d for d in self . device_ids ) print \"\" % asctime ( localtime ( ) ) print \"\" % os . path . join ( self . save_path , self . save_file ) print \"\" next_data = self . get_next_batch ( ) if self . adp_drop : dropRate = self . set_dropRate ( dropRate ) ; epoch_cost = print_epoch_cost = False while self . epoch <= self . num_epochs : data = next_data self . epoch , self . batchnum = data [ ] , data [ ] if self . batchnum == : if print_epoch_cost : print \"\" + str ( epoch_cost ) epoch_cost = print_epoch_cost = True self . print_iteration ( ) sys . stdout . flush ( ) if self . batchnum == and self . adp_drop : dropRate = self . adjust_dropRate ( dropRate ) compute_time_py = time ( ) self . start_batch ( data ) next_data = self . get_next_batch ( ) batch_output = self . finish_batch ( ) self . train_outputs += [ batch_output ] epoch_cost += self . print_train_results ( ) if self . get_num_batches_done ( ) % self . testing_freq == : self . sync_with_host ( ) self . test_outputs += [ self . get_test_error ( ) ] self . print_test_results ( ) self . print_test_status ( ) self . conditional_save ( ) self . print_train_time ( time ( ) - compute_time_py ) self . cleanup ( ) def cleanup ( self ) : sys . exit ( ) def set_dropRate ( self , dropRate ) : print \"\" , dropRate self . libmodel . setDropRate ( dropRate ) ; def adjust_dropRate ( self , dropRate ) : if not self . train_outputs : return dropRate costs , num_cases = self . train_outputs [ - ] [ ] , self . train_outputs [ - ] [ ] for errname in costs . keys ( ) : if costs [ errname ] [ ] < ( - dropRate ) : dropRate += self . set_dropRate ( dropRate ) return dropRate def sync_with_host ( self ) : self . libmodel . syncWithHost ( ) def print_model_state ( self ) : pass def get_num_batches_done ( self ) : return len ( self . train_batch_range ) * ( self . epoch - ) + self . batchnum - self . train_batch_range [ ] + def get_next_batch ( self , train = True ) : dp = self . train_data_provider if not train : dp = self . test_data_provider data = self . parse_batch_data ( dp . get_next_batch ( ) , train = train ) w = dp . get_out_img_size ( ) h = dp . get_out_img_size ( ) d = dp . get_out_img_depth ( ) if self . img_rs and train : assert ( w * h * d == data [ ] [ ] . shape [ ] ) self . libmodel . preprocess ( [ data [ ] [ ] ] , w , h , d , , ) return data def parse_batch_data ( self , batch_data , train = True ) : return batch_data [ ] , batch_data [ ] , batch_data [ ] [ '' ] def start_batch ( self , batch_data , train = True ) : self . libmodel . startBatch ( batch_data [ ] , not train ) def finish_batch ( self ) : return self . libmodel . finishBatch ( ) def print_iteration ( self ) : print \"\" % ( self . epoch , self . batchnum ) , def print_train_time ( self , compute_time_py ) : print \"\" % ( compute_time_py ) def print_train_results ( self ) : batch_error = self . train_outputs [ - ] [ ] if not ( batch_error > and batch_error < ) : print \"\" % batch_error self . cleanup ( ) print \"\" % ( batch_error ) , def print_test_results ( self ) : batch_error = self . test_outputs [ - ] [ ] print \"\" % ( NL , batch_error ) , def print_test_status ( self ) : status = ( len ( self . test_outputs ) == or self . test_outputs [ - ] [ ] < self . test_outputs [ - ] [ ] ) and \"\" or \"\" print status , def conditional_save ( self ) : batch_error = self . test_outputs [ - ] [ ] if batch_error > and batch_error < self . max_test_err : self . save_state ( ) else : print \"\" % self . max_test_err , def aggregate_test_outputs ( self , test_outputs ) : test_error = tuple ( [ sum ( t [ r ] for t in test_outputs ) / ( if self . test_one else len ( self . test_batch_range ) ) for r in range ( len ( test_outputs [ - ] ) ) ] ) return test_error def get_test_error ( self ) : next_data = self . get_next_batch ( train = False ) test_outputs = [ ] while True : data = next_data self . start_batch ( data , train = False ) load_next = not self . test_one and data [ ] < self . test_batch_range [ - ] if load_next : next_data = self . get_next_batch ( train = False ) test_outputs += [ self . finish_batch ( ) ] ", "answer": "if self . test_only :"}, {"prompt": " import unittest import tushare . stock . fundamental as fd class Test ( unittest . TestCase ) : def set_data ( self ) : self . code = '' self . start = '' self . end = '' self . year = self . quarter = def test_get_stock_basics ( self ) : ", "answer": "print ( fd . get_stock_basics ( ) )"}, {"prompt": " import dbexts , cmd , sys , os if sys . platform . startswith ( \"\" ) : import java . lang . String \"\"\"\"\"\" __version__ = \"\" class IsqlExit ( Exception ) : pass class Prompt : \"\"\"\"\"\" def __init__ ( self , isql ) : self . isql = isql def __str__ ( self ) : prompt = \"\" % ( self . isql . db . dbname ) if len ( self . isql . sqlbuffer ) > : prompt = \"\" return prompt if sys . platform . startswith ( \"\" ) : def __tojava__ ( self , cls ) : if cls == java . lang . String : return self . __str__ ( ) return False class IsqlCmd ( cmd . Cmd ) : def __init__ ( self , db = None , delimiter = \"\" , comment = ( '' , '' ) ) : cmd . Cmd . __init__ ( self , completekey = None ) if db is None or type ( db ) == type ( \"\" ) : self . db = dbexts . dbexts ( db ) else : self . db = db self . kw = { } self . sqlbuffer = [ ] self . comment = comment self . delimiter = delimiter self . prompt = Prompt ( self ) def parseline ( self , line ) : command , arg , line = cmd . Cmd . parseline ( self , line ) if command and command < > \"\" : command = command . lower ( ) return command , arg , line def do_which ( self , arg ) : \"\"\"\"\"\" print self . db return False def do_EOF ( self , arg ) : return False def do_p ( self , arg ) : \"\"\"\"\"\" try : exec arg . strip ( ) in globals ( ) except : print sys . exc_info ( ) [ ] return False def do_column ( self , arg ) : \"\"\"\"\"\" return False def do_use ( self , arg ) : \"\"\"\"\"\" self . db = self . db . __class__ ( arg . strip ( ) ) return False def do_table ( self , arg ) : \"\"\"\"\"\" if len ( arg . strip ( ) ) : self . db . table ( arg , ** self . kw ) else : self . db . table ( None , ** self . kw ) return False def do_proc ( self , arg ) : \"\"\"\"\"\" if len ( arg . strip ( ) ) : self . db . proc ( arg , ** self . kw ) else : self . db . proc ( None , ** self . kw ) return False def do_schema ( self , arg ) : \"\"\"\"\"\" print self . db . schema ( arg ) print return False def do_delimiter ( self , arg ) : \"\"\"\"\"\" delimiter = arg . strip ( ) if len ( delimiter ) > : self . delimiter = delimiter def do_o ( self , arg ) : \"\"\"\"\"\" if not arg : fp = self . db . out try : if fp : fp . close ( ) finally : self . db . out = None else : fp = open ( arg , \"\" ) self . db . out = fp def do_q ( self , arg ) : \"\"\"\"\"\" try : if self . db . out : self . db . out . close ( ) finally : return True def do_set ( self , arg ) : \"\"\"\"\"\" if len ( arg . strip ( ) ) == : items = self . kw . items ( ) if len ( items ) : print for a in dbexts . console ( items , ( \"\" , \"\" ) ) [ : - ] : print a print return False d = filter ( lambda x : len ( x ) > , map ( lambda x : x . strip ( ) , arg . split ( \"\" ) ) ) if len ( d ) == : if self . kw . has_key ( d [ ] ) : del self . kw [ d [ ] ] else : self . kw [ d [ ] ] = eval ( d [ ] ) def do_i ( self , arg ) : fp = open ( arg ) try : print for line in fp . readlines ( ) : line = self . precmd ( line ) stop = self . onecmd ( line ) stop = self . postcmd ( stop , line ) finally : fp . close ( ) return False def default ( self , arg ) : try : token = arg . strip ( ) if not token : return False comment = [ token . startswith ( x ) for x in self . comment ] if reduce ( lambda x , y : x or y , comment ) : return False if token [ ] == '' : token = token [ : ] if len ( token ) >= len ( self . delimiter ) : if token [ - * len ( self . delimiter ) : ] == self . delimiter : self . sqlbuffer . append ( token [ : - * len ( self . delimiter ) ] ) if self . sqlbuffer : q = \"\" . join ( self . sqlbuffer ) print q self . db . isql ( q , ** self . kw ) self . sqlbuffer = [ ] if self . db . updatecount : print if self . db . updatecount == : ", "answer": "print \"\""}, {"prompt": " \"\"\"\"\"\" from . import pool from . . _compat import queue ", "answer": "def map ( requests , ** kwargs ) :"}, {"prompt": " import unittest import shutil import os from angular_scaffold . management . commands . helpers . _generate_assets import generate_assets from angular_scaffold . management . commands . helpers . _generate_debugger import generate_debugger class GenerateDebuggerTest ( unittest . TestCase ) : ", "answer": "def setUp ( self ) :"}, {"prompt": " from django . shortcuts import render_to_response from demoproject . chartdemo . models import MonthlyWeatherByCity from chartit import DataPool , Chart def homepage ( request ) : ds = DataPool ( series = [ { '' : { '' : MonthlyWeatherByCity . objects . all ( ) } , '' : [ '' , '' , '' , '' ] } ", "answer": "] )"}, {"prompt": " from revscoring . languages import polish from . import enwiki , mediawiki , wikipedia , wikitext badwords = [ polish . badwords . revision . diff . match_delta_sum , polish . badwords . revision . diff . match_delta_increase , polish . badwords . revision . diff . match_delta_decrease , ", "answer": "polish . badwords . revision . diff . match_prop_delta_sum ,"}, {"prompt": " import datetime from django . core . urlresolvers import reverse from django import http from django . utils import timezone from mox import IsA from horizon . templatetags import sizeformat from openstack_dashboard import api from openstack_dashboard . test import helpers as test from openstack_dashboard import usage INDEX_URL = reverse ( '' ) class UsageViewTests ( test . BaseAdminViewTests ) : @ test . create_stubs ( { api . nova : ( '' , '' , ) , api . keystone : ( '' , ) , api . neutron : ( '' , ) , api . network : ( '' , '' ) } ) def test_usage ( self ) : ", "answer": "now = timezone . now ( )"}, {"prompt": " \"\"\"\"\"\" import os . path as op import mne from mne . datasets import sample data_path = sample . data_path ( ) raw_empty_room_fname = op . join ( data_path , '' , '' , '' ) raw_empty_room = mne . io . read_raw_fif ( raw_empty_room_fname ) raw_fname = op . join ( data_path , '' , '' , '' ) raw = mne . io . read_raw_fif ( raw_fname ) raw . info [ '' ] += [ '' ] noise_cov = mne . compute_raw_covariance ( raw_empty_room , tmin = , tmax = None ) events = mne . find_events ( raw ) epochs = mne . Epochs ( raw , events , event_id = , tmin = - , tmax = , baseline = ( - , ) ) noise_cov_baseline = mne . compute_covariance ( epochs ) noise_cov . plot ( raw_empty_room . info , proj = True ) noise_cov_baseline . plot ( epochs . info ) cov = mne . compute_covariance ( epochs , tmax = , method = '' ) evoked = epochs . average ( ) evoked . plot_white ( cov ) ", "answer": "covs = mne . compute_covariance ( epochs , tmax = , method = ( '' , '' ) ,"}, {"prompt": " '''''' def __virtual__ ( ) : '''''' return '' if '' in __salt__ else False def _refine_mode ( mode ) : '''''' mode = str ( mode ) . lower ( ) if any ( [ mode . startswith ( '' ) , mode == '' , mode == '' ] ) : return '' if any ( [ mode . startswith ( '' ) , mode == '' , mode == '' ] ) : return '' if any ( [ mode . startswith ( '' ) ] ) : return '' return '' def _refine_value ( value ) : '''''' value = str ( value ) . lower ( ) if value in ( '' , '' , '' , '' ) : return '' if value in ( '' , '' , '' , '' ) : return '' return None def _refine_module_state ( module_state ) : '''''' module_state = str ( module_state ) . lower ( ) if module_state in ( '' , '' , '' , '' , '' ) : return '' if module_state in ( '' , '' , '' , '' , '' ) : return '' return '' def mode ( name ) : '''''' ret = { '' : name , '' : False , '' : '' , '' : { } } tmode = _refine_mode ( name ) if tmode == '' : ret [ '' ] = '' . format ( name ) return ret mode = __salt__ [ '' ] ( ) if mode == tmode : ret [ '' ] = True ret [ '' ] = '' . format ( tmode ) return ret if __opts__ [ '' ] : ret [ '' ] = '' . format ( tmode ) ret [ '' ] = None return ret mode = __salt__ [ '' ] ( tmode ) if mode == tmode : ret [ '' ] = True ret [ '' ] = '' . format ( tmode ) return ret ret [ '' ] = '' . format ( tmode ) return ret def boolean ( name , value , persist = False ) : '''''' ret = { '' : name , '' : True , '' : '' , '' : { } } bools = __salt__ [ '' ] ( ) if name not in bools : ret [ '' ] = '' . format ( name ) ret [ '' ] = False return ret rvalue = _refine_value ( value ) if rvalue is None : ret [ '' ] = '' '' . format ( value ) ret [ '' ] = False return ret state = bools [ name ] [ '' ] == rvalue default = bools [ name ] [ '' ] == rvalue if persist : if state and default : ret [ '' ] = '' return ret else : if state : ret [ '' ] = '' return ret if __opts__ [ '' ] : ret [ '' ] = None ret [ '' ] = '' . format ( name , rvalue ) return ret if __salt__ [ '' ] ( name , rvalue , persist ) : ret [ '' ] = '' . format ( name , rvalue ) return ret ret [ '' ] = '' . format ( name , rvalue ) return ret def module ( name , module_state = '' , version = '' ) : '''''' ret = { '' : name , '' : True , '' : '' , '' : { } } modules = __salt__ [ '' ] ( ) if name not in modules : ret [ '' ] = '' . format ( name ) ret [ '' ] = False return ret rmodule_state = _refine_module_state ( module_state ) if rmodule_state == '' : ret [ '' ] = '' '' . format ( module_state , module ) ret [ '' ] = False return ret ", "answer": "if version != '' :"}, {"prompt": " from django . contrib import admin from django . core . mail import get_connection from . models import Member from . . storage . models import Package class PackageInline ( admin . TabularInline ) : model = Package max_num = class MemberAdmin ( admin . ModelAdmin ) : list_display = ( '' , '' , '' , '' , '' , '' , ) list_filter = ( '' , '' , '' , '' , ) search_fields = ( '' , '' , ) actions = [ '' ] actions_on_bottom = True exclude = ( '' , '' , ) inlines = [ PackageInline , ] ", "answer": "def resend_registration ( self , request , queryset ) :"}, {"prompt": " \"\"\"\"\"\" import warnings import numbers import numpy as np import scipy . sparse as sp class DataConversionWarning ( UserWarning ) : \"\"\"\"\"\" pass warnings . simplefilter ( \"\" , DataConversionWarning ) def _assert_all_finite ( X ) : \"\"\"\"\"\" X = np . asanyarray ( X ) if ( X . dtype . char in np . typecodes [ '' ] and not np . isfinite ( X . sum ( ) ) and not np . isfinite ( X ) . all ( ) ) : raise ValueError ( \"\" \"\" % X . dtype ) def _shape_repr ( shape ) : \"\"\"\"\"\" if len ( shape ) == : return \"\" joined = \"\" . join ( \"\" % e for e in shape ) if len ( shape ) == : joined += '' return \"\" % joined def _num_samples ( x ) : \"\"\"\"\"\" if hasattr ( x , '' ) : raise TypeError ( '' '' % x ) if not hasattr ( x , '' ) and not hasattr ( x , '' ) : if hasattr ( x , '' ) : x = np . asarray ( x ) else : raise TypeError ( \"\" % type ( x ) ) if hasattr ( x , '' ) : if len ( x . shape ) == : raise TypeError ( \"\" \"\" % x ) return x . shape [ ] else : return len ( x ) def _ensure_sparse_format ( spmatrix , accept_sparse , dtype , copy , force_all_finite ) : \"\"\"\"\"\" if accept_sparse in [ None , False ] : raise TypeError ( '' '' '' ) if dtype is None : dtype = spmatrix . dtype changed_format = False if ( isinstance ( accept_sparse , ( list , tuple ) ) and spmatrix . format not in accept_sparse ) : spmatrix = spmatrix . asformat ( accept_sparse [ ] ) changed_format = True if dtype != spmatrix . dtype : spmatrix = spmatrix . astype ( dtype ) elif copy and not changed_format : spmatrix = spmatrix . copy ( ) if force_all_finite : if not hasattr ( spmatrix , \"\" ) : warnings . warn ( \"\" % spmatrix . format ) else : _assert_all_finite ( spmatrix . data ) return spmatrix def check_symmetric ( array , tol = , raise_warning = True , raise_exception = False ) : \"\"\"\"\"\" if ( array . ndim != ) or ( array . shape [ ] != array . shape [ ] ) : raise ValueError ( \"\" \"\" . format ( array . shape ) ) if sp . issparse ( array ) : diff = array - array . T if diff . format not in [ '' , '' , '' ] : diff = diff . tocsr ( ) symmetric = np . all ( abs ( diff . data ) < tol ) else : symmetric = np . allclose ( array , array . T , atol = tol ) if not symmetric : if raise_exception : raise ValueError ( \"\" ) if raise_warning : warnings . warn ( \"\" \"\" ) if sp . issparse ( array ) : conversion = '' + array . format array = getattr ( * ( array + array . T ) , conversion ) ( ) else : array = * ( array + array . T ) return array def check_random_state ( seed ) : \"\"\"\"\"\" if seed is None or seed is np . random : return np . random . mtrand . _rand if isinstance ( seed , ( numbers . Integral , np . integer ) ) : return np . random . RandomState ( seed ) if isinstance ( seed , np . random . RandomState ) : return seed raise ValueError ( '' '' % seed ) def check_array ( array , accept_sparse = None , dtype = \"\" , order = None , copy = False , force_all_finite = True , ensure_2d = True , allow_nd = False , ensure_min_samples = , ensure_min_features = , warn_on_dtype = False ) : \"\"\"\"\"\" if isinstance ( accept_sparse , str ) : accept_sparse = [ accept_sparse ] dtype_numeric = dtype == \"\" dtype_orig = getattr ( array , \"\" , None ) if not hasattr ( dtype_orig , '' ) : dtype_orig = None if dtype_numeric : if dtype_orig is not None and dtype_orig . kind == \"\" : dtype = np . float64 else : dtype = None if isinstance ( dtype , ( list , tuple ) ) : if dtype_orig is not None and dtype_orig in dtype : dtype = None else : dtype = dtype [ ] if sp . issparse ( array ) : array = _ensure_sparse_format ( array , accept_sparse , dtype , copy , force_all_finite ) else : array = np . array ( array , dtype = dtype , order = order , copy = copy ) if ensure_2d : if array . ndim == : if ensure_min_samples >= : raise ValueError ( \"\" \"\" % estimator_name ) warnings . warn ( \"\" \"\" \"\" \"\" , DeprecationWarning ) array = np . atleast_2d ( array ) array = np . array ( array , dtype = dtype , order = order , copy = copy ) if dtype_numeric and array . dtype . kind == \"\" : array = array . astype ( np . float64 ) if not allow_nd and array . ndim >= : raise ValueError ( \"\" % ( array . ndim ) ) if force_all_finite : _assert_all_finite ( array ) shape_repr = _shape_repr ( array . shape ) if ensure_min_samples > : n_samples = _num_samples ( array ) if n_samples < ensure_min_samples : raise ValueError ( \"\" \"\" % ( n_samples , shape_repr , ensure_min_samples ) ) if ensure_min_features > and array . ndim == : ", "answer": "n_features = array . shape [ ]"}, {"prompt": " import sys import unittest2 as unittest from raxcli . utils import get_enum_as_dict class TestUtils ( unittest . TestCase ) : def test_get_enum_as_dict ( self ) : class EnumClass1 ( object ) : KEY1 = KEY_TWO_TWO = SOME_KEY_SOME_SOME = result1 = get_enum_as_dict ( EnumClass1 , friendly_names = False ) result2 = get_enum_as_dict ( EnumClass1 , friendly_names = True ) result1_reversed = get_enum_as_dict ( EnumClass1 , reverse = True , friendly_names = False ) expected1 = { '' : , '' : , '' : } expected2 = { '' : , '' : , '' : } expected3 = { : '' , : '' , : '' } self . assertDictEqual ( result1 , expected1 ) self . assertDictEqual ( result2 , expected2 ) self . assertDictEqual ( result1_reversed , expected3 ) ", "answer": "if __name__ == '' :"}, {"prompt": " from __future__ import unicode_literals from django . db import models , migrations import datetime class Migration ( migrations . Migration ) : dependencies = [ ( '' , '' ) , ] operations = [ ", "answer": "migrations . AddField ("}, {"prompt": " from enum import Enum class FileType ( Enum ) : ", "answer": "assembly = \"\""}, {"prompt": " import uuid from keystoneauth1 import fixture as ks_fixture from keystoneauth1 import session from keystoneclient_kerberos . tests import base from keystoneclient_kerberos import v3 class TestFederatedAuth ( base . TestCase ) : def setUp ( self ) : super ( TestFederatedAuth , self ) . setUp ( ) self . protocol = uuid . uuid4 ( ) . hex self . identity_provider = uuid . uuid4 ( ) . hex @ property def token_url ( self ) : return \"\" % ( self . TEST_V3_URL , self . identity_provider , self . protocol ) def test_unscoped_federated_auth ( self ) : token_id , _ = self . kerberos_mock . mock_auth_success ( url = self . token_url , method = '' ) plugin = v3 . FederatedKerberos ( auth_url = self . TEST_V3_URL , protocol = self . protocol , identity_provider = self . identity_provider ) sess = session . Session ( ) tok = plugin . get_token ( sess ) self . assertEqual ( token_id , tok ) def test_project_scoped_federated_auth ( self ) : ", "answer": "self . kerberos_mock . mock_auth_success ( url = self . token_url , method = '' )"}, {"prompt": " from __future__ import unicode_literals from django . test import TestCase from django . dispatch import Signal from hooks . signalhook import hook class MockSignal : def __init__ ( self , providing_args = None ) : self . providing_args = providing_args ", "answer": "def connect ( self , func , sender = None , dispatch_uid = None ) :"}, {"prompt": " import sys , os extensions = [ ] templates_path = [ '' ] source_suffix = '' master_doc = '' project = u'' copyright = u'' version = '' release = '' exclude_patterns = [ '' ] pygments_style = '' html_theme = '' html_static_path = [ '' ] htmlhelp_basename = '' latex_elements = { } latex_documents = [ ( '' , '' , u'' , u'' , '' ) , ] man_pages = [ ( '' , '' , u'' , [ u'' ] , ) ] texinfo_documents = [ ( '' , '' , u'' , u'' , '' , '' , ", "answer": "'' ) ,"}, {"prompt": " import numpy as np import matplotlib . pyplot as plt ", "answer": "from agnez import embedding2d , embedding2dplot , timeseries2d , timeseries2dplot"}, {"prompt": " \"\"\"\"\"\" import re from core . common import retrieve_content __url__ = \"\" __check__ = \"\" ", "answer": "__info__ = \"\""}, {"prompt": " from datetime import datetime import pygame from pygame . mixer import Sound from ui import colours from ui . widgets . background import LcarsBackgroundImage , LcarsImage from ui . widgets . gifimage import LcarsGifImage from ui . widgets . lcars_widgets import LcarsText , LcarsButton from ui . widgets . screen import LcarsScreen from ui . widgets . sprite import LcarsMoveToMouse class ScreenMain ( LcarsScreen ) : def setup ( self , all_sprites ) : all_sprites . add ( LcarsBackgroundImage ( \"\" ) , layer = ) all_sprites . add ( LcarsText ( colours . BLACK , ( , ) , \"\" ) , layer = ) all_sprites . add ( LcarsText ( colours . ORANGE , ( , ) , \"\" , ) , layer = ) all_sprites . add ( LcarsText ( colours . BLACK , ( , ) , \"\" ) , layer = ) all_sprites . add ( LcarsText ( colours . BLACK , ( , ) , \"\" ) , layer = ) all_sprites . add ( LcarsText ( colours . BLACK , ( , ) , \"\" ) , layer = ) all_sprites . add ( LcarsText ( colours . BLACK , ( , ) , \"\" ) , layer = ) all_sprites . add ( LcarsText ( colours . WHITE , ( , ) , \"\" , ) , layer = ) all_sprites . add ( LcarsText ( colours . BLUE , ( , ) , \"\" , ) , layer = ) all_sprites . add ( LcarsText ( colours . BLUE , ( , ) , \"\" , ) , layer = ) all_sprites . add ( LcarsText ( colours . BLUE , ( , ) , \"\" , ) , layer = ) self . info_text = all_sprites . get_sprites_from_layer ( ) self . stardate = LcarsText ( colours . BLUE , ( , ) , \"\" , ) self . lastClockUpdate = all_sprites . add ( self . stardate , layer = ) all_sprites . add ( LcarsButton ( colours . RED_BROWN , ( , ) , \"\" , self . logoutHandler ) , layer = ) all_sprites . add ( LcarsButton ( colours . BEIGE , ( , ) , \"\" , self . sensorsHandler ) , layer = ) all_sprites . add ( LcarsButton ( colours . PURPLE , ( , ) , \"\" , self . gaugesHandler ) , layer = ) all_sprites . add ( LcarsButton ( colours . PEACH , ( , ) , \"\" , self . weatherHandler ) , layer = ) all_sprites . add ( LcarsGifImage ( \"\" , ( , ) , ) , layer = ) self . sensor_gadget = LcarsGifImage ( \"\" , ( , ) , ) self . sensor_gadget . visible = False all_sprites . add ( self . sensor_gadget , layer = ) self . dashboard = LcarsImage ( \"\" , ( , ) ) self . dashboard . visible = False all_sprites . add ( self . dashboard , layer = ) self . weather = LcarsImage ( \"\" , ( , ) ) self . weather . visible = False all_sprites . add ( self . weather , layer = ) self . beep1 = Sound ( \"\" ) Sound ( \"\" ) . play ( ) def update ( self , screenSurface , fpsClock ) : if pygame . time . get_ticks ( ) - self . lastClockUpdate > : self . stardate . setText ( \"\" . format ( datetime . now ( ) . strftime ( \"\" ) ) ) self . lastClockUpdate = pygame . time . get_ticks ( ) LcarsScreen . update ( self , screenSurface , fpsClock ) def handleEvents ( self , event , fpsClock ) : LcarsScreen . handleEvents ( self , event , fpsClock ) if event . type == pygame . MOUSEBUTTONDOWN : self . beep1 . play ( ) if event . type == pygame . MOUSEBUTTONUP : return False def hideInfoText ( self ) : if self . info_text [ ] . visible : for sprite in self . info_text : sprite . visible = False def gaugesHandler ( self , item , event , clock ) : self . hideInfoText ( ) self . sensor_gadget . visible = False self . dashboard . visible = True self . weather . visible = False ", "answer": "def sensorsHandler ( self , item , event , clock ) :"}, {"prompt": " import datetime from south . db import db from south . v2 import SchemaMigration from django . db import models class Migration ( SchemaMigration ) : def forwards ( self , orm ) : db . add_column ( '' , '' , self . gf ( '' ) ( default = '' , max_length = ) , keep_default = False ) db . add_column ( '' , '' , self . gf ( '' ) ( default = '' , max_length = ) , keep_default = False ) db . add_column ( '' , '' , self . gf ( '' ) ( default = '' , max_length = ) , keep_default = False ) def backwards ( self , orm ) : db . delete_column ( '' , '' ) db . delete_column ( '' , '' ) db . delete_column ( '' , '' ) models = { '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) } , '' : { '' : { '' : \"\" , '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) } , '' : { '' : { '' : \"\" , '' : \"\" , '' : '' , '' : \"\" } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : '' , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : \"\" } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { } ) , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { } ) , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) ", "answer": "} ,"}, {"prompt": " '''''' try : import regex as re except ImportError : import re from collections import defaultdict import os , io , json from datetime import datetime , timedelta from arelle import XbrlConst from arelle . ModelDtsObject import ModelConcept STMT = r\"\" notDET = r\"\" notCMPRH = r\"\" isCMPRH = r\"\" '''''' rePARENTHETICAL = r\"\" notPAR = \"\" + rePARENTHETICAL + \"\" isPAR = \"\" + rePARENTHETICAL + \"\" UGT_TOPICS = None def RE ( * args ) : return re . compile ( '' . join ( args ) , re . IGNORECASE ) EFMtableCodes = [ ( \"\" , RE ( STMT , notDET , notPAR ) , ( \"\" , ) ) , ( \"\" , RE ( STMT , notDET , isPAR ) , ( \"\" , ) ) , ( \"\" , RE ( STMT , notDET , notPAR ) , ( \"\" , ) ) , ( \"\" , RE ( STMT , notDET , isPAR ) , ( \"\" , ) ) , ( \"\" , RE ( STMT , notDET , notPAR ) , ( \"\" , ) ) , ( \"\" , RE ( STMT , notDET , isPAR ) , ( \"\" , ) ) , ( \"\" , RE ( STMT , notDET , notPAR ) , ( \"\" , \"\" ) ) , ( \"\" , RE ( STMT , notDET , isPAR ) , ( \"\" , \"\" ) ) , ( \"\" , RE ( STMT , notDET , notPAR ) , ( \"\" , ) ) , ( \"\" , RE ( STMT , notDET , isPAR ) , ( \"\" , ) ) , ( \"\" , RE ( STMT , notDET , notPAR ) , ( \"\" , ) ) , ( \"\" , RE ( STMT , notDET , isPAR ) , ( \"\" , ) ) , ( \"\" , RE ( STMT , notDET , notPAR ) , ( \"\" , ) ) , ( \"\" , RE ( STMT , notDET , isPAR ) , ( \"\" , ) ) , ( \"\" , RE ( r\"\" ) , None ) , ( \"\" , RE ( STMT , notDET , notPAR , r\"\" ) , None ) , ( \"\" , RE ( STMT , notDET , isPAR , r\"\" ) , None ) , ( \"\" , RE ( STMT , notDET , notPAR , r\"\" ) , None ) , ( \"\" , RE ( STMT , notDET , notPAR , notCMPRH , r\"\" ) , None ) , ( \"\" , RE ( STMT , notDET , isPAR , notCMPRH , r\"\" ) , None ) , ( \"\" , RE ( STMT , notDET , notPAR , isCMPRH , r\"\" ) , None ) , ( \"\" , RE ( STMT , notDET , isPAR , isCMPRH , r\"\" ) , None ) , ( \"\" , RE ( STMT , notDET , notPAR , r\"\" ) , None ) , ( \"\" , RE ( STMT , notDET , isPAR , r\"\" ) , None ) , ( \"\" , RE ( STMT , notDET , notPAR , r\"\" ) , None ) , ( \"\" , RE ( STMT , notDET , isPAR , r\"\" ) , None ) , ( \"\" , RE ( STMT , notDET , notPAR , r\"\" ) , None ) , ( \"\" , RE ( STMT , notDET , notPAR , r\"\" ) , None ) , ( \"\" , RE ( STMT , notDET , isPAR , r\"\" ) , None ) , ( \"\" , RE ( STMT , notDET , isPAR , r\"\" ) , None ) , ( \"\" , RE ( STMT , notDET , notPAR , r\"\" ) , None ) , ( \"\" , RE ( STMT , notDET , isPAR , r\"\" ) , None ) , ( \"\" , RE ( STMT , notDET , notPAR , r\"\" ) , None ) , ( \"\" , RE ( STMT , notDET , isPAR , r\"\" ) , None ) , ( \"\" , RE ( STMT , notDET , notPAR , r\"\" ) , None ) , ( \"\" , RE ( STMT , notDET , notPAR , r\"\" ) , None ) , ( \"\" , RE ( STMT , notDET , isPAR , r\"\" ) , None ) , ( \"\" , RE ( STMT , notDET , notPAR , r\"\" ) , None ) , ( \"\" , RE ( STMT , notDET , notPAR , r\"\" ) , None ) , ( \"\" , RE ( STMT , notDET , isPAR , r\"\" ) , None ) , ( \"\" , RE ( STMT , notDET , notPAR , r\"\" ) , None ) , ( \"\" , RE ( STMT , notDET , notPAR , r\"\" ) , None ) , ( \"\" , RE ( STMT , notDET , notPAR , r\"\" ) , None ) , ( \"\" , RE ( STMT , notDET , notPAR , r\"\" ) , None ) , ( \"\" , RE ( STMT , notDET , isPAR , r\"\" ) , None ) , ( \"\" , RE ( STMT , notDET , notPAR , r\"\" ) , None ) , ( \"\" , RE ( STMT , notDET , isPAR , r\"\" ) , None ) , ( \"\" , RE ( STMT , notDET , notPAR , r\"\" ) , None ) , ( \"\" , RE ( STMT , notDET , isPAR , r\"\" ) , None ) , ( \"\" , RE ( STMT , notDET , notPAR , r\"\" ) , None ) , ( \"\" , RE ( STMT , notDET , isPAR , r\"\" ) , None ) , ( \"\" , RE ( STMT , notDET , notPAR , r\"\" ) , None ) , ( \"\" , RE ( STMT , notDET , isPAR , r\"\" ) , None ) , ( \"\" , RE ( STMT , notDET , notPAR , r\"\" ) , None ) , ( \"\" , RE ( STMT , notDET , notPAR , r\"\" ) , None ) , ( \"\" , RE ( STMT , notDET , isPAR , r\"\" ) , None ) ] HMRCtableCodes = [ ( \"\" , RE ( r\"\" ) , None ) , ( \"\" , RE ( r\"\" ) , None ) , ( \"\" , RE ( r\"\" ) , None ) , ( \"\" , RE ( r\"\" ) , None ) , ( \"\" , RE ( r\"\" ) , None ) , ] def evaluateRoleTypesTableCodes ( modelXbrl ) : disclosureSystem = modelXbrl . modelManager . disclosureSystem if disclosureSystem . validationType in ( \"\" , \"\" ) : detectMultipleOfCode = False if disclosureSystem . validationType == \"\" : tableCodes = list ( EFMtableCodes ) detectMultipleOfCode = any ( v and any ( v . startswith ( dt ) for dt in ( '' , '' , '' , '' ) ) for docTypeConcept in modelXbrl . nameConcepts . get ( '' , ( ) ) for docTypeFact in modelXbrl . factsByQname . get ( docTypeConcept . qname , ( ) ) for v in ( docTypeFact . value , ) ) elif disclosureSystem . validationType == \"\" : tableCodes = list ( HMRCtableCodes ) codeRoleURI = { } roleURICode = { } roleTypes = [ roleType ", "answer": "for roleURI in modelXbrl . relationshipSet ( XbrlConst . parentChild ) . linkRoleUris"}, {"prompt": " import sys OPCODES = { '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : } NAMES = dict ( ( v , k ) for k , v in OPCODES . iteritems ( ) ) module = sys . modules [ __name__ ] for name , value in OPCODES . iteritems ( ) : setattr ( module , name , value ) class Machine : def __init__ ( self , sequence ) : self . offset = self . sequence = sequence self . stack = [ ] def step ( self ) : instruction = NAMES [ self . sequence [ self . offset ] ] method = getattr ( self , \"\" % instruction . lower ( ) ) method ( ) return self . offset >= and self . offset < len ( self . sequence ) def run ( self ) : result = True while result : result = self . step ( ) def instruction_nop ( self ) : self . offset += def instruction_halt ( self ) : self . offset = - def instruction_load ( self ) : self . offset += address = self . sequence [ self . offset ] self . stack . append ( self . sequence [ address ] ) self . offset += def instruction_save ( self ) : self . offset += address = self . sequence [ self . offset ] self . sequence [ address ] = self . stack . pop ( ) self . offset += def instruction_push ( self ) : self . offset += self . stack . append ( self . sequence [ self . offset ] ) self . offset += def instruction_pop ( self ) : self . offset += self . stack . pop ( ) def instruction_dup ( self ) : self . offset += self . stack . append ( self . stack [ - ] ) def instruction_jmp ( self ) : self . offset += address = self . sequence [ self . offset ] self . offset = address def instruction_call ( self ) : self . offset += self . stack . append ( self . offset + ) address = self . sequence [ self . offset ] self . offset = address def instruction_ret ( self ) : address = self . stack . pop ( ) self . offset = address def instruction_jlt ( self ) : self . offset += address = self . sequence [ self . offset ] value = self . stack . pop ( ) self . offset += if value > : self . offset = address def instruction_jlte ( self ) : self . offset += address = self . sequence [ self . offset ] value = self . stack . pop ( ) self . offset += if value >= : self . offset = address def instruction_je ( self ) : self . offset += address = self . sequence [ self . offset ] value = self . stack . pop ( ) self . offset += if value == : self . offset = address def instruction_jne ( self ) : self . offset += address = self . sequence [ self . offset ] value = self . stack . pop ( ) self . offset += if value != : self . offset = address def instruction_jgte ( self ) : self . offset += address = self . sequence [ self . offset ] value = self . stack . pop ( ) self . offset += if value <= : self . offset = address def instruction_jgt ( self ) : self . offset += address = self . sequence [ self . offset ] value = self . stack . pop ( ) self . offset += if value < : self . offset = address def instruction_cmplt ( self ) : self . offset += b = self . stack . pop ( ) a = self . stack . pop ( ) self . stack . append ( int ( a < b ) ) def instruction_cmplte ( self ) : self . offset += b = self . stack . pop ( ) a = self . stack . pop ( ) ", "answer": "self . stack . append ( int ( a <= b ) )"}, {"prompt": " from collections import MutableMapping from threading import Lock try : from collections import OrderedDict except ImportError : from . packages . ordered_dict import OrderedDict __all__ = [ '' ] _Null = object ( ) class RecentlyUsedContainer ( MutableMapping ) : \"\"\"\"\"\" ContainerCls = OrderedDict def __init__ ( self , maxsize = , dispose_func = None ) : self . _maxsize = maxsize self . dispose_func = dispose_func self . _container = self . ContainerCls ( ) self . _lock = Lock ( ) def __getitem__ ( self , key ) : with self . _lock : item = self . _container . pop ( key ) self . _container [ key ] = item return item def __setitem__ ( self , key , value ) : evicted_value = _Null ", "answer": "with self . _lock :"}, {"prompt": " \"\"\"\"\"\" from datetime import datetime from sqlalchemy import Column , Integer , Text , String , Boolean , ForeignKey , DateTime from sqlalchemy . orm import relation , sessionmaker , aliased from sqlalchemy . ext . declarative import declarative_base Base = declarative_base ( ) Session = sessionmaker ( ) db_prefix = '' class Node ( Base ) : \"\"\"\"\"\" __tablename__ = db_prefix + '' id = Column ( String ( ) , primary_key = True ) document = Column ( String ( ) , nullable = False ) source = Column ( Text , nullable = False ) def nested_comments ( self , username , moderator ) : \"\"\"\"\"\" session = Session ( ) if username : sq = session . query ( CommentVote ) . filter ( CommentVote . username == username ) . subquery ( ) cvalias = aliased ( CommentVote , sq ) q = session . query ( Comment , cvalias . value ) . outerjoin ( cvalias ) else : q = session . query ( Comment ) q = q . filter ( Comment . path . like ( str ( self . id ) + '' ) ) if not moderator : q = q . filter ( Comment . displayed == True ) results = q . order_by ( Comment . path ) . all ( ) session . close ( ) return self . _nest_comments ( results , username ) def _nest_comments ( self , results , username ) : \"\"\"\"\"\" comments = [ ] list_stack = [ comments ] for r in results : if username : comment , vote = r else : comment , vote = ( r , ) inheritance_chain = comment . path . split ( '' ) [ : ] if len ( inheritance_chain ) == len ( list_stack ) + : parent = list_stack [ - ] [ - ] list_stack . append ( parent [ '' ] ) elif len ( inheritance_chain ) < len ( list_stack ) : while len ( inheritance_chain ) < len ( list_stack ) : list_stack . pop ( ) list_stack [ - ] . append ( comment . serializable ( vote = vote ) ) return comments def __init__ ( self , id , document , source ) : self . id = id self . document = document self . source = source class CommentVote ( Base ) : \"\"\"\"\"\" ", "answer": "__tablename__ = db_prefix + ''"}, {"prompt": " \"\"\"\"\"\" from importlib import import_module from flask import current_app from flask_oauthlib . client import OAuthRemoteApp as BaseRemoteApp from flask . ext . security import current_user from werkzeug . local import LocalProxy from . utils import get_config , update_recursive from . views import create_blueprint _security = LocalProxy ( lambda : current_app . extensions [ '' ] ) _social = LocalProxy ( lambda : current_app . extensions [ '' ] ) _datastore = LocalProxy ( lambda : _social . datastore ) _logger = LocalProxy ( lambda : current_app . logger ) default_config = { '' : '' , '' : None , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' } class OAuthRemoteApp ( BaseRemoteApp ) : def __init__ ( self , id , module , install , * args , ** kwargs ) : BaseRemoteApp . __init__ ( self , None , ** kwargs ) self . id = id self . module = module ", "answer": "def get_connection ( self ) :"}, {"prompt": " from setuptools import setup try : with open ( '' ) as f : long_description = f . read ( ) except IOError : with open ( '' ) as f : long_description = f . read ( ) setup ( name = '' , version = '' , description = '' , long_description = long_description , url = '' , author = '' , author_email = '' , license = '' , classifiers = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , ] , keywords = '' , packages = [ '' , ] , install_requires = [ '' , '' ] , entry_points = { '' : [ '' , ] , } , ", "answer": ") "}, {"prompt": " from ztag . annotation import * class AVTECHDevice ( Annotation ) : ", "answer": "protocol = protocols . MODBUS"}, {"prompt": " from subprocess import Popen import sys import pygame class Run ( ) : def __init__ ( self , fona ) : self . fona = fona self . headset = False self . get_audio_mode ( ) self . RED = ( , , ) self . GREEN = ( , , ) self . WHITE = ( , , ) self . menu = pygame . image . load ( '' ) self . menu_rect = self . menu . get_rect ( ) self . font = pygame . font . Font ( '' , ) self . off = self . font . render ( '' , True , self . RED , self . WHITE ) self . fona_power = self . font . render ( '' , True , self . GREEN , self . WHITE ) self . fona_power_rect = self . off . get_rect ( ) self . fona_power_rect . centerx = self . fona_power_rect . centery = self . on = self . font . render ( '' , True , self . GREEN , self . WHITE ) self . rect = self . off . get_rect ( ) self . rect . centerx = self . rect . y = self . exit = False self . blit_one_surface = { '' : [ ] , '' : [ ] } self . blit = { '' : [ self . menu , self . fona_power , self . off ] , '' : [ self . menu_rect , self . fona_power_rect , self . rect ] } if self . headset : self . blit [ '' ] [ ] = self . on else : self . blit [ '' ] [ ] = self . off self . next_app = None def get_audio_mode ( self ) : audio_config = open ( '' , '' ) file = audio_config . readlines ( ) for i in range ( , len ( file ) ) : if file [ i ] [ ] == '' : pass else : file [ i ] = file [ i ] . rstrip ( ) if '' in file [ i ] : mode = file [ i ] mode = mode . split ( '' ) self . mode = int ( mode [ ] ) if self . mode == : self . headset = False else : self . headset = True def run_app ( self ) : pass def get_events ( self , event ) : if event . pos [ ] > and event . pos [ ] < : self . delete_sms ( ) if event . pos [ ] > and event . pos [ ] < : self . set_headset ( ) if event . pos [ ] > and event . pos [ ] < : self . exit = True def on_first_run ( self ) : self . exit = False def delete_sms ( self ) : self . fona . transmit ( '' ) self . exit = True def set_headset ( self ) : if self . headset : self . blit [ '' ] [ ] = self . off self . headset = False self . fona . transmit ( '' ) else : self . blit [ '' ] [ ] = self . on ", "answer": "self . headset = True"}, {"prompt": " CHUNK = b'' ", "answer": "FILE = b''"}, {"prompt": " def test ( a , b = , c = ) : ", "answer": "print '' % ( a , b , c )"}, {"prompt": " \"\"\"\"\"\" import axelrod from . test_player import TestHeadsUp , TestPlayer C , D = axelrod . Actions . C , axelrod . Actions . D class TestTitForTat ( TestPlayer ) : \"\"\"\"\"\" name = \"\" player = axelrod . TitForTat expected_classifier = { '' : , '' : False , '' : set ( ) , '' : False , '' : False , '' : False } def test_strategy ( self ) : \"\"\"\"\"\" self . first_play_test ( C ) def test_effect_of_strategy ( self ) : \"\"\"\"\"\" self . markov_test ( [ C , D , C , D ] ) self . responses_test ( [ C ] * , [ C , C , C , C ] , [ C ] ) self . responses_test ( [ C ] * , [ C , C , C , C , D ] , [ D ] ) class TestTitFor2Tats ( TestPlayer ) : name = '' player = axelrod . TitFor2Tats expected_classifier = { '' : , '' : False , '' : set ( ) , '' : False , '' : False , '' : False } def test_strategy ( self ) : \"\"\"\"\"\" self . first_play_test ( C ) def test_effect_of_strategy ( self ) : \"\"\"\"\"\" self . responses_test ( [ C , C , C ] , [ D , D , D ] , [ D ] ) self . responses_test ( [ C , C , D , D ] , [ D , D , D , C ] , [ C ] ) class TestTwoTitsForTat ( TestPlayer ) : name = '' player = axelrod . TwoTitsForTat expected_classifier = { '' : , '' : False , '' : set ( ) , '' : False , '' : False , '' : False } def test_strategy ( self ) : \"\"\"\"\"\" self . first_play_test ( C ) def test_effect_of_strategy ( self ) : \"\"\"\"\"\" self . responses_test ( [ C ] , [ D ] , [ D ] ) self . responses_test ( [ C , C ] , [ D , D ] , [ D ] ) self . responses_test ( [ C , C , C ] , [ D , D , C ] , [ D ] ) self . responses_test ( [ C , C , D , D ] , [ D , D , C , C ] , [ C ] ) class TestBully ( TestPlayer ) : name = \"\" player = axelrod . Bully expected_classifier = { '' : , '' : False , '' : set ( ) , '' : False , '' : False , '' : False } def test_strategy ( self ) : \"\"\"\"\"\" self . first_play_test ( D ) def test_affect_of_strategy ( self ) : \"\"\"\"\"\" self . markov_test ( [ D , C , D , C ] ) class TestSneakyTitForTat ( TestPlayer ) : name = \"\" player = axelrod . SneakyTitForTat expected_classifier = { '' : float ( '' ) , '' : False , '' : set ( ) , '' : False , '' : False , '' : False } def test_strategy ( self ) : \"\"\"\"\"\" self . first_play_test ( C ) def test_effect_of_strategy ( self ) : \"\"\"\"\"\" self . responses_test ( [ C , C ] , [ C , C ] , [ D ] ) self . responses_test ( [ C , C , D , D ] , [ C , C , C , D ] , [ C ] ) class TestSuspiciousTitForTat ( TestPlayer ) : name = '' player = axelrod . SuspiciousTitForTat expected_classifier = { '' : , '' : False , '' : set ( ) , '' : False , '' : False , '' : False } def test_strategy ( self ) : \"\"\"\"\"\" self . first_play_test ( D ) def test_affect_of_strategy ( self ) : \"\"\"\"\"\" self . markov_test ( [ C , D , C , D ] ) class TestAntiTitForTat ( TestPlayer ) : name = '' player = axelrod . AntiTitForTat expected_classifier = { '' : , '' : False , '' : set ( ) , '' : False , '' : False , '' : False } def test_strategy ( self ) : \"\"\"\"\"\" self . first_play_test ( C ) def test_affect_of_strategy ( self ) : \"\"\"\"\"\" self . markov_test ( [ D , C , D , C ] ) class TestHardTitForTat ( TestPlayer ) : name = \"\" player = axelrod . HardTitForTat expected_classifier = { '' : , '' : False , '' : set ( ) , '' : False , '' : False , '' : False } def test_strategy ( self ) : \"\"\"\"\"\" self . first_play_test ( C ) def test_effect_of_strategy ( self ) : \"\"\"\"\"\" self . responses_test ( [ C , C , C ] , [ C , C , C ] , [ C ] ) self . responses_test ( [ C , C , C ] , [ D , C , C ] , [ D ] ) self . responses_test ( [ C , C , C ] , [ C , D , C ] , [ D ] ) self . responses_test ( [ C , C , C ] , [ C , C , D ] , [ D ] ) self . responses_test ( [ C , C , C , C ] , [ D , C , C , C ] , [ C ] ) class TestHardTitFor2Tats ( TestPlayer ) : name = \"\" player = axelrod . HardTitFor2Tats expected_classifier = { '' : , '' : False , '' : set ( ) , ", "answer": "'' : False ,"}, {"prompt": " import re import six import sys import fixtures import testtools from climateclient import shell from climateclient import tests FAKE_ENV = { '' : '' , '' : '' , '' : '' , '' : '' } class ClimateShellTestCase ( tests . TestCase ) : def make_env ( self , exclude = None , fake_env = FAKE_ENV ) : env = dict ( ( k , v ) for k , v in fake_env . items ( ) if k != exclude ) self . useFixture ( fixtures . MonkeyPatch ( '' , env ) ) def setUp ( self ) : super ( ClimateShellTestCase , self ) . setUp ( ) self . climate_shell = shell . ClimateShell ( ) def shell ( self , argstr , exitcodes = ( , ) ) : orig = sys . stdout ", "answer": "orig_stderr = sys . stderr"}, {"prompt": " \"\"\"\"\"\" import sys , re if sys . version_info >= ( , ) : def u ( s ) : return s def unicode ( x , errors = None ) : if hasattr ( x , '' ) : return x . __unicode__ ( ) return str ( x ) else : def u ( s ) : return unicode ( s ) unicode = unicode class NamespaceMetaclass ( type ) : def __getattr__ ( self , name ) : if name [ : ] == '' : raise AttributeError ( name ) if self == Namespace : raise ValueError ( \"\" ) tagspec = self . __tagspec__ if tagspec is not None and name not in tagspec : raise AttributeError ( name ) classattr = { } if self . __stickyname__ : classattr [ '' ] = name cls = type ( name , ( self . __tagclass__ , ) , classattr ) setattr ( self , name , cls ) return cls class Tag ( list ) : class Attr ( object ) : def __init__ ( self , ** kwargs ) : self . __dict__ . update ( kwargs ) def __init__ ( self , * args , ** kwargs ) : super ( Tag , self ) . __init__ ( args ) self . attr = self . Attr ( ** kwargs ) def __unicode__ ( self ) : return self . unicode ( indent = ) __str__ = __unicode__ def unicode ( self , indent = ) : l = [ ] SimpleUnicodeVisitor ( l . append , indent ) . visit ( self ) return u ( \"\" ) . join ( l ) def __repr__ ( self ) : name = self . __class__ . __name__ return \"\" % ( name , id ( self ) ) Namespace = NamespaceMetaclass ( '' , ( object , ) , { '' : None , '' : Tag , '' : False , } ) class HtmlTag ( Tag ) : def unicode ( self , indent = ) : l = [ ] HtmlVisitor ( l . append , indent , shortempty = False ) . visit ( self ) return u ( \"\" ) . join ( l ) class html ( Namespace ) : __tagclass__ = HtmlTag __stickyname__ = True __tagspec__ = dict ( [ ( x , ) for x in ( '' '' '' '' '' '' '' '' '' '' ) . split ( '' ) if x ] ) class Style ( object ) : def __init__ ( self , ** kw ) : for x , y in kw . items ( ) : x = x . replace ( '' , '' ) setattr ( self , x , y ) class raw ( object ) : \"\"\"\"\"\" def __init__ ( self , uniobj ) : self . uniobj = uniobj class SimpleUnicodeVisitor ( object ) : \"\"\"\"\"\" def __init__ ( self , write , indent = , curindent = , shortempty = True ) : self . write = write self . cache = { } self . visited = { } self . indent = indent self . curindent = curindent self . parents = [ ] self . shortempty = shortempty def visit ( self , node ) : \"\"\"\"\"\" cls = node . __class__ try : visitmethod = self . cache [ cls ] except KeyError : for subclass in cls . __mro__ : visitmethod = getattr ( self , subclass . __name__ , None ) if visitmethod is not None : break else : visitmethod = self . __object self . cache [ cls ] = visitmethod visitmethod ( node ) def __object ( self , obj ) : self . write ( escape ( unicode ( obj ) ) ) def raw ( self , obj ) : self . write ( obj . uniobj ) def list ( self , obj ) : assert id ( obj ) not in self . visited self . visited [ id ( obj ) ] = for elem in obj : self . visit ( elem ) def Tag ( self , tag ) : assert id ( tag ) not in self . visited try : tag . parent = self . parents [ - ] except IndexError : tag . parent = None self . visited [ id ( tag ) ] = tagname = getattr ( tag , '' , tag . __class__ . __name__ ) if self . curindent and not self . _isinline ( tagname ) : self . write ( \"\" + u ( '' ) * self . curindent ) if tag : self . curindent += self . indent self . write ( u ( '' ) % ( tagname , self . attributes ( tag ) ) ) self . parents . append ( tag ) for x in tag : self . visit ( x ) self . parents . pop ( ) self . write ( u ( '' ) % tagname ) self . curindent -= self . indent else : nameattr = tagname + self . attributes ( tag ) if self . _issingleton ( tagname ) : self . write ( u ( '' ) % ( nameattr , ) ) else : self . write ( u ( '' ) % ( nameattr , tagname ) ) def attributes ( self , tag ) : attrlist = dir ( tag . attr ) attrlist . sort ( ) l = [ ] for name in attrlist : res = self . repr_attribute ( tag . attr , name ) if res is not None : l . append ( res ) l . extend ( self . getstyle ( tag ) ) return u ( \"\" ) . join ( l ) def repr_attribute ( self , attrs , name ) : if name [ : ] != '' : ", "answer": "value = getattr ( attrs , name )"}, {"prompt": " import sys PY2 = sys . version_info [ ] == if sys . version_info [ ] == and sys . version_info [ ] < : ", "answer": "from ordereddict import OrderedDict"}, {"prompt": " from numpy import array , sqrt , zeros from numpy . random import randn from numpy . testing import assert_allclose from commpy . channelcoding . ldpc import get_ldpc_code_params , ldpc_bp_decode from commpy . utilities import hamming_dist import os from nose . plugins . attrib import attr @ attr ( '' ) class TestLDPCCode ( object ) : @ classmethod def setup_class ( cls ) : dir = os . path . dirname ( __file__ ) ldpc_design_file_1 = os . path . join ( dir , '' ) cls . ldpc_code_params = get_ldpc_code_params ( ldpc_design_file_1 ) @ classmethod def teardown_class ( cls ) : pass def test_ldpc_bp_decode ( self ) : N = k = rate = Es = snr_list = array ( [ , ] ) niters = tx_codeword = zeros ( N , int ) ldpcbp_iters = fer_array_ref = array ( [ / , / ] ) fer_array_test = zeros ( len ( snr_list ) ) for idx , ebno in enumerate ( snr_list ) : noise_std = / sqrt ( ( ** ( ebno / ) ) * rate * / Es ) fer_cnt_bp = for iter_cnt in xrange ( niters ) : awgn_array = noise_std * randn ( N ) rx_word = - ( * tx_codeword ) + awgn_array rx_llrs = * rx_word / ( noise_std ** ) [ dec_word , out_llrs ] = ldpc_bp_decode ( rx_llrs , self . ldpc_code_params , ldpcbp_iters ) num_bit_errors = hamming_dist ( tx_codeword , dec_word ) if num_bit_errors > : fer_cnt_bp += if fer_cnt_bp >= : fer_array_test [ idx ] = float ( fer_cnt_bp ) / ( iter_cnt + ) ", "answer": "break"}, {"prompt": " from collections import Counter from datetime import date import logging import os import re import tempfile from django . conf import settings import requests from orchestra . google_apps . errors import FailedRequest from orchestra . google_apps . errors import InvalidUrlError from orchestra . google_apps . errors import GoogleDriveError from orchestra . google_apps . permissions import read_with_link_permission from orchestra . google_apps . permissions import write_with_link_permission from orchestra . google_apps . service import Service from orchestra . utils . common_regex import image_file_regex from orchestra . utils . settings import run_if logger = logging . getLogger ( __name__ ) _image_mimetype_regex = re . compile ( '' , re . IGNORECASE ) TEAM_MESSAGES_TEMPLATE_ID = '' def _get_image_mimetype ( response , title ) : \"\"\"\"\"\" if ( response . headers . get ( '' ) and _image_mimetype_regex . search ( response . headers . get ( '' ) ) ) : return response . headers . get ( '' ) extension = title . split ( '' ) [ - ] return '' . format ( extension ) @ run_if ( '' ) def add_image ( service , folder_id , url ) : \"\"\"\"\"\" response = requests . get ( url , stream = True ) if response . status_code != : raise FailedRequest ( '' '' , ( url ) ) temp = tempfile . NamedTemporaryFile ( mode = '' , delete = False ) for chunk in response . iter_content ( ) : temp . write ( chunk ) title_regex = image_file_regex . search ( response . url ) if title_regex is None : raise InvalidUrlError ( '' ) title = title_regex . group ( ) mimetype = _get_image_mimetype ( response , title ) temp . close ( ) google_image = service . insert_file ( title , '' , folder_id , mimetype , temp . name ) os . unlink ( temp . name ) return google_image @ run_if ( '' ) def create_media_folder_with_images ( parent_id , image_links , folder_name ) : \"\"\"\"\"\" service = Service ( settings . GOOGLE_P12_PATH , settings . GOOGLE_SERVICE_EMAIL ) folder = create_folder_with_permissions ( parent_id , folder_name , [ read_with_link_permission ] ) folder_id = folder [ '' ] counter = Counter ( ) for image_link in image_links : try : image = add_image ( service , folder_id , image_link ) counter [ '' ] += logger . info ( '' , image ) except ( InvalidUrlError , FailedRequest ) : counter [ '' ] += logger . exception ( '' , image_link ) return { '' : folder , '' : counter } @ run_if ( '' ) def create_folder_with_permissions ( parent_id , folder_name , permissions = None ) : \"\"\"\"\"\" service = Service ( settings . GOOGLE_P12_PATH , settings . GOOGLE_SERVICE_EMAIL ) folder = service . insert_folder ( folder_name , parent_id ) if folder is None : raise GoogleDriveError ( '' ) permissions = permissions or [ ] for permission in permissions : service . add_permission ( folder . get ( '' ) , permission ) return folder @ run_if ( '' ) def create_project_google_folder ( project ) : \"\"\"\"\"\" today = date . today ( ) . strftime ( '' ) parent_id = ( project . project_data . get ( '' ) or settings . GOOGLE_PROJECT_ROOT_ID ) folder = create_folder_with_permissions ( parent_id , '' . join ( ( today , project . short_description ) ) , [ write_with_link_permission ] ) folder_id = folder . get ( '' ) project . project_data [ '' ] = folder_id project . team_messages_url = create_document_from_template ( TEAM_MESSAGES_TEMPLATE_ID , '' , [ folder_id ] , [ write_with_link_permission ] ) [ '' ] project . save ( ) return folder @ run_if ( '' ) def create_document_from_template ( template_id , name , parent_ids = None , permissions = None ) : service = Service ( settings . GOOGLE_P12_PATH , settings . GOOGLE_SERVICE_EMAIL ) upload_info = service . copy_file ( template_id , name , parent_ids = parent_ids ) if upload_info is None : raise GoogleDriveError ( '' . format ( name ) ) logger . info ( upload_info ) document_id = upload_info . get ( '' ) permissions = permissions or [ ] for permission in permissions : service . add_permission ( document_id , permission ) upload_info [ '' ] = '' upload_info [ '' ] = document_id return upload_info @ run_if ( '' ) def download_file ( file_metadata ) : \"\"\"\"\"\" service = Service ( settings . GOOGLE_P12_PATH , settings . GOOGLE_SERVICE_EMAIL ) mimetype = file_metadata [ '' ] title = file_metadata [ '' ] return service . get_file_content ( file_metadata [ '' ] ) , title , mimetype ", "answer": "@ run_if ( '' )"}, {"prompt": " \"\"\"\"\"\" import mne from mne . event import make_fixed_length_events from mne . datasets import sample from mne . time_frequency import compute_epochs_csd from mne . beamformer import tf_dics from mne . viz import plot_source_spectrogram print ( __doc__ ) data_path = sample . data_path ( ) raw_fname = data_path + '' noise_fname = data_path + '' event_fname = data_path + '' fname_fwd = data_path + '' subjects_dir = data_path + '' label_name = '' fname_label = data_path + '' % label_name raw = mne . io . read_raw_fif ( raw_fname , preload = True ) raw . info [ '' ] = [ '' ] left_temporal_channels = mne . read_selection ( '' ) picks = mne . pick_types ( raw . info , meg = '' , eeg = False , eog = False , stim = False , exclude = '' , selection = left_temporal_channels ) raw . pick_channels ( [ raw . ch_names [ pick ] for pick in picks ] ) reject = dict ( mag = ) raw . info . normalize_proj ( ) tmin , tmax , tstep = - , , tmin_plot , tmax_plot = - , event_id = events = mne . read_events ( event_fname ) epochs = mne . Epochs ( raw , events , event_id , tmin , tmax , baseline = None , preload = True , proj = True , reject = reject ) raw_noise = mne . io . read_raw_fif ( noise_fname , preload = True ) raw_noise . info [ '' ] = [ '' ] raw_noise . pick_channels ( [ raw_noise . ch_names [ pick ] for pick in picks ] ) raw_noise . info . normalize_proj ( ) events_noise = make_fixed_length_events ( raw_noise , event_id ) epochs_noise = mne . Epochs ( raw_noise , events_noise , event_id , tmin_plot , tmax_plot , baseline = None , preload = True , proj = True , reject = reject ) epochs_noise . info . normalize_proj ( ) epochs_noise . apply_proj ( ) epochs_noise = epochs_noise [ : len ( epochs . events ) ] forward = mne . read_forward_solution ( fname_fwd , surf_ori = True ) label = mne . read_label ( fname_label ) freq_bins = [ ( , ) , ( , ) , ( , ) , ( , ) ] win_lengths = [ , , , ] n_ffts = [ , , , ] subtract_evoked = False noise_csds = [ ] for freq_bin , win_length , n_fft in zip ( freq_bins , win_lengths , n_ffts ) : noise_csd = compute_epochs_csd ( epochs_noise , mode = '' , fmin = freq_bin [ ] , fmax = freq_bin [ ] , fsum = True , tmin = - win_length , tmax = , n_fft = n_fft ) noise_csds . append ( noise_csd ) stcs = tf_dics ( epochs , forward , noise_csds , tmin , tmax , tstep , win_lengths , freq_bins = freq_bins , subtract_evoked = subtract_evoked , n_ffts = n_ffts , reg = , label = label ) plot_source_spectrogram ( stcs , freq_bins , tmin = tmin_plot , tmax = tmax_plot , ", "answer": "source_index = None , colorbar = True ) "}, {"prompt": " import logging import os import sys logging . basicConfig ( level = logging . ERROR ) top_dir = os . path . abspath ( os . path . join ( os . path . dirname ( __file__ ) , os . pardir , os . pardir ) ) sys . path . insert ( , top_dir ) import taskflow . engines from taskflow . patterns import graph_flow as gf from taskflow import task import example_utils as eu class CompileTask ( task . Task ) : \"\"\"\"\"\" default_provides = '' def execute ( self , source_filename ) : object_filename = '' % os . path . splitext ( source_filename ) [ ] print ( '' % ( source_filename , object_filename ) ) return object_filename class LinkTask ( task . Task ) : \"\"\"\"\"\" default_provides = '' def __init__ ( self , executable_path , * args , ** kwargs ) : super ( LinkTask , self ) . __init__ ( * args , ** kwargs ) self . _executable_path = executable_path def execute ( self , ** kwargs ) : object_filenames = list ( kwargs . values ( ) ) print ( '' % ( self . _executable_path , '' . join ( object_filenames ) ) ) return self . _executable_path class BuildDocsTask ( task . Task ) : \"\"\"\"\"\" default_provides = '' def execute ( self , ** kwargs ) : for source_filename in kwargs . values ( ) : print ( \"\" % source_filename ) return '' def make_flow_and_store ( source_files , executable_only = False ) : flow = gf . TargetedFlow ( '' ) object_targets = [ ] store = { } for source in source_files : source_stored = '' % source object_stored = '' % source store [ source_stored ] = source object_targets . append ( object_stored ) flow . add ( CompileTask ( name = '' % source , rebind = { '' : source_stored } , provides = object_stored ) ) flow . add ( BuildDocsTask ( requires = list ( store . keys ( ) ) ) ) object_targets . append ( '' ) link_task = LinkTask ( '' , requires = object_targets ) flow . add ( link_task ) if executable_only : flow . set_target ( link_task ) return flow , store if __name__ == \"\" : SOURCE_FILES = [ '' , '' , '' ] eu . print_wrapped ( '' ) flow , store = make_flow_and_store ( SOURCE_FILES ) ", "answer": "taskflow . engines . run ( flow , store = store )"}, {"prompt": " from socket import _GLOBAL_DEFAULT_TIMEOUT import time ", "answer": "from . . exceptions import TimeoutStateError"}, {"prompt": " \"\"\"\"\"\" from __future__ import division , absolute_import , print_function import sys import re import time import textwrap import subprocess class Benchmark ( object ) : \"\"\"\"\"\" goal_time = def run_monitored ( code ) : \"\"\"\"\"\" if not sys . platform . startswith ( '' ) : raise RuntimeError ( \"\" ) code = textwrap . dedent ( code ) process = subprocess . Popen ( [ sys . executable , '' , code ] ) peak_memusage = - start = time . time ( ) while True : ret = process . poll ( ) if ret is not None : break with open ( '' % process . pid , '' ) as f : procdata = f . read ( ) m = re . search ( '' , procdata , re . S | re . I ) if m is not None : memusage = float ( m . group ( ) ) * peak_memusage = max ( memusage , peak_memusage ) time . sleep ( ) process . wait ( ) duration = time . time ( ) - start if process . returncode != : raise AssertionError ( \"\" % code ) return duration , peak_memusage def get_mem_info ( ) : \"\"\"\"\"\" if not sys . platform . startswith ( '' ) : raise RuntimeError ( \"\" ) ", "answer": "info = { }"}, {"prompt": " import sublime import os import re import glob from . ml_options import MlOptions from . roxy_options import RoxyOptions SETTINGS_FILE = \"\" class MlSettings : _stored_search_paths = None _search_paths = None _sublime_options = None @ staticmethod def merge_dicts ( dict1 , dict2 ) : for key in dict2 : value = dict2 [ key ] if ( ( key in dict1 ) and isinstance ( value , dict ) ) : MlSettings . merge_dicts ( dict1 [ key ] , value ) else : dict1 [ key ] = value @ staticmethod def settings ( ) : if ( not MlSettings . _sublime_options ) : default_file = os . path . join ( \"\" , \"\" , SETTINGS_FILE ) user_file = os . path . join ( sublime . packages_path ( ) , \"\" , SETTINGS_FILE ) default_options = MlOptions ( default_file ) MlSettings . _sublime_options = default_options . options . copy ( ) if ( os . path . exists ( user_file ) ) : user_options = MlOptions ( user_file ) MlSettings . merge_dicts ( MlSettings . _sublime_options , user_options . options ) return MlSettings . _sublime_options def write_settings_sub_pref ( self , key , sub_key , value ) : user_file = os . path . join ( sublime . packages_path ( ) , \"\" , SETTINGS_FILE ) user_options = MlOptions ( user_file ) user_options . set_sub_pref ( key , sub_key , value ) def __init__ ( self ) : self . _roxy_options = None self . _proj_options = None def get_search_paths ( self ) : stored_search_paths = self . get_xcc_pref ( \"\" ) if ( not stored_search_paths ) : return None if ( not isinstance ( stored_search_paths , list ) ) : stored_search_paths = [ stored_search_paths ] if ( stored_search_paths != MlSettings . _stored_search_paths ) : MlSettings . _stored_search_paths = stored_search_paths resolved_search_paths = [ ] for search_path in stored_search_paths : if os . path . exists ( search_path ) : resolved_search_paths . append ( search_path ) else : current_options_file = self . get_current_options_file ( ) if ( re . match ( SETTINGS_FILE , current_options_file ) == None ) : root_folder = os . path . dirname ( current_options_file ) for found_path in glob . glob ( os . path . join ( root_folder , search_path ) ) : resolved_search_paths . append ( found_path ) MlSettings . _search_paths = resolved_search_paths return MlSettings . _search_paths def projectOptions ( self ) : if not self . _proj_options : self . _proj_options = MlOptions ( ) return self . _proj_options def roxyOptions ( self ) : if not self . _roxy_options : self . _roxy_options = RoxyOptions ( self . roxy_env ( ) ) return self . _roxy_options def roxy_env ( self ) : return MlSettings . settings ( ) . get ( \"\" ) . get ( \"\" ) or \"\" def use_roxy ( self ) : return MlSettings . settings ( ) . get ( \"\" ) . get ( \"\" ) == True def get_pref ( self , key ) : if self . projectOptions ( ) . has_key ( key ) : return self . projectOptions ( ) . get ( key ) elif ( self . use_roxy ( ) == True and self . roxyOptions ( ) . has_key ( key ) ) : return self . roxyOptions ( ) . get ( key ) return self . settings ( ) . get ( key ) def get_sub_pref ( self , key , sub_key ) : if self . projectOptions ( ) . has_subkey ( key , sub_key ) : return self . projectOptions ( ) . get_sub_pref ( key , sub_key ) if ( self . use_roxy ( ) == True and self . roxyOptions ( ) . has_key ( sub_key ) ) : return self . roxyOptions ( ) . get ( sub_key ) return self . settings ( ) . get ( key ) . get ( sub_key ) def set_sub_pref ( self , key , sub_key , value ) : if self . projectOptions ( ) . has_key ( key ) : self . projectOptions ( ) . set_sub_pref ( key , sub_key , value ) elif ( self . use_roxy ( ) == True and self . roxyOptions ( ) . has_key ( key ) ) : ", "answer": "return"}, {"prompt": " from __future__ import absolute_import , unicode_literals from builtins import list import pytest from pytest_nodev import blacklists from pytest_nodev import collect def test_import_coverage ( ) : \"\"\"\"\"\" from imp import reload reload ( blacklists ) reload ( collect ) def test_collect_stdlib_distributions ( ) : stdlib_distributions = list ( collect . collect_stdlib_distributions ( ) ) assert len ( stdlib_distributions ) == _ , module_names = stdlib_distributions [ ] assert len ( module_names ) > def test_collect_installed_distributions ( ) : installed_distributions = list ( collect . collect_installed_distributions ( ) ) assert len ( installed_distributions ) > for spec , module_names in installed_distributions : if spec . startswith ( '' ) : break assert module_names == [ '' ] def test_collect_distributions ( ) : distributions = list ( collect . collect_distributions ( [ '' ] ) ) assert len ( distributions ) == _ , module_names = distributions [ ] assert len ( module_names ) == assert len ( list ( collect . collect_distributions ( [ '' ] ) ) ) == def test_import_module ( ) : assert collect . import_module ( '' ) with pytest . raises ( ImportError ) : collect . import_module ( '' , module_blacklist_pattern = '' ) with pytest . raises ( ImportError ) : collect . import_module ( '' ) def test_import_distributions ( ) : distributions = [ ( '' , [ '' ] ) ] module_names = list ( collect . import_distributions ( distributions ) ) assert module_names == [ '' ] distributions = [ ( '' , [ '' ] ) ] module_names = list ( collect . import_distributions ( distributions ) ) assert module_names == [ ] def test_generate_module_objects ( ) : expected_item = ( '' , collect . generate_module_objects ) assert expected_item in list ( collect . generate_module_objects ( collect ) ) def test_generate_objects_from_modules ( ) : import re modules = { '' : collect , '' : re } ", "answer": "include_patterns = [ '' ]"}, {"prompt": " from nailgun . objects . serializers . base import BasicSerializer class PluginLinkSerializer ( BasicSerializer ) : fields = ( \"\" , \"\" , \"\" , \"\" , ", "answer": "\"\""}, {"prompt": " from _simple_example import ffi ", "answer": "lib = ffi . dlopen ( None )"}, {"prompt": " __author__ = '' from tornado import options from viewfinder . backend . www . test import service_base_test from viewfinder . backend . www . tools import merge_tool class MergeToolTestCase ( service_base_test . ServiceBaseTestCase ) : \"\"\"\"\"\" def testMerge ( self ) : self . _validate = False self . _RunAsync ( merge_tool . Merge , ", "answer": "self . _client ,"}, {"prompt": " import mock from oslo_utils import uuidutils from nova import objects from nova . objects import instance_mapping from nova . tests . unit . objects import test_cell_mapping from nova . tests . unit . objects import test_objects def get_db_mapping ( ** updates ) : db_mapping = { '' : , '' : uuidutils . generate_uuid ( ) , '' : None , '' : '' , '' : None , '' : None , } db_mapping [ \"\" ] = test_cell_mapping . get_db_mapping ( id = ) ", "answer": "db_mapping [ '' ] = db_mapping [ \"\" ] [ \"\" ]"}, {"prompt": " from __future__ import absolute_import , unicode_literals import hashlib from django import template from django . utils . six . moves . urllib . parse import urlencode register = template . Library ( ) class GravatarUrlNode ( template . Node ) : def __init__ ( self , email , size = ) : self . email = template . Variable ( email ) self . size = size def render ( self , context ) : try : email = self . email . resolve ( context ) except template . VariableDoesNotExist : ", "answer": "return ''"}, {"prompt": " \"\"\"\"\"\" import numpy as np from sklearn . externals . joblib import Memory from . . import _utils from . . _utils import logger , CacheMixin from . . _utils . niimg import _get_data_dtype from . . _utils . class_inspect import get_params from . . _utils . niimg_conversions import _check_same_fov from . . import image from . base_masker import filter_and_extract , BaseMasker class _ExtractionFunctor ( object ) : func_name = '' def __init__ ( self , _resampled_maps_img_ , _resampled_mask_img_ ) : self . _resampled_maps_img_ = _resampled_maps_img_ self . _resampled_mask_img_ = _resampled_mask_img_ def __call__ ( self , imgs ) : from . . regions import signal_extraction return signal_extraction . img_to_signals_maps ( imgs , self . _resampled_maps_img_ , mask_img = self . _resampled_mask_img_ ) class NiftiMapsMasker ( BaseMasker , CacheMixin ) : \"\"\"\"\"\" def __init__ ( self , maps_img , mask_img = None , allow_overlap = True , smoothing_fwhm = None , standardize = False , detrend = False , low_pass = None , high_pass = None , t_r = None , resampling_target = \"\" , memory = Memory ( cachedir = None , verbose = ) , memory_level = , verbose = ) : self . maps_img = maps_img self . mask_img = mask_img self . allow_overlap = allow_overlap self . smoothing_fwhm = smoothing_fwhm self . standardize = standardize self . detrend = detrend self . low_pass = low_pass self . high_pass = high_pass self . t_r = t_r self . resampling_target = resampling_target self . memory = memory self . memory_level = memory_level self . verbose = verbose if resampling_target not in ( \"\" , \"\" , \"\" , None ) : raise ValueError ( \"\" \"\" + str ( resampling_target ) ) if self . mask_img is None and resampling_target == \"\" : raise ValueError ( \"\" \"\" \"\" ) def fit ( self , X = None , y = None ) : \"\"\"\"\"\" logger . log ( \"\" % _utils . _repr_niimgs ( self . maps_img ) [ : ] , verbose = self . verbose ) self . maps_img_ = _utils . check_niimg_4d ( self . maps_img ) if self . mask_img is not None : logger . log ( \"\" % _utils . _repr_niimgs ( self . mask_img ) [ : ] , verbose = self . verbose ) self . mask_img_ = _utils . check_niimg_3d ( self . mask_img ) else : self . mask_img_ = None if self . resampling_target is None and self . mask_img_ is not None : _check_same_fov ( mask = self . mask_img_ , maps = self . maps_img_ , raise_error = True ) elif self . resampling_target == \"\" and self . mask_img_ is not None : if self . verbose > : print ( \"\" ) self . maps_img_ = image . resample_img ( self . maps_img_ , target_affine = self . mask_img_ . get_affine ( ) , target_shape = self . mask_img_ . shape , interpolation = \"\" , copy = True ) elif self . resampling_target == \"\" and self . mask_img_ is not None : if self . verbose > : print ( \"\" ) self . mask_img_ = image . resample_img ( self . mask_img_ , target_affine = self . maps_img_ . get_affine ( ) , target_shape = self . maps_img_ . shape [ : ] , interpolation = \"\" , copy = True ) return self def _check_fitted ( self ) : if not hasattr ( self , \"\" ) : raise ValueError ( '' '' % self . __class__ . __name__ ) def fit_transform ( self , imgs , confounds = None ) : \"\"\"\"\"\" return self . fit ( ) . transform ( imgs , confounds = confounds ) def transform_single_imgs ( self , imgs , confounds = None ) : \"\"\"\"\"\" if not hasattr ( self , '' ) : self . _resampled_maps_img_ = self . maps_img_ ", "answer": "if not hasattr ( self , '' ) :"}, {"prompt": " \"\"\"\"\"\" from pwn import * shell = ssh ( host = '' , user = '' , password = '' ) log . info ( \"\" % shell . whoami ( ) ) log . info ( \"\" % shell . pwd ( ) ) tube = shell . run ( '' ) tube . send ( \"\" ) tube . shutdown ( \"\" ) print tube . recvall ( ) shell . set_working_directory ( ) log . info ( \"\" % shell . pwd ( ) ) ", "answer": "shell . upload_data ( \"\"\"\"\"\" , '' )"}, {"prompt": " '''''' import os , io , time , json , socket , logging , zlib , datetime from arelle . ModelDtsObject import ModelConcept , ModelResource , ModelRelationship from arelle . ModelInstanceObject import ModelFact from arelle . ModelDocument import Type from arelle import XbrlConst , XmlUtil , UrlUtil import urllib . request from urllib . error import HTTPError , URLError from lxml import etree TRACERDFFILE = None RDFTURTLEFILE_HOSTNAME = \"\" RDFXMLFILE_HOSTNAME = \"\" def insertIntoDB ( modelXbrl , user = None , password = None , host = None , port = None , database = None , timeout = None , product = None , rssItem = None , ** kwargs ) : rdfdb = None try : rdfdb = XbrlSemanticRdfDatabaseConnection ( modelXbrl , user , password , host , port , database , timeout ) rdfdb . insertXbrl ( rssItem = rssItem ) rdfdb . close ( ) except Exception as ex : if rdfdb is not None : try : rdfdb . close ( rollback = True ) except Exception as ex2 : pass raise def isDBPort ( host , port , db , timeout = ) : if host in ( RDFTURTLEFILE_HOSTNAME , RDFXMLFILE_HOSTNAME ) : return True t = while t < timeout : try : conn = urllib . request . urlopen ( \"\" . format ( host , port or '' , db ) ) return True except HTTPError : return False except URLError : return False except socket . timeout : t = t + return False Namespace = URIRef = Literal = Graph = L = XSD = RDF = RDFS = None DEFAULT_GRAPH_CLASS = None XML = XBRL = XBRLI = LINK = QName = Filing = DTS = Aspect = AspectType = None DocumentTypes = RoleType = ArcRoleType = Relationship = ArcRoleCycles = None DataPoint = Context = Period = Unit = None SEC = None def initRdflibNamespaces ( ) : global Namespace , URIRef , Literal , Graph , L , XSD , RDF , RDFS , DEFAULT_GRAPH_CLASS if Namespace is None : from rdflib import Namespace , URIRef , Literal , Graph from rdflib import Literal as L from rdflib . namespace import XSD , RDF , RDFS DEFAULT_GRAPH_CLASS = Graph global XML , XBRL , XBRLI , LINK , QName , Filing , DTS , Aspect , AspectType , DocumentTypes , RoleType , ArcRoleType , Relationship , ArcRoleCycles , DataPoint , Context , Period , Unit , SEC if XML is None : XML = Namespace ( \"\" ) XBRL = Namespace ( \"\" ) XBRLI = Namespace ( \"\" ) LINK = Namespace ( \"\" ) QName = Namespace ( \"\" ) Filing = Namespace ( \"\" ) DTS = Namespace ( \"\" ) DocumentTypes = { Type . INSTANCE : XBRL . Instance , Type . INLINEXBRL : XBRL . InlineHtml , Type . SCHEMA : XBRL . Schema , Type . LINKBASE : XBRL . Linkbase , Type . UnknownXML : XML . Document } Aspect = Namespace ( \"\" ) AspectType = Namespace ( \"\" ) RoleType = Namespace ( \"\" ) ArcRoleType = Namespace ( \"\" ) Relationship = Namespace ( \"\" ) ArcRoleCycles = Namespace ( \"\" ) DataPoint = Namespace ( \"\" ) Context = Namespace ( \"\" ) Period = Namespace ( \"\" ) Unit = Namespace ( \"\" ) SEC = Namespace ( \"\" ) def modelObjectDocumentUri ( modelObject ) : return URIRef ( UrlUtil . ensureUrl ( modelObject . modelDocument . uri ) ) def modelObjectUri ( modelObject ) : return URIRef ( '' . join ( ( modelObjectDocumentUri ( modelObject ) , XmlUtil . elementFragmentIdentifier ( modelObject ) ) ) ) def qnameUri ( qname , sep = '' ) : return URIRef ( sep . join ( ( qname . namespaceURI , qname . localName ) ) ) def qnamePrefix_Name ( qname , sep = '' ) : prefix = { XbrlConst . xsd : '' , XbrlConst . xml : '' , XbrlConst . xbrli : '' , XbrlConst . link : '' , XbrlConst . gen : '' , XbrlConst . xlink : '' } . get ( qname . namespaceURI , qname . prefix ) return L ( sep . join ( ( prefix , qname . localName ) ) ) def modelObjectQnameUri ( modelObject , sep = '' ) : return qnameUri ( modelObject . qname , sep ) class XRDBException ( Exception ) : def __init__ ( self , code , message , ** kwargs ) : self . code = code self . message = message self . kwargs = kwargs self . args = ( self . __repr__ ( ) , ) def __repr__ ( self ) : return _ ( '' ) . format ( self . code , self . message % self . kwargs ) class XbrlSemanticRdfDatabaseConnection ( ) : def __init__ ( self , modelXbrl , user , password , host , port , database , timeout ) : try : initRdflibNamespaces ( ) except ImportError : raise XRDBException ( \"\" , _ ( \"\" ) ) self . modelXbrl = modelXbrl self . disclosureSystem = modelXbrl . modelManager . disclosureSystem self . isRdfTurtleFile = host == RDFTURTLEFILE_HOSTNAME self . isRdfXmlFile = host == RDFXMLFILE_HOSTNAME if self . isRdfTurtleFile or self . isRdfXmlFile : self . turtleFile = database else : connectionUrl = \"\" . format ( host , port or '' ) self . url = connectionUrl if database : self . url += '' + database auth_handler = urllib . request . HTTPBasicAuthHandler ( ) if user : auth_handler . add_password ( realm = None , uri = connectionUrl , user = user , passwd = password ) self . conn = urllib . request . build_opener ( auth_handler ) self . timeout = timeout or self . verticePropTypes = { } def close ( self , rollback = False ) : try : if not ( self . isRdfTurtleFile or self . isRdfXmlFile ) : self . conn . close ( ) self . __dict__ . clear ( ) except Exception as ex : self . __dict__ . clear ( ) raise @ property def isClosed ( self ) : return not bool ( self . __dict__ ) def showStatus ( self , msg , clearAfter = None ) : self . modelXbrl . modelManager . showStatus ( msg , clearAfter ) def initializeGraph ( self , graph = None ) : g = graph or DEFAULT_GRAPH_CLASS ( ) g . bind ( \"\" , XML ) g . bind ( \"\" , XBRL ) g . bind ( \"\" , XBRLI ) g . bind ( \"\" , LINK ) g . bind ( \"\" , QName ) g . bind ( \"\" , Filing ) g . bind ( \"\" , DTS ) g . bind ( \"\" , Aspect ) g . bind ( \"\" , AspectType ) g . bind ( \"\" , RoleType ) g . bind ( \"\" , ArcRoleType ) g . bind ( \"\" , ArcRoleCycles ) g . bind ( \"\" , Relationship ) g . bind ( \"\" , DataPoint ) g . bind ( \"\" , Context ) g . bind ( \"\" , Period ) g . bind ( \"\" , Unit ) g . bind ( \"\" , SEC ) return g def execute ( self , activity , graph = None , query = None ) : if graph is not None : headers = { '' : '' , '' : '' , '' : \"\" } data = graph . serialize ( format = '' if self . isRdfXmlFile else '' , encoding = '' ) elif query is not None : headers = { '' : '' , '' : '' } data = ( \"\" + query ) . encode ( '' ) else : return None if TRACERDFFILE : with io . open ( TRACERDFFILE , \"\" ) as fh : fh . write ( b\"\" ) fh . write ( data ) if ( self . isRdfTurtleFile or self . isRdfXmlFile ) and data is not None : with io . open ( self . turtleFile , \"\" ) as fh : fh . write ( data ) return None if graph is not None or query is not None : url = self . url + \"\" request = urllib . request . Request ( url , data = data , headers = headers ) try : with self . conn . open ( request , timeout = self . timeout ) as fp : results = fp . read ( ) . decode ( '' ) try : results = json . loads ( results ) except ValueError : pass except HTTPError as err : results = err . fp . read ( ) . decode ( '' ) if TRACERDFFILE : with io . open ( TRACERDFFILE , \"\" , encoding = '' ) as fh : fh . write ( \"\" . format ( str ( results ) ) ) if isinstance ( results , str ) and query is not None : parser = etree . HTMLParser ( ) htmlDoc = etree . parse ( io . StringIO ( results ) , parser ) body = htmlDoc . find ( \"\" ) if body is not None : error = \"\" . join ( text for text in body . itertext ( ) ) else : error = results raise XRDBException ( \"\" , _ ( \"\" ) , activity = activity , error = error ) return results def commit ( self , graph ) : self . execute ( \"\" , graph = graph ) def loadGraphRootVertices ( self ) : self . showStatus ( \"\" ) pass def getDBsize ( self ) : self . showStatus ( \"\" ) return def insertXbrl ( self , rssItem ) : try : from arelle import ValidateXbrlDimensions ValidateXbrlDimensions . loadDimensionDefaults ( self . modelXbrl ) startedAt = time . time ( ) self . identifyPreexistingDocuments ( ) g = self . initializeGraph ( ) self . insertSchema ( g ) self . insertFiling ( rssItem , g ) self . insertDocuments ( g ) self . insertDataDictionary ( g ) self . modelXbrl . profileStat ( _ ( \"\" ) , time . time ( ) - startedAt ) startedAt = time . time ( ) self . insertDataPoints ( g ) self . modelXbrl . profileStat ( _ ( \"\" ) , time . time ( ) - startedAt ) startedAt = time . time ( ) self . insertRelationshipSets ( g ) self . modelXbrl . profileStat ( _ ( \"\" ) , time . time ( ) - startedAt ) self . insertValidationResults ( g ) self . modelXbrl . profileStat ( _ ( \"\" ) , time . time ( ) - startedAt ) self . showStatus ( \"\" ) self . commit ( g ) self . modelXbrl . profileStat ( _ ( \"\" ) , time . time ( ) - startedAt ) self . showStatus ( \"\" , clearAfter = ) ", "answer": "except Exception as ex :"}, {"prompt": " from . config import config ", "answer": "__version__ = ''"}, {"prompt": " from __future__ import absolute_import import io from django import http from datatap . datataps import StreamDataTap from hyperadmin . mediatypes . common import MediaType class DataTap ( MediaType ) : def __init__ ( self , api_request , datatap_class , ** kwargs ) : self . datatap_class = datatap_class super ( DataTap , self ) . __init__ ( api_request , ** kwargs ) def get_content ( self , form_link , state ) : instream = state . get_resource_items ( ) datatap = state . endpoint . get_datatap ( instream = instream ) serialized_dt = self . datatap_class ( instream = datatap ) payload = io . BytesIO ( ) serialized_dt . send ( payload ) return payload . getvalue ( ) def serialize ( self , content_type , link , state ) : if self . detect_redirect ( link ) : return self . handle_redirect ( link , content_type ) content = self . get_content ( link , state ) response = http . HttpResponse ( content , content_type ) return response def get_datatap ( self , request ) : if hasattr ( request , '' ) : payload = request . body else : payload = request . raw_post_data return self . datatap_class ( StreamDataTap ( io . BytesIO ( payload ) ) ) def deserialize ( self , request ) : datatap = self . get_datatap ( request ) data = list ( datatap ) [ ] ", "answer": "return { '' : data ,"}, {"prompt": " import multiprocessing from six . moves import range from . base import ProxyDataFlow from . . utils . concurrency import ensure_proc_terminate from . . utils import logger __all__ = [ '' ] class PrefetchProcess ( multiprocessing . Process ) : def __init__ ( self , ds , queue ) : \"\"\"\"\"\" super ( PrefetchProcess , self ) . __init__ ( ) self . ds = ds self . queue = queue def run ( self ) : self . ds . reset_state ( ) while True : for dp in self . ds . get_data ( ) : self . queue . put ( dp ) class PrefetchData ( ProxyDataFlow ) : \"\"\"\"\"\" def __init__ ( self , ds , nr_prefetch , nr_proc = ) : \"\"\"\"\"\" super ( PrefetchData , self ) . __init__ ( ds ) self . _size = self . size ( ) self . nr_proc = nr_proc self . nr_prefetch = nr_prefetch ", "answer": "self . queue = multiprocessing . Queue ( self . nr_prefetch )"}, {"prompt": " from datetime import date , datetime , timedelta from pandas . compat import range from pandas import compat import numpy as np from pandas . tseries . tools import to_datetime , normalize_date from pandas . core . common import ABCSeries , ABCDatetimeIndex from dateutil . relativedelta import relativedelta , weekday from dateutil . easter import easter import pandas . tslib as tslib from pandas . tslib import Timestamp , OutOfBoundsDatetime , Timedelta import functools import operator __all__ = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ] def as_timestamp ( obj ) : if isinstance ( obj , Timestamp ) : return obj try : return Timestamp ( obj ) except ( OutOfBoundsDatetime ) : pass return obj def as_datetime ( obj ) : f = getattr ( obj , '' , None ) if f is not None : obj = f ( ) return obj def apply_wraps ( func ) : @ functools . wraps ( func ) def wrapper ( self , other ) : if other is tslib . NaT : return tslib . NaT elif isinstance ( other , ( timedelta , Tick , DateOffset ) ) : return func ( self , other ) elif isinstance ( other , ( np . datetime64 , datetime , date ) ) : other = as_timestamp ( other ) tz = getattr ( other , '' , None ) nano = getattr ( other , '' , ) try : if self . _adjust_dst and isinstance ( other , Timestamp ) : other = other . tz_localize ( None ) result = func ( self , other ) if self . _adjust_dst : result = tslib . _localize_pydatetime ( result , tz ) result = Timestamp ( result ) if self . normalize : result = result . normalize ( ) if not self . normalize and nano != : if not isinstance ( self , Nano ) and result . nanosecond != nano : if result . tz is not None : value = tslib . tz_convert_single ( result . value , '' , result . tz ) else : value = result . value result = Timestamp ( value + nano ) if tz is not None and result . tzinfo is None : result = tslib . _localize_pydatetime ( result , tz ) except OutOfBoundsDatetime : result = func ( self , as_datetime ( other ) ) if self . normalize : result = normalize_date ( result ) if tz is not None and result . tzinfo is None : result = tslib . _localize_pydatetime ( result , tz ) return result return wrapper def apply_index_wraps ( func ) : @ functools . wraps ( func ) def wrapper ( self , other ) : result = func ( self , other ) if self . normalize : result = result . to_period ( '' ) . to_timestamp ( ) return result return wrapper def _is_normalized ( dt ) : if ( dt . hour != or dt . minute != or dt . second != or dt . microsecond != or getattr ( dt , '' , ) != ) : return False return True class ApplyTypeError ( TypeError ) : pass class CacheableOffset ( object ) : _cacheable = True class DateOffset ( object ) : \"\"\"\"\"\" _cacheable = False _normalize_cache = True _kwds_use_relativedelta = ( '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ) _use_relativedelta = False _adjust_dst = False normalize = False def __init__ ( self , n = , normalize = False , ** kwds ) : self . n = int ( n ) self . normalize = normalize self . kwds = kwds self . _offset , self . _use_relativedelta = self . _determine_offset ( ) def _determine_offset ( self ) : kwds_no_nanos = dict ( ( k , v ) for k , v in self . kwds . items ( ) if k not in ( '' , '' ) ) use_relativedelta = False if len ( kwds_no_nanos ) > : if any ( k in self . _kwds_use_relativedelta for k in kwds_no_nanos ) : use_relativedelta = True offset = relativedelta ( ** kwds_no_nanos ) else : offset = timedelta ( ** kwds_no_nanos ) else : offset = timedelta ( ) return offset , use_relativedelta @ apply_wraps def apply ( self , other ) : if self . _use_relativedelta : other = as_datetime ( other ) if len ( self . kwds ) > : tzinfo = getattr ( other , '' , None ) if tzinfo is not None and self . _use_relativedelta : other = other . replace ( tzinfo = None ) if self . n > : for i in range ( self . n ) : other = other + self . _offset else : for i in range ( - self . n ) : other = other - self . _offset if tzinfo is not None and self . _use_relativedelta : other = tslib . _localize_pydatetime ( other , tzinfo ) return as_timestamp ( other ) else : return other + timedelta ( self . n ) @ apply_index_wraps def apply_index ( self , i ) : \"\"\"\"\"\" if not type ( self ) is DateOffset : raise NotImplementedError ( \"\" \"\" \"\" % ( self . __class__ . __name__ , ) ) relativedelta_fast = set ( [ '' , '' , '' , '' , '' , '' , '' , '' ] ) if ( self . _use_relativedelta and set ( self . kwds ) . issubset ( relativedelta_fast ) ) : months = ( ( self . kwds . get ( '' , ) * + self . kwds . get ( '' , ) ) * self . n ) if months : shifted = tslib . shift_months ( i . asi8 , months ) i = i . _shallow_copy ( shifted ) weeks = ( self . kwds . get ( '' , ) ) * self . n if weeks : i = ( i . to_period ( '' ) + weeks ) . to_timestamp ( ) + i . to_perioddelta ( '' ) timedelta_kwds = dict ( ( k , v ) for k , v in self . kwds . items ( ) if k in [ '' , '' , '' , '' , '' ] ) if timedelta_kwds : delta = Timedelta ( ** timedelta_kwds ) i = i + ( self . n * delta ) return i elif not self . _use_relativedelta and hasattr ( self , '' ) : return i + ( self . _offset * self . n ) else : raise NotImplementedError ( \"\" \"\" \"\" % ( set ( self . kwds ) - relativedelta_fast ) , ) def isAnchored ( self ) : return ( self . n == ) def copy ( self ) : return self . __class__ ( self . n , normalize = self . normalize , ** self . kwds ) def _should_cache ( self ) : return self . isAnchored ( ) and self . _cacheable def _params ( self ) : all_paras = dict ( list ( vars ( self ) . items ( ) ) + list ( self . kwds . items ( ) ) ) if '' in all_paras and not all_paras [ '' ] : all_paras . pop ( '' ) exclude = [ '' , '' , '' , '' ] attrs = [ ( k , v ) for k , v in all_paras . items ( ) if ( k not in exclude ) and ( k [ ] != '' ) ] attrs = sorted ( set ( attrs ) ) params = tuple ( [ str ( self . __class__ ) ] + attrs ) return params def __repr__ ( self ) : className = getattr ( self , '' , type ( self ) . __name__ ) exclude = set ( [ '' , '' , '' ] ) attrs = [ ] for attr in sorted ( self . __dict__ ) : if ( ( attr == '' and len ( self . kwds ) == ) or attr . startswith ( '' ) ) : continue elif attr == '' : kwds_new = { } for key in self . kwds : if not hasattr ( self , key ) : kwds_new [ key ] = self . kwds [ key ] if len ( kwds_new ) > : attrs . append ( '' . join ( ( attr , repr ( kwds_new ) ) ) ) else : if attr not in exclude : attrs . append ( '' . join ( ( attr , repr ( getattr ( self , attr ) ) ) ) ) if abs ( self . n ) != : plural = '' else : plural = '' n_str = \"\" if self . n != : n_str = \"\" % self . n out = '' % n_str + className + plural if attrs : out += '' + '' . join ( attrs ) out += '>' return out @ property def name ( self ) : return self . rule_code def __eq__ ( self , other ) : if other is None : return False if isinstance ( other , compat . string_types ) : from pandas . tseries . frequencies import to_offset other = to_offset ( other ) if not isinstance ( other , DateOffset ) : return False return self . _params ( ) == other . _params ( ) def __ne__ ( self , other ) : return not self == other def __hash__ ( self ) : return hash ( self . _params ( ) ) def __call__ ( self , other ) : return self . apply ( other ) def __add__ ( self , other ) : if isinstance ( other , ( ABCDatetimeIndex , ABCSeries ) ) : return other + self try : return self . apply ( other ) except ApplyTypeError : return NotImplemented def __radd__ ( self , other ) : return self . __add__ ( other ) def __sub__ ( self , other ) : if isinstance ( other , datetime ) : raise TypeError ( '' ) elif type ( other ) == type ( self ) : return self . __class__ ( self . n - other . n , normalize = self . normalize , ** self . kwds ) else : return NotImplemented def __rsub__ ( self , other ) : if isinstance ( other , ( ABCDatetimeIndex , ABCSeries ) ) : return other - self return self . __class__ ( - self . n , normalize = self . normalize , ** self . kwds ) + other def __mul__ ( self , someInt ) : return self . __class__ ( n = someInt * self . n , normalize = self . normalize , ** self . kwds ) def __rmul__ ( self , someInt ) : return self . __mul__ ( someInt ) def __neg__ ( self ) : return self . __class__ ( - self . n , normalize = self . normalize , ** self . kwds ) def rollback ( self , dt ) : \"\"\"\"\"\" dt = as_timestamp ( dt ) if not self . onOffset ( dt ) : dt = dt - self . __class__ ( , normalize = self . normalize , ** self . kwds ) return dt def rollforward ( self , dt ) : \"\"\"\"\"\" dt = as_timestamp ( dt ) if not self . onOffset ( dt ) : dt = dt + self . __class__ ( , normalize = self . normalize , ** self . kwds ) return dt def onOffset ( self , dt ) : if self . normalize and not _is_normalized ( dt ) : return False if type ( self ) == DateOffset or isinstance ( self , Tick ) : return True a = dt b = ( ( dt + self ) - self ) return a == b def _beg_apply_index ( self , i , freq ) : \"\"\"\"\"\" off = i . to_perioddelta ( '' ) from pandas . tseries . frequencies import get_freq_code base , mult = get_freq_code ( freq ) base_period = i . to_period ( base ) if self . n <= : roll = np . where ( base_period . to_timestamp ( ) == i - off , self . n , self . n + ) else : roll = self . n base = ( base_period + roll ) . to_timestamp ( ) return base + off def _end_apply_index ( self , i , freq ) : \"\"\"\"\"\" off = i . to_perioddelta ( '' ) from pandas . tseries . frequencies import get_freq_code base , mult = get_freq_code ( freq ) base_period = i . to_period ( base ) if self . n > : roll = np . where ( base_period . to_timestamp ( how = '' ) == i - off , self . n , self . n - ) else : roll = self . n base = ( base_period + roll ) . to_timestamp ( how = '' ) return base + off @ property def _prefix ( self ) : raise NotImplementedError ( '' ) @ property def rule_code ( self ) : return self . _prefix @ property def freqstr ( self ) : try : code = self . rule_code except NotImplementedError : return repr ( self ) if self . n != : fstr = '' % ( self . n , code ) else : fstr = code return fstr @ property def nanos ( self ) : raise ValueError ( \"\" . format ( self ) ) class SingleConstructorOffset ( DateOffset ) : @ classmethod def _from_name ( cls , suffix = None ) : if suffix : raise ValueError ( \"\" % suffix ) return cls ( ) class BusinessMixin ( object ) : \"\"\"\"\"\" def __repr__ ( self ) : className = getattr ( self , '' , self . __class__ . __name__ ) if abs ( self . n ) != : plural = '' else : plural = '' n_str = \"\" if self . n != : n_str = \"\" % self . n out = '' % n_str + className + plural + self . _repr_attrs ( ) + '>' return out def _repr_attrs ( self ) : if self . offset : attrs = [ '' % repr ( self . offset ) ] else : attrs = None out = '' if attrs : out += '' + '' . join ( attrs ) return out class BusinessDay ( BusinessMixin , SingleConstructorOffset ) : \"\"\"\"\"\" _prefix = '' ", "answer": "_adjust_dst = True"}, {"prompt": " from __future__ import unicode_literals import mock import os import unittest from mkdocs import nav , legacy from mkdocs . exceptions import ConfigurationError from mkdocs . tests . base import dedent class SiteNavigationTests ( unittest . TestCase ) : def test_simple_toc ( self ) : pages = [ { '' : '' } , { '' : '' } ] expected = dedent ( \"\"\"\"\"\" ) site_navigation = nav . SiteNavigation ( pages ) self . assertEqual ( str ( site_navigation ) . strip ( ) , expected ) self . assertEqual ( len ( site_navigation . nav_items ) , ) self . assertEqual ( len ( site_navigation . pages ) , ) def test_empty_toc_item ( self ) : pages = [ '' , { '' : '' } ] expected = dedent ( \"\"\"\"\"\" ) site_navigation = nav . SiteNavigation ( pages ) self . assertEqual ( str ( site_navigation ) . strip ( ) , expected ) self . assertEqual ( len ( site_navigation . nav_items ) , ) self . assertEqual ( len ( site_navigation . pages ) , ) def test_indented_toc ( self ) : pages = [ { '' : '' } , { '' : [ { '' : '' } , { '' : '' } , { '' : '' } , ] } , { '' : [ { '' : '' } , { '' : '' } ] } ] expected = dedent ( \"\"\"\"\"\" ) site_navigation = nav . SiteNavigation ( pages ) self . assertEqual ( str ( site_navigation ) . strip ( ) , expected ) self . assertEqual ( len ( site_navigation . nav_items ) , ) self . assertEqual ( len ( site_navigation . pages ) , ) def test_nested_ungrouped ( self ) : pages = [ { '' : '' } , { '' : '' } , { '' : '' } , ] expected = dedent ( \"\"\"\"\"\" ) site_navigation = nav . SiteNavigation ( pages ) self . assertEqual ( str ( site_navigation ) . strip ( ) , expected ) self . assertEqual ( len ( site_navigation . nav_items ) , ) self . assertEqual ( len ( site_navigation . pages ) , ) def test_nested_ungrouped_no_titles ( self ) : pages = [ '' , '' , '' ] expected = dedent ( \"\"\"\"\"\" ) site_navigation = nav . SiteNavigation ( pages ) self . assertEqual ( str ( site_navigation ) . strip ( ) , expected ) self . assertEqual ( len ( site_navigation . nav_items ) , ) self . assertEqual ( len ( site_navigation . pages ) , ) @ mock . patch . object ( os . path , '' , '' ) def test_nested_ungrouped_no_titles_windows ( self ) : pages = [ '' , '' , '' , ] expected = dedent ( \"\"\"\"\"\" ) site_navigation = nav . SiteNavigation ( pages ) self . assertEqual ( str ( site_navigation ) . strip ( ) , expected ) self . assertEqual ( len ( site_navigation . nav_items ) , ) self . assertEqual ( len ( site_navigation . pages ) , ) def test_walk_simple_toc ( self ) : pages = [ { '' : '' } , { '' : '' } ] expected = [ dedent ( \"\"\"\"\"\" ) , dedent ( \"\"\"\"\"\" ) ] site_navigation = nav . SiteNavigation ( pages ) for index , page in enumerate ( site_navigation . walk_pages ( ) ) : self . assertEqual ( str ( site_navigation ) . strip ( ) , expected [ index ] ) def test_walk_empty_toc ( self ) : pages = [ '' , { '' : '' } ] expected = [ dedent ( \"\"\"\"\"\" ) , dedent ( \"\"\"\"\"\" ) ] site_navigation = nav . SiteNavigation ( pages ) for index , page in enumerate ( site_navigation . walk_pages ( ) ) : self . assertEqual ( str ( site_navigation ) . strip ( ) , expected [ index ] ) def test_walk_indented_toc ( self ) : pages = [ { '' : '' } , { '' : [ { '' : '' } , { '' : '' } , { '' : '' } , ] } , { '' : [ { '' : '' } , { '' : '' } ] } ] expected = [ dedent ( \"\"\"\"\"\" ) , dedent ( \"\"\"\"\"\" ) , dedent ( \"\"\"\"\"\" ) , ", "answer": "dedent ( \"\"\"\"\"\" ) ,"}, {"prompt": " import os ", "answer": "from kokki import Package , File , Service , Script"}, {"prompt": " from __future__ import absolute_import , unicode_literals from django . core . urlresolvers import reverse from django . test import TestCase from wagtail . tests . utils import WagtailTestUtils class TestStyleGuide ( TestCase , WagtailTestUtils ) : def setUp ( self ) : ", "answer": "self . login ( )"}, {"prompt": " \"\"\"\"\"\" from django . conf . urls . defaults import * import django . views . defaults from django . views . generic . base import RedirectView from codereview import feeds urlpatterns = patterns ( '' , ( r'' , '' ) , ( r'' , RedirectView . as_view ( url = '' ) ) , ( r'' , '' ) , ( r'' , '' ) , ( r'' , RedirectView . as_view ( url = '' ) ) , ( r'' , '' ) , ( r'' , '' ) , ( r'' , '' ) , ( r'' , '' ) , ( r'' , '' ) , ( r'' , '' ) , ( r'' , '' , { } , '' ) , ( r'' , '' ) , ( r'' , '' ) , ( r'' , '' ) , ( r'' , '' ) , ( r'' , '' ) , ( r'' , '' ) , ( r'' , '' ) , ( r'' , '' ) , ( r'' , '' ) , ( r'' , '' ) , ( r'' , '' ) , ( r'' , '' ) , ( r'' , '' ) , ( r'' , '' ) , ( r'' , django . views . defaults . page_not_found , { } , '' ) , ( r'' , '' ) , ( r'' , django . views . defaults . page_not_found , { } , '' ) , ( r'' , '' ) , ( r'' , '' ) , ( r'' , '' ) , ( r'' , '' ) , ( r'' , '' ) , ( r'' , '' ) , ( r'' , '' ) , ( r'' , '' ) , ( r'' , '' ) , ( r'' , '' ) , ( r'' , '' ) , ( r'' , '' ) , ( r'' , '' ) , ( r'' , '' ) , ( r'' , '' ) , ( r'' , '' ) , ", "answer": "( r'' , '' ) ,"}, {"prompt": " __all__ = [ \"\" , \"\" , \"\" ] import emacs , notemacs , vi ", "answer": "editingmodes = [ emacs . EmacsMode , notemacs . NotEmacsMode , vi . ViMode ] "}, {"prompt": " import cgi from google . appengine . datastore . datastore_query import Cursor ", "answer": "from google . appengine . ext import ndb"}, {"prompt": " \"\"\"\"\"\" import anydbm import thread class BaseDB : def __init__ ( self , filename , type ) : self . type = type self . filename = filename if self . filename : self . db = None else : self . db = { } self . lock = thread . allocate_lock ( ) def create ( self ) : \"\"\"\"\"\" if self . filename : self . db = anydbm . open ( self . filename , \"\" ) self . db [ \"\" ] = self . type self . db . sync ( ) else : self . db = { } def open ( self ) : \"\"\"\"\"\" if not self . filename : raise ValueError ( \"\" ) self . db = anydbm . open ( self . filename , \"\" ) try : if self . db [ \"\" ] != self . type : raise ValueError ( \"\" % self . type ) except KeyError : raise ValueError ( \"\" ) def __getitem__ ( self , username ) : if self . db == None : raise AssertionError ( \"\" ) self . lock . acquire ( ) try : valueStr = self . db [ username ] finally : ", "answer": "self . lock . release ( )"}, {"prompt": " from oslo_config import cfg from oslo_log import log as logging import six from sahara import conductor as c from sahara import context from sahara import exceptions as ex from sahara . i18n import _LE from sahara . plugins import base as plugin_base from sahara . service import api from sahara . service . edp . binary_retrievers import dispatch from sahara . service . edp import job_manager as manager from sahara . utils import edp from sahara . utils import proxy as p conductor = c . API LOG = logging . getLogger ( __name__ ) CONF = cfg . CONF def get_job_types ( ** kwargs ) : hints = kwargs . get ( \"\" , [ \"\" ] ) [ ] . lower ( ) == \"\" plugin_names = kwargs . get ( \"\" , [ ] ) all_plugins = plugin_base . PLUGINS . get_plugins ( ) if plugin_names : plugins = filter ( lambda x : x . name in plugin_names , all_plugins ) else : plugins = all_plugins job_types = kwargs . get ( \"\" , edp . JOB_TYPES_ALL ) versions = kwargs . get ( \"\" , [ ] ) res = [ ] for job_type in job_types : job_entry = { \"\" : job_type , \"\" : [ ] } for plugin in plugins : types_for_plugin = plugin . get_edp_job_types ( versions ) p = plugin . dict ", "answer": "p [ \"\" ] = { }"}, {"prompt": " import logging import os import shutil import yaml from stackstrap . jinja import JinjaInterface class ProjectException ( Exception ) : pass class Project ( object ) : def __init__ ( self , name ) : self . log = logging . getLogger ( \"\" ) self . name = name self . short_name = self . name def create ( self , template ) : if os . path . exists ( self . name ) : raise ProjectException ( \"\" . format ( name = self . name ) ) if not template . validated : template . validate ( ) self . log . info ( ( \"\" + \"\" ) . format ( name = self . name , template = template . name ) ) template . copy_to ( self . name ) render_context = { '' : self . name , '' : self , ", "answer": "'' : template ,"}, {"prompt": " from __future__ import division from six . moves import range import array CRC_POLY = def process_word ( data , crc = ) : if len ( data ) < : d_array = array . array ( '' , data ) for x in range ( , - len ( data ) ) : d_array . insert ( , ) d_array . reverse ( ) data = d_array . tostring ( ) d = array . array ( '' , data ) [ ] ", "answer": "crc = crc ^ d"}, {"prompt": " class SftpException ( Exception ) : pass class SftpConfigException ( SftpException ) : pass class SftpMountException ( SftpException ) : ", "answer": "def __init__ ( self , mount_cmd , mount_cmd_output ) :"}, {"prompt": " from lamson import queue , server , mail from nose . tools import * import shutil import os from mock import * import mailbox USE_SAFE = False def setup ( ) : if os . path . exists ( \"\" ) : shutil . rmtree ( \"\" ) def teardown ( ) : setup ( ) def test_push ( ) : q = queue . Queue ( \"\" , safe = USE_SAFE ) q . clear ( ) msg = mail . MailResponse ( To = \"\" , From = \"\" , Subject = \"\" , Body = \"\" ) key = q . push ( msg ) assert key , \"\" return q def test_pop ( ) : q = test_push ( ) key , msg = q . pop ( ) assert key , \"\" assert msg , \"\" % key assert msg [ '' ] == \"\" assert msg [ '' ] == \"\" assert msg [ '' ] == \"\" assert msg . body ( ) == \"\" assert q . count ( ) == , \"\" assert not q . pop ( ) [ ] def test_get ( ) : q = test_push ( ) msg = mail . MailResponse ( To = \"\" , From = \"\" , Subject = \"\" , Body = \"\" ) key = q . push ( str ( msg ) ) assert key , \"\" msg = q . get ( key ) assert msg , \"\" % key def test_remove ( ) : q = test_push ( ) msg = mail . MailResponse ( To = \"\" , From = \"\" , Subject = \"\" , Body = \"\" ) key = q . push ( str ( msg ) ) assert key , \"\" assert q . count ( ) == , \"\" % q . count ( ) q . remove ( key ) assert q . count ( ) == , \"\" % q . count ( ) def test_safe_maildir ( ) : global USE_SAFE USE_SAFE = True test_push ( ) test_pop ( ) test_get ( ) test_remove ( ) def test_oversize_protections ( ) : overq = queue . Queue ( \"\" , pop_limit = ) overq . clear ( ) for i in range ( ) : overq . push ( \"\" * ) assert_equal ( overq . count ( ) , ) key , msg = overq . pop ( ) assert not key and not msg , \"\" assert_equal ( overq . count ( ) , ) setup ( ) overq = queue . Queue ( \"\" , pop_limit = , oversize_dir = \"\" ) moveq = queue . Queue ( \"\" ) for i in range ( ) : overq . push ( \"\" * ) key , msg = overq . pop ( ) assert not key and not msg , \"\" assert_equal ( overq . count ( ) , ) assert_equal ( moveq . count ( ) , ) moveq . clear ( ) overq . clear ( ) @ patch ( '' , new = Mock ( ) ) @ raises ( mailbox . ExternalClashError ) def test_SafeMaildir_name_clash ( ) : try : shutil . rmtree ( \"\" ) except : pass sq = queue . SafeMaildir ( '' ) sq . add ( \"\" ) def raise_OSError ( * x , ** kw ) : err = OSError ( '' ) err . errno = raise err @ patch ( '' , new = Mock ( ) ) @ raises ( OSError ) def test_SafeMaildir_throws_errno_failure ( ) : ", "answer": "setup ( )"}, {"prompt": " \"\"\"\"\"\" import seaborn as sns sns . set ( style = \"\" ) df = sns . load_dataset ( \"\" ) sns . lmplot ( x = \"\" , y = \"\" , col = \"\" , hue = \"\" , data = df , ", "answer": "col_wrap = , ci = None , palette = \"\" , size = ,"}, {"prompt": " import time import numpy import pyfora . Exceptions as Exceptions class ListTestCases ( object ) : \"\"\"\"\"\" def test_handle_empty_list ( self ) : def f ( ) : return [ ] self . equivalentEvaluationTest ( f ) def test_list_str ( self ) : t1 = ( , ) self . equivalentEvaluationTest ( lambda : str ( t1 ) ) def test_return_list ( self ) : def f ( ) : return [ , , , , ] self . equivalentEvaluationTest ( f ) def test_list_in_loop ( self ) : def f ( ct ) : ix = l = [ ] while ix < ct : l = l + [ ix ] ix = ix + res = for e in l : res = res + e return res ct = ", "answer": "res = self . evaluateWithExecutor ( f , ct )"}, {"prompt": " import sys from tiget . git import init_repo , GitError from tiget . utils import print_error , post_mortem ", "answer": "from tiget . plugins import load_plugin"}, {"prompt": " class BasicBlock ( object ) : \"\"\"\"\"\" def __init__ ( self , id , bb , fc ) : self . _fc = fc self . id = id \"\"\"\"\"\" self . startEA = bb . startEA \"\"\"\"\"\" self . endEA = bb . endEA \"\"\"\"\"\" self . type = self . _fc . _q . calc_block_type ( self . id ) \"\"\"\"\"\" def preds ( self ) : \"\"\"\"\"\" q = self . _fc . _q for i in xrange ( , self . _fc . _q . npred ( self . id ) ) : yield self . _fc [ q . pred ( self . id , i ) ] def succs ( self ) : \"\"\"\"\"\" q = self . _fc . _q for i in xrange ( , q . nsucc ( self . id ) ) : yield self . _fc [ q . succ ( self . id , i ) ] class FlowChart ( object ) : \"\"\"\"\"\" def __init__ ( self , f = None , bounds = None , flags = ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " import mock from oslo_concurrency import processutils from nova . tests . unit . volume . encryptors import test_cryptsetup from nova . volume . encryptors import luks class LuksEncryptorTestCase ( test_cryptsetup . CryptsetupEncryptorTestCase ) : def _create ( self , connection_info ) : return luks . LuksEncryptor ( connection_info ) ", "answer": "@ mock . patch ( '' )"}, {"prompt": " import json import logging import os from pathlib import Path from urllib . request import urlopen , Request logger = logging . getLogger ( __name__ ) def get_links ( client_id ) : headers = { '' : '' . format ( client_id ) } req = Request ( '' , headers = headers , method = '' ) with urlopen ( req ) as resp : data = json . loads ( resp . read ( ) . decode ( '' ) ) return map ( lambda item : item [ '' ] , data [ '' ] ) def download_link ( directory , link ) : download_path = directory / os . path . basename ( link ) with urlopen ( link ) as image , download_path . open ( '' ) as f : f . write ( image . read ( ) ) logger . info ( '' , link ) ", "answer": "def setup_download_dir ( ) :"}, {"prompt": " from __future__ import unicode_literals from flask_restplus import ( marshal , marshal_with , marshal_with_field , fields , Api , Resource ) try : from collections import OrderedDict except ImportError : from ordereddict import OrderedDict from . import TestCase class HelloWorld ( Resource ) : def get ( self ) : return { } class MarshallingTestCase ( TestCase ) : def test_marshal ( self ) : model = OrderedDict ( [ ( '' , fields . Raw ) ] ) marshal_dict = OrderedDict ( [ ( '' , '' ) , ( '' , '' ) ] ) output = marshal ( marshal_dict , model ) self . assertEquals ( output , { '' : '' } ) def test_marshal_with_envelope ( self ) : model = OrderedDict ( [ ( '' , fields . Raw ) ] ) marshal_dict = OrderedDict ( [ ( '' , '' ) , ( '' , '' ) ] ) output = marshal ( marshal_dict , model , envelope = '' ) self . assertEquals ( output , { '' : { '' : '' } } ) def test_marshal_decorator ( self ) : model = OrderedDict ( [ ( '' , fields . Raw ) ] ) @ marshal_with ( model ) def try_me ( ) : return OrderedDict ( [ ( '' , '' ) , ( '' , '' ) ] ) self . assertEquals ( try_me ( ) , { '' : '' } ) def test_marshal_decorator_with_envelope ( self ) : model = OrderedDict ( [ ( '' , fields . Raw ) ] ) @ marshal_with ( model , envelope = '' ) def try_me ( ) : return OrderedDict ( [ ( '' , '' ) , ( '' , '' ) ] ) self . assertEquals ( try_me ( ) , { '' : { '' : '' } } ) def test_marshal_decorator_tuple ( self ) : model = OrderedDict ( [ ( '' , fields . Raw ) ] ) @ marshal_with ( model ) def try_me ( ) : headers = { '' : } return OrderedDict ( [ ( '' , '' ) , ( '' , '' ) ] ) , , headers self . assertEquals ( try_me ( ) , ( { '' : '' } , , { '' : } ) ) def test_marshal_decorator_tuple_with_envelope ( self ) : model = OrderedDict ( [ ( '' , fields . Raw ) ] ) @ marshal_with ( model , envelope = '' ) def try_me ( ) : headers = { '' : } return OrderedDict ( [ ( '' , '' ) , ( '' , '' ) ] ) , , headers self . assertEquals ( try_me ( ) , ( { '' : { '' : '' } } , , { '' : } ) ) def test_marshal_field_decorator ( self ) : model = fields . Raw @ marshal_with_field ( model ) def try_me ( ) : return '' self . assertEquals ( try_me ( ) , '' ) def test_marshal_field_decorator_tuple ( self ) : model = fields . Raw @ marshal_with_field ( model ) def try_me ( ) : return '' , , { '' : } self . assertEquals ( ( '' , , { '' : } ) , try_me ( ) ) def test_marshal_field ( self ) : model = OrderedDict ( { '' : fields . Raw ( ) } ) marshal_fields = OrderedDict ( [ ( '' , '' ) , ( '' , '' ) ] ) output = marshal ( marshal_fields , model ) self . assertEquals ( output , { '' : '' } ) def test_marshal_tuple ( self ) : model = OrderedDict ( { '' : fields . Raw } ) marshal_fields = OrderedDict ( [ ( '' , '' ) , ( '' , '' ) ] ) output = marshal ( ( marshal_fields , ) , model ) self . assertEquals ( output , [ { '' : '' } ] ) def test_marshal_tuple_with_envelope ( self ) : model = OrderedDict ( { '' : fields . Raw } ) marshal_fields = OrderedDict ( [ ( '' , '' ) , ( '' , '' ) ] ) output = marshal ( ( marshal_fields , ) , model , envelope = '' ) self . assertEquals ( output , { '' : [ { '' : '' } ] } ) def test_marshal_nested ( self ) : model = OrderedDict ( [ ( '' , fields . Raw ) , ( '' , fields . Nested ( { '' : fields . String , } ) ) ] ) marshal_fields = OrderedDict ( [ ( '' , '' ) , ( '' , '' ) , ( '' , { '' : '' } ) ] ) output = marshal ( marshal_fields , model ) expected = OrderedDict ( [ ( '' , '' ) , ( '' , OrderedDict ( [ ( '' , '' ) ] ) ) ] ) self . assertEquals ( output , expected ) def test_marshal_nested_with_non_null ( self ) : model = OrderedDict ( [ ( '' , fields . Raw ) , ( '' , fields . Nested ( OrderedDict ( [ ( '' , fields . String ) , ( '' , fields . String ) ] ) , allow_null = False ) ) ] ) marshal_fields = [ OrderedDict ( [ ( '' , '' ) , ( '' , '' ) , ( '' , None ) ] ) ] output = marshal ( marshal_fields , model ) expected = [ OrderedDict ( [ ( '' , '' ) , ( '' , OrderedDict ( [ ( '' , None ) , ( '' , None ) ] ) ) ] ) ] self . assertEquals ( output , expected ) def test_marshal_nested_with_null ( self ) : model = OrderedDict ( [ ( '' , fields . Raw ) , ( '' , fields . Nested ( ", "answer": "OrderedDict ( ["}, {"prompt": " \"\"\"\"\"\" import argparse ", "answer": "from scaffold import projectfolders , projectfiles"}, {"prompt": " \"\"\"\"\"\" import warnings , socket , sys from zope . interface import implements from twisted . internet import base , interfaces , main , error from twisted . python import log , failure from twisted . internet . _dumbwin32proc import Process from twisted . internet . win32eventreactor import _ThreadedWin32EventsMixin from twisted . internet . iocpreactor import iocpsupport as _iocp from twisted . internet . iocpreactor . const import WAIT_TIMEOUT from twisted . internet . iocpreactor import tcp , udp try : from twisted . protocols . tls import TLSMemoryBIOFactory except ImportError : TLSMemoryBIOFactory = None _extraInterfaces = ( ) warnings . warn ( \"\" \"\" ) else : _extraInterfaces = ( interfaces . IReactorSSL , ) from twisted . python . compat import set MAX_TIMEOUT = EVENTS_PER_LOOP = KEY_NORMAL , KEY_WAKEUP = range ( ) _NO_GETHANDLE = error . ConnectionFdescWentAway ( '' ) _NO_FILEDESC = error . ConnectionFdescWentAway ( '' ) class IOCPReactor ( base . _SignalReactorMixin , base . ReactorBase , _ThreadedWin32EventsMixin ) : implements ( interfaces . IReactorTCP , interfaces . IReactorUDP , interfaces . IReactorMulticast , interfaces . IReactorProcess , * _extraInterfaces ) port = None def __init__ ( self ) : base . ReactorBase . __init__ ( self ) self . port = _iocp . CompletionPort ( ) self . handles = set ( ) def addActiveHandle ( self , handle ) : self . handles . add ( handle ) def removeActiveHandle ( self , handle ) : self . handles . discard ( handle ) def doIteration ( self , timeout ) : \"\"\"\"\"\" processed_events = ", "answer": "if timeout is None :"}, {"prompt": " from lxml import etree from zeep . xsd import Schema def test_parse_response ( ) : schema_node = etree . fromstring ( b\"\"\"\"\"\" . strip ( ) ) response_node = etree . fromstring ( b\"\"\"\"\"\" . strip ( ) ) schema = Schema ( schema_node . find ( '' ) ) assert schema response_type = schema . get_element ( '' ) nsmap = { '' : '' , '' : '' , } ", "answer": "node = response_node . find ( '' , namespaces = nsmap )"}, {"prompt": " \"\"\"\"\"\" from time import time as _time from collections import deque import heapq __all__ = [ '' , '' , '' , '' , '' ] class Empty ( Exception ) : \"\" pass class Full ( Exception ) : \"\" pass class Queue : \"\"\"\"\"\" def __init__ ( self , maxsize = ) : try : import threading except ImportError : import dummy_threading as threading self . maxsize = maxsize self . _init ( maxsize ) self . mutex = threading . Lock ( ) self . not_empty = threading . Condition ( self . mutex ) self . not_full = threading . Condition ( self . mutex ) self . all_tasks_done = threading . Condition ( self . mutex ) self . unfinished_tasks = def task_done ( self ) : \"\"\"\"\"\" self . all_tasks_done . acquire ( ) try : unfinished = self . unfinished_tasks - if unfinished <= : if unfinished < : raise ValueError ( '' ) self . all_tasks_done . notify_all ( ) self . unfinished_tasks = unfinished finally : self . all_tasks_done . release ( ) def join ( self ) : \"\"\"\"\"\" self . all_tasks_done . acquire ( ) try : while self . unfinished_tasks : self . all_tasks_done . wait ( ) finally : self . all_tasks_done . release ( ) def qsize ( self ) : \"\"\"\"\"\" self . mutex . acquire ( ) n = self . _qsize ( ) self . mutex . release ( ) return n def empty ( self ) : \"\"\"\"\"\" self . mutex . acquire ( ) n = not self . _qsize ( ) self . mutex . release ( ) return n def full ( self ) : \"\"\"\"\"\" self . mutex . acquire ( ) ", "answer": "n = < self . maxsize == self . _qsize ( )"}, {"prompt": " from django . test import TestCase from django . core . exceptions import ValidationError from core . interface . static_intr . models import StaticInterface from systems . models import System from mozdns . domain . models import Domain from mozdns . address_record . models import AddressRecord from mozdns . ptr . models import PTR from mozdns . ip . utils import ip_to_domain_name class V6StaticInterTests ( TestCase ) : def create_domain ( self , name , ip_type = None , delegated = False ) : if ip_type is None : ip_type = '' if name in ( '' , '' , '' ) : pass else : name = ip_to_domain_name ( name , ip_type = ip_type ) d = Domain ( name = name , delegated = delegated ) d . clean ( ) ", "answer": "self . assertTrue ( d . is_reverse )"}, {"prompt": " from __future__ import print_function , unicode_literals , absolute_import import os import os . path import shutil import logging from simiki . config import parse_config from simiki . utils import ( copytree , mkdir_p , listdir_nohidden ) class Initiator ( object ) : conf_template_dn = \"\" config_fn = \"\" fabfile_fn = \"\" demo_fn = \"\" def __init__ ( self , config_file , target_path ) : self . config_file = config_file self . config = parse_config ( self . config_file ) self . source_path = os . path . dirname ( __file__ ) self . target_path = target_path @ staticmethod def get_file ( src , dst ) : if os . path . exists ( dst ) : logging . warning ( \"\" . format ( dst ) ) return dst_directory = os . path . dirname ( dst ) if not os . path . exists ( dst_directory ) : mkdir_p ( dst_directory ) logging . info ( \"\" . format ( dst_directory ) ) shutil . copyfile ( src , dst ) logging . info ( \"\" . format ( dst ) ) def get_config_file ( self ) : dst_config_file = os . path . join ( self . target_path , self . config_fn ) self . get_file ( self . config_file , dst_config_file ) def get_fabfile ( self ) : src_fabfile = os . path . join ( self . source_path , self . conf_template_dn , self . fabfile_fn ) dst_fabfile = os . path . join ( self . target_path , self . fabfile_fn ) self . get_file ( src_fabfile , dst_fabfile ) def get_demo_page ( self ) : nohidden_dir = listdir_nohidden ( os . path . join ( self . target_path , self . config [ '' ] ) ) if next ( nohidden_dir , False ) : return ", "answer": "src_demo = os . path . join ( self . source_path , self . conf_template_dn ,"}, {"prompt": " import sublime , sublime_plugin from . gist . lib import util class HaoGistEvent ( sublime_plugin . EventListener ) : def on_post_save_async ( self , view ) : settings = util . get_settings ( ) ; ", "answer": "if settings [ \"\" ] not in view . file_name ( ) : return"}, {"prompt": " \"\"\"\"\"\" import datetime from string import Template SPECIES_DURATION = { : , : , : , } TEMPLATE = \"\"\"\"\"\" NOTES = { : \"\" , : \"\" , : \"\" , : \"\" , : \"\" , : \"\" , : \"\" , : \"\" , : \"\" , : \"\" , : \"\" , : \"\" , : \"\" , : \"\" , : \"\" , : \"\" , : \"\" , } ", "answer": "def get_cantus_firmus ( notes ) :"}, {"prompt": " from nose . tools import * from tests . base import OsfTestCase import json from modularodm import Q from framework . mongo . utils import to_mongo from website . project . model import ensure_schemas , MetaSchema , Node from tests import factories from scripts . migration . migrate_registered_meta import ( main as do_migration , prepare_nodes ) SCHEMA_NAMES = [ '' , '' , '' , '' , '' ] OLD_META = { '' : { '' : '' , } , '' : { '' : '' , '' : '' , '' : '' , } , '' : { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , } , '' : { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , } , '' : { '' : '' , '' : '' , '' : '' , } } class TestMigrateSchemas ( OsfTestCase ) : def _make_registration ( self , schemas ) : if not isinstance ( schemas , list ) : schemas = [ schemas ] reg = factories . RegistrationFactory ( ) reg . save ( ) self . db [ '' ] . update ( { '' : reg . _id } , { '' : { '' : { to_mongo ( schema . name ) : json . dumps ( OLD_META [ schema . name ] ) for schema in schemas } , '' : None } } ) def setUp ( self ) : super ( TestMigrateSchemas , self ) . setUp ( ) MetaSchema . remove ( ) ensure_schemas ( ) self . regular_old_node = factories . NodeFactory ( ) self . open_ended_schema = MetaSchema . find_one ( Q ( '' , '' , SCHEMA_NAMES [ ] ) & Q ( '' , '' , ) ) self . open_ended = self . _make_registration ( self . open_ended_schema ) self . standard_schema = MetaSchema . find_one ( Q ( '' , '' , SCHEMA_NAMES [ ] ) & Q ( '' , '' , ) ) self . standard = self . _make_registration ( self . standard_schema ) self . brandt_pre_schema = MetaSchema . find_one ( Q ( '' , '' , SCHEMA_NAMES [ ] ) & Q ( '' , '' , ) ) self . brandt_pre = self . _make_registration ( self . brandt_pre_schema ) self . brandt_post_schema = MetaSchema . find_one ( Q ( '' , '' , SCHEMA_NAMES [ ] ) & Q ( '' , '' , ) ) self . brandt_post = self . _make_registration ( self . brandt_post_schema ) self . multiple = self . _make_registration ( [ self . brandt_pre_schema , self . brandt_post_schema ] ) self . confirmatory_schema = MetaSchema . find_one ( Q ( '' , '' , '' ) ) self . confirmatory = self . _make_registration ( self . confirmatory_schema ) self . db [ '' ] . update ( { } , { '' : { '' : None } } , multi = True ) def tearDown ( self ) : super ( TestMigrateSchemas , self ) . tearDown ( ) self . db [ '' ] . remove ( ) def test_prepare_nodes ( self ) : prepare_nodes ( self . db ) for node in self . db [ '' ] . find ( ) : assert_equal ( node [ '' ] , [ ] ) ", "answer": "def test_migrate_registration_schemas ( self ) :"}, {"prompt": " from django . conf import settings STAFF_ONLY = getattr ( settings , '' , False ) DEFAULT_LIST_ID = getattr ( settings , '' , ) DEFAULT_ASSIGNEE = getattr ( settings , '' , None ) ", "answer": "PUBLIC_SUBMIT_REDIRECT = getattr ( settings , '' , '' ) "}, {"prompt": " from freezegun import freeze_time from moto . swf . exceptions import SWFWorkflowExecutionClosedError from moto . swf . models import ( ActivityTask , ActivityType , Timeout , ", "answer": ")"}, {"prompt": " \"\"\"\"\"\" import dns . name import collections class NameDict ( collections . MutableMapping ) : \"\"\"\"\"\" __slots__ = [ \"\" , \"\" , \"\" ] def __init__ ( self , * args , ** kwargs ) : self . __store = dict ( ) self . max_depth = self . max_depth_items = self . update ( dict ( * args , ** kwargs ) ) def __update_max_depth ( self , key ) : if len ( key ) == self . max_depth : self . max_depth_items = self . max_depth_items + elif len ( key ) > self . max_depth : self . max_depth = len ( key ) self . max_depth_items = def __getitem__ ( self , key ) : return self . __store [ key ] def __setitem__ ( self , key , value ) : if not isinstance ( key , dns . name . Name ) : raise ValueError ( '' ) self . __store [ key ] = value self . __update_max_depth ( key ) def __delitem__ ( self , key ) : value = self . __store . pop ( key ) if len ( value ) == self . max_depth : self . max_depth_items = self . max_depth_items - if self . max_depth_items == : self . max_depth = for k in self . __store : self . __update_max_depth ( k ) def __iter__ ( self ) : ", "answer": "return iter ( self . __store )"}, {"prompt": " import unittest ", "answer": "import jsonrpclib"}, {"prompt": " from __future__ import absolute_import import sys from grizzled . system import * VERSIONS = [ ( '' , ) , ( '' , ) , ( '' , ) , ( '' , ) ] class TestSys ( object ) : def test_version_conversions ( self ) : for s , i in VERSIONS : yield self . do_one_version_conversion , s , i def do_one_version_conversion ( self , string_version , binary_version ) : h = python_version ( string_version ) s = python_version_string ( binary_version ) assert h == binary_version assert s == string_version def test_current_version ( self ) : ensure_version ( sys . hexversion ) ensure_version ( python_version_string ( sys . hexversion ) ) major , minor , patch , final , rem = sys . version_info binary_version = python_version ( '' % ( major , minor , patch ) ) ", "answer": "def test_class_for_name ( self ) :"}, {"prompt": " from django . db import transaction from greenqueue . models import TaskResult from greenqueue . exceptions import ResultDoesNotExist from . base import BaseStorageBackend from ... import settings try : import cPickle as pickle except ImportError : import pickle import base64 class StorageBackend ( BaseStorageBackend ) : def get ( self , uuid , default = None ) : ", "answer": "try :"}, {"prompt": " value = def get_value ( ) : ", "answer": "return value "}, {"prompt": " \"\"\"\"\"\" import sys if sys . version_info < ( , ) : uni = unicode else : uni = str import collections import json import uuid from base64 import b64decode from base64 import b64encode from flowy . result import is_result_proxy , TaskError , SuspendTask , wait from flowy . operations import first __all__ = [ '' , '' , '' ] def check_err_and_placeholders ( result , value ) : err , placeholders = result try : wait ( value ) except TaskError : if err is None : err = value else : err = first ( err , value ) except SuspendTask : placeholders = True return err , placeholders def collect_err_and_results ( result , value ) : err , results = result if not is_result_proxy ( value ) : return result try : wait ( value ) except TaskError : if err is None : err = value else : err = first ( err , value ) except SuspendTask : pass else : if results is None : results = [ ] results . append ( value ) return err , results def traverse_data ( value , f = check_err_and_placeholders , initial = ( None , False ) , seen = frozenset ( ) , make_list = True ) : if is_result_proxy ( value ) : try : wait ( value ) except TaskError : return value , f ( initial , value ) except SuspendTask : return value , f ( initial , value ) return value . __wrapped__ , f ( initial , value ) if isinstance ( value , ( bytes , uni ) ) : return value , f ( initial , value ) res = initial if isinstance ( value , collections . Iterable ) : if id ( value ) in seen : raise ValueError ( '' ) seen = seen | frozenset ( [ id ( value ) ] ) if isinstance ( value , collections . Mapping ) : d = { } for k , v in value . items ( ) : k_ , res = traverse_data ( k , f , res , seen , make_list = False ) v_ , res = traverse_data ( v , f , res , seen , make_list = make_list ) d [ k_ ] = v_ return d , res if ( isinstance ( value , collections . Iterable ) and isinstance ( value , collections . Sized ) ) : l = [ ] ", "answer": "for x in value :"}, {"prompt": " import os import abc import numpy as np import scipy . linalg import scipy . signal as sig class Basis ( object ) : __metaclass__ = abc . ABCMeta def __init__ ( self , B , dt , dt_max , orth = False , norm = False , allow_instantaneous = False ) : self . B = B self . dt = dt self . dt_max = dt_max self . orth = orth self . norm = norm self . allow_instantaneous = allow_instantaneous self . basis = self . interpolate_basis ( self . create_basis ( ) , self . dt , self . dt_max , self . norm ) self . L = self . basis . shape [ ] @ abc . abstractmethod def create_basis ( self ) : raise NotImplementedError ( ) def convolve_with_basis ( self , S ) : \"\"\"\"\"\" ( T , K ) = S . shape ( R , B ) = self . basis . shape F = np . empty ( ( T , K , B ) ) for b in np . arange ( B ) : F [ : , : , b ] = sig . fftconvolve ( S , np . reshape ( self . basis [ : , b ] , ( R , ) ) , '' ) [ : T , : ] if np . amin ( self . basis ) >= and np . amin ( S ) >= : np . clip ( F , , np . inf , out = F ) assert np . amin ( F ) >= , \"\" return F def interpolate_basis ( self , basis , dt , dt_max , norm = True ) : L , B = basis . shape t_int = np . arange ( , dt_max , step = dt ) t_bas = np . linspace ( , dt_max , L ) ibasis = np . zeros ( ( len ( t_int ) , B ) ) for b in np . arange ( B ) : ibasis [ : , b ] = np . interp ( t_int , t_bas , basis [ : , b ] ) if norm : ibasis /= ( dt * np . sum ( ibasis , axis = ) ) if not self . allow_instantaneous : ibasis = np . vstack ( ( np . zeros ( ( , B ) ) , ibasis ) ) return ibasis def create_basis ( self ) : raise NotImplementedError ( \"\" ) class CosineBasis ( Basis ) : \"\"\"\"\"\" def __init__ ( self , B , dt , dt_max , orth = False , norm = True , allow_instantaneous = False , n_eye = , a = / , b = , L = ) : self . n_eye = n_eye self . a = a self . b = b self . L = L super ( CosineBasis , self ) . __init__ ( B , dt , dt_max , orth , norm , allow_instantaneous ) def create_basis ( self ) : n_pts = self . L n_cos = self . B - self . n_eye n_eye = self . n_eye assert n_cos >= and n_eye >= n_bas = n_eye + n_cos basis = np . zeros ( ( n_pts , n_bas ) ) basis [ : n_eye , : n_eye ] = np . eye ( n_eye ) a = self . a b = self . b nlin = lambda t : np . log ( a * t + b ) u_ir = nlin ( np . arange ( n_pts ) ) ctrs = u_ir [ np . floor ( np . linspace ( n_eye , ( n_pts / ) , n_cos ) ) . astype ( np . int ) ] if len ( ctrs ) == : w = ctrs / else : w = ( ctrs [ - ] - ctrs [ ] ) / ( n_cos - ) basis_fn = lambda u , c , w : ( np . cos ( np . maximum ( - np . pi , np . minimum ( np . pi , ( u - c ) * np . pi / w / ) ) ) + ) / for i in np . arange ( n_cos ) : basis [ : , n_eye + i ] = basis_fn ( u_ir , ctrs [ i ] , w ) if self . orth : basis = scipy . linalg . orth ( basis ) if self . norm : if np . any ( basis < ) : raise Exception ( \"\" ) ", "answer": "basis = basis / np . tile ( np . sum ( basis , axis = ) , [ n_pts , ] ) / ( / n_pts )"}, {"prompt": " \"\"\"\"\"\" import sys from vispy import app , scene , visuals from vispy . util . filter import gaussian_filter import numpy as np canvas = scene . SceneCanvas ( keys = '' , title = '' '' ) canvas . size = , canvas . show ( ) view = canvas . central_widget . add_view ( ) img_data = np . empty ( ( , , ) , dtype = np . ubyte ) noise = np . random . normal ( size = ( , ) , loc = , scale = ) noise = gaussian_filter ( noise , ( , , ) ) img_data [ : ] = noise [ ... , np . newaxis ] ", "answer": "image = scene . visuals . Image ( img_data , parent = view . scene )"}, {"prompt": " \"\"\"\"\"\" import eventlet . patcher import webob . dec import webob . exc from glance . common import client from glance . common import exception from glance . common import wsgi from glance . tests import functional from glance . tests import utils eventlet . patcher . monkey_patch ( socket = True ) class RedirectTestApp ( object ) : \"\"\"\"\"\" def __init__ ( self , name ) : \"\"\"\"\"\" self . name = name @ webob . dec . wsgify def __call__ ( self , request ) : \"\"\"\"\"\" base = \"\" % request . host path = request . path_qs if path == \"\" : return \"\" elif path == \"\" : url = \"\" % base raise webob . exc . HTTPFound ( location = url ) elif path == \"\" : url = \"\" % base raise webob . exc . HTTPFound ( location = url ) elif path == \"\" : raise webob . exc . HTTPFound ( location = request . url ) elif path . startswith ( \"\" ) : url = \"\" % path . split ( \"\" ) [ - ] raise webob . exc . HTTPFound ( location = url ) elif path == \"\" : return \"\" % self . name elif path == \"\" : return \"\" return \"\" class TestClientRedirects ( functional . FunctionalTest ) : ", "answer": "def setUp ( self ) :"}, {"prompt": " \"\"\"\"\"\" from django . conf import settings ", "answer": "from django . core . serializers import base"}, {"prompt": " import codecs try : import cPickle as pickle except ImportError : import pickle import bz2file import gzip import RDF from utils . logger import get_logger DBPEDIA_RES_URI = \"\" logger = get_logger ( ) def open_file ( file_path ) : \"\"\"\"\"\" open_fn = codecs . open if file_path . endswith ( \"\" ) : open_fn = bz2file . open elif file_path . endswith ( \"\" ) : open_fn = gzip . open return open_fn def get_rdf_parser ( file_path ) : \"\"\"\"\"\" if \"\" in file_path : return RDF . TurtleParser ( ) elif \"\" in file_path : return RDF . NTriplesParser ( ) else : raise ValueError ( \"\" , file_path ) def iterate_rdf_triples ( file_path ) : \"\"\"\"\"\" open_fn = open_file ( file_path ) rdf_parser = get_rdf_parser ( file_path ) with open_fn ( file_path , \"\" ) as in_file : for rdf_line in in_file : rdf_stream = rdf_parser . parse_string_as_stream ( rdf_line , \"\" ) for statement in rdf_stream : yield statement . subject , statement . predicate , statement . object def tuple_generator ( file_path , prefix = None ) : \"\"\"\"\"\" rdf_tuple_iterator = iterate_rdf_triples ( file_path ) counter = for subj , _ , obj in rdf_tuple_iterator : subj = unicode ( subj ) obj = unicode ( obj ) if prefix : subj = subj . replace ( prefix , \"\" ) obj = obj . replace ( prefix , \"\" ) counter += if counter % == : logger . info ( \"\" , counter ) yield subj , obj def generate_subject_object_map ( file_path , prefix = None ) : \"\"\"\"\"\" subj_obj_generator = tuple_generator ( file_path , prefix ) return dict ( subj_obj_generator ) def generate_title_id_map ( redirects_file_path , title_ids_file_path , output_file_path = None ) : \"\"\"\"\"\" ", "answer": "resolved_title_id_map = dict ( )"}, {"prompt": " import sys import os import os . path import re from elasticsearch import Elasticsearch from time import sleep from muppet import DurableChannel , RemoteChannel esStopWords = [ \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ] __name__ = \"\" class AnnotationDispatcher : def __init__ ( self , config , processingStartIndex , processingEndIndex ) : self . config = config self . logger = config [ \"\" ] self . esClient = Elasticsearch ( config [ \"\" ] [ \"\" ] + \"\" + str ( config [ \"\" ] [ \"\" ] ) ) self . bagOfPhrases = { } self . corpusIndex = config [ \"\" ] [ \"\" ] self . corpusType = config [ \"\" ] [ \"\" ] self . corpusFields = config [ \"\" ] [ \"\" ] self . corpusSize = self . processorIndex = config [ \"\" ] [ \"\" ] self . processorType = config [ \"\" ] [ \"\" ] self . processorPhraseType = config [ \"\" ] [ \"\" ] + \"\" self . processingPageSize = config [ \"\" ] self . analyzerIndex = self . corpusIndex + \"\" self . config [ \"\" ] = processingStartIndex self . config [ \"\" ] = processingEndIndex self . config [ \"\" ] = self . processingPageSize self . totalDocumentsDispatched = self . documentsAnnotated = self . documentsNotAnnotated = ", "answer": "self . lastDispatcher = False"}, {"prompt": " from __future__ import unicode_literals from django . db import models , migrations from django . utils . timezone import utc import datetime class Migration ( migrations . Migration ) : replaces = [ ( '' , '' ) , ( '' , '' ) , ( '' , '' ) ] dependencies = [ ] operations = [ migrations . CreateModel ( name = '' , fields = [ ( '' , models . AutoField ( verbose_name = '' , serialize = False , auto_created = True , primary_key = True ) ) , ( '' , models . CharField ( max_length = ) ) , ( '' , models . TextField ( default = '' ) ) , ( '' , models . DateTimeField ( auto_now_add = True , default = datetime . datetime ( , , , , , , , tzinfo = utc ) ) ) , ", "answer": "] ,"}, {"prompt": " \"\"\"\"\"\" __docformat__ = \"\" ", "answer": "from grizzled . db . base import DBDriver"}, {"prompt": " DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( ) MANAGERS = ADMINS DATABASES = { '' : { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , } } TIME_ZONE = '' LANGUAGE_CODE = '' SITE_ID = USE_I18N = True USE_L10N = True USE_TZ = True MEDIA_ROOT = '' MEDIA_URL = '' STATIC_ROOT = '' STATIC_URL = '' STATICFILES_DIRS = ( ) STATICFILES_FINDERS = ( '' , '' , ) SECRET_KEY = '' TEMPLATE_LOADERS = ( '' , ", "answer": "'' ,"}, {"prompt": " GROUPS_INDEX_URL = '' GROUPS_INDEX_VIEW_TEMPLATE = '' GROUPS_CREATE_URL = '' GROUPS_CREATE_VIEW_TEMPLATE = '' GROUPS_UPDATE_URL = '' GROUPS_UPDATE_VIEW_TEMPLATE = '' GROUPS_MANAGE_URL = '' GROUPS_MANAGE_VIEW_TEMPLATE = '' GROUPS_ADD_MEMBER_URL = '' ", "answer": "GROUPS_ADD_MEMBER_VIEW_TEMPLATE = ''"}, {"prompt": " from __future__ import print_function ", "answer": "import argparse"}, {"prompt": " import datetime from south . db import db from south . v2 import DataMigration from django . db import models from fancypages . utils import FP_NODE_MODEL , FP_PAGE_MODEL from fancypages . compat import AUTH_USER_MODEL , AUTH_USER_MODEL_NAME class Migration ( DataMigration ) : def forwards ( self , orm ) : \"\" if FP_NODE_MODEL == '' and FP_PAGE_MODEL == '' : for page in orm . FancyPage . objects . all ( ) : node , __ = orm . PageNode . objects . get_or_create ( depth = page . depth , description = page . description , image = page . image , name = page . name , numchild = page . numchild , path = page . path , slug = page . slug ) page . node = node page . save ( ) def backwards ( self , orm ) : \"\" if FP_NODE_MODEL == '' and FP_PAGE_MODEL == '' : for node in orm . PageNode . objects . all ( ) : node . page . depth = node . depth node . page . description = node . description node . page . image = node . image node . page . name = node . name node . page . numchild = node . numchild node . page . path = node . path node . page . slug = node . slug node . page . save ( ) models = { u'' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : u\"\" . format ( AUTH_USER_MODEL ) } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , u'' : { '' : { '' : '' } , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : u\"\" , '' : '' , '' : '' } ) } , u'' : { '' : { '' : \"\" , '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : u\"\" } ) , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , AUTH_USER_MODEL : { '' : { '' : AUTH_USER_MODEL_NAME } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : u\"\" , '' : '' , '' : '' } ) , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : u\"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) } , u'' : { '' : { '' : \"\" , '' : \"\" , '' : '' , '' : \"\" } , '' : ( '' , [ ] , { '' : '' } ) , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : \"\" , '' : '' , '' : [ '' ] } , u'' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) } , '' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : u\"\" , '' : '' } ) , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) } , '' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : \"\" , '' : \"\" } ) , '' : ( '' , [ ] , { } ) , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : \"\" } ) , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' , '' : \"\" . format ( FP_NODE_MODEL ) } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) } , '' : { '' : { '' : '' } , u'' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) } , '' : { '' : { '' : \"\" , '' : '' , '' : [ '' ] } , u'' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) } , '' : { '' : { '' : '' , '' : [ '' ] } , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , u'' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) } , '' : { '' : { '' : '' , '' : [ '' ] } , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , u'' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) } , '' : { '' : { '' : '' , '' : [ '' ] } , u'' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { } ) } , '' : { '' : { '' : '' } , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , ", "answer": "'' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) ,"}, {"prompt": " import os import signal import subprocess import time from beaver . base_log import BaseLog def create_ssh_tunnel ( beaver_config , logger = None ) : \"\"\"\"\"\" if not beaver_config . use_ssh_tunnel ( ) : return None logger . info ( \"\" ) return BeaverSshTunnel ( beaver_config , logger = logger ) class BeaverSubprocess ( BaseLog ) : \"\"\"\"\"\" def __init__ ( self , beaver_config , logger = None ) : \"\"\"\"\"\" super ( BeaverSubprocess , self ) . __init__ ( logger = logger ) self . _log_template = '' self . _beaver_config = beaver_config self . _command = '' self . _subprocess = None self . _logger = logger def run ( self ) : self . _log_debug ( '' . format ( self . _command ) ) self . _subprocess = subprocess . Popen ( [ '' , '' , self . _command ] , preexec_fn = os . setsid ) self . poll ( ) def poll ( self ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " \"\"\"\"\"\" from __future__ import print_function import sys import argparse import logging from openxc . generator . coder import CodeGenerator from openxc . generator . message_sets import JsonMessageSet from openxc . utils import fatal_error , load_json_from_search_path from . common import configure_logging LOG = logging . getLogger ( __name__ ) DEFAULT_SEARCH_PATH = \"\" def parse_options ( ) : parser = argparse . ArgumentParser ( description = \"\" \"\" ) group = parser . add_mutually_exclusive_group ( required = True ) group . add_argument ( \"\" , \"\" , type = str , nargs = '' , dest = \"\" , metavar = \"\" , help = \"\" \"\" ) group . add_argument ( \"\" , type = str , dest = \"\" , metavar = \"\" , help = \"\" \"\" ) parser . add_argument ( \"\" , \"\" , type = str , nargs = '' , dest = \"\" , metavar = \"\" , help = \"\" ) return parser . parse_args ( ) def main ( ) : configure_logging ( ) arguments = parse_options ( ) ", "answer": "search_paths = arguments . search_paths or [ ]"}, {"prompt": " \"\"\"\"\"\" import sys from pygments . formatter import Formatter __all__ = [ '' ] class EscapeSequence : def __init__ ( self , fg = None , bg = None , bold = False , underline = False ) : self . fg = fg self . bg = bg self . bold = bold self . underline = underline def escape ( self , attrs ) : if len ( attrs ) : return \"\" + \"\" . join ( attrs ) + \"\" return \"\" def color_string ( self ) : attrs = [ ] if self . fg is not None : attrs . extend ( ( \"\" , \"\" , \"\" % self . fg ) ) if self . bg is not None : attrs . extend ( ( \"\" , \"\" , \"\" % self . bg ) ) if self . bold : attrs . append ( \"\" ) if self . underline : attrs . append ( \"\" ) return self . escape ( attrs ) def reset_string ( self ) : attrs = [ ] if self . fg is not None : attrs . append ( \"\" ) if self . bg is not None : attrs . append ( \"\" ) if self . bold or self . underline : attrs . append ( \"\" ) return self . escape ( attrs ) class Terminal256Formatter ( Formatter ) : r\"\"\"\"\"\" name = '' aliases = [ '' , '' , '' ] filenames = [ ] def __init__ ( self , ** options ) : Formatter . __init__ ( self , ** options ) self . xterm_colors = [ ] self . best_match = { } self . style_string = { } self . usebold = '' not in options self . useunderline = '' not in options self . _build_color_table ( ) self . _setup_styles ( ) def _build_color_table ( self ) : self . xterm_colors . append ( ( , , ) ) self . xterm_colors . append ( ( , , ) ) self . xterm_colors . append ( ( , , ) ) self . xterm_colors . append ( ( , , ) ) self . xterm_colors . append ( ( , , ) ) self . xterm_colors . append ( ( , , ) ) self . xterm_colors . append ( ( , , ) ) self . xterm_colors . append ( ( , , ) ) self . xterm_colors . append ( ( , , ) ) self . xterm_colors . append ( ( , , ) ) self . xterm_colors . append ( ( , , ) ) self . xterm_colors . append ( ( , , ) ) self . xterm_colors . append ( ( , , ) ) self . xterm_colors . append ( ( , , ) ) self . xterm_colors . append ( ( , , ) ) self . xterm_colors . append ( ( , , ) ) valuerange = ( , , , , , ) for i in range ( ) : r = valuerange [ ( i // ) % ] g = valuerange [ ( i // ) % ] b = valuerange [ i % ] self . xterm_colors . append ( ( r , g , b ) ) for i in range ( , ) : v = + i * self . xterm_colors . append ( ( v , v , v ) ) def _closest_color ( self , r , g , b ) : distance = * * match = for i in range ( , ) : values = self . xterm_colors [ i ] rd = r - values [ ] gd = g - values [ ] bd = b - values [ ] d = rd * rd + gd * gd + bd * bd if d < distance : match = i distance = d return match def _color_index ( self , color ) : index = self . best_match . get ( color , None ) if index is None : try : rgb = int ( str ( color ) , ) except ValueError : rgb = r = ( rgb >> ) & g = ( rgb >> ) & b = rgb & index = self . _closest_color ( r , g , b ) self . best_match [ color ] = index return index def _setup_styles ( self ) : for ttype , ndef in self . style : escape = EscapeSequence ( ) if ndef [ '' ] : escape . fg = self . _color_index ( ndef [ '' ] ) if ndef [ '' ] : escape . bg = self . _color_index ( ndef [ '' ] ) if self . usebold and ndef [ '' ] : escape . bold = True if self . useunderline and ndef [ '' ] : escape . underline = True self . style_string [ str ( ttype ) ] = ( escape . color_string ( ) , escape . reset_string ( ) ) def format ( self , tokensource , outfile ) : if not self . encoding and hasattr ( outfile , \"\" ) and hasattr ( outfile , \"\" ) and outfile . isatty ( ) and sys . version_info < ( , ) : self . encoding = outfile . encoding return Formatter . format ( self , tokensource , outfile ) def format_unencoded ( self , tokensource , outfile ) : for ttype , value in tokensource : not_found = True while ttype and not_found : ", "answer": "try :"}, {"prompt": " \"\"\"\"\"\" import struct import StringIO import gzip import pyart MASTER_HEADER_SIZE = FIELD_HEADER_SIZE = VLEVEL_HEADER_SIZE = CHUNK_HEADER_SIZE = COMPRESSION_INFO_SIZE = SWEEP_INFO_SIZE = FIELD_NUMBER = NGATES = NFIELDS = INFILE = '' OUTFILE = '' mdvfile = pyart . io . mdv . MdvFile ( INFILE ) number_of_fields = int ( mdvfile . master_header [ '' ] ) bias = mdvfile . field_headers [ FIELD_NUMBER ] [ '' ] ", "answer": "scale = mdvfile . field_headers [ FIELD_NUMBER ] [ '' ]"}, {"prompt": " \"\"\"\"\"\" import sys def gevent_monkey ( * args , ** kwargs ) : import gevent . monkey gevent . monkey . patch_os ( ) gevent . monkey . patch_socket ( dns = True , aggressive = True ) gevent . monkey . patch_ssl ( ) gevent . monkey . patch_time ( ) gevent_monkey ( ) if sys . version_info >= ( , ) : def getresponse_monkey ( ) : import httplib original = httplib . HTTPConnection . getresponse def monkey ( * args , ** kwargs ) : kwargs [ '' ] = True return original ( * args , ** kwargs ) httplib . HTTPConnection . getresponse = monkey getresponse_monkey ( ) def ssl_monkey ( ) : import ssl original = ssl . wrap_socket def wrap_socket_monkey ( * args , ** kwargs ) : kwargs [ '' ] = '' return original ( * args , ** kwargs ) ssl . wrap_socket = wrap_socket_monkey ssl_monkey ( ) import argparse import logging import os import re import textwrap import traceback from wal_e import log_help from wal_e import subprocess from wal_e . exception import UserCritical from wal_e . exception import UserException from wal_e import storage from wal_e . piper import popen_sp from wal_e . worker . pg import PSQL_BIN , psql_csv_run from wal_e . pipeline import LZOP_BIN , PV_BIN , GPG_BIN from wal_e . worker . pg import CONFIG_BIN , PgControlDataParser log_help . configure ( format = '' ) logger = log_help . WalELogger ( '' ) def external_program_check ( to_check = frozenset ( [ PSQL_BIN , LZOP_BIN , PV_BIN ] ) ) : \"\"\"\"\"\" could_not_run = [ ] error_msgs = [ ] def psql_err_handler ( popen ) : assert popen . returncode != error_msgs . append ( textwrap . fill ( '' '' ) ) raise EnvironmentError ( '' '' ) with open ( os . devnull , '' ) as nullf : for program in to_check : try : if program is PSQL_BIN : psql_csv_run ( '' , error_handler = psql_err_handler ) else : if program is PV_BIN : extra_args = [ '' ] else : extra_args = [ ] proc = popen_sp ( [ program ] + extra_args , stdout = nullf , stderr = nullf , stdin = subprocess . PIPE ) proc . stdin . close ( ) proc . wait ( ) except EnvironmentError : could_not_run . append ( program ) if could_not_run : error_msgs . append ( '' + '' . join ( could_not_run ) ) if error_msgs : raise UserException ( '' , '' . join ( error_msgs ) ) return None def extract_segment ( text_with_extractable_segment ) : from wal_e . storage import BASE_BACKUP_REGEXP from wal_e . storage . base import SegmentNumber match = re . match ( BASE_BACKUP_REGEXP , text_with_extractable_segment ) if match is None : return None else : groupdict = match . groupdict ( ) return SegmentNumber ( log = groupdict [ '' ] , seg = groupdict [ '' ] ) def build_parser ( ) : parser = argparse . ArgumentParser ( formatter_class = argparse . RawDescriptionHelpFormatter , description = __doc__ ) aws_group = parser . add_mutually_exclusive_group ( ) aws_group . add_argument ( '' , '' , help = '' '' '' '' ) aws_group . add_argument ( '' , action = '' , help = '' '' '' ) parser . add_argument ( '' , '' , help = '' '' '' '' ) parser . add_argument ( '' , help = '' '' '' ) parser . add_argument ( '' , help = '' '' '' ) parser . add_argument ( '' , help = '' '' '' ) parser . add_argument ( '' , action = '' , help = '' ) subparsers = parser . add_subparsers ( title = '' , dest = '' ) backup_fetchpush_parent = argparse . ArgumentParser ( add_help = False ) backup_fetchpush_parent . add_argument ( '' , help = \"\" \"\" ) backup_fetchpush_parent . add_argument ( '' , '' , type = int , default = , help = '' ) subparsers . add_parser ( '' , help = '' ) backup_list_nodetail_parent = argparse . ArgumentParser ( add_help = False ) wal_fetchpush_parent = argparse . ArgumentParser ( add_help = False ) wal_fetchpush_parent . add_argument ( '' , help = '' ) backup_fetch_parser = subparsers . add_parser ( '' , help = '' , parents = [ backup_fetchpush_parent , backup_list_nodetail_parent ] ) backup_list_parser = subparsers . add_parser ( '' , parents = [ backup_list_nodetail_parent ] , help = '' ) backup_push_parser = subparsers . add_parser ( '' , help = '' , parents = [ backup_fetchpush_parent ] ) backup_push_parser . add_argument ( '' , help = '' '' , dest = '' , metavar = '' , type = int , default = None ) backup_push_parser . add_argument ( '' , help = ( '' '' '' ) , dest = '' , action = '' , default = False ) wal_push_parser = subparsers . add_parser ( '' , help = '' , parents = [ wal_fetchpush_parent ] ) wal_push_parser . add_argument ( '' , '' , type = int , default = , help = '' ) backup_fetch_parser . add_argument ( '' , help = '' ) backup_fetch_parser . add_argument ( '' , help = '' , dest = '' , action = '' , default = False ) backup_fetch_parser . add_argument ( '' , help = ( '' '' ) , type = str , default = None ) backup_list_parser . add_argument ( '' , nargs = '' , default = None , help = '' ) backup_list_parser . add_argument ( '' , default = False , action = '' , help = '' ) wal_fetch_parser = subparsers . add_parser ( '' , help = '' , parents = [ wal_fetchpush_parent ] ) wal_fetch_parser . add_argument ( '' , help = '' ) wal_fetch_parser . add_argument ( ", "answer": "'' , '' , type = int , default = ,"}, {"prompt": " '''''' import tornado . curl_httpclient from tornado . httpclient import HTTPRequest import os from tornado . ioloop import IOLoop from tornado import gen from framework . dependency_management . dependency_resolver import BaseComponent import logging class Proxy_manager ( BaseComponent ) : COMPONENT_NAME = \"\" testing_url = \"\" testing_url_patern = \"\" def __init__ ( self ) : self . register_in_service_locator ( ) self . testing_url = \"\" self . proxies = [ ] self . number_of_proxies = self . proxy_pointer = self . number_of_responses = def load_proxy_list ( self , proxylist_path ) : file_handle = open ( os . path . expanduser ( proxylist_path ) , \"\" ) proxies = [ ] file_buf = file_handle . read ( ) lines = file_buf . split ( \"\" ) for line in lines : if str ( line ) . strip ( ) != \"\" : proxies . append ( line . split ( \"\" ) ) logging . info ( \"\" ) return proxies def get_next_available_proxy ( self ) : if self . proxy_pointer == ( self . number_of_proxies - ) : self . proxy_pointer = else : self . proxy_pointer = self . proxy_pointer + proxy = self . proxies [ self . proxy_pointer ] return { \"\" : proxy , \"\" : self . proxy_pointer } def remove_current_proxy ( self , index ) : del self . proxies [ index ] self . number_of_proxies -= class Proxy_Checker ( ) : Proxies = [ ] number_of_responses = working_proxies = @ staticmethod def check_proxies ( q , proxies ) : Proxy_Checker . number_of_responses = Proxy_Checker . number_of_unchecked_proxies = len ( proxies ) for i in range ( , Proxy_Checker . number_of_unchecked_proxies ) : IOLoop . instance ( ) . add_callback ( Proxy_Checker . handle_proxy_status , proxies [ i ] , i ) IOLoop . instance ( ) . start ( ) q . put ( Proxy_Checker . Proxies ) @ staticmethod @ gen . engine def handle_proxy_status ( proxy , i ) : request = HTTPRequest ( url = Proxy_manager . testing_url , proxy_host = proxy [ ] , proxy_port = int ( proxy [ ] ) , validate_cert = False ", "answer": ")"}, {"prompt": " class DummyPrefs : ", "answer": "graph_options = [ ] "}, {"prompt": " def got_reply ( srcip , srcport , mess , ch ) : print \"\" + mess + \"\" + srcip + \"\" + str ( srcport ) if callfunc == '' : if len ( callargs ) != : raise Exception ( \"\" ) recvmess ( getmyip ( ) , int ( callargs [ ] ) , got_reply ) sendmess ( callargs [ ] , int ( callargs [ ] ) , \"\" + getmyip ( ) + \"\" + str ( callargs [ ] ) , getmyip ( ) , int ( callargs [ ] ) ) ", "answer": "settimer ( , exitall , ( ) ) "}, {"prompt": " from raggregate . models import * import sqlalchemy from sqlalchemy import Column from sqlalchemy import UnicodeText from sqlalchemy import DateTime from sqlalchemy import ForeignKey from raggregate . guid_recipe import GUID import datetime class Notify ( Base ) : ", "answer": "__tablename__ = ''"}, {"prompt": " from datetime import datetime from django . conf import settings from django . contrib . auth . backends import RemoteUserBackend from django . contrib . auth . models import AnonymousUser , User from django . test import TestCase class RemoteUserTest ( TestCase ) : urls = '' middleware = '' backend = '' known_user = '' known_user2 = '' def setUp ( self ) : self . curr_middleware = settings . MIDDLEWARE_CLASSES self . curr_auth = settings . AUTHENTICATION_BACKENDS settings . MIDDLEWARE_CLASSES += ( self . middleware , ) settings . AUTHENTICATION_BACKENDS = ( self . backend , ) def test_no_remote_user ( self ) : \"\"\"\"\"\" num_users = User . objects . count ( ) response = self . client . get ( '' ) self . assert_ ( isinstance ( response . context [ '' ] , AnonymousUser ) ) self . assertEqual ( User . objects . count ( ) , num_users ) response = self . client . get ( '' , REMOTE_USER = None ) self . assert_ ( isinstance ( response . context [ '' ] , AnonymousUser ) ) self . assertEqual ( User . objects . count ( ) , num_users ) response = self . client . get ( '' , REMOTE_USER = '' ) self . assert_ ( isinstance ( response . context [ '' ] , AnonymousUser ) ) self . assertEqual ( User . objects . count ( ) , num_users ) def test_unknown_user ( self ) : \"\"\"\"\"\" num_users = User . objects . count ( ) response = self . client . get ( '' , REMOTE_USER = '' ) self . assertEqual ( response . context [ '' ] . username , '' ) self . assertEqual ( User . objects . count ( ) , num_users + ) User . objects . get ( username = '' ) response = self . client . get ( '' , REMOTE_USER = '' ) self . assertEqual ( User . objects . count ( ) , num_users + ) def test_known_user ( self ) : \"\"\"\"\"\" User . objects . create ( username = '' ) User . objects . create ( username = '' ) num_users = User . objects . count ( ) response = self . client . get ( '' , REMOTE_USER = self . known_user ) self . assertEqual ( response . context [ '' ] . username , '' ) self . assertEqual ( User . objects . count ( ) , num_users ) response = self . client . get ( '' , REMOTE_USER = self . known_user2 ) self . assertEqual ( response . context [ '' ] . username , '' ) self . assertEqual ( User . objects . count ( ) , num_users ) def test_last_login ( self ) : \"\"\"\"\"\" user = User . objects . create ( username = '' ) default_login = datetime ( , , ) user . last_login = default_login user . save ( ) response = self . client . get ( '' , REMOTE_USER = self . known_user ) self . assertNotEqual ( default_login , response . context [ '' ] . last_login ) user = User . objects . get ( username = '' ) user . last_login = default_login user . save ( ) response = self . client . get ( '' , REMOTE_USER = self . known_user ) self . assertEqual ( default_login , response . context [ '' ] . last_login ) def tearDown ( self ) : \"\"\"\"\"\" settings . MIDDLEWARE_CLASSES = self . curr_middleware settings . AUTHENTICATION_BACKENDS = self . curr_auth class RemoteUserNoCreateBackend ( RemoteUserBackend ) : \"\"\"\"\"\" create_unknown_user = False class RemoteUserNoCreateTest ( RemoteUserTest ) : \"\"\"\"\"\" backend = '' def test_unknown_user ( self ) : num_users = User . objects . count ( ) response = self . client . get ( '' , REMOTE_USER = '' ) self . assert_ ( isinstance ( response . context [ '' ] , AnonymousUser ) ) self . assertEqual ( User . objects . count ( ) , num_users ) class CustomRemoteUserBackend ( RemoteUserBackend ) : \"\"\"\"\"\" def clean_username ( self , username ) : \"\"\"\"\"\" return username . split ( '' ) [ ] def configure_user ( self , user ) : \"\"\"\"\"\" user . email = '' user . save ( ) return user class RemoteUserCustomTest ( RemoteUserTest ) : \"\"\"\"\"\" backend = '' known_user = '' known_user2 = '' def test_known_user ( self ) : \"\"\"\"\"\" super ( RemoteUserCustomTest , self ) . test_known_user ( ) self . assertEqual ( User . objects . get ( username = '' ) . email , '' ) ", "answer": "self . assertEqual ( User . objects . get ( username = '' ) . email , '' )"}, {"prompt": " from __future__ import ( absolute_import , division , generators , nested_scopes , print_function , unicode_literals , with_statement ) import sys v = sys . version_info print ( '' % v [ : ] ) ", "answer": "def say_hello ( ) :"}, {"prompt": " from __future__ import unicode_literals from django . db import models , migrations def migrate_invoiced ( apps , schema_editor ) : \"\"\"\"\"\" Event = apps . get_model ( '' , '' ) Event . objects . filter ( invoiced__isnull = True ) . update ( invoice_status = '' ) Event . objects . filter ( invoiced = True ) . update ( invoice_status = '' ) Event . objects . filter ( invoiced = False ) . update ( invoice_status = '' ) class Migration ( migrations . Migration ) : dependencies = [ ( '' , '' ) , ] operations = [ migrations . AddField ( model_name = '' , name = '' , ", "answer": "field = models . CharField ( verbose_name = '' , max_length = , default = '' , blank = True , choices = [ ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) ] ) ,"}, {"prompt": " from theano import tensor from theano . tensor . nnet import conv2d def weights_std ( weights , mask_outputs = None ) : positions = tensor . arange ( weights . shape [ ] ) expected = ( weights * positions ) . sum ( axis = ) expected2 = ( weights * positions ** ) . sum ( axis = ) result = ( expected2 - expected ** ) ** if mask_outputs : result *= mask_outputs return result . sum ( ) / weights . shape [ ] def monotonicity_penalty ( weights , mask_x = None ) : cumsums = tensor . cumsum ( weights , axis = ) penalties = tensor . maximum ( cumsums [ : ] - cumsums [ : - ] , ) . sum ( axis = ) if mask_x : penalties *= mask_x [ : ] return penalties . sum ( ) def entropy ( weights , mask_x ) : entropies = ( weights * tensor . log ( weights + ) ) . sum ( axis = ) entropies *= mask_x return entropies . sum ( ) def conv1d ( sequences , masks , ** kwargs ) : \"\"\"\"\"\" sequences = tensor . as_tensor_variable ( sequences ) masks = tensor . as_tensor_variable ( masks ) image = sequences . dimshuffle ( '' , '' , , ) filters = masks . dimshuffle ( , '' , '' , ) result = conv2d ( image , filters , ** kwargs ) result = result . dimshuffle ( , , , ) ", "answer": "return result . reshape ( result . shape [ : - ] , ndim = )"}, {"prompt": " import os pjoin = os . path . join from twisted . python import log from rce . util . process import execute _CONFIG_CGROUP = \"\"\"\"\"\" _CONFIG_CAP = \"\"\"\"\"\" _FSTAB_BASE = \"\"\"\"\"\" _FSTAB_BIND = \"\"\"\"\"\" class Container ( object ) : \"\"\"\"\"\" def __init__ ( self , reactor , rootfs , conf , hostname ) : \"\"\"\"\"\" self . _reactor = reactor self . _rootfs = rootfs self . _conf = pjoin ( conf , '' ) self . _fstab = pjoin ( conf , '' ) self . _hostname = hostname if not os . path . isabs ( conf ) : raise ValueError ( '' '' ) if not os . path . isdir ( conf ) : raise ValueError ( '' '' . format ( conf ) ) if os . path . exists ( self . _conf ) : raise ValueError ( '' \"\" . format ( conf ) ) if os . path . exists ( self . _fstab ) : raise ValueError ( '' \"\" . format ( conf ) ) self . _ifs = [ ] self . _fstabExt = [ ] def addNetworkInterface ( self , name , link = None , ip = None , up = None , down = None ) : \"\"\"\"\"\" if up : if not os . path . isabs ( up ) : raise ValueError ( '' ) if not os . path . isfile ( up ) : raise ValueError ( '' ) if not os . access ( up , os . X_OK ) : raise ValueError ( '' ) if down : if not os . path . isabs ( down ) : raise ValueError ( '' ) if not os . path . isfile ( down ) : raise ValueError ( '' ) if not os . access ( down , os . X_OK ) : raise ValueError ( '' ) self . _ifs . append ( ( name , link , ip , up , down ) ) def extendFstab ( self , src , fs , ro ) : \"\"\"\"\"\" dst = pjoin ( self . _rootfs , fs ) if not os . path . isabs ( src ) : raise ValueError ( '' ) if not os . path . exists ( src ) : raise ValueError ( '' ) if not os . path . exists ( dst ) : raise ValueError ( '' ) self . _fstabExt . append ( ( src , dst , ro ) ) def _setupFiles ( self ) : \"\"\"\"\"\" with open ( self . _conf , '' ) as f : f . write ( '' . format ( self . _hostname ) ) f . write ( '' ) f . write ( '' . format ( self . _rootfs ) ) ", "answer": "f . write ( '' . format ( self . _fstab ) )"}, {"prompt": " from pandas import compat from pandas . compat import PY3 import numpy as np from pandas import ( Series , Index , Float64Index , Int64Index , RangeIndex , MultiIndex , CategoricalIndex , DatetimeIndex , TimedeltaIndex , PeriodIndex ) from pandas . util . testing import assertRaisesRegexp import pandas . util . testing as tm import pandas as pd class Base ( object ) : \"\"\"\"\"\" _holder = None _compat_props = [ '' , '' , '' , '' , '' ] def setup_indices ( self ) : for name , idx in self . indices . items ( ) : setattr ( self , name , idx ) def verify_pickle ( self , index ) : unpickled = self . round_trip_pickle ( index ) self . assertTrue ( index . equals ( unpickled ) ) def test_pickle_compat_construction ( self ) : if self . _holder is None : return self . assertRaises ( TypeError , self . _holder ) def test_shift ( self ) : idx = self . create_index ( ) self . assertRaises ( NotImplementedError , idx . shift , ) self . assertRaises ( NotImplementedError , idx . shift , , ) def test_create_index_existing_name ( self ) : expected = self . create_index ( ) if not isinstance ( expected , MultiIndex ) : expected . name = '' result = pd . Index ( expected ) tm . assert_index_equal ( result , expected ) result = pd . Index ( expected , name = '' ) expected . name = '' tm . assert_index_equal ( result , expected ) else : expected . names = [ '' , '' ] result = pd . Index ( expected ) tm . assert_index_equal ( result , Index ( Index ( [ ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) ] , dtype = '' ) , names = [ '' , '' ] ) ) result = pd . Index ( expected , names = [ '' , '' ] ) tm . assert_index_equal ( result , Index ( Index ( [ ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) ] , dtype = '' ) , names = [ '' , '' ] ) ) def test_numeric_compat ( self ) : idx = self . create_index ( ) tm . assertRaisesRegexp ( TypeError , \"\" , lambda : idx * ) tm . assertRaisesRegexp ( TypeError , \"\" , lambda : * idx ) div_err = \"\" if PY3 else \"\" tm . assertRaisesRegexp ( TypeError , div_err , lambda : idx / ) tm . assertRaisesRegexp ( TypeError , div_err , lambda : / idx ) tm . assertRaisesRegexp ( TypeError , \"\" , lambda : idx // ) tm . assertRaisesRegexp ( TypeError , \"\" , lambda : // idx ) def test_logical_compat ( self ) : idx = self . create_index ( ) tm . assertRaisesRegexp ( TypeError , '' , lambda : idx . all ( ) ) tm . assertRaisesRegexp ( TypeError , '' , lambda : idx . any ( ) ) def test_boolean_context_compat ( self ) : idx = self . create_index ( ) def f ( ) : if idx : pass tm . assertRaisesRegexp ( ValueError , '' , f ) def test_reindex_base ( self ) : idx = self . create_index ( ) expected = np . arange ( idx . size ) actual = idx . get_indexer ( idx ) tm . assert_numpy_array_equal ( expected , actual ) with tm . assertRaisesRegexp ( ValueError , '' ) : idx . get_indexer ( idx , method = '' ) def test_ndarray_compat_properties ( self ) : idx = self . create_index ( ) self . assertTrue ( idx . T . equals ( idx ) ) self . assertTrue ( idx . transpose ( ) . equals ( idx ) ) values = idx . values for prop in self . _compat_props : self . assertEqual ( getattr ( idx , prop ) , getattr ( values , prop ) ) idx . nbytes idx . values . nbytes def test_repr_roundtrip ( self ) : idx = self . create_index ( ) tm . assert_index_equal ( eval ( repr ( idx ) ) , idx ) def test_str ( self ) : idx = self . create_index ( ) idx . name = '' self . assertTrue ( \"\" in str ( idx ) ) self . assertTrue ( idx . __class__ . __name__ in str ( idx ) ) def test_dtype_str ( self ) : for idx in self . indices . values ( ) : dtype = idx . dtype_str self . assertIsInstance ( dtype , compat . string_types ) if isinstance ( idx , PeriodIndex ) : self . assertEqual ( dtype , '' ) else : self . assertEqual ( dtype , str ( idx . dtype ) ) def test_repr_max_seq_item_setting ( self ) : idx = self . create_index ( ) idx = idx . repeat ( ) with pd . option_context ( \"\" , None ) : repr ( idx ) self . assertFalse ( '' in str ( idx ) ) def test_wrong_number_names ( self ) : def testit ( ind ) : ind . names = [ \"\" , \"\" , \"\" ] for ind in self . indices . values ( ) : assertRaisesRegexp ( ValueError , \"\" , testit , ind ) def test_set_name_methods ( self ) : new_name = \"\" for ind in self . indices . values ( ) : if isinstance ( ind , MultiIndex ) : continue original_name = ind . name new_ind = ind . set_names ( [ new_name ] ) self . assertEqual ( new_ind . name , new_name ) self . assertEqual ( ind . name , original_name ) res = ind . rename ( new_name , inplace = True ) self . assertIsNone ( res ) self . assertEqual ( ind . name , new_name ) self . assertEqual ( ind . names , [ new_name ] ) with assertRaisesRegexp ( ValueError , \"\" ) : ind . set_names ( \"\" , level = ) name = ( '' , '' ) ind . rename ( name , inplace = True ) self . assertEqual ( ind . name , name ) self . assertEqual ( ind . names , [ name ] ) def test_hash_error ( self ) : for ind in self . indices . values ( ) : with tm . assertRaisesRegexp ( TypeError , \"\" % type ( ind ) . __name__ ) : hash ( ind ) def test_copy_and_deepcopy ( self ) : from copy import copy , deepcopy for ind in self . indices . values ( ) : if isinstance ( ind , MultiIndex ) : continue for func in ( copy , deepcopy ) : idx_copy = func ( ind ) self . assertIsNot ( idx_copy , ind ) self . assertTrue ( idx_copy . equals ( ind ) ) new_copy = ind . copy ( deep = True , name = \"\" ) self . assertEqual ( new_copy . name , \"\" ) def test_duplicates ( self ) : for ind in self . indices . values ( ) : if not len ( ind ) : continue if isinstance ( ind , MultiIndex ) : continue idx = self . _holder ( [ ind [ ] ] * ) self . assertFalse ( idx . is_unique ) self . assertTrue ( idx . has_duplicates ) idx . name = '' result = idx . drop_duplicates ( ) self . assertEqual ( result . name , '' ) self . assert_index_equal ( result , Index ( [ ind [ ] ] , name = '' ) ) def test_sort ( self ) : for ind in self . indices . values ( ) : self . assertRaises ( TypeError , ind . sort ) def test_order ( self ) : for ind in self . indices . values ( ) : with tm . assert_produces_warning ( FutureWarning ) : ind . order ( ) def test_mutability ( self ) : for ind in self . indices . values ( ) : if not len ( ind ) : continue self . assertRaises ( TypeError , ind . __setitem__ , , ind [ ] ) def test_view ( self ) : for ind in self . indices . values ( ) : i_view = ind . view ( ) self . assertEqual ( i_view . name , ind . name ) def test_compat ( self ) : for ind in self . indices . values ( ) : self . assertEqual ( ind . tolist ( ) , list ( ind ) ) def test_argsort ( self ) : for k , ind in self . indices . items ( ) : if k in [ '' ] : continue result = ind . argsort ( ) expected = np . array ( ind ) . argsort ( ) tm . assert_numpy_array_equal ( result , expected ) def test_pickle ( self ) : for ind in self . indices . values ( ) : self . verify_pickle ( ind ) ind . name = '' self . verify_pickle ( ind ) def test_take ( self ) : indexer = [ , , , ] for k , ind in self . indices . items ( ) : if k in [ '' , '' , '' ] : continue result = ind . take ( indexer ) expected = ind [ indexer ] self . assertTrue ( result . equals ( expected ) ) if not isinstance ( ind , ( DatetimeIndex , PeriodIndex , TimedeltaIndex ) ) : with tm . assertRaises ( AttributeError ) : ind . freq def test_setops_errorcases ( self ) : for name , idx in compat . iteritems ( self . indices ) : cases = [ , '' ] methods = [ idx . intersection , idx . union , idx . difference , idx . symmetric_difference ] for method in methods : for case in cases : assertRaisesRegexp ( TypeError , \"\" , method , case ) def test_intersection_base ( self ) : for name , idx in compat . iteritems ( self . indices ) : first = idx [ : ] second = idx [ : ] intersect = first . intersection ( second ) if isinstance ( idx , CategoricalIndex ) : pass else : self . assertTrue ( tm . equalContents ( intersect , second ) ) cases = [ klass ( second . values ) for klass in [ np . array , Series , list ] ] for case in cases : if isinstance ( idx , PeriodIndex ) : msg = \"\" with tm . assertRaisesRegexp ( ValueError , msg ) : result = first . intersection ( case ) elif isinstance ( idx , CategoricalIndex ) : pass else : result = first . intersection ( case ) self . assertTrue ( tm . equalContents ( result , second ) ) if isinstance ( idx , MultiIndex ) : msg = \"\" with tm . assertRaisesRegexp ( TypeError , msg ) : result = first . intersection ( [ , , ] ) def test_union_base ( self ) : for name , idx in compat . iteritems ( self . indices ) : first = idx [ : ] second = idx [ : ] everything = idx union = first . union ( second ) self . assertTrue ( tm . equalContents ( union , everything ) ) cases = [ klass ( second . values ) for klass in [ np . array , Series , list ] ] for case in cases : if isinstance ( idx , PeriodIndex ) : msg = \"\" with tm . assertRaisesRegexp ( ValueError , msg ) : result = first . union ( case ) elif isinstance ( idx , CategoricalIndex ) : pass else : result = first . union ( case ) self . assertTrue ( tm . equalContents ( result , everything ) ) if isinstance ( idx , MultiIndex ) : msg = \"\" with tm . assertRaisesRegexp ( TypeError , msg ) : result = first . union ( [ , , ] ) def test_difference_base ( self ) : for name , idx in compat . iteritems ( self . indices ) : first = idx [ : ] second = idx [ : ] answer = idx [ : ] result = first . difference ( second ) if isinstance ( idx , CategoricalIndex ) : pass else : self . assertTrue ( tm . equalContents ( result , answer ) ) cases = [ klass ( second . values ) for klass in [ np . array , Series , list ] ] for case in cases : if isinstance ( idx , PeriodIndex ) : msg = \"\" with tm . assertRaisesRegexp ( ValueError , msg ) : result = first . difference ( case ) elif isinstance ( idx , CategoricalIndex ) : pass elif isinstance ( idx , ( DatetimeIndex , TimedeltaIndex ) ) : self . assertEqual ( result . __class__ , answer . __class__ ) tm . assert_numpy_array_equal ( result . asi8 , answer . asi8 ) else : result = first . difference ( case ) self . assertTrue ( tm . equalContents ( result , answer ) ) if isinstance ( idx , MultiIndex ) : msg = \"\" with tm . assertRaisesRegexp ( TypeError , msg ) : result = first . difference ( [ , , ] ) def test_symmetric_difference ( self ) : for name , idx in compat . iteritems ( self . indices ) : first = idx [ : ] second = idx [ : - ] if isinstance ( idx , CategoricalIndex ) : pass else : answer = idx [ [ , - ] ] result = first . symmetric_difference ( second ) self . assertTrue ( tm . equalContents ( result , answer ) ) cases = [ klass ( second . values ) for klass in [ np . array , Series , list ] ] for case in cases : if isinstance ( idx , PeriodIndex ) : msg = \"\" with tm . assertRaisesRegexp ( ValueError , msg ) : result = first . symmetric_difference ( case ) elif isinstance ( idx , CategoricalIndex ) : pass else : result = first . symmetric_difference ( case ) self . assertTrue ( tm . equalContents ( result , answer ) ) if isinstance ( idx , MultiIndex ) : msg = \"\" with tm . assertRaisesRegexp ( TypeError , msg ) : result = first . symmetric_difference ( [ , , ] ) with tm . assert_produces_warning ( FutureWarning ) : first . sym_diff ( second ) def test_insert_base ( self ) : for name , idx in compat . iteritems ( self . indices ) : result = idx [ : ] if not len ( idx ) : continue self . assertTrue ( idx [ : ] . equals ( result . insert ( , idx [ ] ) ) ) def test_delete_base ( self ) : for name , idx in compat . iteritems ( self . indices ) : if not len ( idx ) : continue if isinstance ( idx , RangeIndex ) : continue expected = idx [ : ] result = idx . delete ( ) self . assertTrue ( result . equals ( expected ) ) self . assertEqual ( result . name , expected . name ) expected = idx [ : - ] result = idx . delete ( - ) self . assertTrue ( result . equals ( expected ) ) self . assertEqual ( result . name , expected . name ) with tm . assertRaises ( ( IndexError , ValueError ) ) : result = idx . delete ( len ( idx ) ) def test_equals_op ( self ) : index_a = self . create_index ( ) if isinstance ( index_a , PeriodIndex ) : return n = len ( index_a ) index_b = index_a [ : - ] index_c = index_a [ : - ] . append ( index_a [ - : - ] ) index_d = index_a [ : ] with tm . assertRaisesRegexp ( ValueError , \"\" ) : index_a == index_b expected1 = np . array ( [ True ] * n ) expected2 = np . array ( [ True ] * ( n - ) + [ False ] ) ", "answer": "tm . assert_numpy_array_equal ( index_a == index_a , expected1 )"}, {"prompt": " \"\"\"\"\"\" from __future__ import unicode_literals , absolute_import from __future__ import print_function , division from topology . platforms . shell import PExpectShell , PExpectBashShell class DockerExecMixin ( object ) : \"\"\"\"\"\" def __init__ ( self , container , command , * args , ** kwargs ) : self . _container = container self . _command = command super ( DockerExecMixin , self ) . __init__ ( * args , ** kwargs ) def _get_connect_command ( self ) : return '' . format ( self . _container , self . _command ) class DockerShell ( DockerExecMixin , PExpectShell ) : \"\"\"\"\"\" ", "answer": "class DockerBashShell ( DockerExecMixin , PExpectBashShell ) :"}, {"prompt": " import sys import plyj . parser import plyj . model as m p = plyj . parser . Parser ( ) tree = p . parse_file ( sys . argv [ ] ) class MyVisitor ( m . Visitor ) : ", "answer": "def __init__ ( self ) :"}, {"prompt": " from django . template import loader , RequestContext from django . http import Http404 , HttpResponse from django . core . xheaders import populate_xheaders from django . core . paginator import Paginator , InvalidPage from django . core . exceptions import ObjectDoesNotExist import warnings warnings . warn ( '' , PendingDeprecationWarning ) def object_list ( request , queryset , paginate_by = None , page = None , allow_empty = True , template_name = None , template_loader = loader , extra_context = None , context_processors = None , template_object_name = '' , mimetype = None ) : \"\"\"\"\"\" if extra_context is None : extra_context = { } queryset = queryset . _clone ( ) if paginate_by : paginator = Paginator ( queryset , paginate_by , allow_empty_first_page = allow_empty ) if not page : page = request . GET . get ( '' , ) try : page_number = int ( page ) except ValueError : if page == '' : page_number = paginator . num_pages else : raise Http404 try : page_obj = paginator . page ( page_number ) except InvalidPage : raise Http404 c = RequestContext ( request , { '' % template_object_name : page_obj . object_list , '' : paginator , '' : page_obj , '' : page_obj . has_other_pages ( ) , '' : paginator . per_page , '' : page_obj . has_next ( ) , '' : page_obj . has_previous ( ) , '' : page_obj . number , '' : page_obj . next_page_number ( ) , '' : page_obj . previous_page_number ( ) , '' : page_obj . start_index ( ) , '' : page_obj . end_index ( ) , '' : paginator . num_pages , '' : paginator . count , '' : paginator . page_range , } , context_processors ) else : c = RequestContext ( request , { '' % template_object_name : queryset , '' : None , '' : None , '' : False , } , context_processors ) if not allow_empty and len ( queryset ) == : raise Http404 for key , value in extra_context . items ( ) : if callable ( value ) : c [ key ] = value ( ) else : c [ key ] = value if not template_name : model = queryset . model template_name = \"\" % ( model . _meta . app_label , model . _meta . object_name . lower ( ) ) t = template_loader . get_template ( template_name ) return HttpResponse ( t . render ( c ) , mimetype = mimetype ) def object_detail ( request , queryset , object_id = None , slug = None , slug_field = '' , template_name = None , template_name_field = None , template_loader = loader , extra_context = None , context_processors = None , template_object_name = '' , mimetype = None ) : \"\"\"\"\"\" if extra_context is None : extra_context = { } model = queryset . model if object_id : queryset = queryset . filter ( pk = object_id ) elif slug and slug_field : queryset = queryset . filter ( ** { slug_field : slug } ) else : raise AttributeError ( \"\" ) try : obj = queryset . get ( ) except ObjectDoesNotExist : raise Http404 ( \"\" % ( model . _meta . verbose_name ) ) if not template_name : template_name = \"\" % ( model . _meta . app_label , model . _meta . object_name . lower ( ) ) if template_name_field : ", "answer": "template_name_list = [ getattr ( obj , template_name_field ) , template_name ]"}, {"prompt": " import sys , os , arcpy , logging , logging . config , shutil , zipfile , glob , ckanclient , datetime , argparse , csv , re import xml . etree . ElementTree as et args = None logger = None output_folder = None source_feature_class = None staging_feature_class = None ckan_client = None temp_workspace = None available_formats = [ '' , '' , '' , '' , '' , '' ] outCoordSystem = \"\" geographicTransformation = '' def main ( ) : \"\"\"\"\"\" global args , output_folder , source_feature_class , staging_feature_class , temp_workspace , logger parser = argparse . ArgumentParser ( fromfile_prefix_chars = '' ) parser . add_argument ( '' , '' , action = '' , dest = '' , help = '' ) parser . add_argument ( '' , '' , action = '' , dest = '' , help = '' ) parser . add_argument ( '' , '' , action = '' , dest = '' , help = '' ) parser . add_argument ( '' , '' , action = '' , dest = '' , required = True , help = '' ) parser . add_argument ( '' , '' , action = '' , dest = '' , help = '' ) parser . add_argument ( '' , '' , action = '' , dest = '' , default = '' , help = '' ) parser . add_argument ( '' , '' , action = '' , dest = '' , default = '' , help = '' ) parser . add_argument ( '' , '' , action = '' , dest = '' , required = True , help = '' ) parser . add_argument ( '' , '' , action = '' , dest = '' , default = '' , help = '' ) parser . add_argument ( '' , '' , action = '' , dest = '' , default = '' , help = '' ) parser . add_argument ( '' , '' , action = '' , dest = '' , default = '' , help = '' ) parser . add_argument ( '' , '' , action = '' , dest = '' , default = '' , help = '' ) parser . add_argument ( '' , '' , action = '' , dest = '' , choices = [ '' , '' , '' , '' ] , default = '' , help = '' ) parser . add_argument ( '' , '' , action = '' , dest = '' , choices = [ '' , '' , '' ] , help = '' ) parser . add_argument ( '' , '' , action = '' , dest = '' , default = '' , help = '' ) parser . add_argument ( '' , '' , action = '' , dest = '' , choices = [ '' , '' , '' ] , default = '' , help = '' ) parser . add_argument ( '' , '' , action = '' , dest = '' , choices = [ '' , '' , '' , '' , '' , '' ] , default = '' , help = '' ) parser . add_argument ( '' , '' , action = '' , dest = '' , choices = [ '' , '' ] , default = '' , help = '' ) parser . add_argument ( '' , '' , action = '' , dest = '' , choices = [ '' , '' , '' , '' ] , default = '' , help = '' ) parser . add_argument ( '' , action = '' , help = '' ) parser . add_argument ( '' , action = '' , help = '' '' ) parser . add_argument ( '' , action = '' , help = '' '' ) args = parser . parse_args ( ) if args . output_folder != None : output_folder = args . output_folder . strip ( ) if args . temp_workspace != None : temp_workspace = args . temp_workspace . strip ( ) if args . source_workspace == None : source_feature_class = args . feature_class else : source_feature_class = os . path . join ( args . source_workspace , args . feature_class ) if args . formats == None : args . formats = available_formats else : args . formats = args . formats . split ( '' ) for arg in args . formats : if not arg in available_formats : raise Exception ( str . format ( \"\" , arg ) ) init_logger ( ) try : logger . info ( '' ) logger . info ( '' ) logger . info ( '' . format ( os . getcwd ( ) ) ) logger . info ( '' . format ( source_feature_class ) ) logger . info ( '' . format ( args . dataset_name ) ) logger . info ( '' . format ( output_folder ) ) logger . info ( '' . format ( args . exe_result ) ) logger . info ( '' . format ( str ( args . formats ) ) ) delete_dataset_temp_folder ( ) output_folder = create_dataset_folder ( ) temp_workspace = create_dataset_temp_folder ( ) if args . exe_result != '' : arcpy . env . outputCoordinateSystem = outCoordSystem arcpy . env . geographicTransformations = geographicTransformation if ( len ( args . formats ) > ) : logger . info ( '' ) staging_feature_class = export_file_geodatabase ( ) drop_exclude_fields ( ) export_metadata ( ) if '' in args . formats : try : logger . info ( '' ) export_shapefile ( ) except : if logger : logger . exception ( '' . format ( args . dataset_name , sys . exc_info ( ) [ ] , sys . exc_info ( ) [ ] ) ) if '' in args . formats : try : logger . info ( '' ) publish_metadata ( ) except : if logger : logger . exception ( '' . format ( args . dataset_name , sys . exc_info ( ) [ ] , sys . exc_info ( ) [ ] ) ) if '' in args . formats : try : logger . info ( '' ) publish_file_geodatabase ( ) except : if logger : logger . exception ( '' . format ( args . dataset_name , sys . exc_info ( ) [ ] , sys . exc_info ( ) [ ] ) ) if '' in args . formats : try : logger . info ( '' ) export_cad ( ) except : if logger : logger . exception ( '' . format ( args . dataset_name , sys . exc_info ( ) [ ] , sys . exc_info ( ) [ ] ) ) if '' in args . formats : try : logger . info ( '' ) export_kml ( ) except : if logger : logger . exception ( '' . format ( args . dataset_name , sys . exc_info ( ) [ ] , sys . exc_info ( ) [ ] ) ) if '' in args . formats : try : logger . info ( '' ) export_csv ( ) except : if logger : logger . exception ( '' . format ( args . dataset_name , sys . exc_info ( ) [ ] , sys . exc_info ( ) [ ] ) ) if args . exe_result != '' : remove_missing_formats_from_publication ( output_folder ) if len ( args . formats ) > : publish_to_ckan ( ) logger . info ( '' + args . dataset_name ) logger . info ( '' ) except : if logger : logger . exception ( '' . format ( args . dataset_name , sys . exc_info ( ) [ ] , sys . exc_info ( ) [ ] ) ) sys . exit ( ) def publish_to_ckan ( ) : \"\"\"\"\"\" global ckan_client ckan_client = ckanclient . CkanClient ( base_location = args . ckan_api , api_key = args . ckan_api_key ) dataset_id = args . ckan_dataset_name_prefix + args . dataset_name dataset_entity = get_remote_dataset ( dataset_id ) if dataset_entity is None : create_dataset ( dataset_id ) else : update_dataset ( dataset_entity ) if args . increment != '' : update_dataset_version ( ) def remove_missing_formats_from_publication ( directory ) : \"\"\"\"\"\" formats = [ ] for exp_format in args . formats : logger . debug ( '' . format ( exp_format ) ) exp_dir = None if exp_format == '' : exp_dir = '' elif exp_format == '' : exp_dir = '' else : exp_dir = exp_format exp_dir = os . path . join ( directory , exp_dir ) if os . path . exists ( exp_dir ) : formats . append ( exp_format ) args . formats = formats def create_folder ( directory , delete = False ) : \"\"\"\"\"\" if os . path . exists ( directory ) and delete : logger . debug ( '' + directory ) shutil . rmtree ( directory ) if not os . path . exists ( directory ) : logger . debug ( '' + directory + '' ) os . makedirs ( directory ) return directory def create_dataset_folder ( ) : \"\"\"\"\"\" directory = os . path . join ( output_folder , get_dataset_filename ( ) ) create_folder ( directory ) return directory def create_dataset_temp_folder ( ) : \"\"\"\"\"\" global temp_workspace directory = os . path . join ( temp_workspace , get_dataset_filename ( ) ) create_folder ( directory ) return directory def delete_dataset_temp_folder ( ) : \"\"\"\"\"\" global temp_workspace name = get_dataset_filename ( ) gdb_folder = os . path . join ( temp_workspace , '' ) gdb_file = os . path . join ( gdb_folder , name + '' ) logger . debug ( '' + gdb_file ) if os . path . exists ( gdb_file ) : arcpy . Delete_management ( gdb_file ) dataset_directory = os . path . join ( temp_workspace , name ) if os . path . exists ( dataset_directory ) : logger . debug ( '' + dataset_directory ) shutil . rmtree ( dataset_directory ) def publish_file ( directory , file_name , file_type ) : \"\"\"\"\"\" folder = create_folder ( os . path . join ( output_folder , file_type ) ) logger . info ( '' + file_name + '' + folder ) shutil . copyfile ( os . path . join ( directory , file_name ) , os . path . join ( folder , file_name ) ) def get_dataset_filename ( ) : \"\"\"\"\"\" global args return args . dataset_name . replace ( '' , '' ) def get_dataset_title ( ) : \"\"\"\"\"\" global args return args . ckan_dataset_title_prefix + '' + args . dataset_title def export_file_geodatabase ( ) : \"\"\"\"\"\" folder = '' name = get_dataset_filename ( ) temp_working_folder = os . path . join ( temp_workspace , folder ) create_folder ( temp_working_folder , True ) gdb_temp = os . path . join ( temp_working_folder , name + '' ) gdb_feature_class = os . path . join ( gdb_temp , name ) if not arcpy . Exists ( gdb_temp ) : logger . debug ( '' + args . gdb_version + '' + gdb_temp ) arcpy . CreateFileGDB_management ( os . path . dirname ( gdb_temp ) , os . path . basename ( gdb_temp ) , args . gdb_version ) logger . debug ( '' + source_feature_class ) logger . debug ( '' + gdb_feature_class ) arcpy . CopyFeatures_management ( source_feature_class , gdb_feature_class ) return gdb_feature_class def publish_file_geodatabase ( ) : \"\"\"\"\"\" folder = '' name = get_dataset_filename ( ) temp_working_folder = os . path . join ( temp_workspace , folder ) logger . debug ( '' ) zip_file_name = os . path . join ( temp_working_folder , name + '' ) zip_file = zipfile . ZipFile ( zip_file_name , '' ) gdb_file_name = os . path . join ( temp_working_folder , name + '' ) for filename in glob . glob ( gdb_file_name + '' ) : if ( not filename . endswith ( '' ) ) : zip_file . write ( filename , name + '' + os . path . basename ( filename ) , zipfile . ZIP_DEFLATED ) zip_file . close ( ) publish_file ( temp_working_folder , name + '' , '' ) def export_shapefile ( ) : \"\"\"\"\"\" folder = '' name = get_dataset_filename ( ) temp_working_folder = os . path . join ( temp_workspace , folder ) create_folder ( temp_working_folder , True ) zip_folder = os . path . join ( temp_working_folder , name ) create_folder ( zip_folder ) source = staging_feature_class destination = os . path . join ( zip_folder , name + '' ) logger . debug ( '' + source + '' + destination + '' ) arcpy . CopyFeatures_management ( source , destination , '' , '' , '' , '' ) logger . debug ( '' ) zip_file = zipfile . ZipFile ( os . path . join ( temp_working_folder , name + '' ) , '' ) for filename in glob . glob ( zip_folder + '' ) : zip_file . write ( filename , os . path . basename ( filename ) , zipfile . ZIP_DEFLATED ) zip_file . close ( ) publish_file ( temp_working_folder , name + '' , '' ) def export_cad ( ) : \"\"\"\"\"\" folder = '' name = get_dataset_filename ( ) temp_working_folder = os . path . join ( temp_workspace , folder ) create_folder ( temp_working_folder , True ) source = staging_feature_class destination = os . path . join ( temp_working_folder , name + '' ) logger . debug ( '' + source + '' + destination + '' ) arcpy . ExportCAD_conversion ( source , '' , destination , '' , '' , '' ) publish_file ( temp_working_folder , name + '' , '' ) def export_kml ( ) : \"\"\"\"\"\" arcpy . CheckOutExtension ( '' ) folder = '' name = get_dataset_filename ( ) temp_working_folder = os . path . join ( temp_workspace , folder ) create_folder ( temp_working_folder , True ) destination = os . path . join ( temp_working_folder , name + '' ) logger . debug ( '' + staging_feature_class + '' ) arcpy . MakeFeatureLayer_management ( staging_feature_class , name , '' , '' ) replace_literal_nulls ( name ) logger . debug ( '' + destination + '' ) arcpy . LayerToKML_conversion ( name , destination , '' , '' , '' , '' , '' ) logger . debug ( '' + name ) arcpy . Delete_management ( name ) publish_file ( temp_working_folder , name + '' , '' ) def export_metadata ( ) : \"\"\"\"\"\" folder = '' name = get_dataset_filename ( ) temp_working_folder = os . path . join ( temp_workspace , folder ) create_folder ( temp_working_folder , True ) source = staging_feature_class raw_metadata_export = os . path . join ( temp_working_folder , name + '' ) arcpy . env . workspace = temp_working_folder installDir = arcpy . GetInstallInfo ( '' ) [ '' ] translator = installDir + '' arcpy . ExportMetadata_conversion ( source , translator , raw_metadata_export ) destination = os . path . join ( temp_working_folder , name + '' ) if os . path . exists ( args . metadata_xslt ) : logger . info ( '' + args . metadata_xslt ) arcpy . XSLTransform_conversion ( raw_metadata_export , args . metadata_xslt , destination , '' ) logger . debug ( '' + destination ) arcpy . MetadataImporter_conversion ( destination , staging_feature_class ) else : logger . warn ( '' . format ( args . dataset_name ) ) os . rename ( raw_metadata_export , destination ) publish_file ( temp_working_folder , name + '' , '' ) def publish_metadata ( ) : \"\"\"\"\"\" folder = '' name = get_dataset_filename ( ) temp_working_folder = os . path . join ( temp_workspace , folder ) publish_file ( temp_working_folder , name + '' , '' ) def export_csv ( ) : \"\"\"\"\"\" folder = '' name = get_dataset_filename ( ) temp_working_folder = os . path . join ( temp_workspace , folder ) create_folder ( temp_working_folder , True ) source = staging_feature_class destination = os . path . join ( temp_working_folder , name + '' ) logger . debug ( '' + source + '' + destination + '' ) rows = arcpy . SearchCursor ( source ) csv_file = open ( destination , '' ) csv_writer = csv . writer ( csv_file ) fieldnames = [ f . name for f in arcpy . ListFields ( source ) ] if '' in fieldnames : fieldnames . remove ( '' ) if '' in fieldnames : fieldnames . remove ( '' ) csv_writer . writerow ( fieldnames ) error_report = '' error_count = for row in rows : values = [ ] for field in fieldnames : values . append ( row . getValue ( field ) ) try : csv_writer . writerow ( values ) except : error_count += error_report = '' . format ( error_report , values ) if logger : logger . debug ( '' . format ( args . dataset_name , sys . exc_info ( ) [ ] , sys . exc_info ( ) [ ] , values ) ) csv_file . close ( ) if error_count > : sys . exc_clear ( ) logger . exception ( '' . format ( args . dataset_name , error_report ) ) else : publish_file ( temp_working_folder , name + '' , '' ) def drop_exclude_fields ( ) : \"\"\"\"\"\" exclude_fields = args . exclude_fields if exclude_fields != None : logger . info ( '' + exclude_fields ) exclude_fields = exclude_fields . replace ( '' , '' ) arcpy . DeleteField_management ( staging_feature_class , exclude_fields ) def replace_literal_nulls ( layer_name ) : \"\"\"\"\"\" logger . debug ( '' ) fields , row , rows = None , None , None try : fields = arcpy . ListFields ( layer_name ) rows = arcpy . UpdateCursor ( layer_name ) for row in rows : for field in fields : if field . type == '' : value = row . getValue ( field . name ) if ( value != None ) : if ( value . find ( '' ) > - ) : logger . debug ( '' . format ( field . name ) ) logger . debug ( '' ) row . setValue ( field . name , None ) logger . debug ( '' . format ( value ) ) rows . updateRow ( row ) logger . debug ( '' . format ( layer_name ) ) finally : if row : del row if rows : del rows def get_remote_dataset ( dataset_id ) : \"\"\"\"\"\" dataset_entity = None try : dataset_entity = ckan_client . package_entity_get ( dataset_id ) logger . info ( '' + dataset_id + '' ) except ckanclient . CkanApiNotFoundError : logger . info ( '' + dataset_id + '' ) return dataset_entity def create_dataset ( dataset_id ) : \"\"\"\"\"\" ", "answer": "dataset_entity = create_local_dataset ( dataset_id )"}, {"prompt": " \"\"\"\"\"\" from zope . interface import Interface , Attribute from twisted . internet . interfaces import IPushProducer from twisted . cred . credentials import IUsernameDigestHash class IRequest ( Interface ) : \"\"\"\"\"\" method = Attribute ( \"\" ) uri = Attribute ( \"\" \"\" ) path = Attribute ( \"\" ) args = Attribute ( \"\" \"\" \"\" \"\" \"\" ) received_headers = Attribute ( \"\" \"\" \"\" ) requestHeaders = Attribute ( \"\" \"\" ) headers = Attribute ( \"\" \"\" \"\" \"\" ) responseHeaders = Attribute ( \"\" ", "answer": "\"\" )"}, {"prompt": " from mozdns . utils import slim_form from base . base . views import BaseListView , BaseDetailView , BaseCreateView from base . base . views import BaseUpdateView , BaseDeleteView class MozdnsListView ( BaseListView ) : \"\"\"\"\"\" template_name = '' class MozdnsDetailView ( BaseDetailView ) : \"\"\"\"\"\" template_name = '' class MozdnsCreateView ( BaseCreateView ) : \"\"\"\"\"\" template_name = '' def get_form ( self , form_class ) : form = super ( MozdnsCreateView , self ) . get_form ( form_class ) domain_pk = self . kwargs . get ( '' , False ) if domain_pk : form = slim_form ( domain_pk = domain_pk , form = form ) reverse_domain_pk = self . kwargs . get ( '' , False ) if reverse_domain_pk : slim_form ( reverse_domain_pk = reverse_domain_pk , form = form ) \"\"\"\"\"\" remove_message = unicode ( '' '' ) for field in form . fields : if field in form . base_fields : if form . base_fields [ field ] . help_text : new_text = form . base_fields [ field ] . help_text . replace ( remove_message , '' ) new_text = new_text . strip ( ) form . base_fields [ field ] . help_text = new_text return form class MozdnsUpdateView ( BaseUpdateView ) : template_name = '' def get_form ( self , form_class ) : form = super ( MozdnsUpdateView , self ) . get_form ( form_class ) \"\"\"\"\"\" remove_message = unicode ( '' '' ) for field in form . fields : if field in form . base_fields : if form . base_fields [ field ] . help_text : new_text = form . base_fields [ field ] . help_text . replace ( remove_message , '' ) new_text = new_text . strip ( ) form . base_fields [ field ] . help_text = new_text return form class MozdnsDeleteView ( BaseDeleteView ) : \"\"\"\"\"\" template_name = '' ", "answer": "succcess_url = '' "}, {"prompt": " import sys import os sys . path . insert ( , os . path . abspath ( '' ) ) extensions = [ '' , ] templates_path = [ '' ] source_suffix = '' master_doc = '' project = u'' copyright = u'' version = '' release = '' exclude_patterns = [ ] pygments_style = '' html_theme = '' html_static_path = [ '' ] htmlhelp_basename = '' ", "answer": "latex_elements = {"}, {"prompt": " from vispy . gloo import util from vispy . testing import run_tests_if_main , assert_raises def test_check_enum ( ) : from vispy . gloo import gl assert util . check_enum ( gl . GL_RGB ) == '' assert util . check_enum ( gl . GL_TRIANGLE_STRIP ) == '' assert util . check_enum ( '' ) == '' assert util . check_enum ( '' ) == '' assert_raises ( ValueError , util . check_enum , int ( gl . GL_RGB ) ) assert_raises ( ValueError , util . check_enum , int ( gl . GL_TRIANGLE_STRIP ) ) ", "answer": "assert_raises ( ValueError , util . check_enum , [ ] )"}, {"prompt": " import numpy as np import copy from . . io . pick import _pick_data_channels from . . viz . decoding import plot_gat_matrix , plot_gat_times from . . parallel import parallel_func , check_n_jobs from . . utils import warn , check_version class _DecodingTime ( dict ) : \"\"\"\"\"\" def __repr__ ( self ) : s = \"\" if \"\" in self : s += \"\" % ( self [ \"\" ] ) if \"\" in self : s += \"\" % ( self [ \"\" ] ) if \"\" in self : s += \"\" % ( self [ \"\" ] ) if \"\" in self : s += \"\" % ( self [ \"\" ] ) if \"\" in self : depth = [ len ( ii ) for ii in self [ \"\" ] ] if len ( np . unique ( depth ) ) == : if depth [ ] == : s += \"\" % ( len ( depth ) ) else : s += \"\" % ( len ( depth ) , depth [ ] ) else : s += ( \"\" % ( len ( depth ) , min ( [ len ( ii ) for ii in depth ] ) , max ( ( [ len ( ii ) for ii in depth ] ) ) ) ) return \"\" % s class _GeneralizationAcrossTime ( object ) : \"\"\"\"\"\" def __init__ ( self , picks = None , cv = , clf = None , train_times = None , test_times = None , predict_method = '' , predict_mode = '' , scorer = None , n_jobs = ) : from sklearn . preprocessing import StandardScaler from sklearn . linear_model import LogisticRegression from sklearn . pipeline import Pipeline self . cv = cv self . train_times = ( _DecodingTime ( ) if train_times is None else _DecodingTime ( train_times ) ) if test_times is None : self . test_times = _DecodingTime ( ) elif test_times == '' : self . test_times = '' else : self . test_times = _DecodingTime ( test_times ) if clf is None : scaler = StandardScaler ( ) estimator = LogisticRegression ( ) clf = Pipeline ( [ ( '' , scaler ) , ( '' , estimator ) ] ) self . clf = clf self . predict_mode = predict_mode self . scorer = scorer self . picks = picks self . predict_method = predict_method self . n_jobs = n_jobs def fit ( self , epochs , y = None ) : \"\"\"\"\"\" from sklearn . base import clone for att in [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ] : if hasattr ( self , att ) : delattr ( self , att ) n_jobs = self . n_jobs X , y , self . picks_ = _check_epochs_input ( epochs , y , self . picks ) self . ch_names = [ epochs . ch_names [ p ] for p in self . picks_ ] self . cv_ , self . _cv_splits = _set_cv ( self . cv , clf = self . clf , X = X , y = y ) self . y_train_ = y self . train_times_ = _sliding_window ( epochs . times , self . train_times , epochs . info [ '' ] ) parallel , p_func , n_jobs = parallel_func ( _fit_slices , n_jobs ) n_chunks = min ( len ( self . train_times_ [ '' ] ) , n_jobs ) time_chunks = np . array_split ( self . train_times_ [ '' ] , n_chunks ) out = parallel ( p_func ( clone ( self . clf ) , X [ ... , np . unique ( np . concatenate ( time_chunk ) ) ] , y , time_chunk , self . _cv_splits ) for time_chunk in time_chunks ) self . estimators_ = sum ( out , list ( ) ) return self def predict ( self , epochs ) : \"\"\"\"\"\" if not hasattr ( self . clf , self . predict_method ) : raise NotImplementedError ( '' % ( self . clf , self . predict_method ) ) if not hasattr ( self , '' ) : raise RuntimeError ( '' ) if self . predict_mode not in [ '' , '' ] : raise ValueError ( '' '' ) if self . predict_mode == '' : n_est_cv = [ len ( estimator ) for estimator in self . estimators_ ] heterogeneous_cv = len ( set ( n_est_cv ) ) != mismatch_cv = n_est_cv [ ] != len ( self . _cv_splits ) mismatch_y = len ( self . y_train_ ) != len ( epochs ) if heterogeneous_cv or mismatch_cv or mismatch_y : raise ValueError ( '' '' ) for att in [ '' , '' , '' , '' , '' ] : if hasattr ( self , att ) : delattr ( self , att ) _warn_once . clear ( ) X , y , _ = _check_epochs_input ( epochs , None , self . picks_ ) if not np . all ( [ len ( test ) for train , test in self . _cv_splits ] ) : warn ( '' ) if self . test_times == '' : test_times = _DecodingTime ( ) test_times [ '' ] = [ [ s ] for s in self . train_times_ [ '' ] ] test_times [ '' ] = [ [ s ] for s in self . train_times_ [ '' ] ] elif isinstance ( self . test_times , dict ) : test_times = copy . deepcopy ( self . test_times ) else : raise ValueError ( '' ) if '' not in test_times : if '' not in self . train_times_ . keys ( ) : ValueError ( '' ) ", "answer": "test_times [ '' ] = test_times . get ( '' ,"}, {"prompt": " from pims . api import * from . _version import get_versions __version__ = get_versions ( ) [ '' ] ", "answer": "del get_versions "}, {"prompt": " \"\"\"\"\"\" from sympy . physics . mechanics import dynamicsymbols , MechanicsStrPrinter from sympy . physics . mechanics import ReferenceFrame , Point from sympy import solve , symbols def msprint ( expr ) : pr = MechanicsStrPrinter ( ) return pr . doprint ( expr ) q0 , q1 , q2 = dynamicsymbols ( '' ) q0d , q1d , q2d = dynamicsymbols ( '' , level = ) u1 , u2 , u3 = dynamicsymbols ( '' ) LA , LB , LP = symbols ( '' ) p1 , p2 , p3 = symbols ( '' ) E = ReferenceFrame ( '' ) A = E . orientnew ( '' , '' , [ q0 , E . x ] ) B = A . orientnew ( '' , '' , [ q1 , A . y ] ) C = B . orientnew ( '' , '' , [ , B . x ] ) D = C . orientnew ( '' , '' , [ , C . x ] ) pO = Point ( '' ) pAs = pO . locatenew ( '' , LA * A . z ) pP = pO . locatenew ( '' , LP * A . z ) pBs = pP . locatenew ( '' , LB * B . z ) ", "answer": "pCs = pBs . locatenew ( '' , q2 * B . z )"}, {"prompt": " from health_messages import Health_Message as HM import health_protocol as HP import ipaddr import psutil import sys import subprocess from hardware import matcher import re from commands import getstatusoutput as cmd import threading from sets import Set import os def is_in_network ( left , right ) : '' return ipaddr . IPv4Address ( left ) in ipaddr . IPv4Network ( right ) def get_multiple_values ( hw , level1 , level2 , level3 ) : result = [ ] temp_level2 = level2 for entry in hw : if level2 == '' : temp_level2 = entry [ ] if ( level1 == entry [ ] and temp_level2 == entry [ ] and level3 == entry [ ] ) : result . append ( entry [ ] ) return result def get_value ( hw_ , level1 , level2 , level3 ) : for entry in hw_ : if ( level1 == entry [ ] and level2 == entry [ ] and level3 == entry [ ] ) : return entry [ ] return None def fatal_error ( error ) : '''''' HP . logger . error ( '' % error ) sys . exit ( ) def run_sysbench_cpu ( hw_ , max_time , cpu_count , processor_num = - ) : '' taskset = '' if ( processor_num < ) : sys . stderr . write ( '' '' % ( max_time , cpu_count ) ) else : sys . stderr . write ( '' % ( processor_num , max_time , cpu_count ) ) taskset = '' % hex ( << processor_num ) cmds = '' '' % ( taskset , max_time , cpu_count ) sysbench_cmd = subprocess . Popen ( cmds , shell = True , stdout = subprocess . PIPE ) for line in sysbench_cmd . stdout : if \"\" in line . decode ( ) : title , perf = line . decode ( ) . rstrip ( '' ) . replace ( '' , '' ) . split ( '' ) if processor_num == - : hw_ . append ( ( '' , '' , '' , str ( int ( perf ) / max_time ) ) ) else : hw_ . append ( ( '' , '' % processor_num , '' , str ( int ( perf ) / max_time ) ) ) def get_available_memory ( ) : try : return psutil . virtual_memory ( ) . total except Exception : return psutil . avail_phymem ( ) def check_mem_size ( block_size , cpu_count ) : dsplit = re . compile ( r'' ) ssplit = re . compile ( r'' ) unit = ssplit . findall ( block_size ) unit_in_bytes = if unit [ ] == '' : unit_in_bytes = elif unit [ ] == '' : unit_in_bytes = * elif unit [ ] == '' : unit_in_bytes = * * size_in_bytes = unit_in_bytes * int ( dsplit . findall ( block_size ) [ ] ) * cpu_count if ( size_in_bytes > get_available_memory ( ) ) : return False return True def stop_netservers ( message ) : sys . stderr . write ( '' ) status , output = cmd ( '' ) def start_bench_server ( message , port_number ) : sys . stderr . write ( '' % ( message . my_peer_name , port_number ) ) status , output = cmd ( '' % port_number ) def get_my_ip_port ( message ) : return get_ip_port ( message , message . my_peer_name ) def get_ip_port ( message , ip ) : port_number = for host in message . peer_servers : if host [ ] == ip : port_number = message . ports_list [ host [ ] ] break return port_number def start_netservers ( message ) : threads = { } sys . stderr . write ( '' % ( len ( message . peer_servers ) - ) ) for server in message . peer_servers : if message . my_peer_name != server [ ] : port_number = get_ip_port ( message , server [ ] ) sys . stderr . write ( \"\" % ( message . my_peer_name , port_number , server [ ] ) ) threads [ port_number ] = threading . Thread ( target = start_bench_server , args = tuple ( [ message , port_number ] ) ) threads [ port_number ] . start ( ) def add_netperf_suboption ( sub_options , value ) : if len ( sub_options ) == : sub_options = \"\" return \"\" % ( sub_options , value ) def start_bench_client ( ip , port , message ) : netperf_mode = \"\" unit = \"\" sub_options = \"\" if message . network_test == HM . BANDWIDTH : netperf_mode = \"\" unit = \"\" if message . block_size != \"\" : sub_options = add_netperf_suboption ( sub_options , \"\" % ( message . block_size , message . block_size ) ) if message . network_connection == HM . UDP : netperf_mode = \"\" elif message . network_test == HM . LATENCY : netperf_mode = \"\" if message . network_connection == HM . UDP : netperf_mode = \"\" sys . stderr . write ( \"\" % ( netperf_mode , message . my_peer_name , ip , port ) ) cmd_netperf = subprocess . Popen ( '' % ( message . running_time , ip , port , netperf_mode , unit , sub_options ) , shell = True , stdout = subprocess . PIPE ) return_code = cmd_netperf . wait ( ) if return_code == : for line in cmd_netperf . stdout : stop = Set ( [ '' , '' , '' , '' , '' , '' ] ) current = Set ( line . split ( ) ) if current . intersection ( stop ) : continue elif ( len ( line . split ( ) ) < ) : continue else : if message . network_test == HM . BANDWIDTH : message . hw . append ( ( '' , '' , '' % ( ip , port ) , str ( line . split ( ) [ ] ) ) ) elif message . network_test == HM . LATENCY : message . hw . append ( ( '' , '' , '' % ( ip , port ) , str ( line . split ( ) [ ] ) ) ) else : sys . stderr . write ( \"\" % cmd_netperf . returncode ) for line in cmd_netperf . stdout : sys . stderr . write ( line ) def run_network_bench ( message ) : run_netperf ( message ) def run_netperf ( message ) : threads = { } nb = sys . stderr . write ( '' % ( message . network_test , message . block_size , message . running_time ) ) for server in message . peer_servers : if message . my_peer_name == server [ ] : continue threads [ nb ] = threading . Thread ( target = start_bench_client , args = [ server [ ] , get_my_ip_port ( message ) , message ] ) threads [ nb ] . start ( ) nb += sys . stderr . write ( '' % nb ) for i in range ( nb ) : threads [ i ] . join ( ) def run_sysbench_memory ( message ) : if message . mode == HM . FORKED : run_sysbench_memory_forked ( message . hw , message . running_time , message . block_size , message . cpu_instances ) else : run_sysbench_memory_threaded ( message . hw , message . running_time , message . block_size , message . cpu_instances ) def run_sysbench_memory_threaded ( hw_ , max_time , block_size , cpu_count , processor_num = - ) : '' check_mem = check_mem_size ( block_size , cpu_count ) taskset = '' if ( processor_num < ) : if check_mem is False : msg = ( \"\" \"\" ) sys . stderr . write ( msg % block_size ) return sys . stderr . write ( '' '' % ( block_size , max_time , cpu_count ) ) else : if check_mem is False : msg = ( \"\" \"\" ) sys . stderr . write ( msg % ( block_size , processor_num ) ) return sys . stderr . write ( '' '' % ( block_size , processor_num , max_time , cpu_count ) ) taskset = '' % hex ( << processor_num ) _cmd = '' '' sysbench_cmd = subprocess . Popen ( _cmd % ( taskset , max_time , cpu_count , block_size ) , shell = True , stdout = subprocess . PIPE ) for line in sysbench_cmd . stdout : if \"\" in line : title , right = line . rstrip ( '' ) . replace ( '' , '' ) . split ( '' ) perf , useless = right . split ( '' ) if processor_num == - : hw_ . append ( ( '' , '' , '' % block_size , perf ) ) else : hw_ . append ( ( '' , '' % processor_num , '' % block_size , perf ) ) def run_sysbench_memory_forked ( hw_ , max_time , block_size , cpu_count ) : '' if check_mem_size ( block_size , cpu_count ) is False : cmd = '' '' sys . stderr . write ( cmd % ( block_size , cpu_count ) ) return sys . stderr . write ( '' '' % ( block_size , max_time , cpu_count ) ) sysbench_cmd = '' for cpu in range ( cpu_count ) : _cmd = '' '' sysbench_cmd += _cmd % ( max_time , block_size ) sysbench_cmd . rstrip ( '' ) sysbench_cmd += '' global_perf = process = subprocess . Popen ( sysbench_cmd , shell = True , stdout = subprocess . PIPE ) for line in process . stdout : if \"\" in line : title , right = line . rstrip ( '' ) . replace ( '' , '' ) . split ( '' ) perf , useless = right . split ( '' ) global_perf += int ( perf ) hw_ . append ( ( '' , '' , '' % ( block_size ) , str ( global_perf ) ) ) def generate_filename_and_macs ( items ) : '''''' hw_items = list ( items ) sysvars = { } ", "answer": "sysvars [ '' ] = ''"}, {"prompt": " import random from oslo_config import cfg from oslo_db import exception as db_exc from oslo_log import log from neutron . _i18n import _LE from neutron . common import exceptions as exc from neutron . common import utils from neutron . plugins . common import utils as p_utils from neutron . plugins . ml2 import driver_api as api LOG = log . getLogger ( __name__ ) IDPOOL_SELECT_SIZE = class BaseTypeDriver ( api . TypeDriver ) : \"\"\"\"\"\" def __init__ ( self ) : try : self . physnet_mtus = utils . parse_mappings ( cfg . CONF . ml2 . physical_network_mtus , unique_values = False ) except Exception as e : LOG . error ( _LE ( \"\" ) , e ) self . physnet_mtus = [ ] def get_mtu ( self , physical_network = None ) : return p_utils . get_deployment_physnet_mtu ( ) class SegmentTypeDriver ( BaseTypeDriver ) : \"\"\"\"\"\" def __init__ ( self , model ) : super ( SegmentTypeDriver , self ) . __init__ ( ) self . model = model self . primary_keys = set ( dict ( model . __table__ . columns ) ) self . primary_keys . remove ( \"\" ) def allocate_fully_specified_segment ( self , session , ** raw_segment ) : \"\"\"\"\"\" network_type = self . get_type ( ) try : with session . begin ( subtransactions = True ) : alloc = ( session . query ( self . model ) . filter_by ( ** raw_segment ) . first ( ) ) if alloc : if alloc . allocated : return else : LOG . debug ( \"\" \"\" , { \"\" : network_type , \"\" : raw_segment } ) count = ( session . query ( self . model ) . filter_by ( allocated = False , ** raw_segment ) . update ( { \"\" : True } ) ) if count : LOG . debug ( \"\" \"\" , { \"\" : network_type , \"\" : raw_segment } ) return alloc LOG . debug ( \"\" \"\" \"\" , { \"\" : network_type , \"\" : raw_segment } ) LOG . debug ( \"\" , { \"\" : network_type , \"\" : raw_segment } ) alloc = self . model ( allocated = True , ** raw_segment ) alloc . save ( session ) LOG . debug ( \"\" , { \"\" : network_type , \"\" : raw_segment } ) except db_exc . DBDuplicateEntry : alloc = None LOG . debug ( \"\" , { \"\" : network_type , \"\" : raw_segment } ) return alloc def allocate_partially_specified_segment ( self , session , ** filters ) : \"\"\"\"\"\" network_type = self . get_type ( ) with session . begin ( subtransactions = True ) : select = ( session . query ( self . model ) . filter_by ( allocated = False , ** filters ) ) allocs = select . limit ( IDPOOL_SELECT_SIZE ) . all ( ) if not allocs : return alloc = random . choice ( allocs ) raw_segment = dict ( ( k , alloc [ k ] ) for k in self . primary_keys ) LOG . debug ( \"\" \"\" , { \"\" : network_type , \"\" : raw_segment } ) count = ( session . query ( self . model ) . filter_by ( allocated = False , ** raw_segment ) . update ( { \"\" : True } ) ) if count : ", "answer": "LOG . debug ( \"\""}, {"prompt": " from __future__ import unicode_literals from future . builtins import str as _str from collections import defaultdict from importlib import import_module from django . apps import apps from django . utils . module_loading import module_has_submodule from mezzanine . pages . models import Page from mezzanine . utils . importing import get_app_name_list processors = defaultdict ( list ) def processor_for ( content_model_or_slug , exact_page = False ) : \"\"\"\"\"\" content_model = None slug = \"\" if isinstance ( content_model_or_slug , ( str , _str ) ) : try : parts = content_model_or_slug . split ( \"\" , ) content_model = apps . get_model ( * parts ) except ( TypeError , ValueError , LookupError ) : slug = content_model_or_slug elif issubclass ( content_model_or_slug , Page ) : content_model = content_model_or_slug else : raise TypeError ( \"\" \"\" \"\" % content_model_or_slug ) def decorator ( func ) : parts = ( func , exact_page ) if content_model : model_name = content_model . _meta . object_name . lower ( ) processors [ model_name ] . insert ( , parts ) else : processors [ \"\" % slug ] . insert ( , parts ) return func return decorator LOADED = False def autodiscover ( ) : \"\"\"\"\"\" global LOADED if LOADED : return LOADED = True for app in get_app_name_list ( ) : try : module = import_module ( app ) except ImportError : pass else : try : import_module ( \"\" % app ) ", "answer": "except :"}, {"prompt": " \"\"\"\"\"\" from __future__ import division import operator import numpy as np from . import csareader as csar from . dwiparams import B2q , nearest_pos_semi_def , q2bg from . . openers import ImageOpener from . . onetime import setattr_on_read as one_time from . . pydicom_compat import pydicom class WrapperError ( Exception ) : pass class WrapperPrecisionError ( WrapperError ) : pass def wrapper_from_file ( file_like , * args , ** kwargs ) : \"\"\"\"\"\" from . . pydicom_compat import read_file with ImageOpener ( file_like ) as fobj : dcm_data = read_file ( fobj , * args , ** kwargs ) return wrapper_from_data ( dcm_data ) def wrapper_from_data ( dcm_data ) : \"\"\"\"\"\" sop_class = dcm_data . get ( '' ) if sop_class == '' : return MultiframeWrapper ( dcm_data ) csa = csar . get_csa_header ( dcm_data ) if csa is None : return Wrapper ( dcm_data ) if csar . is_mosaic ( csa ) : return MosaicWrapper ( dcm_data , csa ) return SiemensWrapper ( dcm_data , csa ) class Wrapper ( object ) : \"\"\"\"\"\" is_csa = False is_mosaic = False is_multiframe = False b_matrix = None q_vector = None b_value = None b_vector = None def __init__ ( self , dcm_data ) : \"\"\"\"\"\" self . dcm_data = dcm_data @ one_time def image_shape ( self ) : \"\"\"\"\"\" shape = ( self . get ( '' ) , self . get ( '' ) ) if None in shape : return None return shape @ one_time def image_orient_patient ( self ) : \"\"\"\"\"\" iop = self . get ( '' ) if iop is None : return None iop = np . array ( list ( map ( float , iop ) ) ) return np . array ( iop ) . reshape ( , ) . T @ one_time def slice_normal ( self ) : iop = self . image_orient_patient if iop is None : return None return np . cross ( iop [ : , ] , iop [ : , ] ) @ one_time def rotation_matrix ( self ) : \"\"\"\"\"\" iop = self . image_orient_patient s_norm = self . slice_normal if iop is None or s_norm is None : return None R = np . eye ( ) R [ : , : ] = np . fliplr ( iop ) R [ : , ] = s_norm if not np . allclose ( np . eye ( ) , np . dot ( R , R . T ) , atol = ) : raise WrapperPrecisionError ( '' '' ) return R @ one_time def voxel_sizes ( self ) : \"\"\"\"\"\" pix_space = self . get ( '' ) if pix_space is None : return None zs = self . get ( '' ) if zs is None : zs = self . get ( '' ) if zs is None : zs = zs = float ( zs ) pix_space = list ( map ( float , pix_space ) ) return tuple ( pix_space + [ zs ] ) @ one_time def image_position ( self ) : \"\"\"\"\"\" ipp = self . get ( '' ) if ipp is None : return None return np . array ( list ( map ( float , ipp ) ) ) @ one_time def slice_indicator ( self ) : \"\"\"\"\"\" ipp = self . image_position s_norm = self . slice_normal if ipp is None or s_norm is None : return None return np . inner ( ipp , s_norm ) @ one_time def instance_number ( self ) : \"\"\"\"\"\" return self . get ( '' ) @ one_time def series_signature ( self ) : \"\"\"\"\"\" signature = { } eq = operator . eq for key in ( '' , '' , '' , '' , '' ) : signature [ key ] = ( self . get ( key ) , eq ) signature [ '' ] = ( self . image_shape , eq ) signature [ '' ] = ( self . image_orient_patient , none_or_close ) signature [ '' ] = ( self . voxel_sizes , none_or_close ) return signature def __getitem__ ( self , key ) : \"\"\"\"\"\" if key not in self . dcm_data : raise KeyError ( '' % key ) return self . dcm_data . get ( key ) def get ( self , key , default = None ) : \"\"\"\"\"\" return self . dcm_data . get ( key , default ) def get_affine ( self ) : \"\"\"\"\"\" ", "answer": "orient = self . rotation_matrix"}, {"prompt": " \"\"\"\"\"\" import re from pygments . lexer import RegexLexer , ExtendedRegexLexer , include , bygroups , default , using from pygments . token import Text , Comment , Operator , Keyword , Name , String , Punctuation from pygments . util import looks_like_xml , html_doctype_matches from pygments . lexers . javascript import JavascriptLexer from pygments . lexers . jvm import ScalaLexer from pygments . lexers . css import CssLexer , _indentation , _starts_block from pygments . lexers . ruby import RubyLexer __all__ = [ '' , '' , '' , '' , '' , '' , '' ] class HtmlLexer ( RegexLexer ) : \"\"\"\"\"\" name = '' aliases = [ '' ] filenames = [ '' , '' , '' , '' ] mimetypes = [ '' , '' ] flags = re . IGNORECASE | re . DOTALL tokens = { '' : [ ( '' , Text ) , ( r'' , Name . Entity ) , ( r'' , Comment . Preproc ) , ( '' , Comment , '' ) , ( r'' , Comment . Preproc ) , ( '' , Comment . Preproc ) , ( r'' , Name . Tag , ( '' , '' ) ) , ( r'' , Name . Tag , ( '' , '' ) ) , ( r'' , Name . Tag , '' ) , ( r'' , Name . Tag ) , ] , '' : [ ( '' , Comment ) , ( '' , Comment , '' ) , ( '' , Comment ) , ] , '' : [ ( r'' , Text ) , ( r'' , bygroups ( Name . Attribute , Text ) , '' ) , ( r'' , Name . Attribute ) , ( r'' , Name . Tag , '' ) , ] , '' : [ ( r'' , Name . Tag , '' ) , ( r'' , using ( JavascriptLexer ) ) , ] , '' : [ ( r'' , Name . Tag , '' ) , ( r'' , using ( CssLexer ) ) , ] , '' : [ ( '' , String , '' ) , ( \"\" , String , '' ) , ( r'' , String , '' ) , ] , } def analyse_text ( text ) : if html_doctype_matches ( text ) : return class DtdLexer ( RegexLexer ) : \"\"\"\"\"\" flags = re . MULTILINE | re . DOTALL name = '' aliases = [ '' ] filenames = [ '' ] mimetypes = [ '' ] tokens = { '' : [ include ( '' ) , ( r'' , bygroups ( Keyword , Text , Name . Tag ) , '' ) , ( r'' , bygroups ( Keyword , Text , Name . Tag ) , '' ) , ( r'' , bygroups ( Keyword , Text , Name . Entity ) , '' ) , ( r'' , bygroups ( Keyword , Text , Name . Tag ) , '' ) , ( r'' , bygroups ( Keyword , Name . Entity , Text , Keyword ) ) , ( r'' , bygroups ( Keyword , Text , Name . Tag ) ) , ( r'' , Keyword . Constant ) , ( r'' , Keyword ) , ] , '' : [ ( r'' , Text ) , ( r'' , Name . Entity ) , ( '' , Comment , '' ) , ( r'' , Operator ) , ( r'' , String . Double ) , ( r'' , String . Single ) , ] , '' : [ ( '' , Comment ) , ( '' , Comment , '' ) , ( '' , Comment ) , ] , '' : [ include ( '' ) , ( r'' , Keyword . Constant ) , ( r'' , Name . Tag ) , ( r'>' , Keyword , '' ) , ] , '' : [ include ( '' ) , ( r'' , Keyword . Constant ) , ( r'' , Keyword . Constant ) , ( r'' , Keyword . Reserved ) , ( r'' , Name . Attribute ) , ( r'>' , Keyword , '' ) , ] , '' : [ include ( '' ) , ( r'' , Keyword . Constant ) , ( r'' , Name . Entity ) , ( r'>' , Keyword , '' ) , ] , '' : [ include ( '' ) , ( r'' , Keyword . Constant ) , ( r'' , Name . Attribute ) , ( r'>' , Keyword , '' ) , ] , } def analyse_text ( text ) : if not looks_like_xml ( text ) and ( '' in text or '' in text or '' in text ) : return class XmlLexer ( RegexLexer ) : \"\"\"\"\"\" flags = re . MULTILINE | re . DOTALL | re . UNICODE name = '' aliases = [ '' ] filenames = [ '' , '' , '' , '' , '' , '' , '' ] mimetypes = [ '' , '' , '' , '' , '' ] tokens = { '' : [ ( '' , Text ) , ( r'' , Name . Entity ) , ( r'' , Comment . Preproc ) , ( '' , Comment , '' ) , ( r'' , Comment . Preproc ) , ( '' , Comment . Preproc ) , ( r'' , Name . Tag , '' ) , ( r'' , Name . Tag ) , ] , '' : [ ( '' , Comment ) , ( '' , Comment , '' ) , ( '' , Comment ) , ] , '' : [ ( r'' , Text ) , ( r'' , Name . Attribute , '' ) , ( r'' , Name . Tag , '' ) , ] , '' : [ ( '' , Text ) , ( '' , String , '' ) , ( \"\" , String , '' ) , ( r'' , String , '' ) , ] , } def analyse_text ( text ) : if looks_like_xml ( text ) : return class XsltLexer ( XmlLexer ) : \"\"\"\"\"\" name = '' aliases = [ '' ] filenames = [ '' , '' , '' ] mimetypes = [ '' , '' ] EXTRA_KEYWORDS = set ( ( '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ) ) def get_tokens_unprocessed ( self , text ) : for index , token , value in XmlLexer . get_tokens_unprocessed ( self , text ) : m = re . match ( '' , value ) if token is Name . Tag and m and m . group ( ) in self . EXTRA_KEYWORDS : yield index , Keyword , value else : yield index , token , value def analyse_text ( text ) : if looks_like_xml ( text ) and '' in text : return class HamlLexer ( ExtendedRegexLexer ) : \"\"\"\"\"\" name = '' aliases = [ '' ] filenames = [ '' ] mimetypes = [ '' ] flags = re . IGNORECASE _dot = r'' _comma_dot = r'' + _dot + '' tokens = { '' : [ ( r'' , Text ) , ( r'' , _indentation ) , ] , '' : [ ( r'' , Name . Class , '' ) , ( r'' , Name . Function , '' ) , ] , '' : [ ( r'' , Punctuation , '' ) , ( r'' + _comma_dot + r'' , bygroups ( Punctuation , using ( RubyLexer ) ) , '' ) , default ( '' ) , ] , '' : [ include ( '' ) , ( r'' , Name . Tag , '' ) , ( r'' + _dot + r'' , Name . Namespace , '' ) , ( r'' + _dot + '' + _dot + r'' , bygroups ( Comment , Comment . Special , Comment ) , '' ) , ( r'' + _dot + r'' , _starts_block ( Comment , '' ) , '' ) , ( r'' + _dot + r'' , _starts_block ( Comment . Preproc , '' ) , '' ) , ( r'' + _comma_dot + r'' , bygroups ( Punctuation , using ( RubyLexer ) ) , '' ) , ( r'' + _dot + r'' , _starts_block ( Name . Decorator , '' ) , '' ) , include ( '' ) , ] , '' : [ include ( '' ) , ( r'' + _dot + '' , using ( RubyLexer ) ) , ( r'' + _dot + '' , using ( RubyLexer ) ) , ( r'' , Text , '' ) , ( r'' , Punctuation , '' ) , ( r'' , Punctuation ) , include ( '' ) , ] , '' : [ ( r'' , Text ) , ( r'' + _dot + '' , bygroups ( String . Interpol , using ( RubyLexer ) , String . Interpol ) ) , ( r'' , Text , '' ) , ] , '' : [ ( r'' , Text ) , ( r'' , Name . Attribute , '' ) , ( r'' , Name . Attribute ) , ( r'' , Text , '' ) , ] , '' : [ ( r'' , Text ) , ( r'' , Name . Variable , '' ) , ( r'' , Name . Variable . Instance , '' ) , ( r'' , Name . Variable . Global , '' ) , ( r\"\" , String , '' ) , ( r'' , String , '' ) , ] , '' : [ ( _dot + '' , Comment ) , ( r'' , Text , '' ) , ] , '' : [ ( _dot + '' , Comment . Preproc ) , ( r'' , Text , '' ) , ] , '' : [ ( r'' , Name . Decorator ) , ( r'' + _dot + '' , bygroups ( String . Interpol , using ( RubyLexer ) , String . Interpol ) ) , ( r'' , Text , '' ) , ] , } class ScamlLexer ( ExtendedRegexLexer ) : \"\"\"\"\"\" name = '' aliases = [ '' ] filenames = [ '' ] mimetypes = [ '' ] flags = re . IGNORECASE _dot = r'' tokens = { '' : [ ( r'' , Text ) , ( r'' , _indentation ) , ] , '' : [ ( r'' , Name . Class , '' ) , ( r'' , Name . Function , '' ) , ] , '' : [ ( r'' , Punctuation , '' ) , ( r'' + _dot + r'' , bygroups ( Punctuation , using ( ScalaLexer ) ) , '' ) , default ( '' ) , ] , '' : [ include ( '' ) , ( r'' , Name . Tag , '' ) , ( r'' + _dot + r'' , Name . Namespace , '' ) , ( r'' + _dot + '' + _dot + r'' , bygroups ( Comment , Comment . Special , Comment ) , '' ) , ( r'' + _dot + r'' , _starts_block ( Comment , '' ) , '' ) , ( r'' + _dot + r'' , _starts_block ( Comment . Preproc , '' ) , '' ) , ( r'' + _dot + r'' , bygroups ( Punctuation , Keyword , using ( ScalaLexer ) ) , '' ) , ( r'' + _dot + r'' , bygroups ( Punctuation , using ( ScalaLexer ) ) , '' ) , ( r'' + _dot + r'' , _starts_block ( Name . Decorator , '' ) , '' ) , include ( '' ) , ] , '' : [ include ( '' ) , ( r'' + _dot + '' , using ( ScalaLexer ) ) , ( r'' + _dot + '' , using ( ScalaLexer ) ) , ( r'' , Text , '' ) , ( r'' , Punctuation , '' ) , ( r'' , Punctuation ) , include ( '' ) , ] , '' : [ ( r'' , Text ) , ( r'' + _dot + '' , bygroups ( String . Interpol , using ( ScalaLexer ) , String . Interpol ) ) , ( r'' , Text , '' ) , ] , '' : [ ( r'' , Text ) , ( r'' , Name . Attribute , '' ) , ( r'' , Name . Attribute ) , ( r'' , Text , '' ) , ] , '' : [ ( r'' , Text ) , ( r'' , Name . Variable , '' ) , ( r'' , Name . Variable . Instance , '' ) , ( r'' , Name . Variable . Global , '' ) , ( r\"\" , String , '' ) , ( r'' , String , '' ) , ] , '' : [ ( _dot + '' , Comment ) , ( r'' , Text , '' ) , ] , '' : [ ( _dot + '' , Comment . Preproc ) , ( r'' , Text , '' ) , ] , '' : [ ( r'' , Name . Decorator ) , ( r'' + _dot + '' , bygroups ( String . Interpol , using ( ScalaLexer ) , String . Interpol ) ) , ( r'' , Text , '' ) , ] , } class JadeLexer ( ExtendedRegexLexer ) : \"\"\"\"\"\" name = '' aliases = [ '' ] filenames = [ '' ] mimetypes = [ '' ] flags = re . IGNORECASE _dot = r'' tokens = { '' : [ ( r'' , Text ) , ( r'' , _indentation ) , ] , '' : [ ( r'' , Name . Class , '' ) , ( r'' , Name . Function , '' ) , ] , '' : [ ( r'' , Punctuation , '' ) , ( r'' + _dot + r'' , bygroups ( Punctuation , using ( ScalaLexer ) ) , '' ) , default ( '' ) , ] , '' : [ include ( '' ) , ( r'' + _dot + r'' , Name . Namespace , '' ) , ( r'' + _dot + '' + _dot + r'' , bygroups ( Comment , Comment . Special , Comment ) , '' ) , ( r'' + _dot + r'' , _starts_block ( Comment , '' ) , '' ) , ( r'' + _dot + r'' , _starts_block ( Comment . Preproc , '' ) , '' ) , ( r'' + _dot + r'' , bygroups ( Punctuation , Keyword , using ( ScalaLexer ) ) , '' ) , ( r'' + _dot + r'' , bygroups ( Punctuation , using ( ScalaLexer ) ) , '' ) , ( r'' + _dot + r'' , _starts_block ( Name . Decorator , '' ) , '' ) , ( r'' , Name . Tag , '' ) , ( r'' , Text , '' ) , ] , '' : [ include ( '' ) , ( r'' + _dot + '' , using ( ScalaLexer ) ) , ( r'' + _dot + '' , using ( ScalaLexer ) ) , ( r'' , Text , '' ) , ( r'' , Punctuation , '' ) , ( r'' , Punctuation ) , include ( '' ) , ] , '' : [ ", "answer": "( r'' , Text ) ,"}, {"prompt": " from datetime import datetime import logging import re from nameparser import HumanName from openelex . base . transform import Transform , registry from openelex . models import Candidate , Contest , Office , Party , RawResult , Result from openelex . lib . text import ocd_type_id from openelex . lib . insertbuffer import BulkInsertBuffer logging . basicConfig ( level = logging . INFO ) logger = logging . getLogger ( __name__ ) meta_fields = [ '' , '' , '' , ] contest_fields = meta_fields + [ '' , '' , '' , '' , '' , '' , ] candidate_fields = meta_fields + [ '' , '' , '' , '' ] result_fields = meta_fields + [ '' , '' , '' , '' , '' ] STATE = '' class BaseTransform ( Transform ) : \"\"\"\"\"\" PARTY_MAP = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' } district_offices = set ( [ '' , '' , '' , '' , ] ) def __init__ ( self ) : super ( BaseTransform , self ) . __init__ ( ) self . _office_cache = { } self . _party_cache = { } self . _contest_cache = { } def get_raw_results ( self ) : return RawResult . objects . filter ( state = STATE ) . no_cache ( ) def get_contest_fields ( self , raw_result ) : fields = self . _get_fields ( raw_result , contest_fields ) fields [ '' ] = self . _get_office ( raw_result ) return fields def _get_fields ( self , raw_result , field_names ) : return { k : getattr ( raw_result , k ) for k in field_names } def _get_office ( self , raw_result ) : office_query = { '' : STATE , '' : self . _clean_office ( raw_result . office ) } if office_query [ '' ] is '' : office_query [ '' ] = '' if office_query [ '' ] in self . district_offices : office_query [ '' ] = raw_result . district or '' key = Office . make_key ( ** office_query ) try : return self . _office_cache [ key ] except KeyError : try : office = Office . objects . get ( ** office_query ) assert key == office . key self . _office_cache [ key ] = office return office except Office . DoesNotExist : logger . error ( \"\" . format ( office_query ) ) raise def get_party ( self , raw_result , attr = '' ) : party = getattr ( raw_result , attr ) if not party : return None clean_abbrev = self . _clean_party ( party ) if not clean_abbrev : return None try : return self . _party_cache [ clean_abbrev ] except KeyError : try : party = Party . objects . get ( abbrev = clean_abbrev ) self . _party_cache [ clean_abbrev ] = party return party except Party . DoesNotExist : logger . error ( \"\" . format ( clean_abbrev ) ) raise def _clean_party ( self , party ) : try : return self . PARTY_MAP [ party ] except KeyError : return None def _clean_office ( self , office ) : \"\"\"\"\"\" presidential_regex = re . compile ( '' , re . IGNORECASE ) senate_regex = re . compile ( '' , re . IGNORECASE ) house_regex = re . compile ( '' , re . IGNORECASE ) governor_regex = re . compile ( '' , re . IGNORECASE ) treasurer_regex = re . compile ( '' , re . IGNORECASE ) auditor_regex = re . compile ( '' , re . IGNORECASE ) sos_regex = re . compile ( '' , re . IGNORECASE ) lt_gov_regex = re . compile ( r'' , re . IGNORECASE ) ospi_regex = re . compile ( '' , re . IGNORECASE ) ag_regex = re . compile ( '' , re . IGNORECASE ) wcpl_regex = re . compile ( '' , re . IGNORECASE ) local_regex = re . compile ( r'' '' , re . IGNORECASE ) national_regex = re . compile ( r'' , re . IGNORECASE ) if re . search ( house_regex , office ) : if re . search ( national_regex , office ) : return '' elif re . search ( local_regex , office ) : return '' else : return None elif re . search ( governor_regex , office ) : return '' elif re . search ( wcpl_regex , office ) : return '' elif re . search ( senate_regex , office ) : if re . search ( national_regex , office ) : return '' elif re . search ( local_regex , office ) : return '' else : return None elif re . search ( lt_gov_regex , office ) : return '' elif re . search ( ospi_regex , office ) : return '' elif re . search ( sos_regex , office ) : return '' elif re . search ( treasurer_regex , office ) : return '' elif re . search ( auditor_regex , office ) : return '' elif re . search ( ag_regex , office ) : return '' elif re . search ( presidential_regex , office ) : return '' else : return None def get_candidate_fields ( self , raw_result ) : year = raw_result . end_date . year fields = self . _get_fields ( raw_result , candidate_fields ) try : name = HumanName ( raw_result . full_name ) except TypeError : name = HumanName ( \"\" . format ( raw_result . given_name , raw_result . family_name ) ) fields [ '' ] = name . first fields [ '' ] = name . last if not fields [ '' ] : fields [ '' ] = \"\" . format ( name . first , name . last ) try : fields [ '' ] = name . middle fields [ '' ] = name . suffix except Exception , e : logger . error ( e ) return fields def get_contest ( self , raw_result ) : \"\"\"\"\"\" key = \"\" % ( raw_result . election_id , raw_result . contest_slug ) try : return self . _contest_cache [ key ] except KeyError : fields = self . get_contest_fields ( raw_result ) fields . pop ( '' ) try : try : contest = Contest . objects . filter ( ** fields ) [ ] except IndexError : contest = Contest . objects . get ( ** fields ) except Exception : print fields print \"\" raise self . _contest_cache [ key ] = contest return contest class CreateContestsTransform ( BaseTransform ) : name = '' def __call__ ( self ) : contests = [ ] seen = set ( ) for result in self . get_raw_results ( ) : key = self . _contest_key ( result ) if key not in seen : fields = self . get_contest_fields ( result ) fields [ '' ] = fields [ '' ] = datetime . now ( ) ", "answer": "contest = Contest ( ** fields )"}, {"prompt": " from wx . lib . embeddedimage import PyEmbeddedImage retriever_logo_liberation = PyEmbeddedImage ( \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" ", "answer": "\"\""}, {"prompt": " \"\"\"\"\"\" from __future__ import print_function from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals import os import sys import gzip import shutil import logging import tempfile import tuf import tuf . hash import tuf . conf import tuf . formats import six HASH_FUNCTION = '' logger = logging . getLogger ( '' ) class TempFile ( object ) : \"\"\"\"\"\" def _default_temporary_directory ( self , prefix ) : \"\"\"\"\"\" try : self . temporary_file = tempfile . NamedTemporaryFile ( prefix = prefix ) except OSError as err : logger . critical ( '' + repr ( err ) ) raise tuf . Error ( err ) def __init__ ( self , prefix = '' ) : \"\"\"\"\"\" self . _compression = None self . _orig_file = None temp_dir = tuf . conf . temporary_directory if temp_dir is not None and tuf . formats . PATH_SCHEMA . matches ( temp_dir ) : try : self . temporary_file = tempfile . NamedTemporaryFile ( prefix = prefix , dir = temp_dir ) except OSError as err : logger . error ( '' + temp_dir + '' + repr ( err ) ) logger . error ( '' ) self . _default_temporary_directory ( prefix ) else : self . _default_temporary_directory ( prefix ) def get_compressed_length ( self ) : \"\"\"\"\"\" return os . stat ( self . temporary_file . name ) . st_size def flush ( self ) : \"\"\"\"\"\" self . temporary_file . flush ( ) def read ( self , size = None ) : \"\"\"\"\"\" if size is None : self . temporary_file . seek ( ) data = self . temporary_file . read ( ) self . temporary_file . seek ( ) return data else : if not ( isinstance ( size , int ) and size > ) : raise tuf . FormatError return self . temporary_file . read ( size ) def write ( self , data , auto_flush = True ) : \"\"\"\"\"\" self . temporary_file . write ( data ) if auto_flush : self . flush ( ) def move ( self , destination_path ) : \"\"\"\"\"\" self . flush ( ) self . seek ( ) destination_file = open ( destination_path , '' ) shutil . copyfileobj ( self . temporary_file , destination_file ) destination_file . close ( ) self . close_temp_file ( ) def seek ( self , * args ) : \"\"\"\"\"\" self . temporary_file . seek ( * args ) def decompress_temp_file_object ( self , compression ) : \"\"\"\"\"\" tuf . formats . NAME_SCHEMA . check_match ( compression ) if self . _orig_file is not None : raise tuf . Error ( '' ) if compression != '' : raise tuf . Error ( '' ) self . seek ( ) self . _compression = compression self . _orig_file = self . temporary_file try : gzip_file_object = gzip . GzipFile ( fileobj = self . temporary_file , mode = '' ) uncompressed_content = gzip_file_object . read ( ) self . temporary_file = tempfile . NamedTemporaryFile ( ) self . temporary_file . write ( uncompressed_content ) self . flush ( ) except Exception as exception : raise tuf . DecompressionError ( exception ) def close_temp_file ( self ) : \"\"\"\"\"\" self . temporary_file . close ( ) if self . _orig_file is not None : self . _orig_file . close ( ) def get_file_details ( filepath , hash_algorithms = [ '' ] ) : \"\"\"\"\"\" tuf . formats . PATH_SCHEMA . check_match ( filepath ) tuf . formats . HASHALGORITHMS_SCHEMA . check_match ( hash_algorithms ) file_hashes = { } if not os . path . exists ( filepath ) : raise tuf . Error ( '' + repr ( filepath ) + '' ) filepath = os . path . abspath ( filepath ) file_length = os . path . getsize ( filepath ) for algorithm in hash_algorithms : digest_object = tuf . hash . digest_filename ( filepath , algorithm ) file_hashes . update ( { algorithm : digest_object . hexdigest ( ) } ) tuf . formats . HASHDICT_SCHEMA . check_match ( file_hashes ) return file_length , file_hashes def ensure_parent_dir ( filename ) : \"\"\"\"\"\" tuf . formats . PATH_SCHEMA . check_match ( filename ) directory = os . path . split ( filename ) [ ] if directory and not os . path . exists ( directory ) : os . makedirs ( directory , ) def file_in_confined_directories ( filepath , confined_directories ) : \"\"\"\"\"\" tuf . formats . RELPATH_SCHEMA . check_match ( filepath ) tuf . formats . RELPATHS_SCHEMA . check_match ( confined_directories ) for confined_directory in confined_directories : if confined_directory == '' : return True filepath = os . path . normpath ( filepath ) confined_directory = os . path . normpath ( confined_directory ) if os . path . dirname ( filepath ) == confined_directory : return True return False def find_delegated_role ( roles , delegated_role ) : \"\"\"\"\"\" tuf . formats . ROLELIST_SCHEMA . check_match ( roles ) tuf . formats . ROLENAME_SCHEMA . check_match ( delegated_role ) role_index = None for index in six . moves . xrange ( len ( roles ) ) : role = roles [ index ] name = role . get ( '' ) if name is None : no_name_message = '' raise tuf . RepositoryError ( no_name_message ) else : if name == delegated_role : if role_index is None : role_index = index else : duplicate_role_message = '' + str ( delegated_role ) + '' raise tuf . RepositoryError ( duplicate_role_message ) else : logger . debug ( '' + repr ( delegated_role ) ) return role_index def ensure_all_targets_allowed ( rolename , list_of_targets , parent_delegations ) : \"\"\"\"\"\" tuf . formats . ROLENAME_SCHEMA . check_match ( rolename ) tuf . formats . RELPATHS_SCHEMA . check_match ( list_of_targets ) tuf . formats . DELEGATIONS_SCHEMA . check_match ( parent_delegations ) if rolename == '' : return roles = parent_delegations [ '' ] role_index = find_delegated_role ( roles , rolename ) if role_index is not None : role = roles [ role_index ] allowed_child_paths = role . get ( '' ) allowed_child_path_hash_prefixes = role . get ( '' ) actual_child_targets = list_of_targets if allowed_child_path_hash_prefixes is not None : consistent = paths_are_consistent_with_hash_prefixes if not consistent ( actual_child_targets , allowed_child_path_hash_prefixes ) : message = repr ( rolename ) + '' + '' raise tuf . ForbiddenTargetError ( message ) elif allowed_child_paths is not None : ", "answer": "for child_target in actual_child_targets :"}, {"prompt": " imports = [ \"\" , \"\" , \"\" , ", "answer": "\"\" ,"}, {"prompt": " import time import logging import requests import simplejson as json from datadog . api . exceptions import ClientError , ApiError , HttpBackoff , HttpTimeout , ApiNotInitialized from datadog . api import _api_version , _max_timeouts , _backoff_period from datadog . util . compat import is_p3k log = logging . getLogger ( '' ) class HTTPClient ( object ) : \"\"\"\"\"\" _backoff_period = _backoff_period _max_timeouts = _max_timeouts _backoff_timestamp = None _timeout_counter = _api_version = _api_version @ classmethod def request ( cls , method , path , body = None , attach_host_name = False , response_formatter = None , error_formatter = None , ** params ) : \"\"\"\"\"\" try : if not cls . _should_submit ( ) : raise HttpBackoff ( \"\" . format ( * cls . _backoff_status ( ) ) ) from datadog . api import _api_key , _application_key , _api_host , _mute , _host_name , _proxies , _max_retries , _timeout , _cacert if _api_key is None : raise ApiNotInitialized ( \"\" \"\" ) params [ '' ] = _api_key if _application_key : params [ '' ] = _application_key url = \"\" % ( _api_host , cls . _api_version , path . lstrip ( \"\" ) ) if attach_host_name and body : if '' in body : for obj_params in body [ '' ] : if obj_params . get ( '' , \"\" ) == \"\" : obj_params [ '' ] = _host_name else : if body . get ( '' , \"\" ) == \"\" : body [ '' ] = _host_name if '' in params and isinstance ( params [ '' ] , list ) : params [ '' ] = '' . join ( params [ '' ] ) headers = { } if isinstance ( body , dict ) : body = json . dumps ( body ) headers [ '' ] = '' start_time = time . time ( ) try : s = requests . Session ( ) http_adapter = requests . adapters . HTTPAdapter ( max_retries = _max_retries ) s . mount ( '' , http_adapter ) result = s . request ( method , url , headers = headers , params = params , data = body , timeout = _timeout , proxies = _proxies , verify = _cacert ) result . raise_for_status ( ) except requests . ConnectionError as e : raise ClientError ( \"\" % ( method , _api_host , url , e ) ) ", "answer": "except requests . exceptions . Timeout as e :"}, {"prompt": " \"\"\"\"\"\" import os from django import forms from django . conf import settings from django . utils . translation import ugettext_lazy from . . lib import events from modoboa . lib import parameters from modoboa . lib . form_utils import YesNoField , SeparatorField from modoboa . lib . sysutils import exec_cmd ADMIN_EVENTS = [ \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ] class AdminParametersForm ( parameters . AdminParametersForm ) : app = \"\" ", "answer": "mbsep = SeparatorField ( label = ugettext_lazy ( \"\" ) )"}, {"prompt": " import select import socket import sys import Queue ", "answer": "server = socket . socket ( socket . AF_INET , socket . SOCK_STREAM )"}, {"prompt": " from optparse import make_option from django . core . management . base import BaseCommand , CommandError from data_set_manager . single_file_column_parser import SingleFileColumnParser from data_set_manager . tasks import create_dataset class Command ( BaseCommand ) : help = ( \"\" \"\" ) option_list = BaseCommand . option_list + ( make_option ( '' , action = '' , type = '' , help = '' ) , make_option ( '' , action = '' , type = '' , help = '' ) , make_option ( '' , action = '' , type = '' , help = '' ) , make_option ( '' , action = '' , type = '' , default = \"\" , help = '' '' ) , make_option ( '' , action = '' , type = '' , ", "answer": "default = None ,"}, {"prompt": " import time import numpy as N import numpy . random from traits . api import Int , Constant , Range , Property , cached_property from traitsui . api import View , Item , HGroup , VGroup , Label from Camera import Camera class DummyGaussian ( Camera ) : plugin_info = { '' : '' , '' : '' , '' : '' , '' : '' , } _zero = Constant ( ) _x_resolution = Property ( fget = lambda self : self . resolution [ ] , depends_on = '' ) _y_resolution = Property ( fget = lambda self : self . resolution [ ] , depends_on = '' ) _half_x_resolution = Property ( depends_on = '' ) _half_y_resolution = Property ( depends_on = '' ) _half_minimum_resolution = Property ( depends_on = '' ) centroid_x = Range ( '' , '' , '' ) centroid_y = Range ( '' , '' , '' ) centroid = Property ( depends_on = '' ) radius = Range ( '' , '' , ) amplitude = Int ( ) noise_amplitude = Int ( ) view = View ( HGroup ( Item ( '' , style = '' ) , Label ( '' ) ) , VGroup ( Item ( '' ) , Item ( '' ) ) , Item ( '' ) , Item ( '' ) , Item ( '' ) , title = '' ) def __init__ ( self , ** traits ) : super ( DummyGaussian , self ) . __init__ ( resolution = ( , ) , id_string = '' , ** traits ) self . _supported_resolutions = [ ( , ) , ( , ) ] @ cached_property def _get__half_x_resolution ( self ) : return self . resolution [ ] / @ cached_property def _get__half_y_resolution ( self ) : ", "answer": "return self . resolution [ ] / "}, {"prompt": " import os import pdb import sys import tempfile sys . path . append ( \"\" ) ", "answer": "from translator . toscalib . tosca_template import ToscaTemplate"}, {"prompt": " from casuarius import Solver , medium class LayoutManager ( object ) : \"\"\"\"\"\" def __init__ ( self ) : self . _solver = Solver ( autosolve = False ) self . _initialized = False self . _running = False def initialize ( self , constraints ) : \"\"\"\"\"\" if self . _initialized : raise RuntimeError ( '' ) solver = self . _solver solver . autosolve = False for cn in constraints : solver . add_constraint ( cn ) solver . autosolve = True self . _initialized = True def replace_constraints ( self , old_cns , new_cns ) : \"\"\"\"\"\" if not self . _initialized : raise RuntimeError ( '' ) solver = self . _solver solver . autosolve = False for cn in old_cns : solver . remove_constraint ( cn ) for cn in new_cns : solver . add_constraint ( cn ) solver . autosolve = True def layout ( self , cb , width , height , size , strength = medium , weight = ) : \"\"\"\"\"\" if not self . _initialized : raise RuntimeError ( '' ) if self . _running : return try : self . _running = True w , h = size ", "answer": "values = [ ( width , w ) , ( height , h ) ]"}, {"prompt": " \"\"\"\"\"\" from collections import UserDict from contextlib import contextmanager from datetime import datetime from functools import partial from functools import wraps import logging from logging . config import dictConfig from importlib import import_module from inspect import signature from inspect import getcallargs import os import sys from threading import Thread from time import sleep from time import time import dateutil . parser import dateutil . rrule from docopt import docopt import psutil from . import __version__ logger = logging . getLogger ( '' ) PALLADIUM_CONFIG_ERROR = \"\"\"\"\"\" def resolve_dotted_name ( dotted_name ) : if '' in dotted_name : module , name = dotted_name . split ( '' ) else : module , name = dotted_name . rsplit ( '' , ) attr = import_module ( module ) for name in name . split ( '' ) : attr = getattr ( attr , name ) return attr def create_component ( specification ) : specification = specification . copy ( ) factory_dotted_name = specification . pop ( '' ) factory = resolve_dotted_name ( factory_dotted_name ) return factory ( ** specification ) class Config ( dict ) : \"\"\"\"\"\" initialized = False def __getitem__ ( self , name ) : try : return super ( Config , self ) . __getitem__ ( name ) except KeyError : raise KeyError ( \"\" \"\" . format ( name , PALLADIUM_CONFIG_ERROR ) ) _config = Config ( ) def get_config ( ** extra ) : if not _config . initialized : _config . update ( extra ) _config . initialized = True fname = os . environ . get ( '' ) if fname is not None : sys . path . insert ( , os . path . dirname ( fname ) ) with open ( fname ) as f : _config . update ( eval ( f . read ( ) , { '' : os . environ } ) ) _initialize_config ( _config ) return _config def initialize_config ( ** extra ) : if _config . initialized : raise RuntimeError ( \"\" ) return get_config ( ** extra ) def _initialize_config_recursive ( mapping ) : rv = [ ] for key , value in tuple ( mapping . items ( ) ) : if isinstance ( value , dict ) : rv . extend ( _initialize_config_recursive ( value ) ) if '' in value : mapping [ key ] = create_component ( value ) rv . append ( mapping [ key ] ) elif isinstance ( value , ( list , tuple ) ) : for i , item in enumerate ( value ) : if isinstance ( item , dict ) : rv . extend ( _initialize_config_recursive ( item ) ) if '' in item : value [ i ] = create_component ( item ) rv . append ( value [ i ] ) return rv def _initialize_config ( config ) : components = [ ] if '' in config : dictConfig ( config [ '' ] ) else : logging . basicConfig ( level = logging . DEBUG ) components = _initialize_config_recursive ( config ) for component in components : if hasattr ( component , '' ) : component . initialize_component ( config ) return config def apply_kwargs ( func , ** kwargs ) : \"\"\"\"\"\" new_kwargs = { } params = signature ( func ) . parameters for param_name in params . keys ( ) : if param_name in kwargs : new_kwargs [ param_name ] = kwargs [ param_name ] return func ( ** new_kwargs ) def args_from_config ( func ) : \"\"\"\"\"\" func_args = signature ( func ) . parameters @ wraps ( func ) def wrapper ( * args , ** kwargs ) : config = get_config ( ) for i , argname in enumerate ( func_args ) : if len ( args ) > i or argname in kwargs : continue elif argname in config : kwargs [ argname ] = config [ argname ] try : getcallargs ( func , * args , ** kwargs ) except TypeError as exc : msg = \"\" . format ( exc . args [ ] , PALLADIUM_CONFIG_ERROR ) exc . args = ( msg , ) raise exc return func ( * args , ** kwargs ) wrapper . __wrapped__ = func return wrapper @ contextmanager def timer ( log = None , message = None ) : if log is not None : log ( \"\" . format ( message ) ) info = { } t0 = time ( ) yield info info [ '' ] = time ( ) - t0 if log is not None : log ( \"\" . format ( message , info [ '' ] ) ) @ contextmanager def session_scope ( session ) : \"\"\"\"\"\" try : yield session session . commit ( ) except : session . rollback ( ) raise finally : session . close ( ) class ProcessStore ( UserDict ) : def __init__ ( self , * args , ** kwargs ) : self . mtime = { } super ( ProcessStore , self ) . __init__ ( * args , ** kwargs ) def __setitem__ ( self , key , item ) : super ( ProcessStore , self ) . __setitem__ ( key , item ) self . mtime [ key ] = datetime . now ( ) def __getitem__ ( self , key ) : return super ( ProcessStore , self ) . __getitem__ ( key ) def __delitem__ ( self , key ) : super ( ProcessStore , self ) . __delitem__ ( key ) del self . mtime [ key ] process_store = ProcessStore ( ) class RruleThread ( Thread ) : \"\"\"\"\"\" def __init__ ( self , func , rrule , sleep_between_checks = ) : \"\"\"\"\"\" super ( RruleThread , self ) . __init__ ( daemon = True ) if isinstance ( rrule , dict ) : rrule = self . _rrule_from_dict ( rrule ) self . func = func self . rrule = rrule self . sleep_between_checks = sleep_between_checks self . last_execution = datetime . now ( ) self . alive = True @ classmethod def _rrule_from_dict ( cls , rrule ) : kwargs = rrule . copy ( ) for key , value in rrule . items ( ) : if isinstance ( value , str ) and hasattr ( dateutil . rrule , value ) : kwargs [ key ] = getattr ( dateutil . rrule , value ) dstart = kwargs . get ( '' ) if isinstance ( dstart , str ) : kwargs [ '' ] = dateutil . parser . parse ( dstart ) return dateutil . rrule . rrule ( ** kwargs ) def run ( self ) : while self . alive : now = datetime . now ( ) if not self . rrule . between ( self . last_execution , now ) : sleep ( self . sleep_between_checks ) continue self . last_execution = now try : self . func ( ) except : logger . exception ( \"\" . format ( self . func . __name__ ) ) def memory_usage_psutil ( ) : \"\"\"\"\"\" process = psutil . Process ( os . getpid ( ) ) mem = process . memory_info ( ) [ ] / float ( ** ) mem_vms = process . memory_info ( ) [ ] / float ( ** ) return mem , mem_vms def version_cmd ( argv = sys . argv [ : ] ) : \"\"\"\"\"\" docopt ( version_cmd . __doc__ , argv = argv ) print ( __version__ ) @ args_from_config def upgrade ( model_persister , from_version = None , to_version = None ) : kwargs = { '' : from_version } if to_version is not None : kwargs [ '' ] = to_version model_persister . upgrade ( ** kwargs ) def upgrade_cmd ( argv = sys . argv [ : ] ) : \"\"\"\"\"\" arguments = docopt ( upgrade_cmd . __doc__ , argv = argv ) initialize_config ( __mode__ = '' ) upgrade ( from_version = arguments [ '' ] , to_version = arguments [ '' ] ) class PluggableDecorator : def __init__ ( self , decorator_config_name ) : self . decorator_config_name = decorator_config_name ", "answer": "self . wrapped = None"}, {"prompt": " import os import logging from argparse import ArgumentParser from utils import load_data from lm import NeuralLM from deepy . trainers import SGDTrainer , LearningRateAnnealer , AdamTrainer from deepy . layers import LSTM ", "answer": "from layers import FullOutputLayer"}, {"prompt": " \"\"\"\"\"\" import re ", "answer": "from google . appengine . tools . devappserver2 import url_handler"}, {"prompt": " \"\"\"\"\"\" from . region_extractor import connected_regions , RegionExtractor from . signal_extraction import ( img_to_signals_labels , signals_to_img_labels , img_to_signals_maps , signals_to_img_maps , ) ", "answer": "__all__ = ["}, {"prompt": " def get_a_tour ( ) : '''''' global graph nodes_degree = { } ", "answer": "for edge in graph :"}, {"prompt": " \"\"\"\"\"\" import os import lxml . etree as ET from django . conf import settings class Response ( object ) : \"\"\"\"\"\" @ staticmethod def _build ( _type , tag , msg , xml ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " import maya . cmds import sys , os . path commandListLocations = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' } def __makeStubFunc ( command , library ) : def stubFunc ( * args , ** keywords ) : \"\"\"\"\"\" maya . cmds . dynamicLoad ( library ) return maya . cmds . __dict__ [ command ] ( * args , ** keywords ) return stubFunc def processCommandList ( ) : \"\"\"\"\"\" try : ", "answer": "commandListPath = os . path . realpath ( os . environ [ '' ] )"}, {"prompt": " import requests from oslo_config import cfg from oslo_log import log as logging from oslo_utils import excutils from networking_odl . common import client as odl_client from networking_bgpvpn . neutron . extensions import bgpvpn as bgpvpn_ext from networking_bgpvpn . neutron . services . common import constants from networking_bgpvpn . neutron . services . service_drivers import driver_api cfg . CONF . import_group ( '' , '' ) LOG = logging . getLogger ( __name__ ) BGPVPNS = '' OPENDAYLIGHT_BGPVPN_DRIVER_NAME = '' class OpenDaylightBgpvpnDriver ( driver_api . BGPVPNDriver ) : \"\"\"\"\"\" def __init__ ( self , service_plugin ) : LOG . debug ( \"\" ) super ( OpenDaylightBgpvpnDriver , self ) . __init__ ( service_plugin ) self . service_plugin = service_plugin self . client = odl_client . OpenDaylightRestClient . create_client ( ) def _scrub_rd_list ( self , bgpvpn ) : if len ( bgpvpn [ '' ] ) > : bgpvpn [ '' ] = bgpvpn [ '' ] [ ] def create_bgpvpn_precommit ( self , context , bgpvpn ) : if bgpvpn [ '' ] != constants . BGPVPN_L3 : raise bgpvpn_ext . BGPVPNTypeNotSupported ( driver = OPENDAYLIGHT_BGPVPN_DRIVER_NAME , type = bgpvpn [ '' ] ) def create_bgpvpn_postcommit ( self , context , bgpvpn ) : url = BGPVPNS try : self . _scrub_rd_list ( bgpvpn ) self . client . sendjson ( '' , url , { BGPVPNS [ : - ] : bgpvpn } ) except requests . exceptions . RequestException : with excutils . save_and_reraise_exception ( ) : d_bgpvpn = self . bgpvpn_db . delete_bgpvpn ( context , bgpvpn [ '' ] ) LOG . debug ( \"\" , d_bgpvpn ) def delete_bgpvpn_postcommit ( self , context , bgpvpn ) : url = BGPVPNS + '' + bgpvpn [ '' ] self . client . sendjson ( '' , url , None ) def update_bgpvpn_postcommit ( self , context , old_bgpvpn , bgpvpn ) : url = BGPVPNS + '' + bgpvpn [ '' ] self . client . sendjson ( '' , url , { BGPVPNS [ : - ] : bgpvpn } ) def create_net_assoc_precommit ( self , context , net_assoc ) : bgpvpns = self . bgpvpn_db . find_bgpvpns_for_network ( context , net_assoc [ '' ] ) if len ( bgpvpns ) > : ", "answer": "raise bgpvpn_ext . BGPVPNNetworkAssocExistsAnotherBgpvpn ("}, {"prompt": " if __name__ == '' : import robotide as _ import wx from robotide . editor . flowsizer import HorizontalFlowSizer from robotide . controller . commands import ChangeTag from robotide . controller . tags import ForcedTag , DefaultTag , Tag class TagsDisplay ( wx . Panel ) : def __init__ ( self , parent , controller ) : wx . Panel . __init__ ( self , parent , wx . ID_ANY ) self . _controller = controller self . _sizer = HorizontalFlowSizer ( ) self . _sizer . SetMinSize ( ( , ) ) self . _tag_boxes = [ ] self . SetSizer ( self . _sizer ) def add_tag ( self , tag ) : self . _add_tagbox ( Properties ( tag , self . _controller ) ) def _add_tagbox ( self , properties ) : tagbox = TagBox ( self , properties ) self . _sizer . Add ( tagbox ) self . _tag_boxes . append ( tagbox ) def build ( self ) : if not ( self . _tag_boxes and self . _tag_boxes [ - ] . add_new ) : self . add_new_tag_tagbox ( rebuild = False ) parent_sizer = self . GetParent ( ) . GetSizer ( ) if parent_sizer : parent_sizer . Layout ( ) def clear ( self ) : self . set_value ( self . _controller ) def close ( self ) : for tag_box in self . _tag_boxes : tag_box . close ( ) def saving ( self ) : for tag_box in self . _tag_boxes : tag_box . saving ( ) def set_value ( self , controller , plugin = None ) : if not self . _tag_boxes : self . _add_tags ( list ( controller ) ) else : self . _modify_values ( controller ) self . build ( ) def add_new_tag_tagbox ( self , rebuild = True ) : self . _add_tagbox ( AddTagBoxProperties ( self . _controller . empty_tag ( ) , self ) ) if rebuild : self . build ( ) def _add_tags ( self , tags ) : for tag in tags : self . add_tag ( tag ) def _modify_values ( self , controller ) : self . _remove_empty_tagboxes ( ) self . _set_tags ( list ( controller ) , self . _tag_boxes [ : ] , controller ) def _remove_empty_tagboxes ( self ) : for tb in self . _tag_boxes [ : ] : if tb . value == '' : self . _destroy_tagbox ( tb ) def _set_tags ( self , tags , tagboxes , controller ) : if not tags : self . _destroy_tagboxes ( tagboxes ) elif not tagboxes : self . _add_tags ( tags ) else : tagboxes [ ] . set_properties ( Properties ( tags [ ] , controller ) ) self . _set_tags ( tags [ : ] , tagboxes [ : ] , controller ) def _destroy_tagboxes ( self , tagboxes ) : for tb in tagboxes : if not tb . add_new : self . _destroy_tagbox ( tb ) def _destroy_tagbox ( self , tagbox ) : tagbox . Destroy ( ) self . _tag_boxes . remove ( tagbox ) def GetSelection ( self ) : return None def get_height ( self ) : return self . _sizer . height class TagBox ( wx . TextCtrl ) : def __init__ ( self , parent , properties ) : wx . TextCtrl . __init__ ( self , parent , wx . ID_ANY , '' , style = wx . TE_CENTER ) self . _bind ( ) self . set_properties ( properties ) def _bind ( self ) : for event , handler in [ ( wx . EVT_SET_FOCUS , self . OnSetFocus ) , ( wx . EVT_KILL_FOCUS , self . OnKillFocus ) , ( wx . EVT_LEFT_UP , self . OnSetFocus ) , ( wx . EVT_KEY_UP , self . OnKeyUp ) , ( wx . EVT_CHAR , self . OnChar ) ] : self . Bind ( event , handler ) def set_properties ( self , properties ) : self . _properties = properties self . _apply_properties ( ) def _apply_properties ( self ) : self . SetValue ( self . _properties . text ) self . SetToolTipString ( self . _properties . tooltip ) self . SetEditable ( self . _properties . enabled ) size = self . _get_size ( ) self . SetMaxSize ( size ) self . SetMinSize ( size ) self . _colorize ( ) def _get_size ( self ) : size = self . GetTextExtent ( self . value ) return wx . Size ( max ( size [ ] + , ) , max ( size [ ] + , ) ) def _colorize ( self ) : self . SetForegroundColour ( self . _properties . foreground_color ) self . SetBackgroundColour ( self . _properties . background_color ) def close ( self ) : self . _update_value ( ) def saving ( self ) : self . _update_value ( ) def OnKeyUp ( self , event ) : if self . _properties . modifiable : if event . GetKeyCode ( ) == wx . WXK_ESCAPE : self . _cancel_editing ( ) elif event . GetKeyCode ( ) == wx . WXK_RETURN : self . _update_value ( ) return elif event . GetKeyCode ( ) == wx . WXK_DELETE : self . SetValue ( '' ) event . Skip ( ) def _cancel_editing ( self ) : self . SetValue ( self . _properties . text ) self . _colorize ( ) def OnChar ( self , event ) : if event . GetKeyCode ( ) != wx . WXK_ESCAPE : self . _properties . activate ( self ) ", "answer": "event . Skip ( )"}, {"prompt": " from ztag . annotation import * class MRV1Server ( Annotation ) : protocol = protocols . HTTP subprotocol = protocols . HTTP . GET port = None ", "answer": "def process ( self , obj , meta ) :"}, {"prompt": " from __future__ import absolute_import , unicode_literals ", "answer": "import copy"}, {"prompt": " from django import template from django . db import transaction from django . core . urlresolvers import reverse from django . http import HttpResponseRedirect from django . template . defaultfilters import slugify from django . forms . util import ErrorList from transifex . txcommon . utils import get_url_pattern from transifex . languages . models import Language from transifex . resources . forms import CreateResourceForm , ResourceTranslationForm , UpdateTranslationForm from transifex . resources . models import Resource from transifex . resources . backends import ResourceBackend , FormatsBackend , ResourceBackendError , FormatsBackendError , content_from_uploaded_file , filename_of_uploaded_file register = template . Library ( ) @ transaction . commit_manually @ register . inclusion_tag ( \"\" ) def upload_create_resource_form ( request , project , prefix = '' ) : \"\"\"\"\"\" resource = None display_form = False if request . method == '' and request . POST . get ( '' , None ) : cr_form = CreateResourceForm ( request . POST , request . FILES , prefix = prefix ) if cr_form . is_valid ( ) : name = cr_form . cleaned_data [ '' ] slug = slugify ( name ) try : Resource . objects . get ( slug = slug , project = project ) ", "answer": "except Resource . DoesNotExist :"}, {"prompt": " import pkgutil import importlib from flask import Blueprint from flask . json import JSONEncoder as BaseJSONEncoder def register_blueprints ( app , package_name , package_path ) : \"\"\"\"\"\" rv = [ ] for _ , name , _ in pkgutil . iter_modules ( package_path ) : m = importlib . import_module ( '' % ( package_name , name ) ) for item in dir ( m ) : item = getattr ( m , item ) if isinstance ( item , Blueprint ) : app . register_blueprint ( item ) rv . append ( item ) ", "answer": "return rv"}, {"prompt": " from topaz . module import ClassDef from topaz . objects . objectobject import W_Object def create_owner ( classdef ) : @ classdef . method ( \"\" ) def method_owner ( self , space ) : return self . w_owner return method_owner def create_to_s ( classdef ) : @ classdef . method ( \"\" ) def method_to_s ( self , space ) : return space . newstr_fromstr ( \"\" % ( classdef . name , self . w_owner . name , self . w_function . name ) ) return method_to_s class W_MethodObject ( W_Object ) : classdef = ClassDef ( \"\" , W_Object . classdef ) def __init__ ( self , space , w_owner , w_function , w_receiver ) : W_Object . __init__ ( self , space ) self . w_owner = w_owner ", "answer": "self . w_function = w_function"}, {"prompt": " import mock from rally . plugins . openstack . context . quotas import manila_quotas ", "answer": "from tests . unit import test"}, {"prompt": " try : ", "answer": "from setuptools . core import setup"}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import , division import errno import inspect import signal import os import sys try : import pwd import grp except ImportError : pwd = grp = None try : import cPickle as pickle except ImportError : import pickle from zope . interface import implementer from zope . interface . verify import verifyObject from twisted . trial import unittest from twisted . test . test_process import MockOS from twisted import plugin , logger from twisted . application . service import IServiceMaker from twisted . application import service , app , reactors from twisted . scripts import twistd from twisted . python . compat import NativeStringIO from twisted . python . usage import UsageError from twisted . python . log import ( ILogObserver as LegacyILogObserver , textFromEventDict ) from twisted . python . components import Componentized from twisted . internet . defer import Deferred from twisted . internet . interfaces import IReactorDaemonize from twisted . internet . test . modulehelpers import AlternateReactor from twisted . python . fakepwd import UserDatabase from twisted . logger import globalLogBeginner , globalLogPublisher , ILogObserver try : from twisted . scripts import _twistd_unix except ImportError : _twistd_unix = None else : from twisted . scripts . _twistd_unix import UnixApplicationRunner from twisted . scripts . _twistd_unix import UnixAppLogger try : from twisted . python import syslog except ImportError : syslog = None try : import profile except ImportError : profile = None try : import pstats import cProfile except ImportError : cProfile = None if getattr ( os , '' , None ) is None : setuidSkip = \"\" else : setuidSkip = None def patchUserDatabase ( patch , user , uid , group , gid ) : \"\"\"\"\"\" pwent = pwd . getpwuid ( os . getuid ( ) ) grent = grp . getgrgid ( os . getgid ( ) ) database = UserDatabase ( ) database . addUser ( user , pwent . pw_passwd , uid , pwent . pw_gid , pwent . pw_gecos , pwent . pw_dir , pwent . pw_shell ) def getgrnam ( name ) : result = list ( grent ) result [ result . index ( grent . gr_name ) ] = group result [ result . index ( grent . gr_gid ) ] = gid result = tuple ( result ) return { group : result } [ name ] patch ( pwd , \"\" , database . getpwnam ) patch ( grp , \"\" , getgrnam ) class MockServiceMaker ( object ) : \"\"\"\"\"\" tapname = '' def makeService ( self , options ) : \"\"\"\"\"\" self . options = options self . service = service . Service ( ) return self . service class CrippledAppLogger ( app . AppLogger ) : \"\"\"\"\"\" def start ( self , application ) : pass class CrippledApplicationRunner ( twistd . _SomeApplicationRunner ) : \"\"\"\"\"\" loggerFactory = CrippledAppLogger def preApplication ( self ) : pass def postApplication ( self ) : pass class ServerOptionsTests ( unittest . TestCase ) : \"\"\"\"\"\" def test_subCommands ( self ) : \"\"\"\"\"\" class FakePlugin ( object ) : def __init__ ( self , name ) : self . tapname = name self . _options = '' + name self . description = '' + name def options ( self ) : return self . _options apple = FakePlugin ( '' ) banana = FakePlugin ( '' ) coconut = FakePlugin ( '' ) donut = FakePlugin ( '' ) def getPlugins ( interface ) : self . assertEqual ( interface , IServiceMaker ) yield coconut yield banana yield donut yield apple config = twistd . ServerOptions ( ) self . assertEqual ( config . _getPlugins , plugin . getPlugins ) config . _getPlugins = getPlugins subCommands = config . subCommands expectedOrder = [ apple , banana , coconut , donut ] for subCommand , expectedCommand in zip ( subCommands , expectedOrder ) : name , shortcut , parserClass , documentation = subCommand self . assertEqual ( name , expectedCommand . tapname ) self . assertEqual ( shortcut , None ) self . assertEqual ( parserClass ( ) , expectedCommand . _options ) , self . assertEqual ( documentation , expectedCommand . description ) def test_sortedReactorHelp ( self ) : \"\"\"\"\"\" class FakeReactorInstaller ( object ) : def __init__ ( self , name ) : self . shortName = '' + name self . description = '' + name apple = FakeReactorInstaller ( '' ) banana = FakeReactorInstaller ( '' ) coconut = FakeReactorInstaller ( '' ) donut = FakeReactorInstaller ( '' ) def getReactorTypes ( ) : yield coconut yield banana yield donut yield apple config = twistd . ServerOptions ( ) self . assertEqual ( config . _getReactorTypes , reactors . getReactorTypes ) config . _getReactorTypes = getReactorTypes config . messageOutput = NativeStringIO ( ) self . assertRaises ( SystemExit , config . parseOptions , [ '' ] ) helpOutput = config . messageOutput . getvalue ( ) indexes = [ ] for reactor in apple , banana , coconut , donut : def getIndex ( s ) : self . assertIn ( s , helpOutput ) indexes . append ( helpOutput . index ( s ) ) getIndex ( reactor . shortName ) getIndex ( reactor . description ) self . assertEqual ( indexes , sorted ( indexes ) , '' % ( helpOutput , ) ) def test_postOptionsSubCommandCausesNoSave ( self ) : \"\"\"\"\"\" config = twistd . ServerOptions ( ) config . subCommand = '' config . postOptions ( ) self . assertEqual ( config [ '' ] , True ) def test_postOptionsNoSubCommandSavesAsUsual ( self ) : \"\"\"\"\"\" config = twistd . ServerOptions ( ) config . postOptions ( ) self . assertEqual ( config [ '' ] , False ) def test_listAllProfilers ( self ) : \"\"\"\"\"\" config = twistd . ServerOptions ( ) helpOutput = str ( config ) for profiler in app . AppProfiler . profilers : self . assertIn ( profiler , helpOutput ) def test_defaultUmask ( self ) : \"\"\"\"\"\" config = twistd . ServerOptions ( ) self . assertEqual ( config [ '' ] , None ) def test_umask ( self ) : \"\"\"\"\"\" config = twistd . ServerOptions ( ) config . parseOptions ( [ '' , '' ] ) self . assertEqual ( config [ '' ] , ) config . parseOptions ( [ '' , '' ] ) self . assertEqual ( config [ '' ] , ) def test_invalidUmask ( self ) : \"\"\"\"\"\" config = twistd . ServerOptions ( ) self . assertRaises ( UsageError , config . parseOptions , [ '' , '' ] ) if _twistd_unix is None : msg = \"\" test_defaultUmask . skip = test_umask . skip = test_invalidUmask . skip = msg def test_unimportableConfiguredLogObserver ( self ) : \"\"\"\"\"\" config = twistd . ServerOptions ( ) e = self . assertRaises ( UsageError , config . parseOptions , [ '' , '' ] ) self . assertTrue ( e . args [ ] . startswith ( \"\" \"\" ) ) self . assertNotIn ( '' , e . args [ ] ) def test_badAttributeWithConfiguredLogObserver ( self ) : \"\"\"\"\"\" config = twistd . ServerOptions ( ) e = self . assertRaises ( UsageError , config . parseOptions , [ \"\" , \"\" ] ) if sys . version_info <= ( , ) : self . assertTrue ( e . args [ ] . startswith ( \"\" \"\" ) ) else : self . assertTrue ( e . args [ ] . startswith ( \"\" \"\" \"\" ) ) self . assertNotIn ( '' , e . args [ ] ) class TapFileTests ( unittest . TestCase ) : \"\"\"\"\"\" def setUp ( self ) : \"\"\"\"\"\" self . tapfile = self . mktemp ( ) with open ( self . tapfile , '' ) as f : pickle . dump ( service . Application ( \"\" ) , f ) def test_createOrGetApplicationWithTapFile ( self ) : \"\"\"\"\"\" config = twistd . ServerOptions ( ) config . parseOptions ( [ '' , self . tapfile ] ) application = CrippledApplicationRunner ( config ) . createOrGetApplication ( ) self . assertEqual ( service . IService ( application ) . name , '' ) class TestLoggerFactory ( object ) : \"\"\"\"\"\" def __init__ ( self , runner ) : self . runner = runner def start ( self , application ) : \"\"\"\"\"\" self . runner . order . append ( \"\" ) self . runner . hadApplicationLogObserver = hasattr ( self . runner , '' ) def stop ( self ) : \"\"\"\"\"\" class TestApplicationRunner ( app . ApplicationRunner ) : \"\"\"\"\"\" def __init__ ( self , options ) : app . ApplicationRunner . __init__ ( self , options ) self . order = [ ] self . logger = TestLoggerFactory ( self ) def preApplication ( self ) : self . order . append ( \"\" ) self . hadApplicationPreApplication = hasattr ( self , '' ) def postApplication ( self ) : self . order . append ( \"\" ) self . hadApplicationPostApplication = hasattr ( self , '' ) class ApplicationRunnerTests ( unittest . TestCase ) : \"\"\"\"\"\" def setUp ( self ) : config = twistd . ServerOptions ( ) self . serviceMaker = MockServiceMaker ( ) config . loadedPlugins = { '' : self . serviceMaker } config . subOptions = object ( ) config . subCommand = '' self . config = config def test_applicationRunnerGetsCorrectApplication ( self ) : \"\"\"\"\"\" arunner = CrippledApplicationRunner ( self . config ) arunner . run ( ) self . assertIdentical ( self . serviceMaker . options , self . config . subOptions , \"\" \"\" ) self . assertIdentical ( self . serviceMaker . service , service . IService ( arunner . application ) . services [ ] , \"\" \"\" ) def test_preAndPostApplication ( self ) : \"\"\"\"\"\" s = TestApplicationRunner ( self . config ) s . run ( ) self . assertFalse ( s . hadApplicationPreApplication ) self . assertTrue ( s . hadApplicationPostApplication ) self . assertTrue ( s . hadApplicationLogObserver ) self . assertEqual ( s . order , [ \"\" , \"\" , \"\" ] ) def _applicationStartsWithConfiguredID ( self , argv , uid , gid ) : \"\"\"\"\"\" self . config . parseOptions ( argv ) events = [ ] class FakeUnixApplicationRunner ( twistd . _SomeApplicationRunner ) : def setupEnvironment ( self , chroot , rundir , nodaemon , umask , pidfile ) : events . append ( '' ) def shedPrivileges ( self , euid , uid , gid ) : events . append ( ( '' , euid , uid , gid ) ) def startReactor ( self , reactor , oldstdout , oldstderr ) : events . append ( '' ) def removePID ( self , pidfile ) : pass @ implementer ( service . IService , service . IProcess ) class FakeService ( object ) : processName = None uid = None gid = None def setName ( self , name ) : pass def setServiceParent ( self , parent ) : pass def disownServiceParent ( self ) : pass def privilegedStartService ( self ) : events . append ( '' ) def startService ( self ) : events . append ( '' ) def stopService ( self ) : pass application = FakeService ( ) verifyObject ( service . IService , application ) verifyObject ( service . IProcess , application ) runner = FakeUnixApplicationRunner ( self . config ) runner . preApplication ( ) runner . application = application runner . postApplication ( ) self . assertEqual ( events , [ '' , '' , ( '' , False , uid , gid ) , '' , '' ] ) def test_applicationStartsWithConfiguredNumericIDs ( self ) : \"\"\"\"\"\" uid = gid = self . _applicationStartsWithConfiguredID ( [ \"\" , str ( uid ) , \"\" , str ( gid ) ] , uid , gid ) test_applicationStartsWithConfiguredNumericIDs . skip = setuidSkip def test_applicationStartsWithConfiguredNameIDs ( self ) : \"\"\"\"\"\" user = \"\" uid = group = \"\" gid = patchUserDatabase ( self . patch , user , uid , group , gid ) self . _applicationStartsWithConfiguredID ( [ \"\" , user , \"\" , group ] , uid , gid ) test_applicationStartsWithConfiguredNameIDs . skip = setuidSkip def test_startReactorRunsTheReactor ( self ) : \"\"\"\"\"\" reactor = DummyReactor ( ) runner = app . ApplicationRunner ( { \"\" : False , \"\" : \"\" , \"\" : False } ) runner . startReactor ( reactor , None , None ) self . assertTrue ( reactor . called , \"\" ) class UnixApplicationRunnerSetupEnvironmentTests ( unittest . TestCase ) : \"\"\"\"\"\" if _twistd_unix is None : skip = \"\" unset = object ( ) def setUp ( self ) : self . root = self . unset self . cwd = self . unset self . mask = self . unset self . daemon = False self . pid = os . getpid ( ) self . patch ( os , '' , lambda path : setattr ( self , '' , path ) ) self . patch ( os , '' , lambda path : setattr ( self , '' , path ) ) self . patch ( os , '' , lambda mask : setattr ( self , '' , mask ) ) self . runner = UnixApplicationRunner ( twistd . ServerOptions ( ) ) self . runner . daemonize = self . daemonize def daemonize ( self , reactor ) : \"\"\"\"\"\" self . daemon = True self . patch ( os , '' , lambda : self . pid + ) def test_chroot ( self ) : \"\"\"\"\"\" self . runner . setupEnvironment ( \"\" , \"\" , True , None , None ) self . assertEqual ( self . root , \"\" ) def test_noChroot ( self ) : \"\"\"\"\"\" self . runner . setupEnvironment ( None , \"\" , True , None , None ) self . assertIdentical ( self . root , self . unset ) def test_changeWorkingDirectory ( self ) : \"\"\"\"\"\" self . runner . setupEnvironment ( None , \"\" , True , None , None ) self . assertEqual ( self . cwd , \"\" ) def test_daemonize ( self ) : \"\"\"\"\"\" with AlternateReactor ( FakeDaemonizingReactor ( ) ) : self . runner . setupEnvironment ( None , \"\" , False , None , None ) self . assertTrue ( self . daemon ) def test_noDaemonize ( self ) : \"\"\"\"\"\" self . runner . setupEnvironment ( None , \"\" , True , None , None ) self . assertFalse ( self . daemon ) def test_nonDaemonPIDFile ( self ) : \"\"\"\"\"\" pidfile = self . mktemp ( ) self . runner . setupEnvironment ( None , \"\" , True , None , pidfile ) with open ( pidfile , '' ) as f : pid = int ( f . read ( ) ) self . assertEqual ( pid , self . pid ) def test_daemonPIDFile ( self ) : \"\"\"\"\"\" pidfile = self . mktemp ( ) with AlternateReactor ( FakeDaemonizingReactor ( ) ) : self . runner . setupEnvironment ( None , \"\" , False , None , pidfile ) with open ( pidfile , '' ) as f : pid = int ( f . read ( ) ) self . assertEqual ( pid , self . pid + ) def test_umask ( self ) : \"\"\"\"\"\" with AlternateReactor ( FakeDaemonizingReactor ( ) ) : self . runner . setupEnvironment ( None , \"\" , False , , None ) self . assertEqual ( self . mask , ) def test_noDaemonizeNoUmask ( self ) : \"\"\"\"\"\" self . runner . setupEnvironment ( None , \"\" , True , None , None ) self . assertIdentical ( self . mask , self . unset ) def test_daemonizedNoUmask ( self ) : \"\"\"\"\"\" with AlternateReactor ( FakeDaemonizingReactor ( ) ) : self . runner . setupEnvironment ( None , \"\" , False , None , None ) self . assertEqual ( self . mask , ) class UnixApplicationRunnerStartApplicationTests ( unittest . TestCase ) : \"\"\"\"\"\" if _twistd_unix is None : skip = \"\" def test_setupEnvironment ( self ) : \"\"\"\"\"\" options = twistd . ServerOptions ( ) options . parseOptions ( [ '' , '' , '' , '' , '' , '' , '' , '' , '' ] ) application = service . Application ( \"\" ) self . runner = UnixApplicationRunner ( options ) args = [ ] def fakeSetupEnvironment ( self , chroot , rundir , nodaemon , umask , pidfile ) : args . extend ( ( chroot , rundir , nodaemon , umask , pidfile ) ) self . assertEqual ( inspect . getargspec ( self . runner . setupEnvironment ) , inspect . getargspec ( fakeSetupEnvironment ) ) self . patch ( UnixApplicationRunner , '' , fakeSetupEnvironment ) self . patch ( UnixApplicationRunner , '' , lambda * a , ** kw : None ) self . patch ( app , '' , lambda * a , ** kw : None ) self . runner . startApplication ( application ) self . assertEqual ( args , [ '' , '' , True , , '' ] ) class UnixApplicationRunnerRemovePIDTests ( unittest . TestCase ) : \"\"\"\"\"\" if _twistd_unix is None : skip = \"\" def test_removePID ( self ) : \"\"\"\"\"\" runner = UnixApplicationRunner ( { } ) path = self . mktemp ( ) os . makedirs ( path ) pidfile = os . path . join ( path , \"\" ) open ( pidfile , \"\" ) . close ( ) runner . removePID ( pidfile ) self . assertFalse ( os . path . exists ( pidfile ) ) def test_removePIDErrors ( self ) : \"\"\"\"\"\" runner = UnixApplicationRunner ( { } ) runner . removePID ( \"\" ) errors = self . flushLoggedErrors ( OSError ) self . assertEqual ( len ( errors ) , ) self . assertEqual ( errors [ ] . value . errno , errno . ENOENT ) class FakeNonDaemonizingReactor ( object ) : \"\"\"\"\"\" def __init__ ( self ) : self . _beforeDaemonizeCalled = False self . _afterDaemonizeCalled = False def beforeDaemonize ( self ) : self . _beforeDaemonizeCalled = True def afterDaemonize ( self ) : self . _afterDaemonizeCalled = True def addSystemEventTrigger ( self , * args , ** kw ) : \"\"\"\"\"\" @ implementer ( IReactorDaemonize ) class FakeDaemonizingReactor ( FakeNonDaemonizingReactor ) : \"\"\"\"\"\" class DummyReactor ( object ) : \"\"\"\"\"\" called = False def run ( self ) : \"\"\"\"\"\" if self . called : raise RuntimeError ( \"\" ) self . called = True class AppProfilingTests ( unittest . TestCase ) : \"\"\"\"\"\" def test_profile ( self ) : \"\"\"\"\"\" config = twistd . ServerOptions ( ) config [ \"\" ] = self . mktemp ( ) config [ \"\" ] = \"\" profiler = app . AppProfiler ( config ) reactor = DummyReactor ( ) profiler . run ( reactor ) self . assertTrue ( reactor . called ) with open ( config [ \"\" ] ) as f : data = f . read ( ) self . assertIn ( \"\" , data ) self . assertIn ( \"\" , data ) if profile is None : test_profile . skip = \"\" def _testStats ( self , statsClass , profile ) : out = NativeStringIO ( ) stdout = self . patch ( sys , '' , out ) stats = statsClass ( profile ) stats . print_stats ( ) stdout . restore ( ) data = out . getvalue ( ) self . assertIn ( \"\" , data ) self . assertIn ( \"\" , data ) def test_profileSaveStats ( self ) : \"\"\"\"\"\" config = twistd . ServerOptions ( ) config [ \"\" ] = self . mktemp ( ) config [ \"\" ] = \"\" config [ \"\" ] = True profiler = app . AppProfiler ( config ) reactor = DummyReactor ( ) profiler . run ( reactor ) self . assertTrue ( reactor . called ) self . _testStats ( pstats . Stats , config [ '' ] ) if profile is None : test_profileSaveStats . skip = \"\" def test_withoutProfile ( self ) : \"\"\"\"\"\" savedModules = sys . modules . copy ( ) config = twistd . ServerOptions ( ) config [ \"\" ] = \"\" profiler = app . AppProfiler ( config ) sys . modules [ \"\" ] = None try : self . assertRaises ( SystemExit , profiler . run , None ) finally : sys . modules . clear ( ) sys . modules . update ( savedModules ) def test_profilePrintStatsError ( self ) : \"\"\"\"\"\" class ErroneousProfile ( profile . Profile ) : def print_stats ( self ) : raise RuntimeError ( \"\" ) self . patch ( profile , \"\" , ErroneousProfile ) config = twistd . ServerOptions ( ) config [ \"\" ] = self . mktemp ( ) config [ \"\" ] = \"\" profiler = app . AppProfiler ( config ) reactor = DummyReactor ( ) oldStdout = sys . stdout self . assertRaises ( RuntimeError , profiler . run , reactor ) self . assertIdentical ( sys . stdout , oldStdout ) if profile is None : test_profilePrintStatsError . skip = \"\" def test_cProfile ( self ) : \"\"\"\"\"\" config = twistd . ServerOptions ( ) config [ \"\" ] = self . mktemp ( ) config [ \"\" ] = \"\" profiler = app . AppProfiler ( config ) reactor = DummyReactor ( ) profiler . run ( reactor ) self . assertTrue ( reactor . called ) with open ( config [ \"\" ] ) as f : data = f . read ( ) self . assertIn ( \"\" , data ) self . assertIn ( \"\" , data ) if cProfile is None : test_cProfile . skip = \"\" def test_cProfileSaveStats ( self ) : \"\"\"\"\"\" config = twistd . ServerOptions ( ) config [ \"\" ] = self . mktemp ( ) config [ \"\" ] = \"\" config [ \"\" ] = True profiler = app . AppProfiler ( config ) reactor = DummyReactor ( ) profiler . run ( reactor ) self . assertTrue ( reactor . called ) self . _testStats ( pstats . Stats , config [ '' ] ) if cProfile is None : test_cProfileSaveStats . skip = \"\" def test_withoutCProfile ( self ) : \"\"\"\"\"\" savedModules = sys . modules . copy ( ) sys . modules [ \"\" ] = None config = twistd . ServerOptions ( ) config [ \"\" ] = \"\" profiler = app . AppProfiler ( config ) try : self . assertRaises ( SystemExit , profiler . run , None ) finally : sys . modules . clear ( ) sys . modules . update ( savedModules ) def test_unknownProfiler ( self ) : \"\"\"\"\"\" config = twistd . ServerOptions ( ) config [ \"\" ] = self . mktemp ( ) config [ \"\" ] = \"\" error = self . assertRaises ( SystemExit , app . AppProfiler , config ) self . assertEqual ( str ( error ) , \"\" ) def test_defaultProfiler ( self ) : \"\"\"\"\"\" profiler = app . AppProfiler ( { } ) self . assertEqual ( profiler . profiler , \"\" ) def test_profilerNameCaseInsentive ( self ) : \"\"\"\"\"\" profiler = app . AppProfiler ( { \"\" : \"\" } ) self . assertEqual ( profiler . profiler , \"\" ) def _patchTextFileLogObserver ( patch ) : \"\"\"\"\"\" logFiles = [ ] oldFileLogObserver = logger . textFileLogObserver def observer ( logFile , * args , ** kwargs ) : logFiles . append ( logFile ) return oldFileLogObserver ( logFile , * args , ** kwargs ) patch ( logger , '' , observer ) return logFiles def _setupSyslog ( testCase ) : \"\"\"\"\"\" logMessages = [ ] class fakesyslogobserver ( object ) : def __init__ ( self , prefix ) : logMessages . append ( prefix ) def emit ( self , eventDict ) : logMessages . append ( eventDict ) testCase . patch ( syslog , \"\" , fakesyslogobserver ) return logMessages class AppLoggerTests ( unittest . TestCase ) : \"\"\"\"\"\" def setUp ( self ) : \"\"\"\"\"\" self . observers = [ ] def beginLoggingTo ( observers ) : for observer in observers : self . observers . append ( observer ) globalLogPublisher . addObserver ( observer ) self . patch ( globalLogBeginner , '' , beginLoggingTo ) def tearDown ( self ) : \"\"\"\"\"\" for observer in self . observers : globalLogPublisher . removeObserver ( observer ) def _makeObserver ( self ) : \"\"\"\"\"\" @ implementer ( ILogObserver ) class TestObserver ( object ) : _logs = [ ] def __call__ ( self , event ) : self . _logs . append ( event ) return TestObserver ( ) def _checkObserver ( self , observer ) : \"\"\"\"\"\" self . assertEqual ( self . observers , [ observer ] ) self . assertIn ( \"\" , observer . _logs [ ] [ \"\" ] ) self . assertIn ( \"\" , observer . _logs [ ] [ \"\" ] ) def test_start ( self ) : \"\"\"\"\"\" logger = app . AppLogger ( { } ) observer = self . _makeObserver ( ) logger . _getLogObserver = lambda : observer logger . start ( Componentized ( ) ) self . _checkObserver ( observer ) def test_startUsesApplicationLogObserver ( self ) : \"\"\"\"\"\" application = Componentized ( ) observer = self . _makeObserver ( ) application . setComponent ( ILogObserver , observer ) logger = app . AppLogger ( { } ) logger . start ( application ) self . _checkObserver ( observer ) def _setupConfiguredLogger ( self , application , extraLogArgs = { } , appLogger = app . AppLogger ) : \"\"\"\"\"\" observer = self . _makeObserver ( ) logArgs = { \"\" : lambda : observer } logArgs . update ( extraLogArgs ) logger = appLogger ( logArgs ) logger . start ( application ) return observer def test_startUsesConfiguredLogObserver ( self ) : \"\"\"\"\"\" application = Componentized ( ) self . _checkObserver ( self . _setupConfiguredLogger ( application ) ) def test_configuredLogObserverBeatsComponent ( self ) : \"\"\"\"\"\" observer = self . _makeObserver ( ) application = Componentized ( ) application . setComponent ( ILogObserver , observer ) self . _checkObserver ( self . _setupConfiguredLogger ( application ) ) self . assertEqual ( observer . _logs , [ ] ) def test_configuredLogObserverBeatsLegacyComponent ( self ) : \"\"\"\"\"\" nonlogs = [ ] application = Componentized ( ) application . setComponent ( LegacyILogObserver , nonlogs . append ) self . _checkObserver ( self . _setupConfiguredLogger ( application ) ) self . assertEqual ( nonlogs , [ ] ) def test_loggerComponentBeatsLegacyLoggerComponent ( self ) : \"\"\"\"\"\" nonlogs = [ ] observer = self . _makeObserver ( ) application = Componentized ( ) application . setComponent ( ILogObserver , observer ) application . setComponent ( LegacyILogObserver , nonlogs . append ) logger = app . AppLogger ( { } ) logger . start ( application ) self . _checkObserver ( observer ) self . assertEqual ( nonlogs , [ ] ) def test_configuredLogObserverBeatsSyslog ( self ) : \"\"\"\"\"\" logs = _setupSyslog ( self ) application = Componentized ( ) self . _checkObserver ( self . _setupConfiguredLogger ( application , { \"\" : True } , UnixAppLogger ) ) self . assertEqual ( logs , [ ] ) if _twistd_unix is None or syslog is None : test_configuredLogObserverBeatsSyslog . skip = ( \"\" ) def test_configuredLogObserverBeatsLogfile ( self ) : \"\"\"\"\"\" application = Componentized ( ) path = self . mktemp ( ) self . _checkObserver ( self . _setupConfiguredLogger ( application , { \"\" : \"\" } ) ) self . assertFalse ( os . path . exists ( path ) ) def test_getLogObserverStdout ( self ) : \"\"\"\"\"\" logger = app . AppLogger ( { \"\" : \"\" } ) logFiles = _patchTextFileLogObserver ( self . patch ) logger . _getLogObserver ( ) self . assertEqual ( len ( logFiles ) , ) self . assertIdentical ( logFiles [ ] , sys . stdout ) logger = app . AppLogger ( { \"\" : \"\" } ) logger . _getLogObserver ( ) self . assertEqual ( len ( logFiles ) , ) self . assertIdentical ( logFiles [ ] , sys . stdout ) def test_getLogObserverFile ( self ) : \"\"\"\"\"\" logFiles = _patchTextFileLogObserver ( self . patch ) filename = self . mktemp ( ) logger = app . AppLogger ( { \"\" : filename } ) logger . _getLogObserver ( ) self . assertEqual ( len ( logFiles ) , ) self . assertEqual ( logFiles [ ] . path , os . path . abspath ( filename ) ) def test_stop ( self ) : \"\"\"\"\"\" removed = [ ] observer = object ( ) def remove ( observer ) : removed . append ( observer ) self . patch ( globalLogPublisher , '' , remove ) logger = app . AppLogger ( { } ) logger . _observer = observer logger . stop ( ) self . assertEqual ( removed , [ observer ] ) logger . stop ( ) self . assertEqual ( removed , [ observer ] ) self . assertIdentical ( logger . _observer , None ) def test_legacyObservers ( self ) : \"\"\"\"\"\" logs = [ ] logger = app . AppLogger ( { } ) @ implementer ( LegacyILogObserver ) class LoggerObserver ( object ) : \"\"\"\"\"\" def __call__ ( self , x ) : \"\"\"\"\"\" logs . append ( x ) logger . _observerFactory = lambda : LoggerObserver ( ) logger . start ( Componentized ( ) ) self . assertIn ( \"\" , textFromEventDict ( logs [ ] ) ) warnings = self . flushWarnings ( [ self . test_legacyObservers ] ) self . assertEqual ( len ( warnings ) , ) def test_unmarkedObserversDeprecated ( self ) : \"\"\"\"\"\" logs = [ ] logger = app . AppLogger ( { } ) logger . _getLogObserver = lambda : logs . append logger . start ( Componentized ( ) ) self . assertIn ( \"\" , textFromEventDict ( logs [ ] ) ) warnings = self . flushWarnings ( [ self . test_unmarkedObserversDeprecated ] ) self . assertEqual ( len ( warnings ) , ) self . assertEqual ( warnings [ ] [ \"\" ] , ( \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" ) ) class UnixAppLoggerTests ( unittest . TestCase ) : \"\"\"\"\"\" if _twistd_unix is None : skip = \"\" def setUp ( self ) : \"\"\"\"\"\" self . signals = [ ] def fakeSignal ( sig , f ) : self . signals . append ( ( sig , f ) ) self . patch ( signal , \"\" , fakeSignal ) def test_getLogObserverStdout ( self ) : \"\"\"\"\"\" logFiles = _patchTextFileLogObserver ( self . patch ) logger = UnixAppLogger ( { \"\" : \"\" , \"\" : True } ) logger . _getLogObserver ( ) self . assertEqual ( len ( logFiles ) , ) self . assertIdentical ( logFiles [ ] , sys . stdout ) logger = UnixAppLogger ( { \"\" : \"\" , \"\" : True } ) logger . _getLogObserver ( ) self . assertEqual ( len ( logFiles ) , ) self . assertIdentical ( logFiles [ ] , sys . stdout ) def test_getLogObserverStdoutDaemon ( self ) : \"\"\"\"\"\" logger = UnixAppLogger ( { \"\" : \"\" , \"\" : False } ) error = self . assertRaises ( SystemExit , logger . _getLogObserver ) self . assertEqual ( str ( error ) , \"\" ) def test_getLogObserverFile ( self ) : \"\"\"\"\"\" logFiles = _patchTextFileLogObserver ( self . patch ) filename = self . mktemp ( ) logger = UnixAppLogger ( { \"\" : filename } ) logger . _getLogObserver ( ) self . assertEqual ( len ( logFiles ) , ) self . assertEqual ( logFiles [ ] . path , os . path . abspath ( filename ) ) self . assertEqual ( len ( self . signals ) , ) self . assertEqual ( self . signals [ ] [ ] , signal . SIGUSR1 ) d = Deferred ( ) def rotate ( ) : d . callback ( None ) logFiles [ ] . rotate = rotate rotateLog = self . signals [ ] [ ] rotateLog ( None , None ) return d def test_getLogObserverDontOverrideSignalHandler ( self ) : \"\"\"\"\"\" def fakeGetSignal ( sig ) : self . assertEqual ( sig , signal . SIGUSR1 ) return object ( ) self . patch ( signal , \"\" , fakeGetSignal ) filename = self . mktemp ( ) logger = UnixAppLogger ( { \"\" : filename } ) logger . _getLogObserver ( ) self . assertEqual ( self . signals , [ ] ) def test_getLogObserverDefaultFile ( self ) : \"\"\"\"\"\" logFiles = _patchTextFileLogObserver ( self . patch ) logger = UnixAppLogger ( { \"\" : \"\" , \"\" : False } ) logger . _getLogObserver ( ) self . assertEqual ( len ( logFiles ) , ) self . assertEqual ( logFiles [ ] . path , os . path . abspath ( \"\" ) ) def test_getLogObserverSyslog ( self ) : \"\"\"\"\"\" logs = _setupSyslog ( self ) logger = UnixAppLogger ( { \"\" : True , \"\" : \"\" } ) observer = logger . _getLogObserver ( ) self . assertEqual ( logs , [ \"\" ] ) observer ( { \"\" : \"\" } ) self . assertEqual ( logs , [ \"\" , { \"\" : \"\" } ] ) if syslog is None : test_getLogObserverSyslog . skip = \"\" class DaemonizeTests ( unittest . TestCase ) : \"\"\"\"\"\" def setUp ( self ) : self . mockos = MockOS ( ) self . config = twistd . ServerOptions ( ) self . patch ( _twistd_unix , '' , self . mockos ) self . runner = _twistd_unix . UnixApplicationRunner ( self . config ) self . runner . application = service . Application ( \"\" ) self . runner . oldstdout = sys . stdout self . runner . oldstderr = sys . stderr self . runner . startReactor = lambda * args : None def test_success ( self ) : \"\"\"\"\"\" with AlternateReactor ( FakeDaemonizingReactor ( ) ) : self . runner . postApplication ( ) self . assertEqual ( self . mockos . actions , [ ( '' , '' ) , ( '' , ) , ( '' , True ) , '' , ( '' , True ) , ( '' , - , '' ) , ( '' , '' ) ] ) self . assertEqual ( self . mockos . closed , [ - , - ] ) def test_successInParent ( self ) : \"\"\"\"\"\" self . mockos . child = False self . mockos . readData = \"\" with AlternateReactor ( FakeDaemonizingReactor ( ) ) : self . assertRaises ( SystemError , self . runner . postApplication ) self . assertEqual ( self . mockos . actions , [ ( '' , '' ) , ( '' , ) , ( '' , True ) , ( '' , - , ) , ( '' , ) , ( '' , '' ) ] ) self . assertEqual ( self . mockos . closed , [ - ] ) def test_successEINTR ( self ) : \"\"\"\"\"\" written = [ ] def raisingWrite ( fd , data ) : written . append ( ( fd , data ) ) if len ( written ) == : raise IOError ( errno . EINTR ) self . mockos . write = raisingWrite with AlternateReactor ( FakeDaemonizingReactor ( ) ) : self . runner . postApplication ( ) self . assertEqual ( self . mockos . actions , [ ( '' , '' ) , ( '' , ) , ( '' , True ) , '' , ( '' , True ) , ( '' , '' ) ] ) self . assertEqual ( self . mockos . closed , [ - , - ] ) self . assertEqual ( [ ( - , '' ) , ( - , '' ) ] , written ) def test_successInParentEINTR ( self ) : \"\"\"\"\"\" read = [ ] def raisingRead ( fd , size ) : read . append ( ( fd , size ) ) if len ( read ) == : raise IOError ( errno . EINTR ) return \"\" self . mockos . read = raisingRead self . mockos . child = False with AlternateReactor ( FakeDaemonizingReactor ( ) ) : self . assertRaises ( SystemError , self . runner . postApplication ) self . assertEqual ( self . mockos . actions , [ ( '' , '' ) , ( '' , ) , ( '' , True ) , ( '' , ) , ( '' , '' ) ] ) self . assertEqual ( self . mockos . closed , [ - ] ) self . assertEqual ( [ ( - , ) , ( - , ) ] , read ) def test_error ( self ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " import os from giotto . utils import parse_kwargs from giotto . controllers import GiottoController from giotto . control import Redirection cmd_execution_snippet = \"\"\"\"\"\" def make_cmd_invocation ( invocation , args , kwargs ) : \"\"\"\"\"\" if not invocation . endswith ( '' ) : invocation += '' if not invocation . startswith ( '' ) : invocation = '' + invocation cmd = invocation for arg in args : cmd += str ( arg ) + \"\" rendered_kwargs = [ ] for k , v in kwargs . items ( ) : rendered_kwargs . append ( \"\" % ( k , v ) ) return [ '' , cmd ] + rendered_kwargs class CMDRequest ( object ) : def __init__ ( self , argv ) : self . enviornment = os . environ self . argv = argv class CMDController ( GiottoController ) : \"\"\"\"\"\" name = '' default_mimetype = '' def get_invocation ( self ) : return self . request . argv [ ] def get_controller_name ( self ) : return '' def get_raw_data ( self ) : \"\"\"\"\"\" arguments = self . request . argv [ : ] if not arguments [ ] . startswith ( '' ) : arguments = arguments [ : ] return parse_kwargs ( arguments ) def get_concrete_response ( self ) : result = self . get_data_response ( ) if type ( result ) == Redirection : invocation , args , kwargs = result . rendered_invocation rendered_invocation = make_cmd_invocation ( invocation , args , kwargs ) req = CMDRequest ( rendered_invocation ) return CMDController ( req , self . manifest , self . model_mock ) else : response = { '' : [ result [ '' ] ] , '' : [ ] , } ", "answer": "stdout = response [ '' ]"}, {"prompt": " from django . contrib . auth import get_user_model import mock from django . test import TestCase from pushy . utils import send_push_notification from pushy . models import PushNotification , Device class AddTaskTestCase ( TestCase ) : def setUp ( self ) : self . payload = { '' : '' , '' : '' , } def test_add_task ( self ) : mock_task = mock . Mock ( ) with mock . patch ( '' , new = mock_task ) as mocked_task : send_push_notification ( '' , self . payload ) notification = PushNotification . objects . latest ( '' ) mocked_task . assert_called_once_with ( notification_id = notification . id ) self . assertEquals ( notification . payload , self . payload ) def test_add_task_filter_device ( self ) : device = Device . objects . create ( key = '' , type = Device . DEVICE_TYPE_IOS ) mock_task = mock . Mock ( ) with mock . patch ( '' , new = mock_task ) as mocked_task : send_push_notification ( '' , self . payload , device = device ) notification = PushNotification . objects . latest ( '' ) mocked_task . assert_called_with ( kwargs = { '' : device . id , '' : notification . payload } ) def test_add_task_filter_on_user ( self ) : user = get_user_model ( ) . objects . create_user ( username = '' , email = '' , password = '' ) mock_task = mock . Mock ( ) with mock . patch ( '' , new = mock_task ) as mocked_task : send_push_notification ( '' , self . payload , filter_user = user ) notification = PushNotification . objects . latest ( '' ) mocked_task . assert_called_with ( notification_id = notification . id ) self . assertEqual ( notification . filter_user , user . id ) self . assertEqual ( notification . filter_type , ) def test_add_task_filter_on_device_type ( self ) : mock_task = mock . Mock ( ) with mock . patch ( '' , new = mock_task ) as mocked_task : send_push_notification ( '' , self . payload , filter_type = Device . DEVICE_TYPE_IOS ) notification = PushNotification . objects . latest ( '' ) mocked_task . assert_called_with ( notification_id = notification . id ) self . assertEqual ( notification . filter_user , ) self . assertEqual ( notification . filter_type , Device . DEVICE_TYPE_IOS ) def test_add_task_filter_on_device_type_and_user ( self ) : user = get_user_model ( ) . objects . create_user ( username = '' , email = '' , password = '' ) mock_task = mock . Mock ( ) with mock . patch ( '' , new = mock_task ) as mocked_task : send_push_notification ( '' , self . payload , filter_type = Device . DEVICE_TYPE_IOS , filter_user = user ) notification = PushNotification . objects . latest ( '' ) mocked_task . assert_called_with ( notification_id = notification . id ) ", "answer": "self . assertEqual ( notification . filter_user , user . id )"}, {"prompt": " from msrest . pipeline import ClientRawResponse from msrestazure . azure_exceptions import CloudError from msrestazure . azure_operation import AzureOperationPoller import uuid from . . import models class DeploymentsOperations ( object ) : \"\"\"\"\"\" def __init__ ( self , client , config , serializer , deserializer ) : self . _client = client self . _serialize = serializer self . _deserialize = deserializer self . config = config def delete ( self , resource_group_name , deployment_name , custom_headers = { } , raw = False , ** operation_config ) : \"\"\"\"\"\" url = '' path_format_arguments = { '' : self . _serialize . url ( \"\" , resource_group_name , '' , pattern = '' ) , '' : self . _serialize . url ( \"\" , deployment_name , '' ) , '' : self . _serialize . url ( \"\" , self . config . subscription_id , '' ) } url = self . _client . format_url ( url , ** path_format_arguments ) query_parameters = { } query_parameters [ '' ] = self . _serialize . query ( \"\" , self . config . api_version , '' ) header_parameters = { } header_parameters [ '' ] = '' if self . config . generate_client_request_id : header_parameters [ '' ] = str ( uuid . uuid1 ( ) ) if custom_headers : header_parameters . update ( custom_headers ) if self . config . accept_language is not None : header_parameters [ '' ] = self . _serialize . header ( \"\" , self . config . accept_language , '' ) def long_running_send ( ) : request = self . _client . delete ( url , query_parameters ) return self . _client . send ( request , header_parameters , ** operation_config ) def get_long_running_status ( status_link , headers = { } ) : request = self . _client . get ( status_link ) request . headers . update ( headers ) return self . _client . send ( request , header_parameters , ** operation_config ) def get_long_running_output ( response ) : if response . status_code not in [ , ] : exp = CloudError ( response ) exp . request_id = response . headers . get ( '' ) raise exp if raw : client_raw_response = ClientRawResponse ( None , response ) return client_raw_response if raw : response = long_running_send ( ) return get_long_running_output ( response ) long_running_operation_timeout = operation_config . get ( '' , self . config . long_running_operation_timeout ) return AzureOperationPoller ( long_running_send , get_long_running_output , get_long_running_status , long_running_operation_timeout ) def check_existence ( self , resource_group_name , deployment_name , custom_headers = { } , raw = False , ** operation_config ) : \"\"\"\"\"\" url = '' path_format_arguments = { '' : self . _serialize . url ( \"\" , resource_group_name , '' , pattern = '' ) , '' : self . _serialize . url ( \"\" , deployment_name , '' ) , '' : self . _serialize . url ( \"\" , self . config . subscription_id , '' ) } url = self . _client . format_url ( url , ** path_format_arguments ) query_parameters = { } query_parameters [ '' ] = self . _serialize . query ( \"\" , self . config . api_version , '' ) header_parameters = { } header_parameters [ '' ] = '' if self . config . generate_client_request_id : header_parameters [ '' ] = str ( uuid . uuid1 ( ) ) if custom_headers : header_parameters . update ( custom_headers ) if self . config . accept_language is not None : header_parameters [ '' ] = self . _serialize . header ( \"\" , self . config . accept_language , '' ) request = self . _client . head ( url , query_parameters ) response = self . _client . send ( request , header_parameters , ** operation_config ) if response . status_code not in [ , ] : exp = CloudError ( response ) exp . request_id = response . headers . get ( '' ) raise exp deserialized = ( response . status_code == ) if raw : client_raw_response = ClientRawResponse ( deserialized , response ) return client_raw_response return deserialized def create_or_update ( self , resource_group_name , deployment_name , properties = None , custom_headers = { } , raw = False , ** operation_config ) : \"\"\"\"\"\" parameters = models . Deployment ( properties = properties ) url = '' path_format_arguments = { '' : self . _serialize . url ( \"\" , resource_group_name , '' , pattern = '' ) , '' : self . _serialize . url ( \"\" , deployment_name , '' ) , '' : self . _serialize . url ( \"\" , self . config . subscription_id , '' ) } url = self . _client . format_url ( url , ** path_format_arguments ) query_parameters = { } query_parameters [ '' ] = self . _serialize . query ( \"\" , self . config . api_version , '' ) header_parameters = { } header_parameters [ '' ] = '' if self . config . generate_client_request_id : header_parameters [ '' ] = str ( uuid . uuid1 ( ) ) if custom_headers : header_parameters . update ( custom_headers ) if self . config . accept_language is not None : header_parameters [ '' ] = self . _serialize . header ( \"\" , self . config . accept_language , '' ) body_content = self . _serialize . body ( parameters , '' ) def long_running_send ( ) : request = self . _client . put ( url , query_parameters ) return self . _client . send ( request , header_parameters , body_content , ** operation_config ) def get_long_running_status ( status_link , headers = { } ) : request = self . _client . get ( status_link ) request . headers . update ( headers ) return self . _client . send ( request , header_parameters , ** operation_config ) def get_long_running_output ( response ) : if response . status_code not in [ , ] : exp = CloudError ( response ) exp . request_id = response . headers . get ( '' ) raise exp deserialized = None if response . status_code == : deserialized = self . _deserialize ( '' , response ) if response . status_code == : deserialized = self . _deserialize ( '' , response ) if raw : client_raw_response = ClientRawResponse ( deserialized , response ) return client_raw_response return deserialized if raw : response = long_running_send ( ) return get_long_running_output ( response ) long_running_operation_timeout = operation_config . get ( '' , self . config . long_running_operation_timeout ) return AzureOperationPoller ( long_running_send , get_long_running_output , get_long_running_status , long_running_operation_timeout ) def get ( self , resource_group_name , deployment_name , custom_headers = { } , raw = False , ** operation_config ) : \"\"\"\"\"\" url = '' path_format_arguments = { '' : self . _serialize . url ( \"\" , resource_group_name , '' , pattern = '' ) , '' : self . _serialize . url ( \"\" , deployment_name , '' ) , '' : self . _serialize . url ( \"\" , self . config . subscription_id , '' ) } url = self . _client . format_url ( url , ** path_format_arguments ) query_parameters = { } query_parameters [ '' ] = self . _serialize . query ( \"\" , self . config . api_version , '' ) header_parameters = { } header_parameters [ '' ] = '' if self . config . generate_client_request_id : header_parameters [ '' ] = str ( uuid . uuid1 ( ) ) if custom_headers : header_parameters . update ( custom_headers ) if self . config . accept_language is not None : header_parameters [ '' ] = self . _serialize . header ( \"\" , self . config . accept_language , '' ) request = self . _client . get ( url , query_parameters ) response = self . _client . send ( request , header_parameters , ** operation_config ) if response . status_code not in [ ] : exp = CloudError ( response ) exp . request_id = response . headers . get ( '' ) raise exp deserialized = None if response . status_code == : deserialized = self . _deserialize ( '' , response ) if raw : client_raw_response = ClientRawResponse ( deserialized , response ) return client_raw_response return deserialized def cancel ( self , resource_group_name , deployment_name , custom_headers = { } , raw = False , ** operation_config ) : \"\"\"\"\"\" url = '' path_format_arguments = { '' : self . _serialize . url ( \"\" , resource_group_name , '' , pattern = '' ) , '' : self . _serialize . url ( \"\" , deployment_name , '' ) , '' : self . _serialize . url ( \"\" , self . config . subscription_id , '' ) } url = self . _client . format_url ( url , ** path_format_arguments ) query_parameters = { } query_parameters [ '' ] = self . _serialize . query ( \"\" , self . config . api_version , '' ) header_parameters = { } header_parameters [ '' ] = '' if self . config . generate_client_request_id : header_parameters [ '' ] = str ( uuid . uuid1 ( ) ) if custom_headers : header_parameters . update ( custom_headers ) if self . config . accept_language is not None : header_parameters [ '' ] = self . _serialize . header ( \"\" , self . config . accept_language , '' ) request = self . _client . post ( url , query_parameters ) response = self . _client . send ( request , header_parameters , ** operation_config ) if response . status_code not in [ ] : exp = CloudError ( response ) exp . request_id = response . headers . get ( '' ) raise exp if raw : client_raw_response = ClientRawResponse ( None , response ) return client_raw_response def validate ( self , resource_group_name , deployment_name , properties = None , custom_headers = { } , raw = False , ** operation_config ) : \"\"\"\"\"\" parameters = models . Deployment ( properties = properties ) url = '' path_format_arguments = { '' : self . _serialize . url ( \"\" , resource_group_name , '' , pattern = '' ) , '' : self . _serialize . url ( \"\" , deployment_name , '' ) , '' : self . _serialize . url ( \"\" , self . config . subscription_id , '' ) } url = self . _client . format_url ( url , ** path_format_arguments ) query_parameters = { } query_parameters [ '' ] = self . _serialize . query ( \"\" , self . config . api_version , '' ) header_parameters = { } header_parameters [ '' ] = '' if self . config . generate_client_request_id : header_parameters [ '' ] = str ( uuid . uuid1 ( ) ) if custom_headers : header_parameters . update ( custom_headers ) if self . config . accept_language is not None : header_parameters [ '' ] = self . _serialize . header ( \"\" , self . config . accept_language , '' ) body_content = self . _serialize . body ( parameters , '' ) request = self . _client . post ( url , query_parameters ) response = self . _client . send ( request , header_parameters , body_content , ** operation_config ) if response . status_code not in [ , ] : exp = CloudError ( response ) exp . request_id = response . headers . get ( '' ) raise exp deserialized = None if response . status_code == : deserialized = self . _deserialize ( '' , response ) if response . status_code == : deserialized = self . _deserialize ( '' , response ) if raw : client_raw_response = ClientRawResponse ( deserialized , response ) return client_raw_response return deserialized def export_template ( self , resource_group_name , deployment_name , custom_headers = { } , raw = False , ** operation_config ) : \"\"\"\"\"\" url = '' path_format_arguments = { '' : self . _serialize . url ( \"\" , resource_group_name , '' , pattern = '' ) , '' : self . _serialize . url ( \"\" , deployment_name , '' ) , '' : self . _serialize . url ( \"\" , self . config . subscription_id , '' ) } url = self . _client . format_url ( url , ** path_format_arguments ) query_parameters = { } query_parameters [ '' ] = self . _serialize . query ( \"\" , self . config . api_version , '' ) header_parameters = { } header_parameters [ '' ] = '' if self . config . generate_client_request_id : ", "answer": "header_parameters [ '' ] = str ( uuid . uuid1 ( ) )"}, {"prompt": " import os import warnings from txamqp . content import Content import txamqp . spec from txamqp . protocol import AMQClient from txamqp . client import TwistedDelegate from twisted . internet import error , protocol , reactor from twisted . trial import unittest from twisted . internet . defer import inlineCallbacks , Deferred , returnValue from txamqp . queue import Empty RABBITMQ = \"\" OPENAMQ = \"\" QPID = \"\" class supportedBrokers ( object ) : def __init__ ( self , * supporterBrokers ) : self . supporterBrokers = supporterBrokers def __call__ ( self , f ) : if _get_broker ( ) not in self . supporterBrokers : f . skip = \"\" return f def _get_broker ( ) : return os . environ . get ( \"\" ) USERNAME = '' PASSWORD = '' VHOST = '' HEARTBEAT = class TestBase ( unittest . TestCase ) : clientClass = AMQClient heartbeat = HEARTBEAT def __init__ ( self , * args , ** kwargs ) : unittest . TestCase . __init__ ( self , * args , ** kwargs ) self . host = '' self . port = self . broker = _get_broker ( ) if self . broker is None : warnings . warn ( \"\" \"\" ) self . broker = RABBITMQ if self . broker == RABBITMQ : self . spec = '' elif self . broker == OPENAMQ : self . spec = '' elif self . broker == QPID : self . spec = '' else : raise RuntimeError ( \"\" \"\" % self . broker ) self . user = USERNAME self . password = PASSWORD self . vhost = VHOST self . queues = [ ] self . exchanges = [ ] self . connectors = [ ] @ inlineCallbacks def connect ( self , host = None , port = None , spec = None , user = None , password = None , vhost = None , heartbeat = None , clientClass = None ) : host = host or self . host port = port or self . port spec = spec or self . spec user = user or self . user password = password or self . password vhost = vhost or self . vhost heartbeat = heartbeat or self . heartbeat clientClass = clientClass or self . clientClass delegate = TwistedDelegate ( ) onConn = Deferred ( ) p = clientClass ( delegate , vhost , txamqp . spec . load ( spec ) , heartbeat = heartbeat ) f = protocol . _InstanceFactory ( reactor , p , onConn ) c = reactor . connectTCP ( host , port , f ) def errb ( thefailure ) : thefailure . trap ( error . ConnectionRefusedError ) print \"\" \"\" % ( host , port , self . broker , thefailure , ) thefailure . raiseException ( ) onConn . addErrback ( errb ) self . connectors . append ( c ) client = yield onConn yield client . authenticate ( user , password ) returnValue ( client ) @ inlineCallbacks def setUp ( self ) : try : self . client = yield self . connect ( ) except txamqp . client . Closed , le : le . args = tuple ( ( \"\" \"\" \"\" % ( _get_broker ( ) , USERNAME , PASSWORD , VHOST ) , ) + le . args ) raise self . channel = yield self . client . channel ( ) yield self . channel . channel_open ( ) @ inlineCallbacks def tearDown ( self ) : for ch , q in self . queues : yield ch . queue_delete ( queue = q ) for ch , ex in self . exchanges : yield ch . exchange_delete ( exchange = ex ) for connector in self . connectors : yield connector . disconnect ( ) @ inlineCallbacks def queue_declare ( self , channel = None , * args , ** keys ) : channel = channel or self . channel reply = yield channel . queue_declare ( * args , ** keys ) self . queues . append ( ( channel , reply . queue ) ) returnValue ( reply ) @ inlineCallbacks def exchange_declare ( self , channel = None , ticket = , exchange = '' , type = '' , passive = False , durable = False , auto_delete = False , internal = False , nowait = False , arguments = { } ) : channel = channel or self . channel reply = yield channel . exchange_declare ( ticket , exchange , type , passive , durable , auto_delete , internal , nowait , arguments ) self . exchanges . append ( ( channel , exchange ) ) returnValue ( reply ) def assertChannelException ( self , expectedCode , message ) : self . assertEqual ( \"\" , message . method . klass . name ) self . assertEqual ( \"\" , message . method . name ) self . assertEqual ( expectedCode , message . reply_code ) def assertConnectionException ( self , expectedCode , message ) : self . assertEqual ( \"\" , message . method . klass . name ) self . assertEqual ( \"\" , message . method . name ) self . assertEqual ( expectedCode , message . reply_code ) @ inlineCallbacks def consume ( self , queueName ) : \"\"\"\"\"\" reply = yield self . channel . basic_consume ( queue = queueName , no_ack = True ) returnValue ( ( yield self . client . queue ( reply . consumer_tag ) ) ) ", "answer": "@ inlineCallbacks"}, {"prompt": " import json from optparse import make_option from summary_data . models import District , Candidate_Overlay from django . core . management . base import BaseCommand , CommandError class Command ( BaseCommand ) : help = \"\" requires_model_validation = False ", "answer": "option_list = BaseCommand . option_list + ("}, {"prompt": " from atom . api import Unicode , Typed , ForwardTyped , observe , set_default from enaml . core . declarative import d_ from . control import Control , ProxyControl class ProxyHtml ( ProxyControl ) : \"\"\"\"\"\" declaration = ForwardTyped ( lambda : Html ) def set_source ( self , source ) : raise NotImplementedError class Html ( Control ) : \"\"\"\"\"\" source = d_ ( Unicode ( ) ) hug_width = set_default ( '' ) hug_height = set_default ( '' ) proxy = Typed ( ProxyHtml ) @ observe ( '' ) def _update_proxy ( self , change ) : \"\"\"\"\"\" ", "answer": "super ( Html , self ) . _update_proxy ( change ) "}, {"prompt": " \"\"\"\"\"\" import json import xml . etree . ElementTree as ET from cafe . engine . models . base import AutoMarshallingModel from cloudcafe . compute . common . equality_tools import EqualityTools from cloudcafe . compute . hosts_api . models . resources import Resource class Host ( AutoMarshallingModel ) : def __init__ ( self , ** kwargs ) : for key , value in kwargs . iteritems ( ) : setattr ( self , key , value ) def __eq__ ( self , other ) : \"\"\"\"\"\" return EqualityTools . are_objects_equal ( self , other ) def __ne__ ( self , other ) : \"\"\"\"\"\" return not self . __eq__ ( other ) @ classmethod def _json_to_obj ( cls , serialized_str ) : \"\"\"\"\"\" json_dict = json . loads ( serialized_str ) if '' in json_dict . keys ( ) : resources = [ ] for resource in json_dict . get ( \"\" ) : resources . append ( Resource . _dict_to_obj ( resource . get ( \"\" ) ) ) host = Host ( resources = resources ) return host if '' in json_dict . keys ( ) : hosts = [ ] for host_dict in json_dict . get ( \"\" ) : hosts . append ( cls . _dict_to_obj ( host_dict ) ) return hosts @ classmethod def _dict_to_obj ( cls , host_dict ) : \"\"\"\"\"\" host = Host ( ** host_dict ) return host @ classmethod def _xml_to_obj ( cls , serialized_str ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " from __future__ import unicode_literals from datetime import datetime from django . contrib . auth import get_user_model from django . contrib . auth . models import Group from django . core . urlresolvers import reverse from django . test import TestCase , Client from django . utils . encoding import force_text from . . models import Post , Comment class BaseIntegrationTest ( TestCase ) : \"\"\"\"\"\" def setUp ( self ) : self . client = Client ( ) self . user = get_user_model ( ) ( username = '' , is_staff = True , is_superuser = True ) self . user . set_password ( \"\" ) self . user . save ( ) self . client . login ( username = '' , password = '' ) class AdminIndexTest ( BaseIntegrationTest ) : def test_view_ok ( self ) : response = self . client . get ( reverse ( \"\" ) ) self . assertContains ( response , reverse ( \"\" ) ) class UserListTest ( BaseIntegrationTest ) : def test_search_users_m2m_group ( self ) : group = Group . objects . create ( name = \"\" ) self . user . groups . add ( group ) params = { \"\" : \"\" } response = self . client . get ( reverse ( \"\" ) , params ) self . assertContains ( response , '' ) class CommentListTest ( BaseIntegrationTest ) : def test_search_comments ( self ) : post_1 = Post . objects . create ( title = \"\" , body = \"\" ) post_2 = Post . objects . create ( title = \"\" , body = \"\" ) Comment . objects . create ( body = \"\" , post = post_1 ) Comment . objects . create ( body = \"\" , post = post_1 ) Comment . objects . create ( body = \"\" , post = post_2 ) params = { \"\" : \"\" } response = self . client . get ( reverse ( \"\" ) , params ) self . assertContains ( response , \"\" ) self . assertContains ( response , \"\" ) self . assertNotContains ( response , \"\" ) def test_list_selected_hides ( self ) : post_1 = Post . objects . create ( title = \"\" , body = \"\" ) Comment . objects . create ( body = \"\" , post = post_1 ) response = self . client . get ( reverse ( \"\" ) ) self . assertNotContains ( response , \"\" ) class PostListTest ( BaseIntegrationTest ) : def _create_posts ( self ) : Post . objects . bulk_create ( [ Post ( title = \"\" , body = \"\" , published_date = datetime ( month = , day = , year = ) ) , Post ( title = \"\" , body = \"\" , published_date = datetime ( month = , day = , year = , ) ) , Post ( title = \"\" , body = \"\" , published_date = datetime ( month = , day = , year = , ) , ) , Post ( title = \"\" , body = \"\" , published_date = datetime ( month = , day = , year = , ) ) , Post ( title = \"\" , body = \"\" , published_date = datetime ( month = , day = , year = , ) ) , ] ) def test_view_ok ( self ) : post = Post . objects . create ( title = \"\" , body = \"\" ) response = self . client . get ( reverse ( \"\" ) ) self . assertContains ( response , post . title ) def test_list_filter_presence ( self ) : Post . objects . create ( title = \"\" , body = \"\" ) Post . objects . create ( title = \"\" , body = \"\" ) response = self . client . get ( reverse ( \"\" ) ) self . assertContains ( response , '' ) def test_list_selected_shows ( self ) : Post . objects . create ( title = \"\" , body = \"\" ) response = self . client . get ( reverse ( \"\" ) ) self . assertContains ( response , '' ) def test_actions_displayed ( self ) : response = self . client . get ( reverse ( \"\" ) ) self . assertInHTML ( '' , force_text ( response . content ) ) def test_actions_displayed_twice ( self ) : response = self . client . get ( reverse ( \"\" ) ) self . assertContains ( response , '' ) self . assertContains ( response , '' ) def test_delete_selected_post ( self ) : post = Post . objects . create ( title = \"\" , body = \"\" ) params = { '' : '' , '' : str ( post . pk ) } response = self . client . post ( reverse ( \"\" ) , params ) self . assertInHTML ( '' , force_text ( response . content ) ) def test_delete_selected_post_confirmation ( self ) : post = Post . objects . create ( title = \"\" , body = \"\" ) params = { '' : '' , '' : str ( post . pk ) , '' : '' } response = self . client . post ( reverse ( \"\" ) , params ) self . assertRedirects ( response , reverse ( \"\" ) ) def test_delete_selected_post_none_selected ( self ) : Post . objects . create ( title = \"\" , body = \"\" ) params = { '' : '' } response = self . client . post ( reverse ( \"\" ) , params , follow = True ) self . assertContains ( response , \"\" ) def test_search_posts ( self ) : Post . objects . create ( title = \"\" , body = \"\" ) Post . objects . create ( title = \"\" , body = \"\" ) Post . objects . create ( title = \"\" , body = \"\" ) params = { \"\" : \"\" } response = self . client . get ( reverse ( \"\" ) , params ) self . assertContains ( response , \"\" ) self . assertContains ( response , \"\" ) self . assertNotContains ( response , \"\" ) def test_renderer_title ( self ) : Post . objects . create ( title = '' , body = '' , published = False ) response = self . client . get ( reverse ( '' ) ) ", "answer": "self . assertContains ( response , '' )"}, {"prompt": " import os import socket import sys import httplib import time import StringIO from db_status import DBStatus from trace_event import * _is_prelaunched_process = False def is_prelaunched_process ( ) : return _is_prelaunched_process def wait_for_command ( control_port ) : global _is_prelaunched_process _is_prelaunched_process = True s = socket . socket ( ) try : trace_begin ( \"\" ) bound = False for i in range ( ) : try : s . bind ( ( \"\" , control_port ) ) bound = True break except socket . error : time . sleep ( ) if not bound : raise Exception ( \"\" ) trace_end ( \"\" ) s . listen ( ) trace_begin ( \"\" ) c , a = s . accept ( ) trace_end ( \"\" ) f = c . makefile ( ) trace_begin ( \"\" ) args = eval ( f . readline ( ) , { } , { } ) trace_end ( \"\" ) import quickopen import optparse old_stdout = sys . stdout new_stdout = StringIO . StringIO ( ) sys . stdout = new_stdout old_argv = sys . argv try : ", "answer": "sys . argv = [ sys . argv [ ] ]"}, {"prompt": " \"\"\"\"\"\" import pymel . core . context as context import maya import pymel . core . rendering as rendering import maya . cmds as cmds import pymel . util as util import pymel . core . runtime as runtime import pymel . api as api import pymel . core . system as system import pymel . core . uitypes as ui import pymel . core . uitypes as uitypes import pymel . core . nodetypes as nodetypes import pymel . core . nodetypes as nt import pymel . core . animation as animation import pymel . core . datatypes as dt import pymel . core . language as language import pymel . core . windows as windows import pymel . core . modeling as modeling import pymel . core . effects as effects from pymel . core . general import * from pymel . core . system import * from pymel . core . windows import * from pymel . core . animation import * from pymel . core . context import * from pymel . core . modeling import * from pymel . core . other import * from pymel . core . rendering import * from pymel . core . effects import * from pymel . core . language import Env from pymel . core . language import callbacks from pymel . core . language import MelConversionError from pymel . core . language import MelError from pymel . core . language import Mel from pymel . core . language import evalNoSelectNotify from pymel . core . language import Catch from pymel . core . language import getProcArguments from pymel . core . language import pythonToMel from pymel . core . language import stackTrace from pymel . core . language import resourceManager from pymel . core . language import isValidMelType from pymel . core . language import getMelType from pymel . core . language import conditionExists from pymel . core . language import OptionVarList from pymel . core . language import MelUnknownProcedureError from pymel . core . language import getLastError from pymel . core . language import MelArgumentError from pymel . core . language import evalEcho from pymel . core . language import getMelGlobal from pymel . core . language import OptionVarDict from pymel . core . language import MelGlobals ", "answer": "from pymel . core . language import scriptJob"}, {"prompt": " from __future__ import with_statement import re import datetime import time import errors import threading import gsmcodecs from gsmmodem import GsmModem from devicewrapper import DeviceWrapper from pdusmshandler import PduSmsHandler from textsmshandler import TextSmsHandler class GsmModemNotFound ( Exception ) : pass class AutoGsmModem ( GsmModem ) : \"\"\"\"\"\" cmd_delay = retry_delay = max_retries = modem_lock = threading . RLock ( ) def __init__ ( self , * args , ** kwargs ) : import prober \"\"\"\"\"\" if kwargs . get ( '' , False ) : proberargs = { '' : True } else : proberargs = { } try : del kwargs [ '' ] except : ", "answer": "pass"}, {"prompt": " from asciimatics . renderers import BarChart from asciimatics . screen import Screen import sys import math import time from random import randint def fn ( ) : return randint ( , ) def wv ( x ) : return lambda : + math . sin ( math . pi * ( * time . time ( ) + x ) / ) def demo ( ) : chart = BarChart ( , , [ fn , fn ] , char = \"\" , gradient = [ ( , Screen . COLOUR_GREEN ) , ( , Screen . COLOUR_YELLOW ) , ( , Screen . COLOUR_RED ) ] ) print ( chart ) chart = BarChart ( , , [ wv ( ) , wv ( ) , wv ( ) , wv ( ) , wv ( ) , wv ( ) , wv ( ) , wv ( ) ] , colour = Screen . COLOUR_GREEN , axes = BarChart . BOTH , scale = ) print ( chart ) chart = BarChart ( , , [ lambda : time . time ( ) * % ] , gradient = [ ( , ) , ( , ) , ( , ) , ( , ) , ( , ) , ( , ) , ( , ) , ( , ) , ( , ) , ( , ) ] , char = \">\" , scale = , labels = True , axes = BarChart . X_AXIS ) print ( chart ) chart = BarChart ( , , [ wv ( ) , wv ( ) , wv ( ) , wv ( ) , wv ( ) , wv ( ) , wv ( ) , wv ( ) ] , colour = [ c for c in range ( , ) ] , scale = , axes = BarChart . X_AXIS , intervals = , labels = True , border = False ) ", "answer": "print ( chart )"}, {"prompt": " from dnslib import * q = DNSRecord ( q = DNSQuestion ( \"\" , QTYPE . ANY ) ) a = q . reply ( ) a . add_answer ( RR ( \"\" , QTYPE . A , rdata = A ( \"\" ) , ttl = ) ) print str ( DNSRecord . parse ( a . pack ( ) ) ) == str ( a ) print a a . add_answer ( RR ( \"\" , QTYPE . A , rdata = A ( \"\" ) ) ) a . add_answer ( RR ( \"\" , QTYPE . AAAA , rdata = AAAA ( \"\" ) ) ) ", "answer": "print str ( DNSRecord . parse ( a . pack ( ) ) ) == str ( a )"}, {"prompt": " import sys import textwrap import argparse from calvin . actorstore . store import DocumentationStore from calvin . Tools import cscompiler from calvin . csparser . parser import calvin_parser def _refname ( name ) : return \"\" if name == '' else name . replace ( '' , '' ) class Viz ( object ) : \"\"\"\"\"\" def __init__ ( self ) : super ( Viz , self ) . __init__ ( ) def __str__ ( self ) : raise Exception ( \"\" ) def render ( self ) : return str ( self ) class LinkViz ( Viz ) : \"\"\"\"\"\" def __init__ ( self , link ) : super ( LinkViz , self ) . __init__ ( ) link [ '' ] = _refname ( link [ '' ] ) link [ '' ] = _refname ( link [ '' ] ) self . link = link def __str__ ( self ) : if not self . link [ '' ] : return '' . format ( ** self . link ) elif not self . link [ '' ] : return '' . format ( ** self . link ) else : return '' . format ( ** self . link ) class ActorViz ( Viz ) : \"\"\"\"\"\" docstore = DocumentationStore ( ) def __init__ ( self , name , actor_type , args , ** dummy ) : super ( ActorViz , self ) . __init__ ( ) self . type_color = '' self . name = name self . args = args self . actor_type = actor_type doc = self . docstore . help_raw ( actor_type ) self . set_ports ( doc ) def set_ports ( self , doc ) : inports = [ p for p , _ in doc [ '' ] ] outports = [ p for p , _ in doc [ '' ] ] inlen = len ( inports ) outlen = len ( outports ) ", "answer": "self . portrows = max ( inlen , outlen )"}, {"prompt": " \"\"\"\"\"\" from __future__ import division , print_function , absolute_import import warnings import numpy as np from numpy . testing import ( TestCase , assert_equal , assert_array_equal , assert_ , assert_allclose , assert_raises , run_module_suite ) from numpy import zeros , arange , array , abs , max , ones , eye , iscomplexobj from scipy . linalg import norm from scipy . sparse import spdiags , csr_matrix , SparseEfficiencyWarning from scipy . sparse . linalg import LinearOperator , aslinearoperator from scipy . sparse . linalg . isolve import cg , cgs , bicg , bicgstab , gmres , qmr , minres , lgmres class Case ( object ) : def __init__ ( self , name , A , skip = None ) : self . name = name self . A = A if skip is None : self . skip = [ ] else : self . skip = skip def __repr__ ( self ) : return \"\" % self . name class IterativeParams ( object ) : def __init__ ( self ) : solvers = [ cg , cgs , bicg , bicgstab , gmres , qmr , minres , lgmres ] sym_solvers = [ minres , cg ] posdef_solvers = [ cg ] real_solvers = [ minres ] self . solvers = solvers self . cases = [ ] N = data = ones ( ( , N ) ) data [ , : ] = data [ , : ] = - data [ , : ] = - Poisson1D = spdiags ( data , [ , - , ] , N , N , format = '' ) self . Poisson1D = Case ( \"\" , Poisson1D ) self . cases . append ( Case ( \"\" , Poisson1D ) ) self . cases . append ( Case ( \"\" , Poisson1D . astype ( '' ) , skip = [ minres ] ) ) self . cases . append ( Case ( \"\" , - Poisson1D , ", "answer": "skip = posdef_solvers ) )"}, {"prompt": " import pytest from chillaxd import datatree class TestDataTree ( object ) : def setup_method ( self , method ) : self . test_dt = datatree . DataTree ( ) def test_create_node ( self ) : self . test_dt . create_node ( \"\" . encode ( \"\" ) , \"\" . encode ( \"\" ) ) assert [ \"\" ] == self . test_dt . get_children ( \"\" . encode ( \"\" ) ) assert \"\" == self . test_dt . get_data ( \"\" . encode ( \"\" ) ) self . test_dt . create_node ( \"\" . encode ( \"\" ) , \"\" . encode ( \"\" ) ) assert [ \"\" ] == self . test_dt . get_children ( \"\" . encode ( \"\" ) ) ", "answer": "assert \"\" == self . test_dt . get_data ( \"\" . encode ( \"\" ) )"}, {"prompt": " import os , sys , sha , zlib content = sys . stdin . read ( ) type = '' object = '' % ( type , len ( content ) , content ) sha1sum = sha . new ( object ) . hexdigest ( ) container = '' % sha1sum [ : ] if not os . path . exists ( container ) : os . mkdir ( container ) open ( '' % ( container , sha1sum [ : ] ) , '' ) . write ( zlib . compress ( object ) ) ", "answer": "print sha1sum "}, {"prompt": " __author__ = '' import random from pybrain import SharedFullConnection , MotherConnection , MDLSTMLayer , IdentityConnection from pybrain import ModuleMesh , LinearLayer , TanhLayer , SigmoidLayer from pybrain . structure . networks import BorderSwipingNetwork class CaptureGameNetwork ( BorderSwipingNetwork ) : \"\"\"\"\"\" size = insize = hsize = predefined = None directlink = False componentclass = TanhLayer outcomponentclass = SigmoidLayer peepholes = False outputs = comboutputs = combinputs = rebuilt = False def __init__ ( self , ** args ) : \"\"\"\"\"\" if '' in args : self . size = args [ '' ] args [ '' ] = ( self . size , self . size ) assert self . size > , '' BorderSwipingNetwork . __init__ ( self , ** args ) if not self . rebuilt : self . _buildCaptureNetwork ( ) self . sortModules ( ) ", "answer": "self . rebuilt = True"}, {"prompt": " from __future__ import print_function , unicode_literals from flask import request , make_response from weblab . core . wl import weblab_api import json import traceback from weblab . data . experiments import ExperimentId from weblab . core . coordinator . clients . ilab_batch import RequestSerializer serializer = RequestSerializer ( ) @ weblab_api . route_web ( '' ) def ilab ( ) : action = request . headers . get ( '' ) if action is None : return \"\" if weblab_api . ctx . session_id is None : return \"\" if weblab_api . ctx . reservation_id is None : try : reservation_id_str = weblab_api . api . get_reservation_id_by_session_id ( ) weblab_api . ctx . reservation_id = reservation_id_str except : traceback . print_exc ( ) methods = { '' : process_GetLabConfiguration , '' : process_Submit , '' : process_GetExperimentStatus , '' : process_RetrieveResult , '' : process_SaveAnnotation , '' : process_ListAllClientItems , '' : process_LoadClientItem , '' : process_SaveClientItem , '' : process_GetExperimentInformation , } if not action in methods : return \"\" response = make_response ( methods [ action ] ( ) ) response . content_type = '' if hasattr ( weblab_api . ctx , '' ) : for name , value in weblab_api . ctx . other_cookies : response . set_cookie ( name , value , path = weblab_api . ctx . location ) return response def process_GetLabConfiguration ( self ) : lab_server_id = serializer . parse_get_lab_configuration_request ( request . data ) ilab_request = { '' : '' , } reservation_status = weblab_api . api . reserve_experiment ( ExperimentId ( lab_server_id , '' ) , json . dumps ( ilab_request ) , '' ) lab_configuration = reservation_status . initial_data return serializer . generate_lab_configuration_response ( lab_configuration ) def process_Submit ( self ) : lab_server_id , experiment_specification , _ , _ = serializer . parse_submit_request ( request . data ) ilab_request = { '' : '' , '' : experiment_specification } reservation_status = weblab_api . api . reserve_experiment ( ExperimentId ( lab_server_id , '' ) , json . dumps ( ilab_request ) , '' ) weblab_api . ctx . other_cookies = { '' : reservation_status . reservation_id . id } return \"\"\"\"\"\" % reservation_status . position def process_GetExperimentStatus ( self ) : if self . reservation_id is None : return \"\" reservation_status = weblab_api . api . get_reservation_status ( ) if reservation_status . status == \"\" : length = reservation_status . position status = elif reservation_status . status == \"\" : length = status = elif reservation_status . status == \"\" : length = status = else : raise Exception ( \"\" % reservation_status . status ) return \"\"\"\"\"\" % ( status , length ) def process_RetrieveResult ( self ) : if self . reservation_id is None : return \"\" reservation_status = weblab_api . api . get_reservation_status ( ) try : response = json . loads ( reservation_status . initial_data ) except : return \"\" % reservation_status . initial_data code = response [ '' ] results = response [ '' ] xmlResults = response [ '' ] return serializer . generate_retrieve_result_response ( code , results , xmlResults ) def process_GetExperimentInformation ( self ) : ", "answer": "return \"\"\"\"\"\""}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import import redhawk try : import anydbm except ImportError : import dbm as anydbm import logging import os import shelve import sys VERSION_KEY = '' \"\"\"\"\"\" def _OpenStore ( store_file ) : return shelve . open ( store_file , '' , protocol = - ) def _CloseStoreObject ( store_object ) : store_object . close ( ) def CreateNewStore ( store_file , version ) : \"\"\"\"\"\" assert ( os . path . exists ( store_file ) == False ) store = _OpenStore ( store_file ) store [ VERSION_KEY ] = version _CloseStoreObject ( store ) assert ( os . path . exists ( store_file ) == True ) return None def RemoveExistingStore ( store_file ) : \"\"\"\"\"\" assert ( os . path . exists ( store_file ) == True ) os . remove ( store_file ) assert ( os . path . exists ( store_file ) == False ) return None def IsValidStore ( store_file ) : \"\"\"\"\"\" try : store = _OpenStore ( store_file ) _CloseStoreObject ( store ) except anydbm . error as e : return False return True ", "answer": "class KeyValueStore :"}, {"prompt": " import os from setuptools import setup EXTRAS = { '' : [ '' ] , '' : [ '' , ] , '' : [ '' , '' , ] , '' : [ '' , ] , '' : [ '' , '' , '' , ] } EXTRAS [ '' ] = ( EXTRAS [ '' ] + EXTRAS [ '' ] + EXTRAS [ '' ] + EXTRAS [ '' ] ) try : from setuptools . command import egg_info egg_info . write_toplevel_names except ( ImportError , AttributeError ) : pass else : def _top_level_package ( name ) : return name . split ( '' , ) [ ] def _hacked_write_toplevel_names ( cmd , basename , filename ) : pkgs = dict . fromkeys ( [ _top_level_package ( k ) for k in cmd . distribution . iter_distribution_names ( ) if _top_level_package ( k ) != \"\" ] ) cmd . write_file ( \"\" , filename , '' . join ( pkgs ) + '' ) egg_info . write_toplevel_names = _hacked_write_toplevel_names def read ( fname ) : return open ( os . path . join ( os . path . dirname ( __file__ ) , fname ) ) . read ( ) setup ( name = \"\" , version = \"\" , author = \"\" , author_email = \"\" , maintainer = \"\" , maintainer_email = \"\" , description = ( \"\" \"\" \"\" ) , license = \"\" , keywords = \"\" , url = \"\" , packages = [ '' , ", "answer": "'' ,"}, {"prompt": " from django . conf . urls import url from captcha import views urlpatterns = [ url ( r'' , views . captcha_image , name = '' , kwargs = { '' : } ) , url ( r'' , views . captcha_image , name = '' , kwargs = { '' : } ) , url ( r'' , views . captcha_audio , name = '' ) , ", "answer": "url ( r'' , views . captcha_refresh , name = '' ) ,"}, {"prompt": " \"\"\"\"\"\" ", "answer": "from pygments . lexer import RegexLexer , bygroups , words"}, {"prompt": " import numpy as np from scipy import sparse as sp from nose . tools import assert_raises , assert_equal from numpy . testing import assert_array_equal from sklearn . base import BaseEstimator from sklearn . feature_selection . base import SelectorMixin from sklearn . utils import check_array class StepSelector ( SelectorMixin , BaseEstimator ) : \"\"\"\"\"\" def __init__ ( self , step = ) : self . step = step def fit ( self , X , y = None ) : X = check_array ( X , '' ) self . n_input_feats = X . shape [ ] return self def _get_support_mask ( self ) : mask = np . zeros ( self . n_input_feats , dtype = bool ) mask [ : : self . step ] = True return mask support = [ True , False ] * support_inds = [ , , , , ] ", "answer": "X = np . arange ( ) . reshape ( , )"}, {"prompt": " def factorial ( x ) : if x <= : if x == : return else : raise ValueError ( '' % x ) fact = nn = while nn <= x : fact = fact * nn nn = nn + ", "answer": "if nn != x + : raise ValueError ( '' % x )"}, {"prompt": " from __future__ import unicode_literals , division , absolute_import , print_function import sys import hashlib import math from asn1crypto . util import int_from_bytes , int_to_bytes from . _errors import pretty_message from . _types import type_name , byte_cls , int_types if sys . version_info < ( , ) : chr_cls = chr else : def chr_cls ( num ) : return bytes ( [ num ] ) __all__ = [ '' , ] def pkcs12_kdf ( hash_algorithm , password , salt , iterations , key_length , id_ ) : \"\"\"\"\"\" if not isinstance ( password , byte_cls ) : raise TypeError ( pretty_message ( '''''' , type_name ( password ) ) ) if not isinstance ( salt , byte_cls ) : raise TypeError ( pretty_message ( '''''' , type_name ( salt ) ) ) if not isinstance ( iterations , int_types ) : raise TypeError ( pretty_message ( '''''' , type_name ( iterations ) ) ) if iterations < : raise ValueError ( pretty_message ( '''''' , repr ( iterations ) ", "answer": ") )"}, {"prompt": " from vbench . api import Benchmark from datetime import datetime common_setup = \"\"\"\"\"\" setup = common_setup + \"\"\"\"\"\" panel_shift = Benchmark ( '' , setup , start_date = datetime ( , , ) ) panel_shift_minor = Benchmark ( '' , setup , start_date = datetime ( , , ) ) panel_pct_change_major = Benchmark ( '' , setup , start_date = datetime ( , , ) ) panel_pct_change_minor = Benchmark ( '' , setup , ", "answer": "start_date = datetime ( , , ) )"}, {"prompt": " import os try : from setuptools import setup , find_packages except ImportError : from distutils . core import setup , find_packages VERSION = '' PATH = os . path . dirname ( os . path . abspath ( __file__ ) ) try : LONG_DESC = '' + open ( os . path . join ( PATH , '' ) , '' ) . read ( ) . split ( '' , ) [ - ] except IOError : LONG_DESC = '' setup ( name = '' , version = VERSION , description = \"\" , long_description = LONG_DESC , classifiers = [ '' , '' , '' , '' , '' , '' , ", "answer": "'' ,"}, {"prompt": " from optparse import make_option from django . conf import settings from django . core . management . base import BaseCommand , CommandError from olympia . landfill . generators import generate_themes class Command ( BaseCommand ) : \"\"\"\"\"\" ", "answer": "help = __doc__"}, {"prompt": " from gluon import current from s3 import * from s3layouts import * try : from . layouts import * except ImportError : pass import s3menus as default class S3OptionsMenu ( default . S3OptionsMenu ) : \"\"\"\"\"\" def vol ( self ) : \"\"\"\"\"\" s3 = current . session . s3 ADMIN = s3 . system_roles . ADMIN manager_mode = lambda i : s3 . hrm . mode is None personal_mode = lambda i : s3 . hrm . mode is not None is_org_admin = lambda i : s3 . hrm . orgs and True or ADMIN in s3 . roles settings = current . deployment_settings teams = settings . get_hrm_teams ( ) use_teams = lambda i : teams return M ( c = \"\" ) ( ", "answer": "M ( \"\" , f = \"\" ,"}, {"prompt": " import logging from django . utils . translation import ugettext_lazy as _ ", "answer": "from horizon import tabs"}, {"prompt": " '''''' import sys import hashlib import requests def META_VT_INSPECT ( s , buff ) : md5 = hashlib . md5 ( buff ) . hexdigest ( ) params = { '' : '' , '' : md5 } base_uri = '' response = requests . get ( '' % ( base_uri , '' ) , params = params ) ", "answer": "response_json = response . json ( )"}, {"prompt": " \"\"\"\"\"\" from PySide import QtGui fmts = [ str ( i ) for i in QtGui . QImageReader . supportedImageFormats ( ) ] ", "answer": "print fmts "}, {"prompt": " from gcloud import dns from gcp . testing . flaky import flaky import main import pytest TEST_ZONE_NAME = '' TEST_ZONE_DNS_NAME = '' TEST_ZONE_DESCRIPTION = '' @ pytest . yield_fixture def client ( cloud_config ) : client = dns . Client ( cloud_config . project ) yield client for zone in client . list_zones ( ) [ ] : zone . delete ( ) @ pytest . yield_fixture def zone ( client , cloud_config ) : zone = client . zone ( TEST_ZONE_NAME , TEST_ZONE_DNS_NAME ) zone . description = TEST_ZONE_DESCRIPTION zone . create ( ) yield zone if zone . exists ( ) : zone . delete ( ) @ flaky def test_create_zone ( client , cloud_config ) : ", "answer": "zone = main . create_zone ("}, {"prompt": " \"\"\"\"\"\" from __future__ import unicode_literals import datetime try : from urllib . parse import urlparse except ImportError : from urlparse import urlparse from django . utils . xmlutils import SimplerXMLGenerator from django . utils . encoding import force_text , iri_to_uri from django . utils import datetime_safe from django . utils import six from django . utils . six import StringIO from django . utils . timezone import is_aware def rfc2822_date ( date ) : months = ( '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , ) days = ( '' , '' , '' , '' , '' , '' , '' ) date = datetime_safe . new_datetime ( date ) dow = days [ date . weekday ( ) ] month = months [ date . month - ] time_str = date . strftime ( '' % ( dow , month ) ) if not six . PY3 : time_str = time_str . decode ( '' ) if is_aware ( date ) : offset = date . tzinfo . utcoffset ( date ) timezone = ( offset . days * * ) + ( offset . seconds // ) hour , minute = divmod ( timezone , ) return time_str + '' % ( hour , minute ) else : return time_str + '' def rfc3339_date ( date ) : date = datetime_safe . new_datetime ( date ) time_str = date . strftime ( '' ) if not six . PY3 : time_str = time_str . decode ( '' ) if is_aware ( date ) : offset = date . tzinfo . utcoffset ( date ) timezone = ( offset . days * * ) + ( offset . seconds // ) hour , minute = divmod ( timezone , ) return time_str + '' % ( hour , minute ) else : return time_str + '' def get_tag_uri ( url , date ) : \"\"\"\"\"\" bits = urlparse ( url ) d = '' if date is not None : d = '' % datetime_safe . new_datetime ( date ) . strftime ( '' ) return '' % ( bits . hostname , d , bits . path , bits . fragment ) class SyndicationFeed ( object ) : \"\" def __init__ ( self , title , link , description , language = None , author_email = None , author_name = None , author_link = None , subtitle = None , categories = None , feed_url = None , feed_copyright = None , feed_guid = None , ttl = None , ** kwargs ) : to_unicode = lambda s : force_text ( s , strings_only = True ) if categories : categories = [ force_text ( c ) for c in categories ] if ttl is not None : ttl = force_text ( ttl ) self . feed = { '' : to_unicode ( title ) , '' : iri_to_uri ( link ) , '' : to_unicode ( description ) , '' : to_unicode ( language ) , '' : to_unicode ( author_email ) , '' : to_unicode ( author_name ) , '' : iri_to_uri ( author_link ) , '' : to_unicode ( subtitle ) , '' : categories or ( ) , '' : iri_to_uri ( feed_url ) , '' : to_unicode ( feed_copyright ) , '' : feed_guid or link , '' : ttl , } self . feed . update ( kwargs ) self . items = [ ] def add_item ( self , title , link , description , author_email = None , author_name = None , author_link = None , pubdate = None , comments = None , unique_id = None , enclosure = None , categories = ( ) , item_copyright = None , ttl = None , ** kwargs ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " \"\"\"\"\"\" ", "answer": "__version__ = '' "}, {"prompt": " \"\"\"\"\"\" from __future__ import with_statement import logging import SocketServer import sys import traceback from wsgiref import simple_server from google . appengine . api import appinfo_includes from google . appengine . ext . vmruntime import meta_app from google . appengine . ext . vmruntime import middlewares from google . appengine . ext . vmruntime import vmconfig from google . appengine . ext . vmruntime import vmstub try : import googleclouddebugger except ImportError : pass LISTENING_HOST = '' HTTP_PORT = class VmRuntimeServer ( object ) : \"\"\"\"\"\" def __init__ ( self , host , port , app , appinfo_external ) : \"\"\"\"\"\" self . _host , self . _port = host , port self . _app = app self . _appinfo_external = appinfo_external self . _server = self . CreateServer ( ) logging . info ( '' , self . _host , self . _port ) def RunForever ( self ) : \"\"\"\"\"\" raise NotImplementedError ( ) def CreateServer ( self ) : \"\"\"\"\"\" raise NotImplementedError ( ) class VmRuntimeWSGIRefServer ( VmRuntimeServer ) : def CreateServer ( self ) : return simple_server . make_server ( self . _host , self . _port , self . _app , server_class = self . _ThreadingWSGIServer ) def RunForever ( self ) : try : self . _server . serve_forever ( ) except : logging . error ( '' , self . _host , self . _port ) raise class _ThreadingWSGIServer ( SocketServer . ThreadingMixIn , simple_server . WSGIServer ) : daemon_threads = True class VmRuntimeCherryPyServer ( VmRuntimeServer ) : def CreateServer ( self ) : from cherrypy . wsgiserver import wsgiserver2 wsgiserver2 . socket_error_eintr . append ( ) return wsgiserver2 . CherryPyWSGIServer ( ( self . _host , self . _port ) , self . _app , numthreads = middlewares . MAX_CONCURRENT_REQUESTS , request_queue_size = middlewares . MAX_CONCURRENT_REQUESTS ) def RunForever ( self ) : try : self . _server . start ( ) except : logging . error ( '' , self . _host , self . _port ) raise class VmService ( object ) : \"\"\"\"\"\" server_class = VmRuntimeWSGIRefServer server_class = VmRuntimeCherryPyServer def __init__ ( self , filename , host , port ) : self . filename = filename self . host = host ", "answer": "self . port = port"}, {"prompt": " import os import sys import json import logging from optparse import OptionParser sys . path . insert ( , os . path . join ( os . path . dirname ( __file__ ) , '' ) ) ", "answer": "import jedi"}, {"prompt": " from django . core . exceptions import ImproperlyConfigured from django . test import TestCase from django . test . client import RequestFactory from django . test . utils import override_settings from responsive . conf import settings from responsive . context_processors import device from responsive . utils import Device class ContextProcessorsTest ( TestCase ) : def setUp ( self ) : self . factory = RequestFactory ( ) def test_context_processor_raises_improperlyconfigured_error ( self ) : request = self . factory . get ( '' ) self . assertRaises ( ImproperlyConfigured , device , request ) ", "answer": "@ override_settings ( MIDDLEWARE_CLASSES = ( '' , ) )"}, {"prompt": " import os , sys , string , json , csv from collections import OrderedDict def csv2mlvs ( csvfile , output_dir = \"\" ) : \"\"\"\"\"\" response_dict = OrderedDict ( ) print \"\" , csvfile , \"\" , output_dir , \"\" csvhandle = csv . reader ( open ( csvfile , '' ) , delimiter = '' ) rowindex = ", "answer": "error_list = [ ]"}, {"prompt": " import sys from setuptools import setup from duvet import VERSION try : readme = open ( '' ) long_description = str ( readme . read ( ) ) finally : readme . close ( ) required_pkgs = [ '' , '' , ] if sys . version_info < ( , ) : required_pkgs . append ( '' ) setup ( name = '' , version = VERSION , description = '' , long_description = long_description , author = '' , author_email = '' , url = '' , packages = [ '' , ] , install_requires = required_pkgs , scripts = [ ] , entry_points = { '' : [ '' , ] } , license = '' , classifiers = [ '' , '' , '' , '' , '' , ", "answer": "'' ,"}, {"prompt": " from __future__ import absolute_import , print_function import doctest import fnmatch import importlib import os import pkgutil import blocks import blocks . bricks from blocks . utils . testing import skip_if_not_available def setup ( testobj ) : skip_if_not_available ( modules = [ '' ] ) testobj . globs [ '' ] = absolute_import testobj . globs [ '' ] = print_function def load_tests ( loader , tests , ignore ) : for _ , module , _ in pkgutil . walk_packages ( path = blocks . __path__ , prefix = blocks . __name__ + '' ) : try : tests . addTests ( doctest . DocTestSuite ( module = importlib . import_module ( module ) , setUp = setup , optionflags = doctest . IGNORE_EXCEPTION_DETAIL ) ) except : pass docs = [ ] for root , _ , filenames in os . walk ( os . path . join ( blocks . __path__ [ ] , '' ) ) : for doc in fnmatch . filter ( filenames , '' ) : ", "answer": "docs . append ( os . path . abspath ( os . path . join ( root , doc ) ) )"}, {"prompt": " \"\"\"\"\"\" try : all except NameError : def all ( values ) : ", "answer": "for val in values :"}, {"prompt": " AUTHOR = \"\" DESCRIPTION = \"\" INSTALL_TYPE = \"\" REPOSITORY_LOCATION = \"\" ", "answer": "INSTALL_LOCATION = \"\""}, {"prompt": " from . nnet import ( CrossentropyCategorical1Hot , CrossentropyCategorical1HotGrad , CrossentropySoftmax1HotWithBiasDx , CrossentropySoftmaxArgmax1HotWithBias , LogSoftmax , Prepend_scalar_constant_to_each_row , Prepend_scalar_to_each_row , Softmax , SoftmaxGrad , SoftmaxWithBias , binary_crossentropy , categorical_crossentropy , crossentropy_categorical_1hot , crossentropy_categorical_1hot_grad , crossentropy_softmax_1hot , crossentropy_softmax_1hot_with_bias , crossentropy_softmax_1hot_with_bias_dx , crossentropy_softmax_argmax_1hot_with_bias , crossentropy_softmax_max_and_argmax_1hot , crossentropy_softmax_max_and_argmax_1hot_with_bias , crossentropy_to_crossentropy_with_softmax , crossentropy_to_crossentropy_with_softmax_with_bias , graph_merge_softmax_with_crossentropy_softmax , h_softmax , logsoftmax , logsoftmax_op , prepend_0_to_each_row , prepend_1_to_each_row , ", "answer": "prepend_scalar_to_each_row , relu , softmax , softmax_grad , softmax_graph ,"}, {"prompt": " import cvxopt as co import numpy as np import pylab as pl import matplotlib . pyplot as plt import math from ssad import SSAD from ocsvm import OCSVM from mkl import MKLWrapper from kernel import Kernel if __name__ == '' : \"\"\"\"\"\" P_NORM = N_pos = N_neg = N_unl = yp = co . matrix ( , ( , N_pos ) , '' ) yu = co . matrix ( , ( , N_unl ) , '' ) yn = co . matrix ( - , ( , N_neg ) , '' ) Dy = co . matrix ( [ [ yp ] , [ yu ] , [ yn ] , [ yn ] , [ yn ] , [ yn ] ] ) co . setseed ( ) Dtrainp = co . normal ( , N_pos ) * Dtrainu = co . normal ( , N_unl ) * Dtrainn = co . normal ( , N_neg ) * Dtrain21 = Dtrainn - Dtrain21 [ , : ] = Dtrainn [ , : ] + Dtrain22 = - Dtrain21 ", "answer": "Dtrain = co . matrix ( [ [ Dtrainp ] , [ Dtrainu ] , [ Dtrainn + ] , [ Dtrainn - ] , [ Dtrain21 ] , [ Dtrain22 ] ] )"}, {"prompt": " from gitdh . modules import Module from gitdh import git from syslog import syslog , LOG_INFO , LOG_WARNING class PostReceiveSource ( Module ) : def isEnabled ( self , action ) : return action == \"\" def source ( self ) : firstCommit = self . args [ ] lastCommit = self . args [ ] ref = self . args [ ] if ref . find ( \"\" ) == : branch = ref [ : ] else : syslog ( LOG_WARNING , \"\" % ( ref , self . config . repoPath ) ) return [ ] try : ", "answer": "self . config . branches [ branch ]"}, {"prompt": " \"\"\"\"\"\" import collections as col import copy import xml . etree . ElementTree as ET import six import rack . openstack . common . report . utils as utils class KeyValueView ( object ) : \"\"\"\"\"\" def __init__ ( self , wrapper_name = \"\" ) : self . wrapper_name = wrapper_name def __call__ ( self , model ) : cpy = copy . deepcopy ( model ) ", "answer": "for key , valstr in model . items ( ) :"}, {"prompt": " import sys import os execfile ( '' ) ", "answer": "on_rtd = os . environ . get ( '' , None ) == ''"}, {"prompt": " from __future__ import print_function import base64 import six import unittest from nose . tools import eq_ from ryu . lib import stringify class C1 ( stringify . StringifyMixin ) : def __init__ ( self , a , c ) : print ( \"\" % ( a , c ) ) self . a = a self . _b = '' self . c = c class Test_stringify ( unittest . TestCase ) : \"\"\"\"\"\" def setUp ( self ) : pass def tearDown ( self ) : pass def test_jsondict ( self ) : if six . PY3 : def b64encode ( s ) : return base64 . b64encode ( s ) . decode ( '' ) else : b64encode = base64 . b64encode j = { '' : { '' : '' , '' : '' } } eq_ ( j [ '' ] [ '' ] , b64encode ( b'' ) ) eq_ ( j [ '' ] [ '' ] , b64encode ( b'' ) ) c = C1 ( a = b'' , c = b'' ) c2 = C1 . from_jsondict ( j [ '' ] ) eq_ ( c . __class__ , c2 . __class__ ) eq_ ( c . __dict__ , c2 . __dict__ ) eq_ ( j , c . to_jsondict ( ) ) def test_jsondict2 ( self ) : def my_encode ( x ) : return x . lower ( ) def my_decode ( x ) : return x . upper ( ) j = { '' : { '' : '' , '' : '' } } eq_ ( j [ '' ] [ '' ] , my_encode ( '' ) ) eq_ ( j [ '' ] [ '' ] , my_encode ( '' ) ) ", "answer": "c = C1 ( a = '' , c = '' )"}, {"prompt": " \"\"\"\"\"\" print ( __doc__ ) import netCDF4 import matplotlib . pyplot as plt import pyart filename = '' radar = pyart . io . read_cfradial ( filename ) radar . metadata [ '' ] = '' display = pyart . graph . RadarDisplay ( radar ) fig = plt . figure ( figsize = [ , ] ) fig . subplots_adjust ( hspace = ) xlabel = '' ylabel = '' colorbar_label = '' nplots = radar . nsweeps for snum in radar . sweep_number [ '' ] : fixed_angle = radar . fixed_angle [ '' ] [ snum ] title = '' % ( fixed_angle ) ax = fig . add_subplot ( nplots , , snum + ) display . plot ( '' , snum , vmin = - , vmax = , ", "answer": "mask_outside = False , title = title ,"}, {"prompt": " import pickle import uuid try : import kombu except ImportError : kombu = None from . pubsub_manager import PubSubManager class KombuManager ( PubSubManager ) : \"\"\"\"\"\" name = '' def __init__ ( self , url = '' , channel = '' , write_only = False ) : if kombu is None : raise RuntimeError ( '' '' '' ) super ( KombuManager , self ) . __init__ ( channel = channel ) self . url = url self . writer_conn = kombu . Connection ( self . url ) self . writer_queue = self . _queue ( self . writer_conn ) def _queue ( self , conn = None ) : ", "answer": "exchange = kombu . Exchange ( self . channel , type = '' , durable = False )"}, {"prompt": " from django import forms from django . contrib . auth . models import User from basic . messages . models import Message class MessageForm ( forms . ModelForm ) : to_user = forms . CharField ( ) class Meta : model = Message exclude = ( '' , '' , '' , '' , '' ) def clean_to_user ( self ) : if self . cleaned_data [ '' ] : try : user = User . objects . get ( username = self . cleaned_data [ '' ] ) self . cleaned_data [ '' ] = user return self . cleaned_data [ '' ] except User . DoesNotExist : ", "answer": "pass"}, {"prompt": " \"\"\"\"\"\" class BlockedTest ( Exception ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " import os from setuptools import setup , find_packages here = os . path . abspath ( os . path . dirname ( __file__ ) ) with open ( os . path . join ( here , '' ) ) as f : README = f . read ( ) requires = [ '' , '' , '' , '' , '' , ] setup ( name = '' , version = '' , description = '' , long_description = README , classifiers = [ \"\" , \"\" , \"\" , \"\" , ", "answer": "] ,"}, {"prompt": " import matplotlib . pyplot as plt import pandas . util . testing as t import pandas . stats . moments as m t . N = ts = t . makeTimeSeries ( ) ts [ : : ] = s = ts . cumsum ( ) plt . figure ( figsize = ( , ) ) plt . plot ( s . index , m . ewmvol ( s , span = , min_periods = ) . values , color = '' ) ", "answer": "plt . plot ( s . index , m . rolling_std ( s , , min_periods = ) . values , color = '' )"}, {"prompt": " import sahara . plugins . mapr . domain . node_process as np import sahara . plugins . mapr . domain . service as s import sahara . plugins . mapr . util . commands as cmd import sahara . plugins . mapr . util . validation_utils as vu ZK_CLIENT_PORT = ZOOKEEPER = np . NodeProcess ( name = '' , ui_name = '' , package = '' , open_ports = [ ZK_CLIENT_PORT ] ) WEB_SERVER = np . NodeProcess ( name = '' , ui_name = '' , package = '' , ", "answer": "open_ports = [ ]"}, {"prompt": " \"\"\"\"\"\" import unittest import urlparse import re import types from openid . yadis . discover import discover , DiscoveryFailure from openid import fetchers import discoverdata status_header_re = re . compile ( r'' , re . MULTILINE ) four04_pat = \"\"\"\"\"\" class QuitServer ( Exception ) : pass def mkResponse ( data ) : status_mo = status_header_re . match ( data ) headers_str , body = data . split ( '' , ) headers = { } for line in headers_str . split ( '' ) : k , v = line . split ( '' , ) k = k . strip ( ) . lower ( ) v = v . strip ( ) headers [ k ] = v status = int ( status_mo . group ( ) ) return fetchers . HTTPResponse ( status = status , headers = headers , body = body ) class TestFetcher ( object ) : def __init__ ( self , base_url ) : self . base_url = base_url def fetch ( self , url , headers , body ) : current_url = url while True : parsed = urlparse . urlparse ( current_url ) path = parsed [ ] [ : ] try : data = discoverdata . generateSample ( path , self . base_url ) except KeyError : return fetchers . HTTPResponse ( status = , final_url = current_url , headers = { } , body = '' ) response = mkResponse ( data ) if response . status in [ , , , ] : current_url = response . headers [ '' ] else : response . final_url = current_url return response class TestSecondGet ( unittest . TestCase ) : class MockFetcher ( object ) : def __init__ ( self ) : self . count = ", "answer": "def fetch ( self , uri , headers = None , body = None ) :"}, {"prompt": " \"\"\"\"\"\" from __future__ import unicode_literals import json from oauthlib . common import urlencode , add_params_to_uri class OAuth2Error ( Exception ) : error = None status_code = description = '' def __init__ ( self , description = None , uri = None , state = None , status_code = None , request = None ) : \"\"\"\"\"\" ", "answer": "self . description = description or self . description"}, {"prompt": " import datetime from django . db . backends import util as typecasts from django . utils import unittest TEST_CASES = { '' : ( ( '' , None ) , ( None , None ) , ( '' , datetime . date ( , , ) ) , ( '' , datetime . date ( , , ) ) , ) , '' : ( ( '' , None ) , ( None , None ) , ( '' , datetime . time ( , ) ) , ( '' , datetime . time ( , ) ) , ( '' , datetime . time ( , ) ) , ( '' , datetime . time ( , ) ) , ( '' , datetime . time ( , ) ) , ( '' , datetime . time ( , ) ) , ( '' , datetime . time ( , ) ) , ( '' , datetime . time ( , ) ) , ( '' , datetime . time ( , , ) ) , ( '' , datetime . time ( , , , ) ) , ( '' , datetime . time ( , , , ) ) , ) , '' : ( ( '' , None ) , ( None , None ) , ( '' , datetime . datetime ( , , ) ) , ( '' , datetime . datetime ( , , , , ) ) , ( '' , datetime . datetime ( , , , , , ) ) , ( '' , datetime . datetime ( , , , , , , ) ) , ( '' , datetime . datetime ( , , , , , , ) ) , ", "answer": "( '' , datetime . datetime ( , , , , , , ) ) ,"}, {"prompt": " import webapp2 class LazyHandler ( webapp2 . RequestHandler ) : def get ( self , ** kwargs ) : self . response . out . write ( '' ) class CustomMethodHandler ( webapp2 . RequestHandler ) : def custom_method ( self ) : self . response . out . write ( '' ) def handle_exception ( request , response , exception ) : ", "answer": "return webapp2 . Response ( body = '' ) "}, {"prompt": " \"\"\"\"\"\" import contextlib import datetime import os import shutil import time class Resource : \"\"\"\"\"\" _STATE_UPDATE_INTERVAL = datetime . timedelta ( seconds = ) def __init__ ( self , id , conn ) : \"\"\"\"\"\" self . _id = id self . _conn = conn self . _last_updated = datetime . datetime . min @ property def id ( self ) : \"\"\"\"\"\" return self . _id def is_pending ( self ) : \"\"\"\"\"\" self . _update_state_if_needed ( ) return self . _pending def is_running ( self ) : \"\"\"\"\"\" self . _update_state_if_needed ( ) return self . _running def has_finished ( self ) : \"\"\"\"\"\" self . _update_state_if_needed ( ) return self . _finished def has_succeeded ( self ) : \"\"\"\"\"\" self . _update_state_if_needed ( ) return self . _finished def has_failed ( self ) : \"\"\"\"\"\" self . _update_state_if_needed ( ) return self . _failed def get_error ( self ) : \"\"\"\"\"\" self . _update_state_if_needed ( ) ", "answer": "return self . _error"}, {"prompt": " import pexpect import sys import time def floatfromhex ( h ) : t = float . fromhex ( h ) if t > float . fromhex ( '' ) : t = - ( float . fromhex ( '' ) - t ) pass return t def calcTmpTarget ( objT , ambT ) : m_tmpAmb = ambT / Vobj2 = objT * Tdie2 = m_tmpAmb + S0 = a1 = a2 = - b0 = - b1 = - b2 = c2 = Tref = S = S0 * ( + a1 * ( Tdie2 - Tref ) + a2 * pow ( ( Tdie2 - Tref ) , ) ) Vos = b0 + b1 * ( Tdie2 - Tref ) + b2 * pow ( ( Tdie2 - Tref ) , ) fObj = ( Vobj2 - Vos ) + c2 * pow ( ( Vobj2 - Vos ) , ) tObj = pow ( pow ( Tdie2 , ) + ( fObj / S ) , ) tObj = ( tObj - ) print \"\" % tObj bluetooth_adr = sys . argv [ ] tool = pexpect . spawn ( '' + bluetooth_adr + '' ) tool . expect ( '' ) ", "answer": "print \"\""}, {"prompt": " import json import unicodehelper from . specs . webapps import WebappSpec def detect_webapp ( err , package ) : \"\"\"\"\"\" with open ( package , mode = \"\" ) as f : detect_webapp_string ( err , f . read ( ) ) def detect_webapp_string ( err , data ) : \"\"\"\"\"\" try : u_data = unicodehelper . decode ( data ) webapp = json . loads ( u_data ) ", "answer": "except ValueError as exc :"}, {"prompt": " from __future__ import unicode_literals ", "answer": "from django . db import models , migrations"}, {"prompt": " '''''' import sys import random import alignlib_lite import CGAT . Experiment as E import CGAT . Blat as Blat import CGAT . Iterators as Iterators import CGAT . IndexedFasta as IndexedFasta def fillAlignment ( map_alignment , alignment ) : i = for x , c in enumerate ( alignment ) : if c != \"\" : map_alignment . addPair ( i , x ) i += def main ( argv = None ) : parser = E . OptionParser ( version = \"\" , usage = globals ( ) [ \"\" ] ) parser . add_option ( \"\" , dest = \"\" , type = \"\" , help = \"\" ) parser . add_option ( \"\" , dest = \"\" , action = \"\" , help = \"\" ) parser . add_option ( \"\" , dest = \"\" , type = \"\" , help = \"\" ) parser . add_option ( \"\" , \"\" , dest = \"\" , type = \"\" , help = \"\" ) parser . set_defaults ( quality_threshold = , quality_file = \"\" , filename_map = None , frame = , ) ( options , args ) = E . Start ( parser ) infile = open ( options . filename_map ) map_genes2genome = { } for match in Blat . iterator ( infile ) : assert match . mQueryId not in map_genes2genome , \"\" % match . mQueryId map_genes2genome [ match . mQueryId ] = match infile . close ( ) quality = IndexedFasta . IndexedFasta ( options . quality_file ) quality . setTranslator ( IndexedFasta . TranslatorBytes ( ) ) ninput , noutput , nmissed = , , options . stdout . write ( \"\" ) for line in options . stdin : if line . startswith ( \"\" ) : continue ninput += cluster_id , gene_id , alignment = line [ : - ] . split ( \"\" ) if gene_id not in map_genes2genome : nmissed += E . warn ( \"\" % gene_id ) continue match = map_genes2genome [ gene_id ] ", "answer": "map_gene2genome = match . getMapQuery2Target ( )"}, {"prompt": " \"\"\"\"\"\" from __future__ import print_function , division from sympy . core import S , Symbol , Rational , Integer , Add , Dummy from sympy . core . compatibility import as_int , SYMPY_INTS , range from sympy . core . cache import cacheit from sympy . core . function import Function , expand_mul from sympy . core . numbers import E , pi from sympy . core . relational import LessThan , StrictGreaterThan from sympy . functions . combinatorial . factorials import binomial , factorial from sympy . functions . elementary . exponential import log from sympy . functions . elementary . integers import floor from sympy . functions . elementary . trigonometric import sin , cos , cot from sympy . functions . elementary . miscellaneous import sqrt from sympy . utilities . memoization import recurrence_memo from mpmath import bernfrac , workprec from mpmath . libmp import ifib as _ifib def _product ( a , b ) : p = for k in range ( a , b + ) : p *= k return p _sym = Symbol ( '' ) _symbols = Function ( '' ) class fibonacci ( Function ) : r\"\"\"\"\"\" @ staticmethod def _fib ( n ) : return _ifib ( n ) @ staticmethod @ recurrence_memo ( [ None , S . One , _sym ] ) def _fibpoly ( n , prev ) : return ( prev [ - ] + _sym * prev [ - ] ) . expand ( ) @ classmethod def eval ( cls , n , sym = None ) : if n is S . Infinity : return S . Infinity if n . is_Integer : n = int ( n ) if n < : return S . NegativeOne ** ( n + ) * fibonacci ( - n ) if sym is None : return Integer ( cls . _fib ( n ) ) else : if n < : raise ValueError ( \"\" \"\" ) return cls . _fibpoly ( n ) . subs ( _sym , sym ) def _eval_rewrite_as_sqrt ( self , n ) : return ** ( - n ) * sqrt ( ) * ( ( + sqrt ( ) ) ** n - ( - sqrt ( ) + ) ** n ) / class lucas ( Function ) : \"\"\"\"\"\" @ classmethod def eval ( cls , n ) : if n is S . Infinity : return S . Infinity if n . is_Integer : return fibonacci ( n + ) + fibonacci ( n - ) def _eval_rewrite_as_sqrt ( self , n ) : return ** ( - n ) * ( ( + sqrt ( ) ) ** n + ( - sqrt ( ) + ) ** n ) class bernoulli ( Function ) : r\"\"\"\"\"\" @ staticmethod def _calc_bernoulli ( n ) : s = a = int ( binomial ( n + , n - ) ) for j in range ( , n // + ) : s += a * bernoulli ( n - * j ) a *= _product ( n - - * j + , n - * j ) a //= _product ( * j + , * j + ) if n % == : s = - Rational ( n + , ) - s else : s = Rational ( n + , ) - s return s / binomial ( n + , n ) _cache = { : S . One , : Rational ( , ) , : Rational ( - , ) } _highest = { : , : , : } @ classmethod def eval ( cls , n , sym = None ) : if n . is_Number : if n . is_Integer and n . is_nonnegative : if n is S . Zero : return S . One elif n is S . One : if sym is None : return - S . Half else : return sym - S . Half elif sym is None : if n . is_odd : return S . Zero n = int ( n ) if n > : p , q = bernfrac ( n ) return Rational ( int ( p ) , int ( q ) ) case = n % highest_cached = cls . _highest [ case ] if n <= highest_cached : return cls . _cache [ n ] for i in range ( highest_cached + , n + , ) : b = cls . _calc_bernoulli ( i ) cls . _cache [ i ] = b cls . _highest [ case ] = i return b else : n , result = int ( n ) , [ ] for k in range ( n + ) : result . append ( binomial ( n , k ) * cls ( k ) * sym ** ( n - k ) ) return Add ( * result ) else : raise ValueError ( \"\" \"\" ) if sym is None : if n . is_odd and ( n - ) . is_positive : return S . Zero class bell ( Function ) : r\"\"\"\"\"\" @ staticmethod @ recurrence_memo ( [ , ] ) def _bell ( n , prev ) : s = a = for k in range ( , n ) : a = a * ( n - k ) // k s += a * prev [ k ] return s @ staticmethod @ recurrence_memo ( [ S . One , _sym ] ) def _bell_poly ( n , prev ) : s = a = for k in range ( , n + ) : a = a * ( n - k + ) // ( k - ) s += a * prev [ k - ] return expand_mul ( _sym * s ) @ staticmethod def _bell_incomplete_poly ( n , k , symbols ) : r\"\"\"\"\"\" if ( n == ) and ( k == ) : return S . One elif ( n == ) or ( k == ) : return S . Zero s = S . Zero a = S . One for m in range ( , n - k + ) : s += a * bell . _bell_incomplete_poly ( n - m , k - , symbols ) * symbols [ m - ] a = a * ( n - m ) / m return expand_mul ( s ) @ classmethod def eval ( cls , n , k_sym = None , symbols = None ) : if n . is_Integer and n . is_nonnegative : if k_sym is None : return Integer ( cls . _bell ( int ( n ) ) ) elif symbols is None : return cls . _bell_poly ( int ( n ) ) . subs ( _sym , k_sym ) else : r = cls . _bell_incomplete_poly ( int ( n ) , int ( k_sym ) , symbols ) return r def _eval_rewrite_as_Sum ( self , n , k_sym = None , symbols = None ) : from sympy import Sum if ( k_sym is not None ) or ( symbols is not None ) : return self if not n . is_nonnegative : return self k = Dummy ( '' , integer = True , nonnegative = True ) return / E * Sum ( k ** n / factorial ( k ) , ( k , , S . Infinity ) ) class harmonic ( Function ) : r\"\"\"\"\"\" _functions = { } @ classmethod def eval ( cls , n , m = None ) : from sympy import zeta if m is S . One : return cls ( n ) if m is None : m = S . One if m . is_zero : return n if n is S . Infinity and m . is_Number : if m . is_negative : return S . NaN elif LessThan ( m , S . One ) : return S . Infinity elif StrictGreaterThan ( m , S . One ) : return zeta ( m ) else : return cls if n . is_Integer and n . is_nonnegative and m . is_Integer : if n == : return S . Zero if not m in cls . _functions : @ recurrence_memo ( [ ] ) def f ( n , prev ) : ", "answer": "return prev [ - ] + S . One / n ** m"}, {"prompt": " import abc import logging import six from docker import Client ", "answer": "from tripleo_common . image . base import BaseImageManager"}, {"prompt": " \"\"\"\"\"\" import sys import argparse from ecohydrolib . context import Context from ecohydrolib . metadata import GenericMetadata ", "answer": "from ecohydrolib . metadata import AssetProvenance"}, {"prompt": " from collections import MutableMapping , MutableSequence class BaseIO ( MutableMapping , MutableSequence ) : \"\" tabular = False nested = False binary = False def __init__ ( self , ** kwargs ) : self . __dict__ . update ( kwargs ) self . refresh ( ) def refresh ( self ) : self . load ( ) if getattr ( self , '' , False ) : self . data = [ ] else : self . parse ( ) if hasattr ( self , '' ) and not self . file . closed : self . file . close ( ) def load ( self ) : \"\" pass def parse ( self ) : \"\"\"\"\"\" pass def dump ( self , file = None ) : \"\" if file is None : file = self . file file . write ( str ( self . data ) ) def save ( self ) : \"\" self . dump ( self . file ) field_names = None scan_fields = False _auto_field_names = None def get_field_names ( self ) : \"\" if self . field_names is not None : if isinstance ( self . field_names , str ) : return self . field_names . replace ( '' , '' ) . split ( ) else : return self . field_names if not getattr ( self , '' , None ) : return None if self . _auto_field_names : return self . _auto_field_names if self . scan_fields : field_names = set ( ) for row in self . data : field_names . update ( row . keys ( ) ) field_names = list ( field_names ) else : field_names = list ( self . data [ ] . keys ( ) ) self . _auto_field_names = field_names return field_names @ property def key_field ( self ) : \"\" return None def get_key_field ( self ) : return self . key_field def usable_item ( self , item ) : \"\" return item def parse_usable_item ( self , uitem ) : \"\" return uitem def compute_index ( self , recompute = False ) : key_field = self . get_key_field ( ) if key_field is None : return None if getattr ( self , '' , None ) is not None and not recompute : return self . _index_cache index = { } for i , item in enumerate ( self . data ) : uitem = self . usable_item ( item ) if isinstance ( uitem , dict ) : key = uitem . get ( key_field , None ) else : key = getattr ( uitem , key_field , None ) if key is not None : index [ key ] = i self . _index_cache = index return index def find_index ( self , key ) : index = self . compute_index ( ) if index is not None : return index . get ( key , None ) else : return key def __len__ ( self ) : return len ( self . data ) def __getitem__ ( self , key ) : index = self . find_index ( key ) if index is None : raise KeyError return self . usable_item ( self . data [ index ] ) def __setitem__ ( self , key , uitem ) : ", "answer": "item = self . parse_usable_item ( uitem )"}, {"prompt": " \"\"\"\"\"\" print ( __doc__ ) import numpy as np from matplotlib import pyplot as pl from matplotlib import cm from sklearn . gaussian_process import GaussianProcessClassifier from sklearn . gaussian_process . kernels import DotProduct , ConstantKernel as C lim = def g ( x ) : \"\"\"\"\"\" return - x [ : , ] - * x [ : , ] ** X = np . array ( [ [ - , - ] , [ , ] , [ , - ] , [ - , - ] , [ , - ] , [ - , ] , [ - , ] , [ , ] ] ) y = np . array ( g ( X ) > , dtype = int ) kernel = C ( , ( , np . inf ) ) * DotProduct ( sigma_0 = ) ** gp = GaussianProcessClassifier ( kernel = kernel ) gp . fit ( X , y ) print ( \"\" % gp . kernel_ ) res = x1 , x2 = np . meshgrid ( np . linspace ( - lim , lim , res ) , np . linspace ( - lim , lim , res ) ) xx = np . vstack ( [ x1 . reshape ( x1 . size ) , x2 . reshape ( x2 . size ) ] ) . T y_true = g ( xx ) y_prob = gp . predict_proba ( xx ) [ : , ] y_true = y_true . reshape ( ( res , res ) ) y_prob = y_prob . reshape ( ( res , res ) ) fig = pl . figure ( ) ax = fig . gca ( ) ax . axes . set_aspect ( '' ) pl . xticks ( [ ] ) pl . yticks ( [ ] ) ax . set_xticklabels ( [ ] ) ax . set_yticklabels ( [ ] ) pl . xlabel ( '' ) pl . ylabel ( '' ) cax = pl . imshow ( y_prob , cmap = cm . gray_r , alpha = , extent = ( - lim , lim , - lim , lim ) ) norm = pl . matplotlib . colors . Normalize ( vmin = , vmax = ) cb = pl . colorbar ( cax , ticks = [ , , , , , ] , norm = norm ) cb . set_label ( '' ) pl . clim ( , ) pl . plot ( X [ y <= , ] , X [ y <= , ] , '' , markersize = ) pl . plot ( X [ y > , ] , X [ y > , ] , '' , markersize = ) cs = pl . contour ( x1 , x2 , y_true , [ ] , colors = '' , linestyles = '' ) cs = pl . contour ( x1 , x2 , y_prob , [ ] , colors = '' , linestyles = '' ) pl . clabel ( cs , fontsize = ) cs = pl . contour ( x1 , x2 , y_prob , [ ] , colors = '' , ", "answer": "linestyles = '' )"}, {"prompt": " from solum . objects import base class Pipeline ( base . CrudMixin ) : VERSION = '' class PipelineList ( list , base . CrudListMixin ) : ", "answer": "\"\"\"\"\"\" "}, {"prompt": " from Tkinter import * import RPi . GPIO as GPIO import time , math C = R1 = B = R0 = GPIO . setmode ( GPIO . BCM ) a_pin = b_pin = buzzer_pin = GPIO . setup ( buzzer_pin , GPIO . OUT ) set_temp = def discharge ( ) : GPIO . setup ( a_pin , GPIO . IN ) GPIO . setup ( b_pin , GPIO . OUT ) GPIO . output ( b_pin , False ) time . sleep ( ) def charge_time ( ) : GPIO . setup ( b_pin , GPIO . IN ) GPIO . setup ( a_pin , GPIO . OUT ) GPIO . output ( a_pin , True ) t1 = time . time ( ) while not GPIO . input ( b_pin ) : pass t2 = time . time ( ) return ( t2 - t1 ) * def analog_read ( ) : discharge ( ) t = charge_time ( ) discharge ( ) ", "answer": "return t"}, {"prompt": " \"\"\"\"\"\" from flexx import app , ui , react nsamples = @ react . input def message_relay ( msg ) : \"\"\"\"\"\" return msg + '' class MessageBox ( ui . Label ) : CSS = \"\"\"\"\"\" @ app . serve class ChatRoom ( ui . Widget ) : \"\"\"\"\"\" def init ( self ) : with ui . HBox ( ) : ui . Widget ( flex = ) with ui . VBox ( ) : self . name = ui . LineEdit ( placeholder_text = '' ) self . people = ui . Label ( flex = , size = ( , ) ) with ui . VBox ( ) : self . messages = MessageBox ( flex = ) with ui . HBox ( ) : self . message = ui . LineEdit ( flex = , placeholder_text = '' ) self . ok = ui . Button ( text = '' ) ui . Widget ( flex = ) self . _update_participants ( ) def _update_participants ( self ) : if not self . session . status : return proxies = app . manager . get_connections ( self . __class__ . __name__ ) names = [ p . app . name . text ( ) for p in proxies ] text = '' % len ( names ) text += '' . join ( [ name or '' for name in sorted ( names ) ] ) self . people . text ( text ) app . call_later ( , self . _update_participants ) @ react . connect ( '' , '' ) def _send_message ( self , down , submit ) : text = self . message . text ( ) if text : name = self . name . text ( ) or '' message_relay ( '' % ( name , text ) ) self . message . text ( '' ) @ react . connect ( '' ) ", "answer": "def new_text ( self , text ) :"}, {"prompt": " from __pyjamas__ import JS , doc , wnd import pyjd if pyjd . is_desktop : from __pyjamas__ import get_main_frame global historyToken historyToken = '' historyListeners = [ ] \"\"\"\"\"\" def addHistoryListener ( listener ) : print \"\" , listener historyListeners . append ( listener ) def back ( ) : wnd ( ) . history . back ( ) def forward ( ) : wnd ( ) . history . forward ( ) def getToken ( ) : global historyToken return historyToken def newItem ( ht ) : global historyToken if historyToken == ht : return ", "answer": "onHistoryChanged ( ht )"}, {"prompt": " \"\"\"\"\"\" from __future__ import division , absolute_import __all__ = [ \"\" ] from twisted . python . runtime import platform ", "answer": "def _getInstallFunction ( platform ) :"}, {"prompt": " \"\"\"\"\"\" import unittest from jinja2 . testsuite import JinjaTestCase from jinja2 import Environment , TemplateSyntaxError , UndefinedError , DictLoader env = Environment ( ) class ForLoopTestCase ( JinjaTestCase ) : def test_simple ( self ) : tmpl = env . from_string ( '' ) assert tmpl . render ( seq = list ( range ( ) ) ) == '' def test_else ( self ) : tmpl = env . from_string ( '' ) assert tmpl . render ( ) == '' def test_empty_blocks ( self ) : tmpl = env . from_string ( '' ) assert tmpl . render ( ) == '' def test_context_vars ( self ) : tmpl = env . from_string ( '''''' ) one , two , _ = tmpl . render ( seq = [ , ] ) . split ( '' ) ( one_index , one_index0 , one_revindex , one_revindex0 , one_first , one_last , one_length ) = one . split ( '' ) ( two_index , two_index0 , two_revindex , two_revindex0 , two_first , two_last , two_length ) = two . split ( '' ) assert int ( one_index ) == and int ( two_index ) == assert int ( one_index0 ) == and int ( two_index0 ) == assert int ( one_revindex ) == and int ( two_revindex ) == assert int ( one_revindex0 ) == and int ( two_revindex0 ) == assert one_first == '' and two_first == '' assert one_last == '' and two_last == '' assert one_length == two_length == '' def test_cycling ( self ) : tmpl = env . from_string ( '''''' ) output = tmpl . render ( seq = list ( range ( ) ) , through = ( '' , '' ) ) assert output == '' * def test_scope ( self ) : tmpl = env . from_string ( '' ) output = tmpl . render ( seq = list ( range ( ) ) ) assert not output def test_varlen ( self ) : def inner ( ) : for item in range ( ) : yield item tmpl = env . from_string ( '' ) output = tmpl . render ( iter = inner ( ) ) assert output == '' def test_noniter ( self ) : tmpl = env . from_string ( '' ) self . assert_raises ( TypeError , tmpl . render ) def test_recursive ( self ) : tmpl = env . from_string ( '''''' ) assert tmpl . render ( seq = [ dict ( a = , b = [ dict ( a = ) , dict ( a = ) ] ) , dict ( a = , b = [ dict ( a = ) , dict ( a = ) ] ) , dict ( a = , b = [ dict ( a = '' ) ] ) ] ) == '' def test_recursive_depth0 ( self ) : tmpl = env . from_string ( '''''' ) self . assertEqual ( tmpl . render ( seq = [ dict ( a = , b = [ dict ( a = ) , dict ( a = ) ] ) , dict ( a = , b = [ dict ( a = ) , dict ( a = ) ] ) , dict ( a = , b = [ dict ( a = '' ) ] ) ] ) , '' ) def test_recursive_depth ( self ) : tmpl = env . from_string ( '''''' ) self . assertEqual ( tmpl . render ( seq = [ dict ( a = , b = [ dict ( a = ) , dict ( a = ) ] ) , dict ( a = , b = [ dict ( a = ) , dict ( a = ) ] ) , dict ( a = , b = [ dict ( a = '' ) ] ) ] ) , '' ) def test_looploop ( self ) : tmpl = env . from_string ( '''''' ) assert tmpl . render ( table = [ '' , '' ] ) == '' def test_reversed_bug ( self ) : tmpl = env . from_string ( '' '' '' ) assert tmpl . render ( items = reversed ( [ , , ] ) ) == '' def test_loop_errors ( self ) : tmpl = env . from_string ( '''''' ) self . assert_raises ( UndefinedError , tmpl . render ) tmpl = env . from_string ( '''''' ) assert tmpl . render ( ) == '' def test_loop_filter ( self ) : tmpl = env . from_string ( '' '' ) assert tmpl . render ( ) == '' tmpl = env . from_string ( '''''' ) assert tmpl . render ( ) == '' def test_loop_unassignable ( self ) : self . assert_raises ( TemplateSyntaxError , env . from_string , '' ) def test_scoped_special_var ( self ) : t = env . from_string ( '' '' ) assert t . render ( seq = ( '' , '' ) ) == '' def test_scoped_loop_var ( self ) : t = env . from_string ( '' '' ) assert t . render ( seq = '' ) == '' t = env . from_string ( '' '' ) assert t . render ( seq = '' ) == '' def test_recursive_empty_loop_iter ( self ) : t = env . from_string ( '''''' ) assert t . render ( dict ( foo = [ ] ) ) == '' def test_call_in_loop ( self ) : t = env . from_string ( '''''' ) assert t . render ( ) == '' def test_scoping_bug ( self ) : t = env . from_string ( '''''' ) assert t . render ( foo = ( , ) ) == '' def test_unpacking ( self ) : tmpl = env . from_string ( '' '' ) assert tmpl . render ( ) == '' class IfConditionTestCase ( JinjaTestCase ) : def test_simple ( self ) : tmpl = env . from_string ( '''''' ) assert tmpl . render ( ) == '' def test_elif ( self ) : tmpl = env . from_string ( '''''' ) assert tmpl . render ( ) == '' def test_else ( self ) : tmpl = env . from_string ( '' ) assert tmpl . render ( ) == '' def test_empty ( self ) : tmpl = env . from_string ( '' ) assert tmpl . render ( ) == '' def test_complete ( self ) : tmpl = env . from_string ( '' '' ) assert tmpl . render ( a = , b = False , c = , d = ) == '' def test_no_scope ( self ) : tmpl = env . from_string ( '' ) assert tmpl . render ( a = True ) == '' tmpl = env . from_string ( '' ) assert tmpl . render ( ) == '' class MacrosTestCase ( JinjaTestCase ) : env = Environment ( trim_blocks = True ) def test_simple ( self ) : tmpl = self . env . from_string ( '''''' ) assert tmpl . render ( ) == '' def test_scoping ( self ) : tmpl = self . env . from_string ( '''''' ) assert tmpl . render ( ) == '' def test_arguments ( self ) : tmpl = self . env . from_string ( '''''' ) assert tmpl . render ( ) == '' def test_varargs ( self ) : tmpl = self . env . from_string ( '''''' ) assert tmpl . render ( ) == '' def test_simple_call ( self ) : tmpl = self . env . from_string ( '''''' ) assert tmpl . render ( ) == '' def test_complex_call ( self ) : tmpl = self . env . from_string ( '''''' ) assert tmpl . render ( ) == '' def test_caller_undefined ( self ) : tmpl = self . env . from_string ( '''''' ) assert tmpl . render ( ) == '' def test_include ( self ) : self . env = Environment ( loader = DictLoader ( { '' : '' } ) ) tmpl = self . env . from_string ( '' ) assert tmpl . render ( ) == '' def test_macro_api ( self ) : tmpl = self . env . from_string ( '' '' '' ) assert tmpl . module . foo . arguments == ( '' , '' ) assert tmpl . module . foo . defaults == ( ) assert tmpl . module . foo . name == '' ", "answer": "assert not tmpl . module . foo . caller"}, {"prompt": " import os from . flann_imagecontentsearch import FlannImageContentSearch def load ( info ) : ", "answer": "index = ''"}, {"prompt": " from __future__ import absolute_import from openstack_dashboard . api import neutron neutronclient = neutron . neutronclient class IKEPolicy ( neutron . NeutronAPIDictWrapper ) : \"\"\"\"\"\" def __init__ ( self , apiresource ) : super ( IKEPolicy , self ) . __init__ ( apiresource ) class IPSecPolicy ( neutron . NeutronAPIDictWrapper ) : \"\"\"\"\"\" def __init__ ( self , apiresource ) : super ( IPSecPolicy , self ) . __init__ ( apiresource ) class IPSecSiteConnection ( neutron . NeutronAPIDictWrapper ) : \"\"\"\"\"\" def __init__ ( self , apiresource ) : super ( IPSecSiteConnection , self ) . __init__ ( apiresource ) class AttributeDict ( dict ) : def __getattr__ ( self , attr ) : return self [ attr ] def __setattr__ ( self , attr , value ) : self [ attr ] = value def readable ( self , request ) : cFormatted = { '' : self . id , '' : self . name , '' : self . description , '' : self . status , } try : cFormatted [ '' ] = self . ikepolicy_id cFormatted [ '' ] = ikepolicy_get ( request , self . ikepolicy_id ) . name except Exception : cFormatted [ '' ] = self . ikepolicy_id cFormatted [ '' ] = self . ikepolicy_id try : cFormatted [ '' ] = self . ipsecpolicy_id cFormatted [ '' ] = ipsecpolicy_get ( request , self . ipsecpolicy_id ) . name except Exception : cFormatted [ '' ] = self . ipsecpolicy_id cFormatted [ '' ] = self . ipsecpolicy_id try : cFormatted [ '' ] = self . vpnservice_id cFormatted [ '' ] = vpnservice_get ( request , self . vpnservice_id ) . name except Exception : cFormatted [ '' ] = self . vpnservice_id cFormatted [ '' ] = self . vpnservice_id return self . AttributeDict ( cFormatted ) class VPNService ( neutron . NeutronAPIDictWrapper ) : \"\"\"\"\"\" def __init__ ( self , apiresource ) : super ( VPNService , self ) . __init__ ( apiresource ) class AttributeDict ( dict ) : def __getattr__ ( self , attr ) : return self [ attr ] def __setattr__ ( self , attr , value ) : self [ attr ] = value def readable ( self , request ) : sFormatted = { '' : self . id , '' : self . name , '' : self . description , '' : self . admin_state_up , '' : self . status , } try : sFormatted [ '' ] = self . subnet_id sFormatted [ '' ] = neutron . subnet_get ( request , self . subnet_id ) . cidr except Exception : sFormatted [ '' ] = self . subnet_id sFormatted [ '' ] = self . subnet_id try : sFormatted [ '' ] = self . router_id sFormatted [ '' ] = neutron . router_get ( request , self . router_id ) . name except Exception : sFormatted [ '' ] = self . router_id sFormatted [ '' ] = self . router_id return self . AttributeDict ( sFormatted ) def vpnservice_create ( request , ** kwargs ) : \"\"\"\"\"\" body = { '' : { '' : kwargs [ '' ] , '' : kwargs [ '' ] , '' : kwargs [ '' ] , '' : kwargs [ '' ] , '' : kwargs [ '' ] } } vpnservice = neutronclient ( request ) . create_vpnservice ( body ) . get ( '' ) return VPNService ( vpnservice ) def vpnservices_get ( request , ** kwargs ) : vpnservices = neutronclient ( request ) . list_vpnservices ( ) . get ( '' ) return [ VPNService ( v ) for v in vpnservices ] def vpnservice_get ( request , vpnservice_id ) : vpnservice = neutronclient ( request ) . show_vpnservice ( vpnservice_id ) . get ( '' ) return VPNService ( vpnservice ) def vpnservice_update ( request , vpnservice_id , ** kwargs ) : vpnservice = neutronclient ( request ) . update_vpnservice ( vpnservice_id , kwargs ) . get ( '' ) return VPNService ( vpnservice ) def vpnservice_delete ( request , vpnservice_id ) : neutronclient ( request ) . delete_vpnservice ( vpnservice_id ) def ikepolicy_create ( request , ** kwargs ) : \"\"\"\"\"\" body = { '' : { '' : kwargs [ '' ] , '' : kwargs [ '' ] , '' : kwargs [ '' ] , '' : kwargs [ '' ] , '' : kwargs [ '' ] , '' : kwargs [ '' ] , '' : kwargs [ '' ] , '' : kwargs [ '' ] } } ikepolicy = neutronclient ( request ) . create_ikepolicy ( body ) . get ( '' ) return IKEPolicy ( ikepolicy ) def ikepolicies_get ( request , ** kwargs ) : ikepolicies = neutronclient ( request ) . list_ikepolicies ( ) . get ( '' ) return [ IKEPolicy ( v ) for v in ikepolicies ] def ikepolicy_get ( request , ikepolicy_id ) : ikepolicy = neutronclient ( request ) . show_ikepolicy ( ikepolicy_id ) . get ( '' ) return IKEPolicy ( ikepolicy ) def ikepolicy_update ( request , ikepolicy_id , ** kwargs ) : ikepolicy = neutronclient ( request ) . update_ikepolicy ( ikepolicy_id , kwargs ) . get ( '' ) ", "answer": "return IKEPolicy ( ikepolicy )"}, {"prompt": " from math . rect import Rect class Node : def __init__ ( self , x , y , width , height ) : self . x = x self . y = y self . width = width self . height = height def does_rect_fit ( self , width , height ) : resultList = [ ] result = False edgeCount = if ( width == self . width or height == self . height or width == self . height or height == self . width ) : if ( width == self . width ) : edgeCount += if ( height == self . height ) : edgeCount += elif ( width == self . height ) : edgeCount += if ( height == self . width ) : edgeCount += elif ( height == self . width ) : edgeCount += elif ( height == self . height ) : edgeCount += if ( width <= self . width and height <= self . height ) : result = True elif ( height <= self . width and width <= self . height ) : result = True resultList . append ( result ) resultList . append ( edgeCount ) return ( resultList ) def get_rect ( self ) : return Rect ( self . x , self . y , self . x + self . width , self . y + self . height ) def validate ( self , node ) : r1 = self . get_rect ( ) r2 = node . get_rect ( ) return ( r1 != r2 ) def merge ( self , node ) : ret = False r1 = self . get_rect ( ) r2 = node . get_rect ( ) r1 . x2 += r1 . y2 += r2 . x2 += r2 . y2 += if ( r1 . x1 == r2 . x1 and r1 . x2 == r2 . x2 and r1 . y1 == r2 . y2 ) : self . y = node . y self . height += node . get_rect ( ) . height ret = True elif ( r1 . x1 == r2 . x1 and r1 . x2 == r2 . x2 and r1 . y2 == r2 . y1 ) : self . height += node . get_rect ( ) . height ret = True elif ( r1 . y1 == r2 . y1 and r1 . y2 == r2 . y1 and r1 . x1 == r2 . x2 ) : self . x = node . x self . width += node . get_rect ( ) . width ", "answer": "ret = True"}, {"prompt": " from debile . slave . wrappers . findbugs import parse_findbugs from debile . slave . utils import cd from debile . utils . commands import run_command def findbugs ( deb , analysis ) : ", "answer": "run_command ( [ \"\" , \"\" , deb , \"\" ] )"}, {"prompt": " from __future__ import absolute_import , print_function , unicode_literals import sys from cms . sitemaps import CMSSitemap from cms . utils . conf import get_cms_setting from django . conf import settings from django . conf . urls import include , patterns , url from django . conf . urls . i18n import i18n_patterns from django . contrib import admin from django . contrib . staticfiles . urls import staticfiles_urlpatterns from djangocms_blog . sitemaps import BlogSitemap admin . autodiscover ( ) urlpatterns = patterns ( '' , url ( r'' , '' , { '' : settings . MEDIA_ROOT , '' : True } ) , url ( r'' , '' , { '' : get_cms_setting ( '' ) , '' : True } ) , url ( r'' , '' ) , url ( r'' , include ( '' ) ) , url ( r'' , '' , { '' : { '' : CMSSitemap , '' : BlogSitemap , ", "answer": "}"}, {"prompt": " from . PBXResolver import * from . PBX_Base import * class PBXBuildRule ( PBX_Base ) : def __init__ ( self , lookup_func , dictionary , project , identifier ) : super ( PBXBuildRule , self ) . __init__ ( lookup_func , dictionary , project , identifier ) ; if '' in dictionary . keys ( ) : ", "answer": "self . compilerSpec = dictionary [ '' ] ;"}, {"prompt": " import mock from oslo_vmware . objects import datacenter from oslo_vmware . tests import base class DatacenterTestCase ( base . TestCase ) : \"\"\"\"\"\" def test_dc ( self ) : self . assertRaises ( ValueError , datacenter . Datacenter , None , '' ) ", "answer": "self . assertRaises ( ValueError , datacenter . Datacenter , mock . Mock ( ) , None )"}, {"prompt": " __version__ = __all__ = [ ", "answer": "\"\" ,"}, {"prompt": " import socket import mock from nova import exception from nova . tests . unit . virt . hyperv import test_base from nova . virt . hyperv import serialproxy class SerialProxyTestCase ( test_base . HyperVBaseTestCase ) : @ mock . patch . object ( socket , '' ) def setUp ( self , mock_socket ) : super ( SerialProxyTestCase , self ) . setUp ( ) ", "answer": "self . _mock_socket = mock_socket"}, {"prompt": " from django . conf . urls import patterns from django . conf . urls import url from disaster_recovery . backups import views urlpatterns = patterns ( '' , url ( r'' , views . IndexView . as_view ( ) , name = '' ) , ", "answer": "url ( r'' , views . DetailView . as_view ( ) , name = '' ) ,"}, {"prompt": " from rllab . algos . npo import NPO from rllab . optimizers . conjugate_gradient_optimizer import ConjugateGradientOptimizer from rllab . core . serializable import Serializable class TRPO ( NPO , Serializable ) : \"\"\"\"\"\" def __init__ ( self , optimizer = None , ", "answer": "optimizer_args = None ,"}, {"prompt": " from . base import BaseCompressor class IdentityCompressor ( BaseCompressor ) : ", "answer": "def compress ( self , value ) :"}, {"prompt": " '''''' '''''' def acovf_fft ( x , demean = True ) : '''''' from scipy import signal ", "answer": "x = np . asarray ( x )"}, {"prompt": " from __future__ import with_statement , absolute_import import os stable_version = '' target_version = '' is_release = stable_version == target_version try : from setuptools import setup has_setuptools = True except ImportError : from distutils . core import setup has_setuptools = False if os . path . exists ( '' ) : ", "answer": "os . chdir ( '' )"}, {"prompt": " def check_args ( args , options ) : ", "answer": "for key in options [ \"\" ] :"}, {"prompt": " import os . path import platform import py class AbstractSDK ( object ) : def _check_helper ( cls , helper ) : if py . path . local . sysfind ( helper ) is None : py . test . skip ( \"\" % helper ) else : return helper _check_helper = classmethod ( _check_helper ) def runtime ( cls ) : for item in cls . RUNTIME : cls . _check_helper ( item ) return cls . RUNTIME runtime = classmethod ( runtime ) def ilasm ( cls ) : ", "answer": "return cls . _check_helper ( cls . ILASM )"}, {"prompt": " from sklearn . datasets import load_files from sklearn . feature_extraction . text import TfidfVectorizer from sklearn . grid_search import GridSearchCV from sklearn . pipeline import Pipeline from sklearn . svm import LinearSVC data = load_files ( '' ) vect = TfidfVectorizer ( ) X = vect . fit_transform ( data . data ) params = { \"\" : [ ( , ) , ( , ) ] , \"\" : [ , , , ] , \"\" : [ , , , , , , ] , \"\" : [ , , , , , , , , , , , ] } clf = Pipeline ( [ ( \"\" , TfidfVectorizer ( sublinear_tf = True ) ) , ( \"\" , LinearSVC ( loss = '' , max_iter = ) ) ] ) ", "answer": "gs = GridSearchCV ( clf , params , verbose = , n_jobs = - )"}, {"prompt": " import sys \"\"\"\"\"\" class LibAcosChecksum ( object ) : def __init__ ( self , data , data_len , checksum_offset = - ) : self . dword_623A0 = self . dword_623A4 = fake_checksum = \"\" self . data = data [ : data_len ] if ( checksum_offset > - ) : self . data = ( self . data [ : checksum_offset ] + fake_checksum + self . data [ checksum_offset + len ( fake_checksum ) : ] ) self . _update ( self . data [ : data_len ] ) self . _finalize ( ) def _update ( self , data ) : size = len ( data ) t0 = self . dword_623A0 a0 = self . dword_623A4 a2 = size a3 = while a3 != a2 : v1 = ord ( data [ a3 ] ) a3 += a0 = ( a0 + v1 ) & ", "answer": "t0 = ( t0 + a0 ) & "}, {"prompt": " import os from scrapy . commands import ScrapyCommand from scrapy . utils . conf import arglist_to_dict from scrapy . utils . python import without_none_values from scrapy . exceptions import UsageError class Command ( ScrapyCommand ) : requires_project = True def syntax ( self ) : ", "answer": "return \"\""}, {"prompt": " from django . contrib import messages from django . contrib . messages . storage . base import Message from django . core import mail from django . http import HttpResponseRedirect , HttpResponsePermanentRedirect class StatusCodeAssertionsMixin ( object ) : redirect_codes = [ HttpResponseRedirect . status_code , HttpResponsePermanentRedirect . status_code ] def assert_status_equal ( self , response , status_code_or_response ) : status_code = self . _get_status_code ( status_code_or_response ) self . assertEqual ( response . status_code , status_code , '' . format ( response . status_code , status_code , ) ) def assert_status_in ( self , response , status_codes_or_responses ) : status_codes = list ( map ( self . _get_status_code , status_codes_or_responses ) ) self . assertIn ( response . status_code , status_codes , '' . format ( response . status_code , '' . join ( str ( code ) for code in status_codes ) , ) ) def _get_redirect_assertion_message ( self , response ) : return '' . format ( response . status_code ) def assert_redirect ( self , response , expected_url = None ) : \"\"\"\"\"\" self . assertIn ( response . status_code , self . redirect_codes , self . _get_redirect_assertion_message ( response ) , ) if expected_url : location_header = response . _headers . get ( '' , None ) self . assertEqual ( location_header , ( '' , str ( expected_url ) ) , '' . format ( expected_url , location_header [ ] , ) ) def assert_not_redirect ( self , response ) : self . assertNotIn ( response . status_code , self . redirect_codes , self . _get_redirect_assertion_message ( response ) ) def _get_status_code ( self , status_code_or_response ) : try : return status_code_or_response . status_code except AttributeError : return status_code_or_response class EmailAssertionsMixin ( object ) : def assert_emails_in_mailbox ( self , count ) : self . assertEqual ( len ( mail . outbox ) , count , '' . format ( len ( mail . outbox ) , count , ) ) def _is_email_matching_criteria ( self , email , ** kwargs ) : for key , value in kwargs . items ( ) : if getattr ( email , key ) != value : return False return True def assert_email ( self , email , ** kwargs ) : for key , value in kwargs . items ( ) : self . assertEqual ( getattr ( email , key ) , value , '' . format ( key , value , getattr ( email , key ) , ) ) def assert_email_exists ( self , ** kwargs ) : for email in mail . outbox : if self . _is_email_matching_criteria ( email , ** kwargs ) : return raise AssertionError ( '' ) class MessagesAssertionsMixin ( object ) : def assert_messages_sent ( self , request , count ) : sent = len ( messages . get_messages ( request ) ) self . assertEqual ( sent , count , '' . format ( sent , count , ) ) def assert_message_exists ( self , request , level , message ) : self . assertIn ( Message ( level = level , message = message ) , messages . get_messages ( request ) , '' ) class _InstanceContext ( object ) : \"\"\"\"\"\" def __init__ ( self , enter_assertion , exit_assertion , model_class , ** kwargs ) : self . enter_assertion = enter_assertion self . exit_assertion = exit_assertion self . model_class = model_class self . kwargs = kwargs def __enter__ ( self ) : self . enter_assertion ( self . model_class , ** self . kwargs ) return self def __exit__ ( self , exc_type , exc_value , traceback ) : self . exit_assertion ( self . model_class , ** self . kwargs ) return True class InstanceAssertionsMixin ( object ) : \"\"\"\"\"\" def assert_instance_exists ( self , model_class , ** kwargs ) : try : obj = model_class . _default_manager . get ( ** kwargs ) self . assertIsNotNone ( obj ) except model_class . DoesNotExist : raise AssertionError ( '' . format ( model_class . __name__ , ) ) def assert_instance_does_not_exist ( self , model_class , ** kwargs ) : try : instance = model_class . _default_manager . get ( ** kwargs ) raise AssertionError ( '' . format ( model_class . __name__ , instance , ) ) except model_class . DoesNotExist : pass def assert_instance_created ( self , model_class , ** kwargs ) : \"\"\"\"\"\" return _InstanceContext ( self . assert_instance_does_not_exist , self . assert_instance_exists , model_class , ** kwargs ) def assert_instance_deleted ( self , model_class , ** kwargs ) : \"\"\"\"\"\" return _InstanceContext ( self . assert_instance_exists , self . assert_instance_does_not_exist , model_class , ** kwargs ) class CompleteAssertionsMixin ( StatusCodeAssertionsMixin , EmailAssertionsMixin , MessagesAssertionsMixin , InstanceAssertionsMixin , ) : ", "answer": "pass "}, {"prompt": " from pprint import pprint from rules import RuleHandler import argparse import logging import modbot import praw import sys def myperformaction ( thing , action , rule , matches ) : logging . info ( \"\" % action ) modbot . performaction = myperformaction def testrule ( rule , thing ) : rh = RuleHandler ( '' , '' ) rule = rh . _read_rule ( rule ) return modbot . matchrules ( thing , [ rule ] ) if __name__ == \"\" : parser = argparse . ArgumentParser ( description = \"\" ) parser . add_argument ( '' , action = '' , default = False ) parser . add_argument ( '' ) parser . add_argument ( '' ) args = parser . parse_args ( ) r = praw . Reddit ( '' % ( modbot . NAME , modbot . VERSION ) ) logging . basicConfig ( level = logging . DEBUG , format = \"\" ) logging . info ( \"\" ) if args . comment : thing = r . request_json ( args . url ) [ ] [ '' ] [ '' ] [ ] else : thing = r . get_submission ( args . url ) logging . info ( \"\" ) ", "answer": "if testrule ( args . rule , thing ) :"}, {"prompt": " \"\"\"\"\"\" import numpy as np from . . core . radar import Radar from . . core . transforms import geographic_to_cartesian from . . filters import GateFilter , moment_based_gate_filter from . _gate_to_grid_map import GateToGridMapper from . _gate_to_grid_map import RoIFunction , ConstantRoI , DistBeamRoI , DistRoI def map_gates_to_grid ( radars , grid_shape , grid_limits , grid_origin = None , grid_origin_alt = None , grid_projection = None , fields = None , gatefilters = False , map_roi = True , weighting_function = '' , toa = , roi_func = '' , constant_roi = , z_factor = , xy_factor = , min_radius = , h_factor = , nb = , bsp = , ** kwargs ) : \"\"\"\"\"\" if isinstance ( radars , Radar ) : radars = ( radars , ) skip_transform = False if len ( radars ) == and grid_origin_alt is None and grid_origin is None : skip_transform = True if grid_origin_alt is None : grid_origin_alt = float ( radars [ ] . altitude [ '' ] ) gatefilters = _parse_gatefilters ( gatefilters , radars ) cy_weighting_function = _detemine_cy_weighting_func ( weighting_function ) projparams = _find_projparams ( grid_origin , radars , grid_projection ) fields = _determine_fields ( fields , radars ) grid_starts , grid_steps = _find_grid_params ( grid_shape , grid_limits ) offsets = _find_offsets ( radars , projparams , grid_origin_alt ) roi_func = _parse_roi_func ( roi_func , constant_roi , z_factor , xy_factor , min_radius , h_factor , nb , bsp , offsets ) nfields = len ( fields ) grid_sum = np . zeros ( grid_shape + ( nfields , ) , dtype = np . float32 ) grid_wsum = np . zeros ( grid_shape + ( nfields , ) , dtype = np . float32 ) gatemapper = GateToGridMapper ( grid_shape , grid_starts , grid_steps , grid_sum , grid_wsum ) for radar , gatefilter in zip ( radars , gatefilters ) : shape = ( radar . nrays , radar . ngates , nfields ) field_data = np . empty ( shape , dtype = '' ) field_mask = np . empty ( shape , dtype = '' ) for i , field in enumerate ( fields ) : fdata = radar . fields [ field ] [ '' ] field_data [ : , : , i ] = np . ma . getdata ( fdata ) field_mask [ : , : , i ] = np . ma . getmaskarray ( fdata ) if gatefilter is False : gatefilter = GateFilter ( radar ) elif gatefilter is None : gatefilter = moment_based_gate_filter ( radar , ** kwargs ) excluded_gates = gatefilter . gate_excluded . astype ( '' ) if skip_transform : gate_x = radar . gate_x [ '' ] gate_y = radar . gate_y [ '' ] else : gate_x , gate_y = geographic_to_cartesian ( radar . gate_longitude [ '' ] , radar . gate_latitude [ '' ] , projparams ) gate_z = radar . gate_altitude [ '' ] - grid_origin_alt gatemapper . map_gates_to_grid ( radar . ngates , radar . nrays , gate_z . astype ( '' ) , gate_y . astype ( '' ) , gate_x . astype ( '' ) , field_data , field_mask , excluded_gates , toa , roi_func , cy_weighting_function ) mweight = np . ma . masked_equal ( grid_wsum , ) msum = np . ma . masked_array ( grid_sum , mweight . mask ) grids = dict ( [ ( f , msum [ ... , i ] / mweight [ ... , i ] ) for i , f in enumerate ( fields ) ] ) if map_roi : roi_array = np . empty ( grid_shape , dtype = np . float32 ) gatemapper . find_roi_for_grid ( roi_array , roi_func ) grids [ '' ] = roi_array return grids def _detemine_cy_weighting_func ( weighting_function ) : \"\"\"\"\"\" if weighting_function . upper ( ) == '' : cy_weighting_function = elif weighting_function . upper ( ) == '' : cy_weighting_function = else : raise ValueError ( '' ) return cy_weighting_function def _find_projparams ( grid_origin , radars , grid_projection ) : \"\"\"\"\"\" if grid_origin is None : lat = float ( radars [ ] . latitude [ '' ] ) lon = float ( radars [ ] . longitude [ '' ] ) grid_origin = ( lat , lon ) grid_origin_lat , grid_origin_lon = grid_origin if grid_projection is None : grid_projection = { '' : '' , '' : True } projparams = grid_projection . copy ( ) if projparams . pop ( '' , False ) : projparams [ '' ] = grid_origin_lon projparams [ '' ] = grid_origin_lat return projparams def _parse_gatefilters ( gatefilters , radars ) : \"\"\"\"\"\" ", "answer": "if isinstance ( gatefilters , GateFilter ) :"}, {"prompt": " import datetime import json import requests try : import requests_cache HAS_CACHE = True except ImportError : HAS_CACHE = False import logging logger = logging sort_choice = [ '' , '' , '' , '' , '' , '' ] class PyPDNS ( object ) : def __init__ ( self , url = '' , basic_auth = None , auth_token = None , enable_cache = False , cache_expire_after = , cache_file = '' ) : self . url = url if enable_cache and not HAS_CACHE : raise Exception ( '' ) self . enable_cache = enable_cache if enable_cache is True : requests_cache . install_cache ( cache_file , backend = '' , expire_after = cache_expire_after ) ", "answer": "self . session = requests_cache . CachedSession ( )"}, {"prompt": " '''''' import base64 import unittest import zlib from StringIO import StringIO import numpy as np from cellprofiler . preferences import set_headless set_headless ( ) import cellprofiler . pipeline as cpp import cellprofiler . cpmodule as cpm import cellprofiler . cpimage as cpi import cellprofiler . measurements as cpmeas import cellprofiler . objects as cpo import cellprofiler . workspace as cpw import cellprofiler . modules . measurecorrelation as M IMAGE1_NAME = '' IMAGE2_NAME = '' OBJECTS_NAME = '' ", "answer": "class TestMeasureCorrelation ( unittest . TestCase ) :"}, {"prompt": " from plumbum . commands . base import BaseCommand from plumbum . commands . processes import run_proc , CommandNotFound , ProcessExecutionError def make_concurrent ( self , rhs ) : if not isinstance ( rhs , BaseCommand ) : raise TypeError ( \"\" ) if isinstance ( self , ConcurrentCommand ) : if isinstance ( rhs , ConcurrentCommand ) : self . commands . extend ( rhs . commands ) else : self . commands . append ( rhs ) return self elif isinstance ( rhs , ConcurrentCommand ) : rhs . commands . insert ( , self ) return rhs else : return ConcurrentCommand ( self , rhs ) BaseCommand . __and__ = make_concurrent class ConcurrentPopen ( object ) : def __init__ ( self , procs ) : self . procs = procs self . stdin = None self . stdout = None self . stderr = None self . encoding = None self . returncode = None @ property def argv ( self ) : return [ getattr ( proc , \"\" , [ ] ) for proc in self . procs ] def poll ( self ) : if self . returncode is not None : return self . returncode rcs = [ proc . poll ( ) for proc in self . procs ] if any ( rc is None for rc in rcs ) : return None self . returncode = for rc in rcs : if rc != : self . returncode = rc break return self . returncode def wait ( self ) : for proc in self . procs : proc . wait ( ) return self . poll ( ) def communicate ( self , input = None ) : if input : raise ValueError ( \"\" ) out_err_tuples = [ proc . communicate ( ) for proc in self . procs ] self . wait ( ) return tuple ( zip ( * out_err_tuples ) ) class ConcurrentCommand ( BaseCommand ) : def __init__ ( self , * commands ) : self . commands = list ( commands ) def formulate ( self , level = , args = ( ) ) : form = [ \"\" ] for cmd in self . commands : form . extend ( cmd . formulate ( level , args ) ) form . append ( \"\" ) return form + [ \"\" ] def popen ( self , * args , ** kwargs ) : return ConcurrentPopen ( [ cmd [ args ] . popen ( ** kwargs ) for cmd in self . commands ] ) def __getitem__ ( self , args ) : \"\"\"\"\"\" if not isinstance ( args , ( tuple , list ) ) : args = [ args , ] if not args : return self else : return ConcurrentCommand ( * ( cmd [ args ] for cmd in self . commands ) ) class Cluster ( object ) : def __init__ ( self , * machines ) : self . machines = list ( machines ) def __enter__ ( self ) : return self def __exit__ ( self , t , v , tb ) : self . close ( ) def close ( self ) : for mach in self . machines : mach . close ( ) del self . machines [ : ] def add_machine ( self , machine ) : self . machines . append ( machine ) def __iter__ ( self ) : return iter ( self . machines ) def filter ( self , pred ) : return self . __class__ ( filter ( pred , self ) ) def which ( self , progname ) : return [ mach . which ( progname ) for mach in self ] def list_processes ( self ) : return [ mach . list_processes ( ) for mach in self ] def pgrep ( self , pattern ) : return [ mach . pgrep ( pattern ) for mach in self ] def path ( self , * parts ) : return [ mach . path ( * parts ) for mach in self ] def __getitem__ ( self , progname ) : if not isinstance ( progname , str ) : raise TypeError ( \"\" % ( type ( progname , ) ) ) return ConcurrentCommand ( * ( mach [ progname ] for mach in self ) ) def __contains__ ( self , cmd ) : try : self [ cmd ] except CommandNotFound : return False else : return True @ property def python ( self ) : return ConcurrentCommand ( * ( mach . python for mach in self ) ) def session ( self ) : return ClusterSession ( * ( mach . session ( ) for mach in self ) ) class ClusterSession ( object ) : ", "answer": "def __init__ ( self , * sessions ) :"}, {"prompt": " '''''' from __future__ import absolute_import import logging import struct log = logging . getLogger ( __name__ ) try : import pypureomapi as omapi omapi_support = True except ImportError as e : omapi_support = False def __virtual__ ( ) : '''''' if omapi_support : return '' return ( False , '' '' ) def _conn ( ) : server_ip = __pillar__ . get ( '' , __opts__ . get ( '' , '' ) ) server_port = __pillar__ . get ( '' , __opts__ . get ( '' , ) ) key = __pillar__ . get ( '' , __opts__ . get ( '' , None ) ) username = __pillar__ . get ( '' , __opts__ . get ( '' , None ) ) return omapi . Omapi ( server_ip , server_port , username = username , key = key ) def add_host ( mac , name = None , ip = None , ddns = False , group = None , supersede_host = False ) : '''''' statements = '' o = _conn ( ) msg = omapi . OmapiMessage . open ( b'' ) msg . message . append ( ( '' , struct . pack ( '' , ) ) ) ", "answer": "msg . message . append ( ( '' , struct . pack ( '' , ) ) )"}, {"prompt": " import uuid from gnocchiclient . tests . functional import base class ResourceTypeClientTest ( base . ClientTestBase ) : RESOURCE_TYPE = str ( uuid . uuid4 ( ) ) def test_help ( self ) : self . gnocchi ( \"\" , params = \"\" ) def test_resource_type_scenario ( self ) : result = self . gnocchi ( '' , params = \"\" ) r = self . parser . listing ( result ) self . assertEqual ( [ { '' : '' , '' : '' } ] , r ) result = self . gnocchi ( u'' , params = u\"\" \"\" % self . RESOURCE_TYPE ) resource = self . details_multiple ( result ) [ ] self . assertEqual ( self . RESOURCE_TYPE , resource [ \"\" ] ) self . assertEqual ( \"\" , resource [ \"\" ] ) result = self . gnocchi ( u'' , params = u\"\" % self . RESOURCE_TYPE ) resource = self . details_multiple ( result ) [ ] self . assertEqual ( self . RESOURCE_TYPE , resource [ \"\" ] ) self . assertEqual ( \"\" , resource [ \"\" ] ) result = self . gnocchi ( '' , params = \"\" % self . RESOURCE_TYPE ) self . assertEqual ( \"\" , result ) result = self . gnocchi ( '' , params = \"\" % self . RESOURCE_TYPE , fail_ok = True , merge_stderr = True ) self . assertFirstLineStartsWith ( result . split ( '' ) , \"\" % self . RESOURCE_TYPE ) result = self . gnocchi ( u'' , ", "answer": "params = u\"\" % self . RESOURCE_TYPE ,"}, {"prompt": " from flask import Flask , Response from werkzeug . routing import BaseConverter , ValidationError from base64 import urlsafe_b64encode , urlsafe_b64decode from bson . objectid import ObjectId from bson . errors import InvalidId import datetime import mmh3 try : import json except ImportError : import simplejson as json try : from bson . objectid import ObjectId except : pass class APIEncoder ( json . JSONEncoder ) : def default ( self , obj ) : if isinstance ( obj , ( datetime . datetime , datetime . date ) ) : return obj . ctime ( ) elif isinstance ( obj , datetime . time ) : return obj . isoformat ( ) elif isinstance ( obj , ObjectId ) : return str ( obj ) ", "answer": "return json . JSONEncoder . default ( self , obj )"}, {"prompt": " from chainer import cuda from chainer . functions . math import identity from chainer import link class Parameter ( link . Link ) : \"\"\"\"\"\" ", "answer": "def __init__ ( self , array ) :"}, {"prompt": " '''''' import os import re import shutil import subprocess import tempfile class Tag ( object ) : def __init__ ( self , name , timestamp = None ) : self . name = name self . timestamp = timestamp class LogEntry ( object ) : def __init__ ( self , msg , affected_paths , author ) : self . msg = msg self . author = author self . _affected_paths = [ p for p in affected_paths if p ] def affects_path ( self , path ) : for apath in self . _affected_paths : if path == '' : return True if apath . startswith ( os . path . join ( path , '' ) ) : return True return False class VcsClientBase ( object ) : def __init__ ( self , path ) : self . path = path def get_tags ( self ) : raise NotImplementedError ( ) def get_latest_tag_name ( self ) : raise NotImplementedError ( ) def get_log_entries ( self , from_tag , to_tag , skip_merges = False ) : raise NotImplementedError ( ) def replace_repository_references ( self , line ) : return line def _find_executable ( self , file_name ) : for path in os . getenv ( '' ) . split ( os . path . pathsep ) : file_path = os . path . join ( path , file_name ) if os . path . isfile ( file_path ) : return file_path return None def _run_command ( self , cmd , env = None ) : cwd = os . path . abspath ( self . path ) result = { '' : '' . join ( cmd ) , '' : cwd } try : proc = subprocess . Popen ( cmd , cwd = cwd , stdout = subprocess . PIPE , stderr = subprocess . STDOUT , env = env ) output , _ = proc . communicate ( ) result [ '' ] = output . rstrip ( ) result [ '' ] = proc . returncode except subprocess . CalledProcessError as e : result [ '' ] = e . output result [ '' ] = e . returncode return result def _truncate_timestamps ( self , tags ) : lengths = [ , , ] for length in lengths : considered_tags = [ t for t in tags if len ( t . timestamp ) > length ] grouped_by_timestamp = { } for t in considered_tags : truncated_timestamp = t . timestamp [ : length ] if truncated_timestamp not in grouped_by_timestamp : grouped_by_timestamp [ truncated_timestamp ] = [ ] grouped_by_timestamp [ truncated_timestamp ] . append ( t ) for truncated_timestamp , similar_tags in grouped_by_timestamp . items ( ) : if len ( similar_tags ) == : similar_tags [ ] . timestamp = truncated_timestamp class GitClient ( VcsClientBase ) : type = '' def __init__ ( self , path ) : super ( GitClient , self ) . __init__ ( path ) self . _executable = self . _find_executable ( '' ) self . _repo_hosting = None self . _github_base_url = '' self . _github_path = None def _get_author ( self , hash_ ) : cmd = [ self . _executable , '' , hash_ , '' , '' , '' ] result = self . _run_command ( cmd ) if result [ '' ] : raise RuntimeError ( '' % result [ '' ] ) return result [ '' ] def get_tags ( self ) : cmd_tag = [ self . _executable , '' , '' , '' , '' ] ", "answer": "result_tag = self . _run_command ( cmd_tag )"}, {"prompt": " \"\"\"\"\"\" from cafe . drivers . unittest . datasets import DatasetList , _Dataset from cafe . drivers . unittest . decorators import memoized from cloudcafe . common . datasets import ModelBasedDatasetToolkit from cloudcafe . blockstorage . composites import VolumesAutoComposite try : from cloudcafe . compute . datasets import ComputeDatasets except Exception as ex : import warnings msg = \"\" warnings . warn ( msg ) class ComputeDatasets ( object ) : pass class BlockstorageDatasets ( ModelBasedDatasetToolkit ) : \"\"\"\"\"\" _volumes = VolumesAutoComposite ( ) @ classmethod @ memoized def _get_volume_types ( cls ) : \"\"\"\"\"\" return cls . _get_model_list ( cls . _volumes . client . list_all_volume_types , '' ) @ classmethod def _get_volume_type_names ( cls ) : \"\"\"\"\"\" vtype_names = [ ] for vtype in cls . _get_volume_types ( ) : vtype_names . append ( vtype . name ) return vtype_names @ classmethod def default_volume_type_model ( cls ) : for vtype in cls . _get_volume_types ( ) : if ( vtype . id_ == cls . _volumes . config . default_volume_type or vtype . name == cls . _volumes . config . default_volume_type ) : return vtype raise Exception ( \"\" ) @ classmethod def default_volume_type ( cls ) : vol_type = cls . default_volume_type_model ( ) dataset = _Dataset ( name = vol_type . name , data_dict = { '' : vol_type . name , '' : vol_type . id_ } ) dataset_list = DatasetList ( ) dataset_list . append ( dataset ) return dataset_list @ classmethod def volume_types ( cls , max_datasets = None , randomize = None , model_filter = None , filter_mode = ModelBasedDatasetToolkit . INCLUSION_MODE , tags = None ) : \"\"\"\"\"\" volume_type_list = cls . _get_volume_types ( ) volume_type_list = cls . _filter_model_list ( volume_type_list , model_filter = model_filter , filter_mode = filter_mode ) dataset_list = DatasetList ( ) for vol_type in volume_type_list : data = { '' : vol_type . name , '' : vol_type . id_ } dataset_list . append_new_dataset ( vol_type . name , data ) dataset_list = cls . _modify_dataset_list ( dataset_list , max_datasets = max_datasets , randomize = randomize ) if tags : dataset_list . apply_test_tags ( * tags ) return dataset_list @ classmethod def configured_volume_types ( cls , max_datasets = None , randomize = False , tags = None ) : \"\"\"\"\"\" volume_type_filter = cls . _volumes . config . volume_type_filter volume_type_filter_mode = cls . _volumes . config . volume_type_filter_mode return cls . volume_types ( max_datasets = max_datasets , randomize = randomize , model_filter = volume_type_filter , filter_mode = volume_type_filter_mode , tags = tags ) class ComputeIntegrationDatasets ( ComputeDatasets , BlockstorageDatasets ) : @ classmethod def images_by_volume_type ( cls , max_datasets = None , randomize = False , image_filter = None , volume_type_filter = None , image_filter_mode = ModelBasedDatasetToolkit . INCLUSION_MODE , volume_type_filter_mode = ModelBasedDatasetToolkit . INCLUSION_MODE ) : \"\"\"\"\"\" image_list = cls . _get_images ( ) image_list = cls . _filter_model_list ( image_list , model_filter = image_filter , filter_mode = image_filter_mode ) volume_type_list = cls . _get_volume_types ( ) volume_type_list = cls . _filter_model_list ( volume_type_list , model_filter = volume_type_filter , filter_mode = volume_type_filter_mode ) dataset_list = DatasetList ( ) for vtype in volume_type_list : for image in image_list : data = { '' : vtype , '' : image } testname = \"\" . format ( str ( vtype . name ) . replace ( \"\" , \"\" ) , str ( image . name ) . replace ( \"\" , \"\" ) ) dataset_list . append_new_dataset ( testname , data ) return cls . _modify_dataset_list ( dataset_list , max_datasets = max_datasets , randomize = randomize ) @ classmethod def flavors_by_images_by_volume_type ( cls , max_datasets = None , randomize = None , flavor_filter = None , volume_type_filter = None , image_filter = None , flavor_filter_mode = ModelBasedDatasetToolkit . INCLUSION_MODE , volume_type_filter_mode = ModelBasedDatasetToolkit . INCLUSION_MODE , image_filter_mode = ModelBasedDatasetToolkit . INCLUSION_MODE , ) : \"\"\"\"\"\" image_list = cls . _get_images ( ) image_list = cls . _filter_model_list ( image_list , model_filter = image_filter , filter_mode = image_filter_mode ) flavor_list = cls . _get_flavors ( ) flavor_list = cls . _filter_model_list ( flavor_list , model_filter = flavor_filter , filter_mode = flavor_filter_mode ) volume_type_list = cls . _get_volume_types ( ) volume_type_list = cls . _filter_model_list ( volume_type_list , model_filter = volume_type_filter , filter_mode = volume_type_filter_mode ) dataset_list = DatasetList ( ) for vtype in volume_type_list : for flavor in flavor_list : for image in image_list : data = { '' : vtype , '' : flavor , '' : image } testname = \"\" . format ( flavor = str ( flavor . name ) , image = str ( image . name ) , vtype = str ( vtype . name ) ) . replace ( '' , '' ) . replace ( '' , '' ) . replace ( '' , '' ) . replace ( '' , '' ) dataset_list . append_new_dataset ( testname , data ) return cls . _modify_dataset_list ( dataset_list , max_datasets = max_datasets , randomize = randomize ) @ classmethod def configured_images ( cls , max_datasets = None , randomize = None ) : \"\"\"\"\"\" image_filter = cls . _volumes . config . image_filter image_filter_mode = cls . _volumes . config . image_filter_mode return cls . images ( max_datasets = max_datasets , randomize = randomize , model_filter = image_filter , filter_mode = image_filter_mode ) @ classmethod def configured_images_by_volume_type ( cls , max_datasets = None , randomize = None ) : \"\"\"\"\"\" ", "answer": "image_filter = cls . _volumes . config . image_filter"}, {"prompt": " import datetime from south . db import db from south . v2 import SchemaMigration from django . db import models class Migration ( SchemaMigration ) : def forwards ( self , orm ) : db . add_column ( '' , '' , self . gf ( '' ) ( default = '' , max_length = , blank = True ) , keep_default = False ) def backwards ( self , orm ) : db . delete_column ( '' , '' ) models = { '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) } , '' : { '' : { '' : \"\" , '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) } , '' : { '' : { '' : \"\" , '' : \"\" , '' : '' , '' : \"\" } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , ", "answer": "'' : ( '' , [ ] , { '' : \"\" , '' : \"\" } ) ,"}, {"prompt": " \"\"\"\"\"\" import re from greplin . scales import aggregation import unittest class AggregationTest ( unittest . TestCase ) : \"\"\"\"\"\" def testNoData ( self ) : \"\" agg = aggregation . Aggregation ( { '' : { ", "answer": "'' : [ aggregation . Sum ( ) ]"}, {"prompt": " from ztag . annotation import * class VerisIndustriesAnnotation ( Annotation ) : ", "answer": "protocol = protocols . MODBUS"}, {"prompt": " from numba import exportmany , export ", "answer": "def mult ( a , b ) :"}, {"prompt": " from msrest . serialization import Model class DiskInstanceView ( Model ) : \"\"\"\"\"\" _attribute_map = { '' : { '' : '' , '' : '' } , '' : { '' : '' , '' : '' } , } def __init__ ( self , name = None , statuses = None ) : ", "answer": "self . name = name"}, {"prompt": " from six . moves import range from nova . cells import state import nova . conf from nova . db . sqlalchemy import models from nova import exception from nova . tests . functional . api_sample_tests import api_sample_base CONF = nova . conf . CONF CONF . import_opt ( '' , '' ) class CellsSampleJsonTest ( api_sample_base . ApiSampleTestBaseV21 ) : extension_name = \"\" def _get_flags ( self ) : f = super ( CellsSampleJsonTest , self ) . _get_flags ( ) f [ '' ] = CONF . osapi_compute_extension [ : ] f [ '' ] . append ( '' ) f [ '' ] . append ( '' '' ) return f def setUp ( self ) : self . flags ( enable = True , db_check_interval = - , group = '' ) super ( CellsSampleJsonTest , self ) . setUp ( ) ", "answer": "self . cells = self . start_service ( '' , manager = CONF . cells . manager )"}, {"prompt": " from flask import Flask , request , session , g , redirect , url_for , abort , render_template , flash , jsonify from flask . ext . sqlalchemy import SQLAlchemy import os basedir = os . path . abspath ( os . path . dirname ( __file__ ) ) DATABASE = '' DEBUG = True SECRET_KEY = '' USERNAME = '' PASSWORD = '' DATABASE_PATH = os . path . join ( basedir , DATABASE ) SQLALCHEMY_DATABASE_URI = '' + DATABASE_PATH app = Flask ( __name__ ) app . config . from_object ( __name__ ) db = SQLAlchemy ( app ) import models @ app . route ( '' ) def index ( ) : \"\"\"\"\"\" entries = db . session . query ( models . Flaskr ) return render_template ( '' , entries = entries ) @ app . route ( '' , methods = [ '' ] ) def add_entry ( ) : \"\"\"\"\"\" if not session . get ( '' ) : abort ( ) new_entry = models . Flaskr ( request . form [ '' ] , request . form [ '' ] ) db . session . add ( new_entry ) db . session . commit ( ) flash ( '' ) return redirect ( url_for ( '' ) ) @ app . route ( '' , methods = [ '' , '' ] ) def login ( ) : \"\"\"\"\"\" error = None if request . method == '' : if request . form [ '' ] != app . config [ '' ] : error = '' elif request . form [ '' ] != app . config [ '' ] : error = '' else : session [ '' ] = True flash ( '' ) return redirect ( url_for ( '' ) ) return render_template ( '' , error = error ) @ app . route ( '' ) def logout ( ) : \"\"\"\"\"\" session . pop ( '' , None ) flash ( '' ) return redirect ( url_for ( '' ) ) @ app . route ( '' , methods = [ '' ] ) def delete_entry ( post_id ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " from oschecks import utils def _check_glance_api ( ) : glance = utils . Glance ( ) glance . add_argument ( '' , dest = '' , type = int , default = , help = '' ) glance . add_argument ( '' , dest = '' , type = int , default = , help = '' ) options , args , client = glance . setup ( ) def images_list ( ) : return list ( client . images . list ( ) ) elapsed , images = utils . timeit ( images_list ) if not images : utils . critical ( \"\" ) if elapsed > options . critical : utils . critical ( \"\" \"\" % ( options . critical , elapsed ) ) elif elapsed > options . warning : utils . warning ( \"\" \"\" % ( options . warning , elapsed ) ) else : utils . ok ( \"\" \"\" % ", "answer": "( len ( images ) , elapsed , elapsed ) )"}, {"prompt": " from __future__ import unicode_literals from django . test import TestCase from rest_framework import serializers from rest_framework_mongoengine . serializers import DocumentSerializer from . models import DumbDocument class ValidationMethodSerializer ( DocumentSerializer ) : class Meta : model = DumbDocument def validate_name ( self , value ) : if len ( value ) < : raise serializers . ValidationError ( '' ) return value . title ( ) class RenamedValidationMethodSerializer ( DocumentSerializer ) : class Meta : model = DumbDocument renamed = serializers . CharField ( source = '' , required = False ) def validate_renamed ( self , value ) : if len ( value ) < : raise serializers . ValidationError ( '' ) return value . title ( ) def custom_field_validator ( value ) : if len ( value ) < : raise serializers . ValidationError ( '' ) class FieldValidatorSerializer ( DocumentSerializer ) : class Meta : model = DumbDocument name = serializers . CharField ( validators = [ custom_field_validator ] ) def custom_model_validator ( data ) : if len ( data [ '' ] ) < : ", "answer": "raise serializers . ValidationError ( '' )"}, {"prompt": " import numpy as np import matplotlib as mpl from matplotlib import pyplot as plt import lineid_plot def test_unique_labels ( ) : line_label1 = [ '' , '' , '' , '' , '' , '' , '' ] x = [ '' , '' , '' , '' , '' , '' , '' ] assert lineid_plot . unique_labels ( line_label1 ) == x def test_minimal_plot ( ) : wave = + np . arange ( ) * flux = np . random . normal ( size = ) line_wave = [ , , , , , , ] line_label1 = [ '' , '' , '' , '' , '' , '' , '' ] lineid_plot . plot_line_ids ( wave , flux , line_wave , line_label1 ) def test_no_line_from_annotation_to_flux ( ) : wave = + np . arange ( ) * flux = np . random . normal ( size = ) line_wave = [ , , , , , , ] line_label1 = [ '' , '' , '' , '' , '' , '' , '' ] lineid_plot . plot_line_ids ( wave , flux , line_wave , line_label1 , extend = False ) def test_multi_plot_user_axes ( ) : wave = + np . arange ( ) * flux = np . random . normal ( size = ) line_wave = [ , , , , , , ] line_label1 = [ '' , '' , '' , '' , '' , '' , '' ] fig = plt . figure ( ) ax = fig . add_axes ( [ , , , ] ) ax . plot ( wave , flux ) lineid_plot . plot_line_ids ( wave , flux , line_wave , line_label1 , ax = ax ) ax1 = fig . add_axes ( [ , , , ] ) ax1 . plot ( wave , flux ) lineid_plot . plot_line_ids ( wave , flux , line_wave , line_label1 , ax = ax1 ) def test_annotate_kwargs_and_plot_kwargs ( ) : wave = + np . arange ( ) * flux = np . random . normal ( size = ) line_wave = [ , , , , , , ] line_label1 = [ '' , '' , '' , '' , '' , '' , '' ] ak = lineid_plot . initial_annotate_kwargs ( ) ak [ '' ] [ '' ] = \"\" pk = lineid_plot . initial_plot_kwargs ( ) pk [ '' ] = \"\" lineid_plot . plot_line_ids ( wave , flux , line_wave , line_label1 , annotate_kwargs = ak , plot_kwargs = pk ) def test_customize_box_and_line ( ) : wave = + np . arange ( ) * flux = np . random . normal ( size = ) line_wave = [ , , , , , , ] line_label1 = [ '' , '' , '' , '' , '' , '' , '' ] fig , ax = lineid_plot . plot_line_ids ( wave , flux , line_wave , line_label1 ) b = ax . findobj ( match = lambda x : x . get_label ( ) == '' ) [ ] b . set_rotation ( ) b . set_text ( \"\" ) line = ax . findobj ( match = lambda x : x . get_label ( ) == '' ) [ ] line . set_color ( \"\" ) line . set_linestyle ( \"\" ) def test_small_change_to_y_loc_of_label ( ) : wave = + np . arange ( ) * flux = np . random . normal ( size = ) ", "answer": "line_wave = [ , , , , , , ]"}, {"prompt": " \"\"\"\"\"\" import pyjd from pyjamas . ui . RootPanel import RootPanel from pyjamas . ui . Button import Button from pyjamas . ui . HTML import HTML from pyjamas . ui . Label import Label from pyjamas import Window import pygwt from __pyjamas__ import doc from pyjamas import DOM from pyjamas . ui . CSS import StyleSheetCssFile from pyjamas . ui . CSS import StyleSheetCssText newcolours = \"\"\"\"\"\" morenewcolours = \"\"\"\"\"\" global sc sc = None def greet ( fred ) : global sc txt = fred . getText ( ) if txt == \"\" : sc = StyleSheetCssText ( newcolours ) fred . setText ( \"\" ) elif txt == \"\" : sc . remove ( ) fred . setText ( \"\" ) elif txt == \"\" : sc = StyleSheetCssText ( morenewcolours ) fred . setText ( \"\" ) elif txt != \"\" : fred . setText ( \"\" ) sc . remove ( ) if __name__ == '' : pyjd . setup ( \"\" ) b = Button ( \"\" , greet , StyleName = '' ) h = HTML ( \"\" , StyleName = '' ) l = Label ( \"\" , StyleName = '' ) base = HTML ( \"\" % pygwt . getModuleBaseURL ( ) , StyleName = '' ) RootPanel ( ) . add ( b ) RootPanel ( ) . add ( h ) RootPanel ( ) . add ( l ) RootPanel ( ) . add ( base ) StyleSheetCssFile ( \"\" ) ", "answer": "pyjd . run ( ) "}, {"prompt": " '''''' import sys import CGAT . Experiment as E from rpy2 . robjects import r as R def main ( argv = None ) : \"\"\"\"\"\" if not argv : argv = sys . argv parser = E . OptionParser ( version = \"\" , usage = globals ( ) [ \"\" ] ) parser . add_option ( \"\" , \"\" , dest = \"\" , type = \"\" , help = \"\" ) ", "answer": "parser . add_option ( \"\" , \"\" , dest = \"\" , type = \"\" ,"}, {"prompt": " \"\"\"\"\"\" import urllib import time import random import urlparse import hmac import binascii import httplib2 try : from urlparse import parse_qs , parse_qsl except ImportError : from cgi import parse_qs , parse_qsl VERSION = '' HTTP_METHOD = '' SIGNATURE_METHOD = '' class Error ( RuntimeError ) : \"\"\"\"\"\" def __init__ ( self , message = '' ) : self . _message = message @ property def message ( self ) : \"\"\"\"\"\" return self . _message def __str__ ( self ) : return self . _message class MissingSignature ( Error ) : pass def build_authenticate_header ( realm = '' ) : \"\"\"\"\"\" return { '' : '' % realm } def escape ( s ) : \"\"\"\"\"\" return urllib . quote ( s , safe = '' ) def generate_timestamp ( ) : \"\"\"\"\"\" return int ( time . time ( ) ) def generate_nonce ( length = ) : \"\"\"\"\"\" return '' . join ( [ str ( random . randint ( , ) ) for i in range ( length ) ] ) def generate_verifier ( length = ) : \"\"\"\"\"\" return '' . join ( [ str ( random . randint ( , ) ) for i in range ( length ) ] ) class Consumer ( object ) : \"\"\"\"\"\" key = None secret = None def __init__ ( self , key , secret ) : self . key = key self . secret = secret if self . key is None or self . secret is None : raise ValueError ( \"\" ) def __str__ ( self ) : data = { '' : self . key , '' : self . secret } return urllib . urlencode ( data ) class Token ( object ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " from sqlalchemy import Column , Integer , MetaData , String , Table from nova import log as logging meta = MetaData ( ) def upgrade ( migrate_engine ) : meta . bind = migrate_engine instances = Table ( '' , meta , autoload = True , autoload_with = migrate_engine ) types = { } for instance in migrate_engine . execute ( instances . select ( ) ) : if instance . instance_type_id is None : types [ instance . id ] = None continue try : types [ instance . id ] = int ( instance . instance_type_id ) except ValueError : logging . warn ( \"\" \"\" % ( instance . id , instance . instance_type_id ) ) types [ instance . id ] = None integer_column = Column ( '' , Integer ( ) , nullable = True ) string_column = instances . c . instance_type_id integer_column . create ( instances ) for instance_id , instance_type_id in types . iteritems ( ) : update = instances . update ( ) . where ( instances . c . id == instance_id ) . values ( instance_type_id_int = instance_type_id ) ", "answer": "migrate_engine . execute ( update )"}, {"prompt": " from __future__ import absolute_import from statsmodels . compat . python import string_types , range from datetime import datetime import numpy as np from scipy import optimize from scipy . stats import t , norm from scipy . signal import lfilter from numpy import dot , log , zeros , pi from numpy . linalg import inv from statsmodels . tools . decorators import ( cache_readonly , resettable_cache ) import statsmodels . tsa . base . tsa_model as tsbase import statsmodels . base . wrapper as wrap from statsmodels . regression . linear_model import yule_walker , GLS from statsmodels . tsa . tsatools import ( lagmat , add_trend , _ar_transparams , _ar_invtransparams , _ma_transparams , _ma_invtransparams , unintegrate , unintegrate_levels ) from statsmodels . tsa . vector_ar import util from statsmodels . tsa . ar_model import AR from statsmodels . tsa . arima_process import arma2ma from statsmodels . tools . numdiff import approx_hess_cs , approx_fprime_cs from statsmodels . tsa . base . datetools import _index_date from statsmodels . tsa . kalmanf import KalmanFilter _armax_notes = \"\"\"\"\"\" _arma_params = \"\"\"\"\"\" _arma_model = \"\" _arima_model = \"\" _arima_params = \"\"\"\"\"\" _predict_notes = \"\"\"\"\"\" _results_notes = \"\"\"\"\"\" _predict = \"\"\"\"\"\" _predict_returns = \"\"\"\"\"\" _arma_predict = _predict % { \"\" : \"\" , \"\" : \"\"\"\"\"\" , \"\" : \"\" , ", "answer": "\"\" : _predict_returns ,"}, {"prompt": " import boto import boto . ec2 import boto . ec2 . blockdevicemapping import socket import time from strider . common . instance_data import InstanceData , SshData import strider . common . logger class EC2 ( object ) : def __init__ ( self , name = None , region = None , access_key_id = None , secret_access_key = None , security_token = None , image_id = None , instance_type = None , key_name = None , security_groups = None , subnet_id = None , ssh = None , user_data = None , tags = None , instance_profile_name = None , block_device_map = None , bake_name = None , bake_description = None , profile_name = None ) : self . name = name self . region = region self . access_key_id = access_key_id self . region = region self . secret_access_key = secret_access_key self . security_token = security_token self . image_id = image_id self . instance_type = instance_type self . key_name = key_name self . security_groups = security_groups self . subnet_id = subnet_id self . ssh = ssh self . user_data = user_data self . tags = tags self . instance_profile_name = instance_profile_name self . block_device_map = block_device_map self . bake_name = bake_name self . bake_description = bake_description self . profile_name = profile_name self . log = strider . utils . logger . get_logger ( '' ) if not self . name : raise Exception ( \"\" ) if not self . instance_type : raise Exception ( \"\" ) ", "answer": "if self . tags and type ( self . tags ) != dict :"}, {"prompt": " from __future__ import unicode_literals from django . db import migrations class Migration ( migrations . Migration ) : dependencies = [ ", "answer": "( '' , '' ) ,"}, {"prompt": " from __future__ import division , print_function , unicode_literals import sys import os import io import re import logging import textwrap import functools from time import mktime , strptime , time from collections import defaultdict from isso . utils import anonymize from isso . compat import string_types try : input = raw_input except NameError : pass try : from urlparse import urlparse except ImportError : from urllib . parse import urlparse from xml . etree import ElementTree logger = logging . getLogger ( \"\" ) def strip ( val ) : if isinstance ( val , string_types ) : return val . strip ( ) return val class Progress ( object ) : def __init__ ( self , end ) : self . end = end or self . istty = sys . stdout . isatty ( ) self . last = def update ( self , i , message ) : if not self . istty or message is None : return cols = int ( ( os . popen ( '' , '' ) . read ( ) ) . split ( ) [ ] ) message = message [ : cols - ] if time ( ) - self . last > : sys . stdout . write ( \"\" . format ( \"\" * cols ) ) sys . stdout . write ( \"\" . format ( i / self . end , message ) ) sys . stdout . flush ( ) self . last = time ( ) def finish ( self , message ) : self . last = self . update ( self . end , message + \"\" ) class Disqus ( object ) : ns = '' internals = '' def __init__ ( self , db , xmlfile , empty_id = False ) : self . threads = set ( [ ] ) self . comments = set ( [ ] ) self . db = db self . xmlfile = xmlfile self . empty_id = empty_id def insert ( self , thread , posts ) : path = urlparse ( thread . find ( '' % Disqus . ns ) . text ) . path remap = dict ( ) if path not in self . db . threads : self . db . threads . new ( path , thread . find ( Disqus . ns + '' ) . text . strip ( ) ) for item in sorted ( posts , key = lambda k : k [ '' ] ) : dsq_id = item . pop ( '' ) item [ '' ] = remap . get ( item . pop ( '' , None ) ) rv = self . db . comments . add ( path , item ) remap [ dsq_id ] = rv [ \"\" ] ", "answer": "self . comments . update ( set ( remap . keys ( ) ) )"}, {"prompt": " \"\"\"\"\"\" import sys import os import unittest def fix_sys_path ( ) : \"\"\"\"\"\" def add_path_first ( path ) : sys . path = [ path ] + [ p for p in sys . path if ( not p == path and not p == ( path + '' ) ) ] ", "answer": "path = os . path . dirname ( os . path . abspath ( __file__ ) )"}, {"prompt": " \"\"\"\"\"\" import os import sys try : from setuptools import setup except ImportError : from distutils . core import setup if sys . argv [ - ] == '' : os . system ( '' ) sys . exit ( ) setup ( name = '' , version = '' , url = '' , author = '' , author_email = '' , description = '' , long_description = open ( '' ) . read ( ) + '' + open ( '' ) . read ( ) , py_modules = [ '' ] , ", "answer": "license = open ( '' ) . read ( ) ,"}, {"prompt": " \"\"\"\"\"\" from __future__ import print_function from statsmodels . compat . python import lrange , zip import time import numpy as np from numpy . testing import assert_almost_equal from scipy import stats from statsmodels . sandbox . gam import AdditiveModel from statsmodels . sandbox . gam import Model as GAM from statsmodels . genmod import families from statsmodels . genmod . generalized_linear_model import GLM from statsmodels . regression . linear_model import OLS , WLS np . random . seed ( ) order = sigma_noise = nobs = lb , ub = - , x1 = np . linspace ( lb , ub , nobs ) x2 = np . sin ( * x1 ) x = np . column_stack ( ( x1 / x1 . max ( ) * , x2 ) ) exog = ( x [ : , : , None ] ** np . arange ( order + ) [ None , None , : ] ) . reshape ( nobs , - ) idx = lrange ( ( order + ) * ) del idx [ order + ] exog_reduced = exog [ : , idx ] y_true = exog . sum ( ) / z = y_true d = x y = y_true + sigma_noise * np . random . randn ( nobs ) example = if example == : m = AdditiveModel ( d ) m . fit ( y ) y_pred = m . results . predict ( d ) for ss in m . smoothers : print ( ss . params ) res_ols = OLS ( y , exog_reduced ) . fit ( ) print ( res_ols . params ) if example > : ", "answer": "import matplotlib . pyplot as plt"}, {"prompt": " import crowd import os , sys , getpass app_url = '' app_user = '' app_pass = '' cs = crowd . CrowdServer ( app_url , app_user , app_pass ) if len ( sys . argv ) > : username = sys . argv [ ] else : username = os . environ [ '' ] password = getpass . getpass ( prompt = '' % username ) session = cs . get_session ( username , password ) if session : print '' % session [ '' ] else : print '' sys . exit ( ) success = cs . validate_session ( session [ '' ] ) if success : ", "answer": "print ''"}, {"prompt": " import fixtures import mock from neutron_lib import constants from neutron . agent . linux import ip_lib from neutron . plugins . ml2 . drivers . linuxbridge . agent import linuxbridge_neutron_agent as lb_agent from neutron . tests . common import config_fixtures from neutron . tests . common import net_helpers from neutron . tests . functional import base from neutron . tests import tools class LinuxbridgeCleanupTest ( base . BaseSudoTestCase ) : def _test_linuxbridge_cleanup ( self , bridge_exists , callback ) : br_fixture = self . useFixture ( tools . SafeCleanupFixture ( net_helpers . LinuxBridgeFixture ( prefix = lb_agent . BRIDGE_NAME_PREFIX ) ) ) . fixture config = callback ( br_fixture ) config . update ( { '' : { '' : '' } } ) temp_dir = self . useFixture ( fixtures . TempDir ( ) ) . path conf = self . useFixture ( config_fixtures . ConfigFileFixture ( base_filename = '' , ", "answer": "config = config ,"}, {"prompt": " \"\"\"\"\"\" def safe_repr ( obj , clip = None ) : \"\"\"\"\"\" try : s = repr ( obj ) if not clip or len ( s ) <= clip : ", "answer": "return s"}, {"prompt": " import re import logging from google . appengine . ext import ndb from endpoints_proto_datastore . ndb import EndpointsModel from endpoints_proto_datastore . ndb import EndpointsAliasProperty from endpoints_proto_datastore . ndb import EndpointsVariantIntegerProperty from protorpc import messages from models . activity_type import ActivityType from models . product_group import ProductGroup class ActivityPost ( EndpointsModel ) : _message_fields_schema = ( '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ) _api_key = None post_id = ndb . StringProperty ( ) gplus_id = ndb . StringProperty ( ) name = ndb . StringProperty ( ) date = ndb . StringProperty ( ) plus_oners = EndpointsVariantIntegerProperty ( variant = messages . Variant . INT32 ) resharers = EndpointsVariantIntegerProperty ( variant = messages . Variant . INT32 ) comments = EndpointsVariantIntegerProperty ( variant = messages . Variant . INT32 ) title = ndb . StringProperty ( ) url = ndb . StringProperty ( ) product_group = ndb . StringProperty ( repeated = True ) activity_type = ndb . StringProperty ( repeated = True ) links = ndb . StringProperty ( ) deleted = ndb . BooleanProperty ( default = False ) def ApiKeySet ( self , value ) : self . _api_key = value @ EndpointsAliasProperty ( setter = ApiKeySet , property_type = messages . StringField ) def api_key ( self ) : return self . _api_key def IdSet ( self , value ) : if not isinstance ( value , basestring ) : raise TypeError ( '' ) self . UpdateFromKey ( ndb . Key ( ActivityPost , value ) ) @ EndpointsAliasProperty ( setter = IdSet , required = True ) def id ( self ) : if self . key is not None : return self . key . string_id ( ) def create_from_gplus_post ( self , gplus_post ) : self . post_id = gplus_post [ \"\" ] self . name = gplus_post [ '' ] [ '' ] self . gplus_id = gplus_post [ '' ] [ '' ] ", "answer": "self . date = gplus_post [ \"\" ]"}, {"prompt": " import utils import utils as u ", "answer": "u . execute ( '' , shell = True )"}, {"prompt": " import crypt from random import SystemRandom def random_salt_function ( salt_len = ) : \"\"\"\"\"\" charset = \"\" charset = charset + charset . upper ( ) + '' chars = [ ] rand = SystemRandom ( ) for _ in range ( salt_len ) : chars . append ( rand . choice ( charset ) ) return \"\" . join ( chars ) def hash_password_function ( password , salt = None , magic = \"\" ) : \"\"\"\"\"\" magic = str ( magic ) if salt is None : salt = random_salt_function ( ) ", "answer": "salt = \"\" . format ( magic = magic , salt = salt )"}, {"prompt": " from doit . tools import create_folder BUILD_PATH = \"\" def task_build ( ) : return { '' : [ ( create_folder , [ BUILD_PATH ] ) , '' ] , '' : [ \"\" % BUILD_PATH ] ", "answer": "} "}, {"prompt": " \"\"\"\"\"\" import sys import os import bigjob . state import socket import threading import time import pdb import traceback import ConfigParser import types import logging logging . basicConfig ( level = logging . DEBUG ) try : import saga except : logging . warning ( \"\" ) sys . path . append ( os . path . dirname ( os . path . abspath ( __file__ ) ) + \"\" ) logging . debug ( str ( sys . path ) ) from threadpool import * if sys . version_info < ( , ) : sys . path . append ( os . path . dirname ( __file__ ) + \"\" ) sys . stderr . write ( \"\" ) if sys . version_info < ( , ) : sys . path . append ( os . path . dirname ( __file__ ) + \"\" ) sys . stderr . write ( \"\" ) if sys . version_info < ( , ) : sys . stderr . write ( \"\" ) sys . exit ( - ) import subprocess \"\"\"\"\"\" CONFIG_FILE = \"\" THREAD_POOL_SIZE = APPLICATION_NAME = \"\" class bigjob_agent : \"\"\"\"\"\" \"\"\"\"\"\" def __init__ ( self , args ) : self . coordination_url = args [ ] self . jobs = [ ] self . processes = { } self . freenodes = [ ] self . busynodes = [ ] self . restarted = { } conf_file = os . path . dirname ( os . path . abspath ( __file__ ) ) + \"\" + CONFIG_FILE config = ConfigParser . ConfigParser ( ) logging . debug ( \"\" + conf_file ) config . read ( conf_file ) default_dict = config . defaults ( ) self . CPR = default_dict [ \"\" ] self . SHELL = default_dict [ \"\" ] self . MPIRUN = default_dict [ \"\" ] logging . debug ( \"\" + self . CPR + \"\" + self . MPIRUN + \"\" + self . SHELL ) self . init_rms ( ) self . failed_polls = self . base_url = args [ ] logging . debug ( \"\" + str ( args ) ) logging . debug ( \"\" + self . base_url ) if ( self . coordination_url . startswith ( \"\" ) ) : try : from coordination . bigjob_coordination_advert import bigjob_coordination logging . debug ( \"\" + self . coordination_url ) except : logging . error ( \"\" ) elif ( self . coordination_url . startswith ( \"\" ) ) : try : from coordination . bigjob_coordination_redis import bigjob_coordination logging . debug ( \"\" + self . coordination_url + \"\" ) except : logger . error ( \"\" ) elif ( self . coordination_url . startswith ( \"\" ) ) : try : from coordination . bigjob_coordination_zmq import bigjob_coordination logging . debug ( \"\" ) except : logging . error ( \"\" + \"\" ) self . coordination = bigjob_coordination ( server_connect_url = self . coordination_url ) self . coordination . set_pilot_state ( self . base_url , str ( bigjob . state . Running ) , False ) self . resource_lock = threading . RLock ( ) self . threadpool = ThreadPool ( THREAD_POOL_SIZE ) self . launcher_thread = threading . Thread ( target = self . dequeue_new_jobs ) self . launcher_thread . start ( ) self . monitoring_thread = threading . Thread ( target = self . start_background_thread ) self . monitoring_thread . start ( ) def init_rms ( self ) : if ( os . environ . get ( \"\" ) != None ) : return self . init_pbs ( ) elif ( os . environ . get ( \"\" ) != None ) : return self . init_sge ( ) else : return self . init_local ( ) return None def init_local ( self ) : \"\"\"\"\"\" try : num_cpus = self . get_num_cpus ( ) for i in range ( , num_cpus ) : self . freenodes . append ( \"\" ) except IOError : self . freenodes = [ \"\" ] def init_sge ( self ) : \"\"\"\"\"\" sge_node_file = os . environ . get ( \"\" ) if sge_node_file == None : return f = open ( sge_node_file ) sgenodes = f . readlines ( ) f . close ( ) for i in sgenodes : columns = i . split ( ) try : for j in range ( , int ( columns [ ] ) ) : logging . debug ( \"\" + columns [ ] . strip ( ) ) self . freenodes . append ( columns [ ] + \"\" ) except : pass return self . freenodes def init_pbs ( self ) : \"\"\"\"\"\" pbs_node_file = os . environ . get ( \"\" ) if pbs_node_file == None : return f = open ( pbs_node_file ) self . freenodes = f . readlines ( ) f . close ( ) num_cpus = self . get_num_cpus ( ) node_dict = { } for i in set ( self . freenodes ) : node_dict [ i ] = self . freenodes . count ( i ) if node_dict [ i ] < num_cpus : node_dict [ i ] = num_cpus self . freenodes = [ ] for i in node_dict . keys ( ) : logging . debug ( \"\" + i + \"\" + str ( node_dict [ i ] ) ) for j in range ( , node_dict [ i ] ) : logging . debug ( \"\" + i . strip ( ) ) self . freenodes . append ( i ) def get_num_cpus ( self ) : cpuinfo = open ( \"\" , \"\" ) cpus = cpuinfo . readlines ( ) cpuinfo . close ( ) num = for i in cpus : if i . startswith ( \"\" ) : num = num + return num def execute_job ( self , job_url , job_dict ) : \"\"\"\"\"\" state = str ( job_dict [ \"\" ] ) if ( state == str ( bigjob . state . Unknown ) or state == str ( bigjob . state . New ) ) : try : logging . debug ( \"\" + str ( job_dict ) ) numberofprocesses = \"\" if ( job_dict . has_key ( \"\" ) == True ) : numberofprocesses = job_dict [ \"\" ] spmdvariation = \"\" if ( job_dict . has_key ( \"\" ) == True ) : spmdvariation = job_dict [ \"\" ] arguments = \"\" if ( job_dict . has_key ( \"\" ) == True ) : arguments_raw = job_dict [ '' ] ; if type ( arguments_raw ) == types . ListType : arguments_list = arguments_raw else : arguments_list = eval ( job_dict [ \"\" ] ) for i in arguments_list : arguments = arguments + \"\" + i workingdirectory = os . getcwd ( ) if ( job_dict . has_key ( \"\" ) == True ) : workingdirectory = job_dict [ \"\" ] environment = os . environ if ( job_dict . has_key ( \"\" ) == True ) : for i in job_dict [ \"\" ] : env = i . split ( \"\" ) environment [ env [ ] ] = env [ ] + \"\" + environment [ env [ ] ] environment [ \"\" ] = workingdirectory + \"\" + environment [ \"\" ] print \"\" , environment [ \"\" ] executable = job_dict [ \"\" ] output = \"\" if ( job_dict . has_key ( \"\" ) == True ) : output = job_dict [ \"\" ] error = \"\" if ( job_dict . has_key ( \"\" ) == True ) : error = job_dict [ \"\" ] self . jobs . append ( job_url ) output_file = os . path . join ( workingdirectory , output ) error_file = os . path . join ( workingdirectory , error ) logging . debug ( \"\" + output_file + \"\" + error_file + \"\" + str ( environment ) ) stdout = open ( output_file , \"\" ) stderr = open ( error_file , \"\" ) command = executable + \"\" + arguments machinefile = self . allocate_nodes ( job_dict ) host = \"\" try : machine_file_handler = open ( machinefile , \"\" ) node = machine_file_handler . readlines ( ) machine_file_handler . close ( ) host = node [ ] . strip ( ) except : pass if ( machinefile == None ) : logging . debug ( \"\" + job_url ) self . coordination . queue_job ( self . base_url , job_url ) return if ( spmdvariation . lower ( ) == \"\" ) : command = \"\" + workingdirectory + \"\" + self . MPIRUN + \"\" + numberofprocesses + \"\" + machinefile + \"\" + command else : command = \"\" + executable + \"\" + workingdirectory + \"\" + command shell = self . SHELL logging . debug ( \"\" + command + \"\" + workingdirectory + \"\" + str ( socket . gethostname ( ) ) + \"\" + shell + \"\" ) p = subprocess . Popen ( args = command , executable = shell , stderr = stderr , stdout = stdout , cwd = workingdirectory , env = environment , shell = True ) logging . debug ( \"\" + command ) dirlist = os . listdir ( workingdirectory ) print dirlist os . system ( \"\" ) self . processes [ job_url ] = p self . coordination . set_job_state ( job_url , str ( bigjob . state . Running ) ) except : traceback . print_exc ( file = sys . stderr ) def allocate_nodes ( self , job_dict ) : \"\"\"\"\"\" self . resource_lock . acquire ( ) number_nodes = int ( job_dict [ \"\" ] ) nodes = [ ] machine_file_name = None if ( len ( self . freenodes ) >= number_nodes ) : unique_nodes = set ( self . freenodes ) for i in unique_nodes : number = self . freenodes . count ( i ) logging . debug ( \"\" + i + \"\" + str ( number ) + \"\" + str ( self . busynodes ) + \"\" + str ( self . freenodes ) ) for j in range ( , number ) : if ( number_nodes > ) : nodes . append ( i ) self . freenodes . remove ( i ) self . busynodes . append ( i ) number_nodes = number_nodes - else : break machine_file_name = self . get_machine_file_name ( job_dict ) machine_file = open ( machine_file_name , \"\" ) machine_file . writelines ( nodes ) machine_file . close ( ) logging . debug ( \"\" + machine_file_name + \"\" + str ( nodes ) ) self . resource_lock . release ( ) return machine_file_name def setup_charmpp_nodefile ( self , allocated_nodes ) : \"\"\"\"\"\" nodefile_string = \"\" for i in allocated_nodes : if i . has_key ( \"\" ) : nodefile_string = nodefile_string + \"\" + i [ \"\" ] + \"\" + str ( i [ \"\" ] ) + \"\" else : nodefile_string = nodefile_string + \"\" + i [ \"\" ] + \"\" + str ( i [ \"\" ] ) + \"\" jd = saga . job . description ( ) jd . executable = \"\" jd . number_of_processes = \"\" jd . spmd_variation = \"\" jd . arguments = [ \"\" + nodefile_string + \"\" , \">\" , \"\" ] jd . output = \"\" jd . error = \"\" job_service_url = saga . url ( \"\" + allocated_nodes [ ] [ \"\" ] ) job_service = saga . job . service ( self . session , job_service_url ) job = job_service . create_job ( jd ) job . run ( ) job . wait ( ) def print_machine_file ( self , filename ) : fh = open ( filename , \"\" ) lines = fh . readlines ( ) fh . close logging . debug ( \"\" + filename + \"\" + str ( lines ) ) def free_nodes ( self , job_url ) : job_dict = self . coordination . get_job ( job_url ) self . resource_lock . acquire ( ) number_nodes = int ( job_dict [ \"\" ] ) machine_file_name = self . get_machine_file_name ( job_dict ) logging . debug ( \"\" + machine_file_name ) allocated_nodes = [ \"\" ] try : machine_file = open ( machine_file_name , \"\" ) allocated_nodes = machine_file . readlines ( ) machine_file . close ( ) except : traceback . print_exc ( file = sys . stderr ) logging . debug ( \"\" + str ( allocated_nodes ) ) for i in allocated_nodes : logging . debug ( \"\" + str ( i ) + \"\" + str ( self . busynodes ) + \"\" + str ( self . freenodes ) ) self . busynodes . remove ( i ) self . freenodes . append ( i ) logging . debug ( \"\" + machine_file_name ) if os . path . exists ( machine_file_name ) : os . remove ( machine_file_name ) self . resource_lock . release ( ) def get_machine_file_name ( self , job_dict ) : \"\"\"\"\"\" job_id = job_dict [ \"\" ] homedir = os . path . expanduser ( '' ) return homedir + \"\" + job_id def dequeue_new_jobs ( self ) : \"\"\"\"\"\" job_counter = while self . is_stopped ( self . base_url ) == False : if len ( self . freenodes ) == : time . sleep ( ) continue logging . debug ( \"\" + self . base_url ) job_url = self . coordination . dequeue_job ( self . base_url ) if job_url == None : time . sleep ( ) continue if job_url == \"\" : break job_counter = job_counter + if ( job_counter % ( THREAD_POOL_SIZE ) ) == : self . threadpool . wait ( ) request = WorkRequest ( self . start_new_job_in_thread , [ job_url ] ) self . threadpool . putRequest ( request ) self . threadpool . wait ( ) logging . debug ( \"\" ) def start_new_job_in_thread ( self , job_url ) : \"\"\"\"\"\" if job_url != None : failed = False ; try : job_dict = self . coordination . get_job ( job_url ) except : failed = True if job_dict == None or failed == True : self . coordination . queue_job ( self . pilot_url , job_url ) logging . debug ( \"\" + job_url + \"\" + str ( job_dict ) ) if ( job_dict [ \"\" ] == str ( bigjob . state . Unknown ) ) : job_dict [ \"\" ] = str ( bigjob . state . New ) self . coordination . set_job_state ( job_url , str ( bigjob . state . New ) ) self . execute_job ( job_url , job_dict ) def monitor_jobs ( self ) : \"\"\"\"\"\" logging . debug ( \"\" % len ( self . jobs ) ) for i in self . jobs : if self . processes . has_key ( i ) : p = self . processes [ i ] p_state = p . poll ( ) logging . debug ( self . print_job ( i ) + \"\" + str ( p_state ) + \"\" + str ( p . returncode ) ) if ( p_state != None and ( p_state == or p_state == ) ) : logging . debug ( \"\" + self . print_job ( i ) ) self . coordination . set_job_state ( i , str ( bigjob . state . Done ) ) self . free_nodes ( i ) del self . processes [ i ] elif p_state != and p_state != and p_state != None : logging . debug ( self . print_job ( i ) + \"\" ) logging . debug ( \"\" + self . print_job ( i ) ) self . coordination . set_job_state ( i , str ( bigjob . state . Failed ) ) self . free_nodes ( i ) del self . processes [ i ] def print_job ( self , job_url ) : job_dict = self . coordination . get_job ( job_url ) return ( \"\" + job_url + \"\" + job_dict [ \"\" ] ) def start_background_thread ( self ) : self . stop = False logging . debug ( \"\" ) logging . debug ( \"\" + str ( len ( self . freenodes ) ) + \"\" + str ( len ( self . busynodes ) ) ) while True and self . stop == False : if self . is_stopped ( self . base_url ) == True : logging . debug ( \"\" ) break else : logging . debug ( \"\" + str ( self . base_url ) + \"\" ) try : self . monitor_jobs ( ) time . sleep ( ) self . failed_polls = except : ", "answer": "traceback . print_exc ( file = sys . stdout )"}, {"prompt": " import argparse from uefi_firmware . uefi import * from uefi_firmware . utils import * from uefi_firmware . flash import FlashDescriptor from uefi_firmware . guids import get_guid_name def debug ( text , cr = True , gen = False ) : if args . generate is not None and not gen : return if args . generate is None and gen : return elif cr : print text else : print text , def label_as_guid_name ( label ) : if args . generate is None : return None ", "answer": "def is_cap ( c ) :"}, {"prompt": " import argparse import cStringIO import urllib2 import sys import zlib import zindex import MySQLdb from PIL import Image import empaths import emcaproj import emcadb import dbconfig import imagecube import numpy as np RESOLUTION = def main ( ) : parser = argparse . ArgumentParser ( description = '' ) parser . add_argument ( '' , action = \"\" ) parser . add_argument ( '' , type = int , action = \"\" ) parser . add_argument ( '' , action = \"\" ) parser . add_argument ( '' , type = int , action = \"\" ) result = parser . parse_args ( ) projdb = emcaproj . EMCAProjectsDB ( ) proj = projdb . getProj ( result . token ) dbcfg = dbconfig . switchDataset ( proj . getDataset ( ) ) _ximgsz = None _yimgsz = None for sl in range ( result . numslices ) : filenm = result . path + '' + '' . format ( sl ) + '' print filenm img = Image . open ( filenm , \"\" ) if _ximgsz == None and _yimgsz == None : _ximgsz , _yimgsz = img . size imarray = np . zeros ( [ result . numslices , _yimgsz , _ximgsz ] , dtype = np . uint16 ) else : assert _ximgsz == img . size [ ] and _yimgsz == img . size [ ] imarray [ sl , : , : ] = np . asarray ( img ) xcubedim , ycubedim , zcubedim = dbcfg . cubedim [ ] xlimit = ( _ximgsz - ) / xcubedim + ylimit = ( _yimgsz - ) / ycubedim + zlimit = ( result . numslices - ) / zcubedim + db = emcadb . EMCADB ( dbcfg , proj ) cursor = db . conn . cursor ( ) for z in range ( zlimit ) : db . commit ( ) for y in range ( ylimit ) : for x in range ( xlimit ) : zmin = z * zcubedim zmax = min ( ( z + ) * zcubedim , result . numslices ) zmaxrel = ( ( zmax - ) % zcubedim ) + ymin = y * ycubedim ymax = min ( ( y + ) * ycubedim , _yimgsz ) ymaxrel = ( ( ymax - ) % ycubedim ) + xmin = x * xcubedim xmax = min ( ( x + ) * xcubedim , _ximgsz ) xmaxrel = ( ( xmax - ) % xcubedim ) + key = zindex . XYZMorton ( [ x , y , z ] ) cube = imagecube . ImageCube16 ( [ xcubedim , ycubedim , zcubedim ] ) cube . data [ : zmaxrel , : ymaxrel , : xmaxrel ] = imarray [ zmin : zmax , ymin : ymax , xmin : xmax ] npz = cube . toNPZ ( ) ", "answer": "sql = \"\" + proj . getTable ( RESOLUTION ) + \"\""}, {"prompt": " from flask_resty import Api , filter_function , Filtering , GenericModelView from marshmallow import fields , Schema import operator import pytest from sqlalchemy import Column , Integer , String import helpers @ pytest . yield_fixture def models ( db ) : class Widget ( db . Model ) : __tablename__ = '' id = Column ( Integer , primary_key = True ) color = Column ( String ) size = Column ( Integer ) db . create_all ( ) yield { '' : Widget , } db . drop_all ( ) @ pytest . fixture def schemas ( ) : class WidgetSchema ( Schema ) : id = fields . Integer ( as_string = True ) color = fields . String ( ) size = fields . Integer ( ) return { '' : WidgetSchema ( ) , } @ pytest . fixture def filter_fields ( ) : @ filter_function ( fields . Boolean ( ) ) def filter_size_is_odd ( model , value ) : return model . size % == int ( value ) return { '' : filter_size_is_odd } @ pytest . fixture ( autouse = True ) def routes ( app , models , schemas , filter_fields ) : class WidgetListView ( GenericModelView ) : model = models [ '' ] schema = schemas [ '' ] filtering = Filtering ( color = operator . eq , size_min = ( '' , operator . ge ) , size_divides = ( '' , lambda size , value : size % value == ) , size_is_odd = filter_fields [ '' ] , ) def get ( self ) : return self . list ( ) api = Api ( app ) api . add_resource ( '' , WidgetListView ) @ pytest . fixture ( autouse = True ) def data ( db , models ) : db . session . add_all ( ( models [ '' ] ( color = '' , size = ) , models [ '' ] ( color = '' , size = ) , models [ '' ] ( color = '' , size = ) , models [ '' ] ( color = '' , size = ) , ) ) db . session . commit ( ) def test_eq ( client ) : response = client . get ( '' ) assert helpers . get_data ( response ) == [ { '' : '' , '' : '' , '' : , } , { '' : '' , '' : '' , '' : , } , ] def test_eq_many ( client ) : response = client . get ( '' ) assert helpers . get_data ( response ) == [ { '' : '' , '' : '' , '' : , } , { '' : '' , '' : '' , '' : , } , ] def test_ge ( client ) : response = client . get ( '' ) assert helpers . get_data ( response ) == [ { '' : '' , '' : '' , '' : , } , { '' : '' , '' : '' , '' : , } , ] def test_custom_operator ( client ) : response = client . get ( '' ) assert helpers . get_data ( response ) == [ { '' : '' , ", "answer": "'' : '' ,"}, {"prompt": " \"\"\"\"\"\" __metaclass__ = type from weakref import ref import gc , threading from twisted . python . threadable import isInIOThread from twisted . internet . test . reactormixins import ReactorBuilder from twisted . python . threadpool import ThreadPool from twisted . internet . interfaces import IReactorThreads class ThreadTestsBuilder ( ReactorBuilder ) : \"\"\"\"\"\" requiredInterfaces = ( IReactorThreads , ) def test_getThreadPool ( self ) : \"\"\"\"\"\" state = [ ] reactor = self . buildReactor ( ) pool = reactor . getThreadPool ( ) self . assertIsInstance ( pool , ThreadPool ) self . assertFalse ( ", "answer": "pool . started , \"\" )"}, {"prompt": " ARCHIVER_INITIATED = '' ARCHIVER_FAILURE = '' ARCHIVER_SUCCESS = '' ARCHIVER_SENT = '' ARCHIVER_PENDING = '' ARCHIVER_CHECKING = '' ARCHIVER_SENDING = '' ARCHIVER_NETWORK_ERROR = '' ARCHIVER_SIZE_EXCEEDED = '' ARCHIVER_FILE_NOT_FOUND = '' ARCHIVER_UNCAUGHT_ERROR = '' ARCHIVER_FAILURE_STATUSES = { ARCHIVER_FAILURE , ARCHIVER_NETWORK_ERROR , ARCHIVER_SIZE_EXCEEDED , ARCHIVER_FILE_NOT_FOUND , ARCHIVER_UNCAUGHT_ERROR , } NO_ARCHIVE_LIMIT = '' class StatResult ( object ) : \"\"\"\"\"\" num_files = def __init__ ( self , target_id , target_name , disk_usage = ) : self . target_id = target_id self . target_name = target_name self . disk_usage = float ( disk_usage ) def __str__ ( self ) : return str ( self . _to_dict ( ) ) def _to_dict ( self ) : return { '' : self . target_id , '' : self . target_name , '' : self . disk_usage , } class AggregateStatResult ( object ) : \"\"\"\"\"\" def __init__ ( self , target_id , target_name , targets = None ) : self . target_id = target_id self . target_name = target_name self . targets = [ target for target in targets if target ] def __str__ ( self ) : return str ( self . _to_dict ( ) ) def _to_dict ( self ) : return { '' : self . target_id , '' : self . target_name , '' : [ target . _to_dict ( ) for target in self . targets ] , ", "answer": "'' : self . num_files ,"}, {"prompt": " import os import yaml from pkg_resources import resource_filename PERSIST_SETTINGS = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , ] DEFAULT_REQUIRED_FACTS = [ '' , '' , '' , '' ] PRECONFIGURED_REQUIRED_FACTS = [ '' , '' ] class OOConfigFileError ( Exception ) : \"\"\"\"\"\" ", "answer": "pass"}, {"prompt": " from django . conf import settings from django . core . mail import EmailMultiAlternatives from django . template . loader import render_to_string def send_custom_mail ( subject , to , template , context , connection = None ) : ", "answer": "context . update ( { '' : settings . SITE_URL } )"}, {"prompt": " from redmine import Redmine class BaseRedmine ( object ) : def __init__ ( self , username = None , password = None , ", "answer": "apikey = None , id = None , url = None , name = None ) :"}, {"prompt": " import sys from django . core . management . base import BaseCommand ", "answer": "from dennis . cmdline import click_run"}, {"prompt": " import os import base64 from datetime import datetime from xos . config import Config from xos . logger import Logger , logging from synchronizers . base . steps import * from django . db . models import F , Q from core . models import * from django . db import reset_queries import json import time import pdb import traceback logger = Logger ( level = logging . INFO ) def f7 ( seq ) : seen = set ( ) seen_add = seen . add return [ x for x in seq if not ( x in seen or seen_add ( x ) ) ] def elim_dups ( backend_str ) : strs = backend_str . split ( '' ) strs = map ( lambda x : x . split ( '' ) [ ] , strs ) strs2 = f7 ( strs ) return '' . join ( strs2 ) ", "answer": "def deepgetattr ( obj , attr ) :"}, {"prompt": " import datetime from south . db import db from south . v2 import SchemaMigration from django . db import models class Migration ( SchemaMigration ) : def forwards ( self , orm ) : db . create_table ( '' , ( ( '' , self . gf ( '' ) ( primary_key = True ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ( '' , self . gf ( '' ) ( null = True , blank = True ) ) , ", "answer": "( '' , self . gf ( '' ) ( db_index = True ) ) ,"}, {"prompt": " import logging from functools import wraps import inspect import re log = logging . getLogger ( '' ) use_newlines = False indent = '' max_param_len = log_function_start = True log_function_exit = True RESET = '' RED = '' GREEN = '' YELLOW = '' BLUE = '' MAGENTA = '' CYAN = '' WHITE = '' BRGREEN = '' r_of = re . compile ( '' ) r_at = re . compile ( '' ) def parse_repr ( obj ) : if inspect . ismethod ( obj ) : pat = r_of else : pat = r_at s = repr ( obj ) m = re . search ( pat , s ) if m : return '' . format ( m . group ( ) ) else : return s def format_arg ( arg ) : \"\"\"\"\"\" s = str ( arg ) if type ( arg ) is type : return s elif isinstance ( arg , object ) and len ( s ) > max_param_len : return parse_repr ( arg ) else : return s def func_name ( f ) : \"\"\"\"\"\" if hasattr ( f , '' ) : qualname = RESET + f . __qualname__ + BRGREEN else : qualname = RESET + f . __name__ + BRGREEN return qualname def log_start ( f , args , kwargs ) : ", "answer": "argspec = inspect . getargspec ( f )"}, {"prompt": " try : from . helper import H except : from helper import H try : from . import settings as S except : import settings as S try : ", "answer": "from . import view as V"}, {"prompt": " from __future__ import unicode_literals from django . db import models , migrations class Migration ( migrations . Migration ) : dependencies = [ ( '' , '' ) , ] operations = [ migrations . AddField ( model_name = '' , ", "answer": "name = '' ,"}, {"prompt": " import os import contextlib from django . contrib . auth . models import User from django . contrib . admin . tests import AdminSeleniumWebDriverTestCase from django . core . urlresolvers import reverse from django . test . utils import override_settings from selenium . webdriver . common . by import By from selenium . webdriver . support . expected_conditions import ( visibility_of_element_located , element_to_be_clickable ) try : import grappelli except ImportError : grappelli = None ", "answer": "from . helpers import CropdusterTestCaseMediaMixin"}, {"prompt": " import datetime from south . db import db from south . v2 import SchemaMigration from django . db import models class Migration ( SchemaMigration ) : def forwards ( self , orm ) : db . create_table ( u'' , ( ( u'' , self . gf ( '' ) ( primary_key = True ) ) , ( '' , self . gf ( '' ) ( related_name = '' , to = orm [ '' ] ) ) , ( '' , self . gf ( '' ) ( related_name = '' , unique = True , to = orm [ '' ] ) ) , ) ) db . send_create_signal ( u'' , [ '' ] ) def backwards ( self , orm ) : db . delete_table ( u'' ) models = { u'' : { '' : { '' : '' } , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : u\"\" , '' : '' , '' : '' } ) } , u'' : { '' : { '' : \"\" , '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , ", "answer": "'' : ( '' , [ ] , { '' : u\"\" } ) ,"}, {"prompt": " \"\"\"\"\"\" import os from . import cassette from . exceptions import BetamaxError from datetime import datetime , timedelta from requests . adapters import BaseAdapter , HTTPAdapter _SENTINEL = object ( ) class BetamaxAdapter ( BaseAdapter ) : \"\"\"\"\"\" def __init__ ( self , ** kwargs ) : super ( BetamaxAdapter , self ) . __init__ ( ) self . cassette = None self . cassette_name = None self . old_adapters = kwargs . pop ( '' , { } ) self . http_adapter = HTTPAdapter ( ** kwargs ) self . serialize = None self . options = { } def cassette_exists ( self ) : \"\"\"\"\"\" if self . cassette_name and os . path . exists ( self . cassette_name ) : return True return False def close ( self ) : \"\"\"\"\"\" self . http_adapter . close ( ) def eject_cassette ( self ) : \"\"\"\"\"\" if self . cassette : self . cassette . eject ( ) self . cassette = None def load_cassette ( self , cassette_name , serialize , options ) : \"\"\"\"\"\" self . cassette_name = cassette_name self . serialize = serialize self . options . update ( options . items ( ) ) placeholders = self . options . get ( '' , { } ) cassette_options = { } default_options = cassette . Cassette . default_cassette_options match_requests_on = self . options . get ( '' , default_options [ '' ] ) cassette_options [ '' ] = self . options . get ( '' , ) cassette_options [ '' ] = self . options . get ( '' ) ", "answer": "cassette_options [ '' ] = self . options . get ( '' )"}, {"prompt": " import json from . core import Service , NoService , NoData , SkipThisService , currency_to_protocol import arrow class Bitstamp ( Service ) : service_id = supported_cryptos = [ '' ] api_homepage = \"\" name = \"\" def get_current_price ( self , crypto , fiat ) : if fiat . lower ( ) != '' : raise SkipThisService ( '' ) url = \"\" response = self . get_url ( url ) . json ( ) return float ( response [ '' ] ) class BlockCypher ( Service ) : service_id = supported_cryptos = [ '' , '' , '' ] api_homepage = \"\" explorer_address_url = \"\" explorer_tx_url = \"\" explorer_blockhash_url = \"\" explorer_blocknum_url = \"\" base_api_url = \"\" json_address_balance_url = base_api_url + \"\" json_txs_url = json_address_balance_url json_unspent_outputs_url = base_api_url + \"\" json_blockhash_url = base_api_url + \"\" json_blocknum_url = base_api_url + \"\" name = \"\" def get_balance ( self , crypto , address , confirmations = ) : url = self . json_address_balance_url . format ( address = address , crypto = crypto ) response = self . get_url ( url ) if confirmations == : return response . json ( ) [ '' ] / elif confirmations == : return response . json ( ) [ '' ] / else : raise SkipThisService ( \"\" ) def get_unspent_outputs ( self , crypto , address , confirmations = ) : url = self . json_unspent_outputs_url . format ( address = address , crypto = crypto ) utxos = [ ] for utxo in self . get_url ( url ) . json ( ) [ '' ] : if utxo [ '' ] < confirmations : continue utxos . append ( dict ( amount = utxo [ '' ] , output = \"\" % ( utxo [ '' ] , utxo [ '' ] ) , address = address , confirmations = utxo [ '' ] , ) ) return utxos def get_transactions ( self , crypto , address , confirmations = ) : url = self . json_txs_url . format ( address = address , crypto = crypto ) transactions = [ ] for tx in self . get_url ( url ) . json ( ) [ '' ] : if utxo [ '' ] < confirmations : continue transactions . append ( dict ( date = arrow . get ( tx [ '' ] ) . datetime , amount = tx [ '' ] / , txid = tx [ '' ] , confirmations = utxo [ '' ] ) ) return transactions def get_optimal_fee ( self , crypto , tx_bytes ) : url = \"\" % crypto fee_kb = self . get_url ( url ) . json ( ) [ '' ] return int ( tx_bytes * fee_kb / ) def get_block ( self , crypto , block_hash = '' , block_number = '' , latest = False ) : if block_hash : url = self . json_blockhash_url . format ( blockhash = block_hash , crypto = crypto ) elif block_number : url = self . json_blocknum_url . format ( blocknum = block_number , crypto = crypto ) r = self . get_url ( url ) . json ( ) return dict ( block_number = r [ '' ] , confirmations = r [ '' ] + , time = arrow . get ( r [ '' ] ) . datetime , sent_value = r [ '' ] / , total_fees = r [ '' ] / , hash = r [ '' ] , merkle_root = r [ '' ] , previous_hash = r [ '' ] , tx_count = r [ '' ] , txids = r [ '' ] ) class BlockSeer ( Service ) : \"\"\"\"\"\" service_id = supported_cryptos = [ '' ] api_homepage = \"\" explorer_address_url = \"\" explorer_tx_url = \"\" explorer_blocknum_url = \"\" explorer_blockhash_url = \"\" json_address_balance_url = \"\" json_txs_url = \"\" name = \"\" def get_balance ( self , crypto , address , confirmations = ) : url = self . json_address_balance_url . format ( address = address ) return self . get_url ( url ) . json ( ) [ '' ] [ '' ] / def get_transactions ( self , crypo , address ) : url = self . json_txs_url . format ( address = address ) transactions = [ ] for tx in self . get_url ( url ) . json ( ) [ '' ] [ '' ] [ '' ] : transactions . append ( dict ( date = arrow . get ( tx [ '' ] ) . datetime , amount = tx [ '' ] / , txid = tx [ '' ] , ) ) return transactions class SmartBitAU ( Service ) : service_id = api_homepage = \"\" base_url = \"\" explorer_address_url = \"\" explorer_tx_url = \"\" explorer_blocknum_url = \"\" explorer_blockhash_url = \"\" name = \"\" supported_cryptos = [ '' ] def get_balance ( self , crypto , address , confirmations = ) : url = \"\" % ( self . base_url , address ) r = self . get_url ( url ) . json ( ) confirmed = float ( r [ '' ] [ '' ] [ '' ] ) if confirmations > : return confirmed else : return confirmed + float ( r [ '' ] [ '' ] [ '' ] ) def get_balance_multi ( self , crypto , addresses , confirmations = ) : url = \"\" % ( self . base_url , \"\" . join ( addresses ) ) response = self . get_url ( url ) . json ( ) ret = { } for data in response [ '' ] : bal = float ( data [ '' ] [ '' ] ) if confirmations == : bal += float ( data [ '' ] [ '' ] ) ret [ data [ '' ] ] = bal return ret def get_transactions ( self , crypto , address , confirmations = ) : url = \"\" % ( self . base_url , address ) transactions = [ ] for tx in self . get_url ( url ) . json ( ) [ '' ] [ '' ] : out_amount = sum ( float ( x [ '' ] ) for x in tx [ '' ] if address in x [ '' ] ) in_amount = sum ( float ( x [ '' ] ) for x in tx [ '' ] if address in x [ '' ] ) transactions . append ( dict ( amount = out_amount - in_amount , date = arrow . get ( tx [ '' ] ) . datetime , fee = float ( tx [ '' ] ) , txid = tx [ '' ] , confirmations = tx [ '' ] , ) ) return transactions def get_unspent_outputs ( self , crypto , address , confirmations = ) : url = \"\" % ( self . base_url , address ) utxos = [ ] for utxo in self . get_url ( url ) . json ( ) [ '' ] : utxos . append ( dict ( amount = utxo [ '' ] , output = \"\" % ( utxo [ '' ] , utxo [ '' ] ) , address = address , confirmations = utxo [ '' ] , scriptpubkey_hex = utxo [ '' ] [ '' ] , scriptpubkey_asm = utxo [ '' ] [ '' ] ) ) return utxos def push_tx ( self , crypto , tx_hex ) : \"\"\"\"\"\" url = \"\" % self . base_url return self . post_url ( url , { '' : tx_hex } ) . content def get_mempool ( self ) : url = \"\" % self . base_url txs = [ ] for tx in self . get_url ( url ) . json ( ) [ '' ] : txs . append ( dict ( first_seen = arrow . get ( tx [ '' ] ) . datetime , size = tx [ '' ] , txid = tx [ '' ] , fee = float ( tx [ '' ] ) , ) ) return txs class Blockr ( Service ) : service_id = supported_cryptos = [ '' , '' , '' , '' , '' , '' , '' ] api_homepage = \"\" explorer_address_url = \"\" explorer_tx_url = \"\" explorer_blockhash_url = \"\" explorer_blocknum_url = \"\" explorer_latest_block = \"\" json_address_url = \"\" json_single_tx_url = \"\" json_txs_url = url = \"\" json_unspent_outputs_url = \"\" name = \"\" def get_balance ( self , crypto , address , confirmations = ) : url = self . json_address_url . format ( address = address , crypto = crypto ) response = self . get_url ( url ) return response . json ( ) [ '' ] [ '' ] def get_balance_multi ( self , crypto , addresses , confirmations = ) : url = self . json_address_url . format ( address = '' . join ( addresses ) , crypto = crypto ) balances = { } for bal in self . get_url ( url ) . json ( ) [ '' ] : balances [ bal [ '' ] ] = bal [ '' ] return balances def _format_tx ( self , tx , address ) : return dict ( date = arrow . get ( tx [ '' ] ) . datetime , amount = tx [ '' ] , txid = tx [ '' ] , confirmations = tx [ '' ] , addresses = [ address ] , ) def get_transactions ( self , crypto , address , confirmations = ) : url = self . json_txs_url . format ( address = address , crypto = crypto ) response = self . get_url ( url ) transactions = [ ] for tx in response . json ( ) [ '' ] [ '' ] : transactions . append ( self . _format_tx ( tx , address ) ) return transactions def get_transactions_multi ( self , crypto , addresses , confirmation = ) : url = self . json_txs_url . format ( address = '' . join ( addresses ) , crypto = crypto ) transactions = [ ] for data in self . get_url ( url ) . json ( ) [ '' ] : for tx in data [ '' ] : transactions . append ( self . _format_tx ( tx , data [ '' ] ) ) return transactions def _format_single_tx ( self , tx ) : ins = [ { '' : x [ '' ] , '' : float ( x [ '' ] ) * - } for x in tx [ '' ] ] outs = [ { '' : x [ '' ] , '' : float ( x [ '' ] ) } for x in tx [ '' ] ] return dict ( time = arrow . get ( tx [ '' ] ) . datetime , block_number = tx [ '' ] , inputs = ins , outputs = outs , txid = tx [ '' ] , total_in = sum ( x [ '' ] for x in ins ) , total_out = sum ( x [ '' ] for x in outs ) , confirmations = tx [ '' ] , fee = float ( tx [ '' ] ) ) def get_single_transaction ( self , crypto , txid ) : url = self . json_single_tx_url . format ( crypto = crypto , txid = txid ) r = self . get_url ( url ) . json ( ) [ '' ] return self . _format_single_tx ( r ) def get_single_transaction_multi ( self , crypto , txids ) : url = self . json_single_tx_url . format ( crypto = crypto , txid = '' . join ( txids ) ) txs = [ ] for tx in self . get_url ( url ) . json ( ) [ '' ] : txs . append ( self . _format_single_tx ( tx ) ) return txs def _format_utxo ( self , utxo , address ) : return dict ( amount = currency_to_protocol ( utxo [ '' ] ) , address = address , output = \"\" % ( utxo [ '' ] , utxo [ '' ] ) , confirmations = utxo [ '' ] ) def get_unspent_outputs ( self , crypto , address , confirmations = ) : url = self . json_unspent_outputs_url . format ( address = address , crypto = crypto ) utxos = [ ] for utxo in self . get_url ( url ) . json ( ) [ '' ] [ '' ] : cons = utxo [ '' ] if cons < confirmations : continue utxos . append ( self . _format_utxo ( utxo , address ) ) return utxos def get_unspent_outputs_multi ( self , crypto , addresses , confirmations = ) : url = self . json_unspent_outputs_url . format ( address = '' . join ( addresses ) , crypto = crypto ) utxos = [ ] for data in self . get_url ( url ) . json ( ) [ '' ] : for utxo in data [ '' ] : cons = utxo [ '' ] if cons < confirmations : continue utxos . append ( self . _format_utxo ( utxo , data [ '' ] ) ) return utxos def push_tx ( self , crypto , tx_hex ) : url = \"\" % crypto resp = self . post_url ( url , { '' : tx_hex } ) . json ( ) if resp [ '' ] == '' : raise ValueError ( \"\" % ( resp [ '' ] , resp [ '' ] , resp [ '' ] ) ) return resp [ '' ] def get_block ( self , crypto , block_hash = '' , block_number = '' , latest = False ) : url = \"\" % ( crypto , block_hash if block_hash else '' , block_number if block_number else '' , '' if latest else '' ) r = self . get_url ( url ) . json ( ) [ '' ] return dict ( block_number = r [ '' ] , confirmations = r [ '' ] , time = arrow . get ( r [ '' ] ) . datetime , sent_value = r [ '' ] , total_fees = float ( r [ '' ] ) , mining_difficulty = r [ '' ] , size = int ( r [ '' ] ) , hash = r [ '' ] , merkle_root = r [ '' ] , previous_hash = r [ '' ] , next_hash = r [ '' ] , tx_count = r [ '' ] , ) class Toshi ( Service ) : api_homepage = \"\" service_id = url = \"\" name = \"\" supported_cryptos = [ '' ] def get_balance ( self , crypto , address , confirmations = ) : url = \"\" % ( self . url , address ) response = self . get_url ( url ) . json ( ) return response [ '' ] / def get_transactions ( self , crypto , address , confirmations = ) : url = \"\" % ( self . url , address ) response = self . get_url ( url ) . json ( ) if confirmations == : to_iterate = response [ '' ] + response [ '' ] else : to_iterate = response [ '' ] transactions = [ ] for tx in to_iterate : if tx [ '' ] < confirmations : continue transactions . append ( dict ( amount = sum ( [ x [ '' ] / for x in tx [ '' ] if address in x [ '' ] ] ) , txid = tx [ '' ] , date = arrow . get ( tx [ '' ] ) . datetime , confirmations = tx [ '' ] ) ) return transactions def get_unspent_outputs ( self , crypto , address , confirmations = ) : url = \"\" % ( self . url , address ) response = self . get_url ( url ) . json ( ) utxos = [ ] for utxo in response : cons = utxo [ '' ] if cons < confirmations : continue utxos . append ( dict ( amount = utxo [ '' ] , address = address , output = \"\" % ( utxo [ '' ] , utxo [ '' ] ) , confirmations = cons ) ) return utxos def push_tx ( self , crypto , tx_hex ) : url = \"\" % ( self . url , tx_hex ) return self . get_url ( url ) . json ( ) [ '' ] def get_block ( self , crypto , block_hash = '' , block_number = '' , latest = False ) : if latest : url = \"\" % self . url else : url = \"\" % ( self . url , block_hash if block_hash else '' , block_number if block_number else '' ) r = self . get_url ( url ) . json ( ) return dict ( block_number = r [ '' ] , confirmations = r [ '' ] , time = arrow . get ( r [ '' ] ) . datetime , sent_value = r [ '' ] / , total_fees = r [ '' ] / , mining_difficulty = r [ '' ] , size = r [ '' ] , hash = r [ '' ] , merkle_root = r [ '' ] , previous_hash = r [ '' ] , next_hash = r [ '' ] [ ] [ '' ] if len ( r [ '' ] ) else None , txids = sorted ( r [ '' ] ) , tx_count = len ( r [ '' ] ) ) class BTCE ( Service ) : service_id = api_homepage = \"\" name = \"\" def get_current_price ( self , crypto , fiat ) : pair = \"\" % ( crypto . lower ( ) , fiat . lower ( ) ) url = \"\" + pair response = self . get_url ( url ) . json ( ) return response [ pair ] [ '' ] class Cryptonator ( Service ) : service_id = api_homepage = \"\" name = \"\" def get_current_price ( self , crypto , fiat ) : pair = \"\" % ( crypto , fiat ) url = \"\" % pair response = self . get_url ( url ) . json ( ) return float ( response [ '' ] [ '' ] ) class Winkdex ( Service ) : service_id = supported_cryptos = [ '' ] api_homepage = \"\" name = \"\" def get_current_price ( self , crypto , fiat ) : if fiat != '' : raise SkipThisService ( \"\" ) url = \"\" return self . get_url ( url ) . json ( ) [ '' ] / , class ChainSo ( Service ) : service_id = api_homepage = \"\" base_url = \"\" explorer_address_url = \"\" supported_cryptos = [ '' , '' , '' ] name = \"\" def get_current_price ( self , crypto , fiat ) : url = \"\" % ( self . base_url , crypto , fiat ) resp = self . get_url ( url ) . json ( ) items = resp [ '' ] [ '' ] if len ( items ) == : raise SkipThisService ( \"\" % ( crypto , fiat ) ) self . name = \"\" % items [ ] [ '' ] return float ( items [ ] [ '' ] ) def get_balance ( self , crypto , address , confirmations = ) : url = \"\" % ( self . base_url , crypto , address , confirmations ) response = self . get_url ( url ) return float ( response . json ( ) [ '' ] [ '' ] ) def get_transactions ( self , crypto , address , confirmations = ) : url = \"\" % ( self . base_url , crypto , address ) response = self . get_url ( url ) transactions = [ ] for tx in response . json ( ) [ '' ] [ '' ] : tx_cons = int ( tx [ '' ] ) if tx_cons < confirmations : continue transactions . append ( dict ( date = arrow . get ( tx [ '' ] ) . datetime , amount = float ( tx [ '' ] ) , txid = tx [ '' ] , confirmations = tx_cons , ) ) return transactions def get_unspent_outputs ( self , crypto , address , confirmations = ) : url = \"\" % ( self . base_url , crypto , address ) utxos = [ ] for utxo in self . get_url ( url ) . json ( ) [ '' ] [ '' ] : utxos . append ( dict ( amount = currency_to_protocol ( utxo [ '' ] ) , address = address , output = \"\" % ( utxo [ '' ] , utxo [ '' ] ) , confirmations = utxo [ '' ] ) ) return utxos def push_tx ( self , crypto , tx_hex ) : url = \"\" % ( self . base_url , crypto ) resp = self . post_url ( url , { '' : tx_hex } ) return resp . json ( ) [ '' ] [ '' ] def get_block ( self , crypto , block_number = '' , block_hash = '' , latest = False ) : if latest : raise SkipThisService ( \"\" ) else : url = \"\" % ( self . base_url , crypto , block_number , block_hash ) r = self . get_url ( url ) . json ( ) [ '' ] return dict ( block_number = r [ '' ] , confirmations = r [ '' ] , time = arrow . get ( r [ '' ] ) . datetime , sent_value = float ( r [ '' ] ) , total_fees = float ( r [ '' ] ) , mining_difficulty = float ( r [ '' ] ) , size = r [ '' ] , hash = r [ '' ] , merkle_root = r [ '' ] , previous_hash = r [ '' ] , next_hash = r [ '' ] , txids = sorted ( [ t [ '' ] for t in r [ '' ] ] ) ) class CoinPrism ( Service ) : service_id = api_homepage = \"\" base_url = \"\" supported_cryptos = [ '' ] name = \"\" def get_balance ( self , crypto , address , confirmations = None ) : url = \"\" % ( self . base_url , address ) resp = self . get_url ( url ) . json ( ) return resp [ '' ] / def get_transactions ( self , crypto , address ) : url = \"\" % ( self . base_url , address ) transactions = [ ] for tx in self . get_url ( url ) . json ( ) : transactions . append ( dict ( amount = sum ( [ x [ '' ] / for x in tx [ '' ] if address in x [ '' ] ] ) , txid = tx [ '' ] , date = arrow . get ( tx [ '' ] ) . datetime , confirmations = tx [ '' ] ) ) return transactions def get_unspent_outputs ( self , crypto , address ) : url = \"\" % ( self . base_url , address ) transactions = [ ] for tx in self . get_url ( url ) . json ( ) : if address in tx [ '' ] : transactions . append ( dict ( amount = tx [ '' ] , address = address , output = \"\" % ( tx [ '' ] , tx [ '' ] ) , confirmations = tx [ '' ] ) ) return transactions def push_tx ( self , crypto , tx_hex ) : \"\"\"\"\"\" url = \"\" return self . post_url ( url , tx_hex ) . content class BitEasy ( Service ) : \"\"\"\"\"\" service_id = api_homepage = \"\" supported_cryptos = [ '' ] explorer_address_url = \"\" explorer_tx_url = \"\" explorer_blockhash_url = \"\" name = \"\" def get_balance ( self , crypto , address , confirmations = ) : url = \"\" + address response = self . get_url ( url ) return response . json ( ) [ '' ] [ '' ] / class BlockChainInfo ( Service ) : service_id = domain = \"\" api_homepage = \"\" supported_cryptos = [ '' ] explorer_address_url = \"\" explorer_tx_url = \"\" explorer_blocknum_url = \"\" explorer_blockhash_url = \"\" name = \"\" def get_balance ( self , crypto , address , confirmations = ) : url = \"\" % ( self . domain , address ) response = self . get_url ( url ) return float ( response . json ( ) [ '' ] ) * def get_unspent_outputs ( self , crypto , address , confirmations = ) : url = \"\" % ( self . domain , address ) response = self . get_url ( url ) if response . content == '' : return [ ] utxos = [ ] for utxo in response . json ( ) [ '' ] : if utxo [ '' ] < confirmations : continue utxos . append ( dict ( output = \"\" % ( utxo [ '' ] , utxo [ '' ] ) , amount = utxo [ '' ] , address = address , ) ) return utxos class BitcoinAbe ( Service ) : service_id = supported_cryptos = [ '' ] base_url = \"\" name = \"\" def get_balance ( self , crypto , address , confirmations = ) : url = self . base_url + \"\" + address response = self . get_url ( url ) return float ( response . content ) class DogeChainInfo ( BitcoinAbe ) : service_id = supported_cryptos = [ '' ] base_url = \"\" api_homepage = \"\" name = \"\" class AuroraCoinEU ( BitcoinAbe ) : service_id = supported_cryptos = [ '' ] base_url = '' name = \"\" class Atorox ( BitcoinAbe ) : service_id = supported_cryptos = [ '' ] base_url = \"\" name = \"\" class FeathercoinCom ( Service ) : service_id = supported_cryptos = [ '' ] api_homepage = \"\" name = \"\" def get_balance ( self , crypto , address , confirmations = ) : url = \"\" % address response = self . get_url ( url ) return float ( response . json ( ) [ '' ] ) class NXTPortal ( Service ) : service_id = supported_cryptos = [ '' ] api_homepage = \"\" name = \"\" def get_balance ( self , crypto , address , confirmations = ) : url = '' + address response = self . get_url ( url ) return float ( response . json ( ) [ '' ] ) * def get_transactions ( self , crypto , address ) : url = '' % address response = self . get_url ( url ) transactions = [ ] for tx in txs : transactions . append ( dict ( date = arrow . get ( tx [ '' ] ) . datetime , amount = tx [ '' ] , txid = tx [ '' ] , confirmations = tx [ '' ] , ) ) return transactions class CryptoID ( Service ) : service_id = api_homepage = \"\" name = \"\" api_key = \"\" supported_cryptos = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ] def get_balance ( self , crypto , address , confirmations = ) : url = \"\" % ( crypto , address , self . api_key ) return float ( self . get_url ( url ) . content ) def get_single_transaction ( self , crypto , txid ) : url = \"\" % ( crypto , txid , self . api_key ) r = self . get_url ( url ) . json ( ) return dict ( time = arrow . get ( r [ '' ] ) . datetime , block_number = r [ '' ] , inputs = [ { '' : x [ '' ] , '' : x [ '' ] } for x in r [ '' ] ] , outputs = [ { '' : x [ '' ] , '' : x [ '' ] } for x in r [ '' ] ] , txid = txid , total_in = r [ '' ] , total_out = r [ '' ] , confirmations = r [ '' ] , ) def get_unspent_outputs ( self , crypto , address , confirmations = ) : url = \"\" % ( crypto , address , self . api_key ) resp = self . get_url ( url ) if resp . status_code != : raise Exception ( \"\" % resp . content ) ret = [ ] for utxo in resp . json ( ) [ '' ] : ret . append ( dict ( output = \"\" % ( utxo [ '' ] , utxo [ '' ] ) , amount = int ( utxo [ '' ] ) , confirmations = utxo [ '' ] , address = address ) ) return ret class CryptapUS ( Service ) : service_id = api_homepage = \"\" name = \"\" supported_cryptos = [ '' , '' , '' , '' , '' , '' , '' , '' , '' ] def get_balance ( self , crypto , address , confirmations = ) : url = \"\" % ( crypto , address ) return float ( self . get_url ( url ) . content ) class BTER ( Service ) : service_id = api_homepage = \"\" name = \"\" def get_current_price ( self , crypto , fiat ) : url_template = \"\" url = url_template % ( crypto , fiat ) response = self . get_url ( url ) . json ( ) if response [ '' ] == '' : url = url_template % ( crypto , '' ) response = self . get_url ( url ) altcoin_btc = float ( response [ '' ] ) url = url_template % ( '' , fiat ) response = self . get_url ( url ) btc_fiat = float ( response [ '' ] ) self . name = '' return ( btc_fiat * altcoin_btc ) return float ( response [ '' ] or ) class BitpayInsight ( Service ) : service_id = supported_cryptos = [ '' ] domain = \"\" protocol = '' api_homepage = \"\" explorer_address_url = \"\" name = \"\" def get_balance ( self , crypto , address , confirmations = ) : url = \"\" % ( self . protocol , self . domain , address ) return float ( self . get_url ( url ) . content ) / def _format_tx ( self , tx , addresses ) : matched_addresses = [ ] my_outs = my_ins = for address in addresses : for x in tx [ '' ] : if address in x [ '' ] [ '' ] : my_outs += float ( x [ '' ] ) matched_addresses . append ( address ) for x in tx [ '' ] : if address in x [ '' ] : my_ins += float ( x [ '' ] ) matched_addresses . append ( address ) return dict ( amount = my_outs - my_ins , date = arrow . get ( tx [ '' ] ) . datetime , txid = tx [ '' ] , confirmations = tx [ '' ] , addresses = list ( set ( matched_addresses ) ) ) def get_transactions ( self , crypto , address ) : url = \"\" % ( self . protocol , self . domain , address ) response = self . get_url ( url ) transactions = [ ] for tx in response . json ( ) [ '' ] : transactions . append ( self . _format_tx ( tx , [ address ] ) ) return transactions def get_transactions_multi ( self , crypto , addresses ) : url = \"\" % ( self . protocol , self . domain , '' . join ( addresses ) ) r = self . get_url ( url ) . json ( ) txs = [ ] for tx in r [ '' ] : txs . append ( self . _format_tx ( tx , addresses ) ) return txs def get_single_transaction ( self , crypto , txid ) : url = \"\" % ( self . protocol , self . domain , txid ) d = self . get_url ( url ) . json ( ) return dict ( time = arrow . get ( d [ '' ] ) . datetime , confirmations = d [ '' ] , total_in = float ( d [ '' ] ) , total_out = float ( d [ '' ] ) , fee = d [ '' ] , inputs = [ { '' : x [ '' ] , '' : x [ '' ] } for x in d [ '' ] ] , outputs = [ { '' : x [ '' ] [ '' ] [ ] , '' : x [ '' ] } for x in d [ '' ] ] , txid = txid , ) def _format_utxo ( self , utxo ) : return dict ( output = \"\" % ( utxo [ '' ] , utxo [ '' ] ) , amount = currency_to_protocol ( utxo [ '' ] ) , confirmations = utxo [ '' ] , address = utxo [ '' ] ) def get_unspent_outputs ( self , crypto , address , confirmations = ) : url = \"\" % ( self . protocol , self . domain , address ) utxos = [ ] for utxo in self . get_url ( url ) . json ( ) : utxos . append ( self . _format_utxo ( utxo ) ) return utxos def get_unspent_outputs_multi ( self , crypto , addresses , confirmations = ) : url = \"\" % ( self . protocol , self . domain , '' . join ( addresses ) ) utxos = [ ] for utxo in self . get_url ( url ) . json ( ) : utxos . append ( self . _format_utxo ( utxo ) ) return utxos def get_block ( self , crypto , block_number = '' , block_hash = '' , latest = False ) : if latest : url = \"\" % ( self . protocol , self . domain ) block_hash = self . get_url ( url ) . json ( ) [ '' ] elif block_number : url = \"\" % ( self . protocol , self . domain , block_number ) block_hash = self . get_url ( url ) . json ( ) [ '' ] url = \"\" % ( self . protocol , self . domain , block_hash ) r = self . get_url ( url ) . json ( ) return dict ( block_number = r [ '' ] , version = r [ '' ] , confirmations = r [ '' ] , time = arrow . get ( r [ '' ] ) . datetime , mining_difficulty = float ( r [ '' ] ) , size = r [ '' ] , hash = r [ '' ] , merkle_root = r [ '' ] , previous_hash = r [ '' ] , next_hash = r . get ( '' , None ) , txids = r [ '' ] , tx_count = len ( r [ '' ] ) ) def push_tx ( self , crypto , tx_hex ) : url = \"\" % ( self . protocol , self . domain ) return self . post_url ( url , { '' : tx_hex } ) . json ( ) [ '' ] def get_optimal_fee ( self , crypto , tx_bytes ) : url = \"\" % ( self . protocol , self . domain ) return self . get_url ( url ) . json ( ) class MYRCryptap ( BitpayInsight ) : service_id = protocol = '' supported_cryptos = [ '' ] domain = \"\" name = \"\" class BirdOnWheels ( BitpayInsight ) : service_id = supported_cryptos = [ '' ] domain = \"\" name = \"\" class ThisIsVTC ( BitpayInsight ) : service_id = supported_cryptos = [ '' ] domain = \"\" name = \"\" class ReddcoinCom ( BitpayInsight ) : service_id = supported_cryptos = [ '' ] domain = \"\" name = \"\" class CoinTape ( Service ) : service_id = api_homepage = \"\" supported_cryptos = [ '' ] base_url = \"\" name = \"\" def get_optimal_fee ( self , crypto , tx_bytes ) : url = self . base_url + \"\" response = self . get_url ( url ) . json ( ) return int ( response [ '' ] * tx_bytes ) class BitGo ( Service ) : service_id = api_homepage = '' name = \"\" base_url = \"\" optimalFeeNumBlocks = supported_cryptos = [ '' ] def get_balance ( self , crypto , address , confirmations = ) : url = \"\" % ( self . base_url , address ) response = self . get_url ( url ) . json ( ) if confirmations == : return response [ '' ] / if confirmations == : return response [ '' ] / else : raise SkipThisService ( '' ) def get_transactions ( self , crypto , address ) : url = \"\" % ( self . base_url , address ) response = self . get_url ( url ) . json ( ) txs = [ ] for tx in response [ '' ] : my_outs = [ x [ '' ] for x in tx [ '' ] if x [ '' ] == address ] txs . append ( dict ( amount = sum ( my_outs ) , date = arrow . get ( tx [ '' ] ) . datetime , txid = tx [ '' ] , confirmations = tx [ '' ] , ) ) return txs def get_unspent_outputs ( self , crypto , address , confirmations = ) : url = \"\" % ( self . base_url , address ) utxos = [ ] for utxo in self . get_url ( url ) . json ( ) [ '' ] : utxos . append ( dict ( output = \"\" % ( utxo [ '' ] , utxo [ '' ] ) , amount = utxo [ '' ] , confirmations = utxo [ '' ] , address = address ) ) return utxos def get_block ( self , crypto , block_number = '' , block_hash = '' , latest = False ) : ", "answer": "if latest :"}, {"prompt": " import sys import os import re from enum import Enum , unique import configuration from configuration import ComponentBaseLineEntry import sorter import shell import shouter from gitFunctions import Commiter , Differ class RTCInitializer : @ staticmethod def initialize ( ) : RTCLogin . loginandcollectstreamuuid ( ) workspace = WorkspaceHandler ( ) config = configuration . get ( ) if config . useexistingworkspace : shouter . shout ( \"\" ) workspace . load ( ) else : workspace . createandload ( config . streamuuid , config . initialcomponentbaselines ) class RTCLogin : @ staticmethod def loginandcollectstreamuuid ( ) : config = configuration . get ( ) shell . execute ( \"\" % ( config . scmcommand , config . repo , config . user , config . password ) ) config . collectstreamuuids ( ) @ staticmethod def logout ( ) : config = configuration . get ( ) shell . execute ( \"\" % ( config . scmcommand , config . repo ) ) class WorkspaceHandler : def __init__ ( self ) : self . config = configuration . get ( ) self . workspace = self . config . workspace self . repo = self . config . repo self . scmcommand = self . config . scmcommand def createandload ( self , stream , componentbaselineentries = [ ] ) : shell . execute ( \"\" % ( self . scmcommand , self . repo , stream , self . workspace ) ) if componentbaselineentries : self . setcomponentstobaseline ( componentbaselineentries , stream ) else : self . setcomponentstobaseline ( ImportHandler ( ) . determineinitialbaseline ( stream ) , stream ) self . load ( ) def load ( self ) : command = \"\" % ( self . scmcommand , self . repo , self . workspace ) if self . config . includecomponentroots : command += \"\" shouter . shout ( \"\" + command ) shell . execute ( command ) shouter . shout ( \"\" ) Commiter . restore_shed_gitignore ( Commiter . get_untracked_statuszlines ( ) ) def setcomponentstobaseline ( self , componentbaselineentries , streamuuid ) : for entry in componentbaselineentries : shouter . shout ( \"\" % ( entry . componentname , entry . component , entry . baselinename , entry . baseline ) ) replacecommand = \"\" % ( self . scmcommand , self . repo , entry . baseline , self . workspace , streamuuid , entry . component ) shell . execute ( replacecommand ) def setnewflowtargets ( self , streamuuid ) : shouter . shout ( \"\" ) if not self . hasflowtarget ( streamuuid ) : shell . execute ( \"\" % ( self . scmcommand , self . repo , self . workspace , streamuuid ) ) command = \"\" % ( self . scmcommand , self . repo , self . workspace , streamuuid ) shell . execute ( command ) def hasflowtarget ( self , streamuuid ) : command = \"\" % ( self . scmcommand , self . repo , self . workspace ) flowtargetlines = shell . getoutput ( command ) for flowtargetline in flowtargetlines : splittedinformationline = flowtargetline . split ( \"\" ) uuidpart = splittedinformationline [ ] . split ( \"\" ) flowtargetuuid = uuidpart [ ] . strip ( ) [ : - ] if streamuuid in flowtargetuuid : return True return False class Changes : latest_accept_command = \"\" @ staticmethod def discard ( * changeentries ) : config = configuration . get ( ) idstodiscard = Changes . _collectids ( changeentries ) exitcode = shell . execute ( config . scmcommand + \"\" + config . workspace + \"\" + config . repo + \"\" + idstodiscard ) if exitcode is : for changeEntry in changeentries : changeEntry . setUnaccepted ( ) @ staticmethod def accept ( logpath , * changeentries ) : for changeEntry in changeentries : shouter . shout ( \"\" + changeEntry . tostring ( ) ) revisions = Changes . _collectids ( changeentries ) config = configuration . get ( ) Changes . latest_accept_command = config . scmcommand + \"\" + config . repo + \"\" + config . workspace + \"\" + revisions exitcode = shell . execute ( Changes . latest_accept_command , logpath , \"\" ) if exitcode is : for changeEntry in changeentries : changeEntry . setAccepted ( ) return True else : return False @ staticmethod def _collectids ( changeentries ) : ids = \"\" for changeentry in changeentries : ids += \"\" + changeentry . revision return ids @ staticmethod def tostring ( * changes ) : logmessage = \"\" for change in changes : logmessage += change . tostring ( ) + \"\" shouter . shout ( logmessage ) class ImportHandler : def __init__ ( self ) : self . config = configuration . get ( ) self . acceptlogpath = self . config . getlogpath ( \"\" ) def getcomponentbaselineentriesfromstream ( self , stream ) : filename = self . config . getlogpath ( \"\" + stream + \"\" ) command = \"\" % ( self . config . scmcommand , self . config . repo , stream ) shell . execute ( command , filename ) componentbaselinesentries = [ ] skippedfirstrow = False islinewithcomponent = component = \"\" baseline = \"\" componentname = \"\" baselinename = \"\" with open ( filename , '' , encoding = shell . encoding ) as file : for line in file : cleanedline = line . strip ( ) if cleanedline : if not skippedfirstrow : skippedfirstrow = True continue splittedinformationline = line . split ( \"\" ) uuidpart = splittedinformationline [ ] . split ( \"\" ) if islinewithcomponent % is : component = uuidpart [ ] . strip ( ) [ : - ] componentname = splittedinformationline [ ] else : baseline = uuidpart [ ] . strip ( ) [ : - ] baselinename = splittedinformationline [ ] if baseline and component : componentbaselinesentries . append ( ComponentBaseLineEntry ( component , baseline , componentname , baselinename ) ) baseline = \"\" component = \"\" componentname = \"\" baselinename = \"\" islinewithcomponent += return componentbaselinesentries def determineinitialbaseline ( self , stream ) : regex = \"\" pattern = re . compile ( regex ) config = self . config componentbaselinesentries = self . getcomponentbaselineentriesfromstream ( stream ) for entry in componentbaselinesentries : shouter . shout ( \"\" + entry . componentname ) command = \"\" % ( entry . component , config . repo , config . user , config . password ) baselineslines = shell . getoutput ( command ) baselineslines . reverse ( ) for baselineline in baselineslines : matcher = pattern . search ( baselineline ) if matcher : matchedstring = matcher . group ( ) uuid = matchedstring [ : - ] entry . baseline = uuid entry . baselinename = \"\" shouter . shout ( \"\" % baselineline ) break return componentbaselinesentries def acceptchangesintoworkspace ( self , changeentries ) : amountofchanges = len ( changeentries ) shouter . shoutwithdate ( \"\" % amountofchanges ) amountofacceptedchanges = for changeEntry in changeentries : amountofacceptedchanges += if not changeEntry . isAccepted ( ) : if not Changes . accept ( self . acceptlogpath , changeEntry ) : shouter . shout ( \"\" ) if not Differ . has_diff ( ) : WorkspaceHandler ( ) . load ( ) shouter . shout ( \"\" % ( amountofacceptedchanges , amountofchanges ) ) Commiter . addandcommit ( changeEntry ) return amountofacceptedchanges @ staticmethod def collect_changes_to_accept_to_avoid_conflicts ( changewhichcantbeacceptedalone , changes , maxchangesetstoaccepttogether ) : changestoaccept = [ changewhichcantbeacceptedalone ] nextchange = ImportHandler . getnextchangeset_fromsamecomponent ( changewhichcantbeacceptedalone , changes ) while True : if nextchange and len ( changestoaccept ) < maxchangesetstoaccepttogether : changestoaccept . append ( nextchange ) nextchange = ImportHandler . getnextchangeset_fromsamecomponent ( nextchange , changes ) else : break return changestoaccept def retryacceptincludingnextchangesets ( self , change , changes ) : issuccessful = False changestoaccept = ImportHandler . collect_changes_to_accept_to_avoid_conflicts ( change , changes , self . config . maxchangesetstoaccepttogether ) amountofchangestoaccept = len ( changestoaccept ) if amountofchangestoaccept > : Changes . tostring ( * changestoaccept ) if self . config . useautomaticconflictresolution or self . is_user_agreeing_to_accept_next_change ( change ) : shouter . shout ( \"\" ) for index in range ( , amountofchangestoaccept ) : toaccept = changestoaccept [ : index + ] if Changes . accept ( self . acceptlogpath , * toaccept ) : issuccessful = True break if not issuccessful : self . is_user_aborting ( change ) @ staticmethod def is_user_agreeing_to_accept_next_change ( change ) : messagetoask = \"\" while True : answer = input ( messagetoask ) . lower ( ) if answer == \"\" : return True elif answer == \"\" : return not ImportHandler . is_user_aborting ( change ) else : shouter . shout ( \"\" + answer ) @ staticmethod def is_user_aborting ( change ) : shouter . shout ( \"\" + Changes . latest_accept_command ) shouter . shout ( \"\" + Commiter . getcommitcommand ( change ) ) reallycontinue = \"\" if input ( reallycontinue ) . lower ( ) == \"\" : return True else : sys . exit ( \"\" ) @ staticmethod def getnextchangeset_fromsamecomponent ( currentchangeentry , changeentries ) : nextchangeentry = None component = currentchangeentry . component nextindex = changeentries . index ( currentchangeentry ) + while not nextchangeentry and nextindex < len ( changeentries ) : candidateentry = changeentries [ nextindex ] if not candidateentry . isAccepted ( ) and candidateentry . component == component : nextchangeentry = candidateentry nextindex += return nextchangeentry def getchangeentriesofstreamcomponents ( self , componentbaselineentries ) : missingchangeentries = { } shouter . shout ( \"\" ) for componentBaseLineEntry in componentbaselineentries : shouter . shout ( \"\" % ( componentBaseLineEntry . baselinename , componentBaseLineEntry . componentname ) ) changeentries = self . getchangeentriesofbaseline ( componentBaseLineEntry . baseline ) for changeentry in changeentries : missingchangeentries [ changeentry . revision ] = changeentry return missingchangeentries def readhistory ( self , componentbaselineentries , streamname ) : ", "answer": "if not self . config . useprovidedhistory :"}, {"prompt": " \"\"\"\"\"\" import fieldtree class Packet ( object ) : \"\" def __init__ ( self ) : self . objects = { } self . index = { } self . sensors = set ( ) Service . packet = self def __str__ ( self ) : objects = self . objects . iteritems ( ) items = ( '' % ( a , b ) for a , b in objects ) return '' % '' . join ( items ) def object ( self , name ) : this = ObjectName ( name ) obj = Object ( self , { '' : this } ) self . add ( obj ) return obj , this def add ( self , obj ) : assert isinstance ( obj , Object ) identifier = obj [ '' ] self . objects [ identifier ] = obj def add_sensor ( self , sensor ) : sensor . packet = self self . sensors . add ( sensor ) def get ( self , n ) : return self . objects [ n . object ] [ n . label ] def commit ( self ) : changeset = { } for name , object in self . objects . iteritems ( ) : if object . has_changes ( ) : changeset [ name ] = object . get_changes ( ) for name , fields in changeset . iteritems ( ) : for key , ( label , value ) in fields . iteritems ( ) : if isinstance ( value , set ) : value = frozenset ( value ) if not self . index . has_key ( key ) : self . index [ key ] = { } self . index [ key ] . setdefault ( value , set ( ) ) . add ( name ) for sensor in self . sensors : if sensor . matches ( changeset ) : sensor . notify ( changeset ) class Object ( fieldtree . FieldTree ) : \"\" def __init__ ( self , packet , fields ) : self . packet = packet self . __changes = { } self . __depth = self . __error = None if isinstance ( fields , dict ) : fields = fields . items ( ) super ( Object , self ) . __init__ ( * fields ) def __str__ ( self ) : items = ( '' % ( a , b ( ) if computation ( b ) else b ) for a , b in self . fields ( ) ) return '' % '' . join ( items ) def __getitem__ ( self , label ) : value = super ( Object , self ) . __getitem__ ( label ) if computation ( value ) : self . __depth += try : value = value ( ) except Exception , e : if self . __error is None : self . __error = Error ( e ) self . __depth -= if ( self . __depth == ) and ( self . __error is not None ) : value = self . __error self . __error = None return value def update ( self , fields ) : if isinstance ( fields , dict ) : if fields . has_key ( '' ) : del self . packet . objects [ self [ '' ] ] self . packet . objects [ fields [ '' ] ] = self fields = fields . items ( ) super ( Object , self ) . update ( fields ) else : super ( Object , self ) . update ( fields , ignore = '' ) def changed ( self , * keys ) : for key in keys : field = self . get_field ( key ) self . __changes [ key ] = field def has_changes ( self ) : return len ( self . __changes ) > def get_changes ( self ) : changes = self . __changes . copy ( ) self . __changes = { } return changes def Service ( original ) : \"\" def compute ( ) : \"\" def value ( n ) : if n . name in Service . accessed : raise CycleError ( \"\" % n . name ) Service . accessed . add ( n . name ) return Service . packet . get ( n ) def evaluate ( arg ) : if isinstance ( arg , ValueName ) : return value ( arg ) elif computation ( arg ) : return arg ( ) else : return arg accessed = Service . accessed . copy ( ) args = [ evaluate ( arg ) for arg in compute . args ] result = compute . original ( * args ) Service . accessed = accessed return result compute . original = original def define ( * args ) : \"\" compute . args = args return compute return define Service . packet = None Service . accessed = set ( ) @ Service def Sum ( a , b ) : return a + b @ Service def Interest ( a , b ) : return a + ( a * b ) @ Service def Get ( a , b ) : return a [ b ] class Sensor ( object ) : def __init__ ( self , obj ) : self . packet = None self . output = obj self . optional_patterns = set ( ) self . mandatory_patterns = set ( ) self . matched = set ( ) def optional ( self , function ) : self . optional_patterns . add ( function ) def mandatory ( self , function ) : self . mandatory_patterns . add ( function ) def matches ( self , changeset ) : optional = set ( ) mandatory = set ( ) self . matched = set ( ) for opt in self . optional_patterns : o = [ opt ( fields ) for name , fields in changeset . iteritems ( ) ] optional . add ( o . count ( True ) ) if o . count ( True ) : self . matched . add ( opt . __name__ ) for man in self . mandatory_patterns : m = [ man ( fields ) for name , fields in changeset . iteritems ( ) ] mandatory . add ( m . count ( True ) ) if m . count ( True ) : self . matched . add ( man . __name__ ) return any ( optional or [ True ] ) and all ( mandatory or [ True ] ) def notify ( self , changeset ) : self . output . update ( { '' : str ( id ( self ) ) } ) self . output . update ( { '' : self . packet } ) self . output . update ( { '' : self . matched } ) class Schema ( object ) : def __init__ ( self , ** kargs ) : self . properties = kargs def __call__ ( self , obj ) : import new for key , value in self . properties . iteritems ( ) : function = lambda self = self , value = value : self [ value ] method = new . instancemethod ( function , obj , type ( obj ) ) setattr ( obj , key , method ) return obj class ObjectName ( str ) : def __call__ ( self , label ) : return ValueName ( self , label ) class ValueName ( object ) : def __init__ ( self , object , label ) : self . object = object self . label = label self . name = object + '' + label class Error ( object ) : def __init__ ( self , e ) : self . exception = e def __repr__ ( self ) : args = ( type ( self . exception ) . __name__ , str ( self . exception ) ) return '' % args class CycleError ( Exception ) : \"\" def computation ( obj ) : \"\" return callable ( obj ) and hasattr ( obj , '' ) def account_test ( ) : packet = Packet ( ) account , this = packet . object ( '' ) total = Sum ( this ( '' ) , this ( '' ) ) account . update ( { '' : , '' : - , '' : total , '' : , '' : Interest ( this ( '' ) , this ( '' ) ) , '' : Interest ( total , this ( '' ) ) , } ) total = account [ '' ] adjusted = account [ '' ] account [ '' ] += total_ = account [ '' ] adj_ = account [ '' ] print total , adjusted , total_ , adj_ packet . commit ( ) print packet . index def cycle_test ( ) : packet = Packet ( ) cycle , this = packet . object ( '' ) cycle . update ( { '' : Sum ( this ( '' ) , this ( '' ) ) , '' : Sum ( this ( '' ) , this ( '' ) ) , '' : } ) print cycle [ '' ] def sensor_test ( ) : first = Packet ( ) example1 , this = first . object ( '' ) example1 . update ( { '' : '' } ) output2 , this = first . object ( '' ) output2 . update ( { '' : '' } ) second = Packet ( ) example2 , this = second . object ( '' ) example2 . update ( { '' : '' , '' : '' } ) output1 , this = second . object ( '' ) output1 . update ( { '' : '' } ) def example_message ( unit ) : for label , value in unit . itervalues ( ) : if ( label == '' ) and ( '' in value ) : return True return False def check_id ( unit ) : ", "answer": "for label , value in unit . itervalues ( ) :"}, {"prompt": " from profiletools . utils import get_my_profile_module_name def fetch_profile ( request ) : \"\"\"\"\"\" context = { } if request . user . is_authenticated ( ) : profile_module_name = get_my_profile_module_name ( ) profile = getattr ( request , profile_module_name , None ) if profile != None : ", "answer": "context [ profile_module_name ] = profile"}, {"prompt": " \"\"\"\"\"\" from django . db import models from django . utils . encoding import python_2_unicode_compatible @ python_2_unicode_compatible class Article ( models . Model ) : headline = models . CharField ( max_length = ) pub_date = models . DateField ( ) expire_date = models . DateField ( ) class Meta : get_latest_by = '' def __str__ ( self ) : return self . headline @ python_2_unicode_compatible class Person ( models . Model ) : ", "answer": "name = models . CharField ( max_length = )"}, {"prompt": " from . resource import Resource ", "answer": "class VirtualMachine ( Resource ) :"}, {"prompt": " from django . conf . urls import patterns , url from siteuser . users import views from siteuser . settings import USING_SOCIAL_LOGIN urlpatterns = patterns ( '' , url ( r'' , views . SiteUserLoginView . as_view ( ) , name = '' ) , url ( r'' , views . SiteUserRegisterView . as_view ( ) , name = '' ) , url ( r'' , views . SiteUserResetPwStepOneView . as_view ( ) , name = '' ) , url ( r'' , views . SiteUserResetPwStepOneDoneView . as_view ( ) , name = '' ) , url ( r'' , views . SiteUserResetPwStepTwoDoneView . as_view ( ) , name = '' ) , url ( r'' , views . SiteUserResetPwStepTwoView . as_view ( ) , name = '' ) , url ( r'' , views . SiteUserChangePwView . as_view ( ) , name = '' ) , url ( r'' , views . SiteUserChangePwDoneView . as_view ( ) , name = '' ) , ", "answer": "url ( r'' , views . logout , name = '' ) ,"}, {"prompt": " '''''' __author__ = \"\" __email__ = \"\" __version__ = \"\" [ : - ] import time import sys import traceback import os import types __all__ = [ '' , '' , '' , '' , '' , '' , '' , '' ] __all__ . extend ( [ '' , '' , '' ] ) if sys . version_info [ : ] < ( , ) : def isinstance ( obj , clsinfo ) : import __builtin__ if type ( clsinfo ) in ( tuple , list ) : for cls in clsinfo : if cls is type : cls = types . ClassType if __builtin__ . isinstance ( obj , cls ) : return return else : return __builtin__ . isinstance ( obj , clsinfo ) def _CmpToKey ( mycmp ) : '' class K ( object ) : def __init__ ( self , obj ) : self . obj = obj def __lt__ ( self , other ) : return mycmp ( self . obj , other . obj ) == - return K __metaclass__ = type def _strclass ( cls ) : return \"\" % ( cls . __module__ , cls . __name__ ) __unittest = class TestResult : \"\"\"\"\"\" def __init__ ( self ) : self . failures = [ ] self . errors = [ ] self . testsRun = self . shouldStop = False def startTest ( self , test ) : \"\" self . testsRun = self . testsRun + def stopTest ( self , test ) : \"\" pass def addError ( self , test , err ) : \"\"\"\"\"\" self . errors . append ( ( test , self . _exc_info_to_string ( err , test ) ) ) def addFailure ( self , test , err ) : \"\"\"\"\"\" self . failures . append ( ( test , self . _exc_info_to_string ( err , test ) ) ) def addSuccess ( self , test ) : \"\" pass def wasSuccessful ( self ) : \"\" return len ( self . failures ) == len ( self . errors ) == def stop ( self ) : \"\" self . shouldStop = True def _exc_info_to_string ( self , err , test ) : \"\"\"\"\"\" exctype , value , tb = err while tb and self . _is_relevant_tb_level ( tb ) : tb = tb . tb_next if exctype is test . failureException : length = self . _count_relevant_tb_levels ( tb ) return '' . join ( traceback . format_exception ( exctype , value , tb , length ) ) return '' . join ( traceback . format_exception ( exctype , value , tb ) ) def _is_relevant_tb_level ( self , tb ) : return '' in tb . tb_frame . f_globals def _count_relevant_tb_levels ( self , tb ) : length = while tb and not self . _is_relevant_tb_level ( tb ) : length += tb = tb . tb_next return length def __repr__ ( self ) : return \"\" % ( _strclass ( self . __class__ ) , self . testsRun , len ( self . errors ) , len ( self . failures ) ) class TestCase : \"\"\"\"\"\" failureException = AssertionError def __init__ ( self , methodName = '' ) : \"\"\"\"\"\" try : self . _testMethodName = methodName testMethod = getattr ( self , methodName ) self . _testMethodDoc = testMethod . __doc__ except AttributeError : raise ValueError , \"\" % ( self . __class__ , methodName ) def setUp ( self ) : \"\" pass def tearDown ( self ) : \"\" pass def countTestCases ( self ) : return def defaultTestResult ( self ) : return TestResult ( ) def shortDescription ( self ) : \"\"\"\"\"\" doc = self . _testMethodDoc return doc and doc . split ( \"\" ) [ ] . strip ( ) or None def id ( self ) : return \"\" % ( _strclass ( self . __class__ ) , self . _testMethodName ) def __eq__ ( self , other ) : if type ( self ) is not type ( other ) : return False return self . _testMethodName == other . _testMethodName def __ne__ ( self , other ) : return not self == other def __hash__ ( self ) : return hash ( ( type ( self ) , self . _testMethodName ) ) def __str__ ( self ) : return \"\" % ( self . _testMethodName , _strclass ( self . __class__ ) ) def __repr__ ( self ) : return \"\" % ( _strclass ( self . __class__ ) , self . _testMethodName ) def run ( self , result = None ) : if result is None : result = self . defaultTestResult ( ) result . startTest ( self ) testMethod = getattr ( self , self . _testMethodName ) try : try : self . setUp ( ) except KeyboardInterrupt : raise except : result . addError ( self , self . _exc_info ( ) ) return ok = False try : testMethod ( ) ok = True except self . failureException : result . addFailure ( self , self . _exc_info ( ) ) except KeyboardInterrupt : raise except : result . addError ( self , self . _exc_info ( ) ) try : self . tearDown ( ) except KeyboardInterrupt : raise except : result . addError ( self , self . _exc_info ( ) ) ok = False if ok : result . addSuccess ( self ) finally : result . stopTest ( self ) def __call__ ( self , * args , ** kwds ) : return self . run ( * args , ** kwds ) def debug ( self ) : \"\"\"\"\"\" self . setUp ( ) getattr ( self , self . _testMethodName ) ( ) self . tearDown ( ) def _exc_info ( self ) : \"\"\"\"\"\" return sys . exc_info ( ) def fail ( self , msg = None ) : \"\"\"\"\"\" raise self . failureException , msg def failIf ( self , expr , msg = None ) : \"\" if expr : raise self . failureException , msg def failUnless ( self , expr , msg = None ) : \"\"\"\"\"\" if not expr : raise self . failureException , msg def failUnlessRaises ( self , excClass , callableObj , * args , ** kwargs ) : \"\"\"\"\"\" try : callableObj ( * args , ** kwargs ) except excClass : return else : if hasattr ( excClass , '' ) : excName = excClass . __name__ else : excName = str ( excClass ) raise self . failureException , \"\" % excName def failUnlessEqual ( self , first , second , msg = None ) : \"\"\"\"\"\" if not first == second : raise self . failureException , ( msg or '' % ( first , second ) ) def failIfEqual ( self , first , second , msg = None ) : \"\"\"\"\"\" if first == second : raise self . failureException , ( msg or '' % ( first , second ) ) def failUnlessAlmostEqual ( self , first , second , places = , msg = None ) : \"\"\"\"\"\" if round ( abs ( second - first ) , places ) != : raise self . failureException , ( msg or '' % ( first , second , places ) ) def failIfAlmostEqual ( self , first , second , places = , msg = None ) : \"\"\"\"\"\" if round ( abs ( second - first ) , places ) == : raise self . failureException , ( msg or '' % ( first , second , places ) ) assertEqual = assertEquals = failUnlessEqual assertNotEqual = assertNotEquals = failIfEqual assertAlmostEqual = assertAlmostEquals = failUnlessAlmostEqual assertNotAlmostEqual = assertNotAlmostEquals = failIfAlmostEqual assertRaises = failUnlessRaises assert_ = assertTrue = failUnless assertFalse = failIf class TestSuite : \"\"\"\"\"\" def __init__ ( self , tests = ( ) ) : self . _tests = [ ] self . addTests ( tests ) def __repr__ ( self ) : return \"\" % ( _strclass ( self . __class__ ) , self . _tests ) __str__ = __repr__ def __eq__ ( self , other ) : if type ( self ) is not type ( other ) : return False return self . _tests == other . _tests def __ne__ ( self , other ) : return not self == other __hash__ = None def __iter__ ( self ) : return iter ( self . _tests ) def countTestCases ( self ) : cases = for test in self . _tests : cases += test . countTestCases ( ) return cases def addTest ( self , test ) : if not hasattr ( test , '' ) : raise TypeError ( \"\" ) if ( isinstance ( test , ( type , types . ClassType ) ) and issubclass ( test , ( TestCase , TestSuite ) ) ) : raise TypeError ( \"\" \"\" ) self . _tests . append ( test ) def addTests ( self , tests ) : if isinstance ( tests , basestring ) : raise TypeError ( \"\" ) for test in tests : self . addTest ( test ) def run ( self , result ) : for test in self . _tests : if result . shouldStop : break test ( result ) return result def __call__ ( self , * args , ** kwds ) : return self . run ( * args , ** kwds ) def debug ( self ) : \"\"\"\"\"\" for test in self . _tests : test . debug ( ) class FunctionTestCase ( TestCase ) : \"\"\"\"\"\" def __init__ ( self , testFunc , setUp = None , tearDown = None , description = None ) : TestCase . __init__ ( self ) self . __setUpFunc = setUp self . __tearDownFunc = tearDown self . __testFunc = testFunc self . __description = description def setUp ( self ) : if self . __setUpFunc is not None : self . __setUpFunc ( ) def tearDown ( self ) : if self . __tearDownFunc is not None : self . __tearDownFunc ( ) def runTest ( self ) : self . __testFunc ( ) def id ( self ) : return self . __testFunc . __name__ def __eq__ ( self , other ) : if type ( self ) is not type ( other ) : return False return self . __setUpFunc == other . __setUpFunc and self . __tearDownFunc == other . __tearDownFunc and self . __testFunc == other . __testFunc and self . __description == other . __description def __ne__ ( self , other ) : return not self == other def __hash__ ( self ) : return hash ( ( type ( self ) , self . __setUpFunc , self . __tearDownFunc , self . __testFunc , self . __description ) ) def __str__ ( self ) : return \"\" % ( _strclass ( self . __class__ ) , self . __testFunc . __name__ ) def __repr__ ( self ) : return \"\" % ( _strclass ( self . __class__ ) , self . __testFunc ) def shortDescription ( self ) : if self . __description is not None : return self . __description doc = self . __testFunc . __doc__ return doc and doc . split ( \"\" ) [ ] . strip ( ) or None class TestLoader : \"\"\"\"\"\" testMethodPrefix = '' sortTestMethodsUsing = cmp suiteClass = TestSuite def loadTestsFromTestCase ( self , testCaseClass ) : \"\"\"\"\"\" if issubclass ( testCaseClass , TestSuite ) : raise TypeError ( \"\" ) testCaseNames = self . getTestCaseNames ( testCaseClass ) if not testCaseNames and hasattr ( testCaseClass , '' ) : testCaseNames = [ '' ] return self . suiteClass ( map ( testCaseClass , testCaseNames ) ) def loadTestsFromModule ( self , module ) : \"\"\"\"\"\" tests = [ ] for name in dir ( module ) : obj = getattr ( module , name ) if ( isinstance ( obj , ( type , types . ClassType ) ) and issubclass ( obj , TestCase ) ) : tests . append ( self . loadTestsFromTestCase ( obj ) ) return self . suiteClass ( tests ) def loadTestsFromName ( self , name , module = None ) : \"\"\"\"\"\" parts = name . split ( '' ) if module is None : parts_copy = parts [ : ] while parts_copy : try : module = __import__ ( '' . join ( parts_copy ) ) break except ImportError : del parts_copy [ - ] if not parts_copy : raise parts = parts [ : ] obj = module for part in parts : parent , obj = obj , getattr ( obj , part ) if type ( obj ) == types . ModuleType : return self . loadTestsFromModule ( obj ) elif ( isinstance ( obj , ( type , types . ClassType ) ) and issubclass ( obj , TestCase ) ) : return self . loadTestsFromTestCase ( obj ) elif ( type ( obj ) == types . UnboundMethodType and isinstance ( parent , ( type , types . ClassType ) ) and issubclass ( parent , TestCase ) ) : return TestSuite ( [ parent ( obj . __name__ ) ] ) elif isinstance ( obj , TestSuite ) : return obj elif hasattr ( obj , '' ) : test = obj ( ) if isinstance ( test , TestSuite ) : return test elif isinstance ( test , TestCase ) : return TestSuite ( [ test ] ) else : raise TypeError ( \"\" % ( obj , test ) ) else : raise TypeError ( \"\" % obj ) def loadTestsFromNames ( self , names , module = None ) : \"\"\"\"\"\" suites = [ self . loadTestsFromName ( name , module ) for name in names ] return self . suiteClass ( suites ) def getTestCaseNames ( self , testCaseClass ) : \"\"\"\"\"\" def isTestMethod ( attrname , testCaseClass = testCaseClass , prefix = self . testMethodPrefix ) : return attrname . startswith ( prefix ) and hasattr ( getattr ( testCaseClass , attrname ) , '' ) testFnNames = filter ( isTestMethod , dir ( testCaseClass ) ) if self . sortTestMethodsUsing : testFnNames . sort ( key = _CmpToKey ( self . sortTestMethodsUsing ) ) return testFnNames defaultTestLoader = TestLoader ( ) def _makeLoader ( prefix , sortUsing , suiteClass = None ) : loader = TestLoader ( ) loader . sortTestMethodsUsing = sortUsing loader . testMethodPrefix = prefix if suiteClass : loader . suiteClass = suiteClass return loader def getTestCaseNames ( testCaseClass , prefix , sortUsing = cmp ) : return _makeLoader ( prefix , sortUsing ) . getTestCaseNames ( testCaseClass ) def makeSuite ( testCaseClass , prefix = '' , sortUsing = cmp , suiteClass = TestSuite ) : return _makeLoader ( prefix , sortUsing , suiteClass ) . loadTestsFromTestCase ( testCaseClass ) def findTestCases ( module , prefix = '' , sortUsing = cmp , suiteClass = TestSuite ) : return _makeLoader ( prefix , sortUsing , suiteClass ) . loadTestsFromModule ( module ) class _WritelnDecorator : \"\"\"\"\"\" def __init__ ( self , stream ) : self . stream = stream def __getattr__ ( self , attr ) : return getattr ( self . stream , attr ) def writeln ( self , arg = None ) : if arg : self . write ( arg ) self . write ( '' ) class _TextTestResult ( TestResult ) : \"\"\"\"\"\" separator1 = '' * separator2 = '' * def __init__ ( self , stream , descriptions , verbosity ) : TestResult . __init__ ( self ) self . stream = stream self . showAll = verbosity > self . dots = verbosity == self . descriptions = descriptions def getDescription ( self , test ) : if self . descriptions : return test . shortDescription ( ) or str ( test ) else : return str ( test ) def startTest ( self , test ) : TestResult . startTest ( self , test ) if self . showAll : self . stream . write ( self . getDescription ( test ) ) self . stream . write ( \"\" ) self . stream . flush ( ) def addSuccess ( self , test ) : TestResult . addSuccess ( self , test ) if self . showAll : self . stream . writeln ( \"\" ) elif self . dots : self . stream . write ( '' ) self . stream . flush ( ) def addError ( self , test , err ) : TestResult . addError ( self , test , err ) if self . showAll : self . stream . writeln ( \"\" ) elif self . dots : self . stream . write ( '' ) self . stream . flush ( ) def addFailure ( self , test , err ) : TestResult . addFailure ( self , test , err ) if self . showAll : self . stream . writeln ( \"\" ) elif self . dots : self . stream . write ( '' ) self . stream . flush ( ) def printErrors ( self ) : if self . dots or self . showAll : self . stream . writeln ( ) self . printErrorList ( '' , self . errors ) self . printErrorList ( '' , self . failures ) def printErrorList ( self , flavour , errors ) : ", "answer": "for test , err in errors :"}, {"prompt": " from . base import BaseSession import hashlib ", "answer": "from . utils import sign_payload , validate_payload , load_payload , dump_payload"}, {"prompt": " from contextlib import contextmanager from atom . api import List , Typed from enaml . widgets . constraints_widget import ProxyConstraintsWidget from . QtCore import QRect , QTimer ", "answer": "from . qt_widget import QtWidget"}, {"prompt": " from django import http from django . db import models from django . contrib . databrowse . datastructures import EasyModel from django . contrib . databrowse . sites import DatabrowsePlugin from django . shortcuts import render_to_response from django . utils . text import capfirst from django . utils . encoding import force_unicode from django . utils . safestring import mark_safe from django . views . generic import dates from django . utils import datetime_safe class DateViewMixin ( object ) : allow_empty = False allow_future = True root_url = None model = None field = None def get_context_data ( self , ** kwargs ) : context = super ( DateViewMixin , self ) . get_context_data ( ** kwargs ) context . update ( { '' : self . root_url , '' : self . model , '' : self . field } ) return context class DayView ( DateViewMixin , dates . DayArchiveView ) : template_name = '' class MonthView ( DateViewMixin , dates . MonthArchiveView ) : template_name = '' class YearView ( DateViewMixin , dates . YearArchiveView ) : template_name = '' class IndexView ( DateViewMixin , dates . ArchiveIndexView ) : template_name = '' class CalendarPlugin ( DatabrowsePlugin ) : def __init__ ( self , field_names = None ) : self . field_names = field_names def field_dict ( self , model ) : \"\"\"\"\"\" if self . field_names is None : return dict ( [ ( f . name , f ) for f in model . _meta . fields if isinstance ( f , models . DateField ) ] ) else : return dict ( [ ( f . name , f ) for f in model . _meta . fields if isinstance ( f , models . DateField ) and f . name in self . field_names ] ) def model_index_html ( self , request , model , site ) : fields = self . field_dict ( model ) if not fields : return u'' return mark_safe ( u'' % u'' . join ( [ '' % ( f . name , force_unicode ( capfirst ( f . verbose_name ) ) ) for f in fields . values ( ) ] ) ) def urls ( self , plugin_name , easy_instance_field ) : if isinstance ( easy_instance_field . field , models . DateField ) : d = easy_instance_field . raw_value return [ mark_safe ( u'' % ( easy_instance_field . model . url ( ) , plugin_name , easy_instance_field . field . name , str ( d . year ) , datetime_safe . new_date ( d ) . strftime ( '' ) . lower ( ) , d . day ) ) ] def model_view ( self , request , model_databrowse , url ) : self . model , self . site = model_databrowse . model , model_databrowse . site self . fields = self . field_dict ( self . model ) if not self . fields : raise http . Http404 ( '' ) if url is None : return self . homepage_view ( request ) url_bits = url . split ( '' ) if url_bits [ ] in self . fields : return self . calendar_view ( request , self . fields [ url_bits [ ] ] , * url_bits [ : ] ) raise http . Http404 ( '' ) def homepage_view ( self , request ) : easy_model = EasyModel ( self . site , self . model ) field_list = self . fields . values ( ) field_list . sort ( key = lambda k : k . verbose_name ) return render_to_response ( '' , { '' : self . site . root_url , '' : easy_model , '' : field_list } ) def calendar_view ( self , request , field , year = None , month = None , day = None ) : easy_model = EasyModel ( self . site , self . model ) root_url = self . site . root_url if day is not None : return DayView . as_view ( year = year , month = month , day = day , date_field = field . name , queryset = easy_model . get_query_set ( ) , root_url = root_url , model = easy_model , field = field ) ( request ) elif month is not None : return MonthView . as_view ( year = year , month = month , date_field = field . name , queryset = easy_model . get_query_set ( ) , ", "answer": "root_url = root_url ,"}, {"prompt": " \"\"\"\"\"\" import netifaces as ni import os import stat import serial from time import time , sleep class Py3status : baudrate = cache_timeout = consider_3G_degraded = False format_down = '' format_error = '' format_no_service = '' format_up = '' interface = \"\" modem = \"\" modem_timeout = def wwan_status ( self , i3s_output_list , i3s_config ) : query = \"\" target_line = \"\" if self . consider_3G_degraded : degraded_netgen = else : degraded_netgen = response = { } response [ '' ] = time ( ) + self . cache_timeout if os . path . exists ( self . modem ) and stat . S_ISCHR ( os . stat ( self . modem ) . st_mode ) : print ( \"\" + self . modem ) try : ", "answer": "ser = serial . Serial ("}, {"prompt": " from setuptools import setup , find_packages setup ( name = '' , py_modules = [ '' ] , version = '' , description = '' , license = '' , url = '' , download_url = '' , author = '' , author_email = '' , install_requires = [ '' ] , keywords = '' , classifiers = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , ", "answer": "] ,"}, {"prompt": " \"\"\"\"\"\" import logging from modularodm import Q from website . models import NodeLog , Node , RegistrationApproval from website . app import init_app from scripts import utils as script_utils from framework . mongo import database as db from framework . transactions . context import TokuTransaction logger = logging . getLogger ( __name__ ) logging . basicConfig ( level = logging . INFO ) def get_targets ( ) : \"\"\"\"\"\" logs = NodeLog . find ( Q ( '' , '' , '' ) | Q ( '' , '' , '' ) | Q ( '' , '' , '' ) | Q ( '' , '' , '' ) | Q ( '' , '' , '' ) | Q ( '' , '' , '' ) | Q ( '' , '' , '' ) | Q ( '' , '' , '' ) | Q ( '' , '' , '' ) | Q ( '' , '' , '' ) ) return logs def get_registered_from ( registration ) : \"\"\"\"\"\" if registration . registered_from : return registration . registered_from_id else : first_log_id = db [ '' ] . find_one ( { '' : registration . _id } ) [ '' ] [ ] log = NodeLog . load ( first_log_id ) return log . params . get ( '' ) or log . params . get ( '' ) def migrate_log ( logs ) : \"\"\"\"\"\" logs_count = logs . count ( ) count = for log in logs : count += node = log . params . get ( '' ) or log . params . get ( '' ) params_node = Node . load ( node ) if params_node . is_registration : log . params [ '' ] = get_registered_from ( params_node ) log . params [ '' ] = params_node . _id else : log . params [ '' ] = RegistrationApproval . load ( log . params [ '' ] ) . _get_registration ( ) . _id log . save ( ) logger . info ( '' . format ( count , logs_count , log . _id , log . action , log . params [ '' ] , log . params [ '' ] ) ) def main ( dry_run ) : logs = get_targets ( ) migrate_log ( logs ) if not dry_run : logger . info ( '' . format ( len ( logs ) ) ) else : ", "answer": "raise RuntimeError ( '' )"}, {"prompt": " import logging import os import random import sys import time logging . basicConfig ( level = logging . ERROR ) top_dir = os . path . abspath ( os . path . join ( os . path . dirname ( __file__ ) , os . pardir , os . pardir ) ) sys . path . insert ( , top_dir ) import futurist import six from taskflow import engines from taskflow . patterns import unordered_flow as uf from taskflow import task from taskflow . utils import threading_utils as tu class DelayedTask ( task . Task ) : def __init__ ( self , name ) : super ( DelayedTask , self ) . __init__ ( name = name ) self . _wait_for = random . random ( ) def execute ( self ) : print ( \"\" % ( self . name , tu . get_ident ( ) ) ) time . sleep ( self . _wait_for ) f1 = uf . Flow ( \"\" ) ", "answer": "f1 . add ( DelayedTask ( \"\" ) )"}, {"prompt": " from django . conf . urls import url from olympia . addons . urls import ADDON_ID from olympia . editors import views , views_themes urlpatterns = ( url ( r'' , views . home , name = '' ) , url ( r'' , views . queue , name = '' ) , url ( r'' , views . queue_nominated , name = '' ) , url ( r'' , views . queue_pending , name = '' ) , url ( r'' , views . queue_prelim , name = '' ) , url ( r'' , views . queue_fast_track , name = '' ) , url ( r'' , views . queue_moderated , name = '' ) , url ( r'' , views . application_versions_json , name = '' ) , url ( r'' , views . unlisted_queue , name = '' ) , url ( r'' , views . unlisted_queue_nominated , name = '' ) , url ( r'' , views . unlisted_queue_pending , name = '' ) , url ( r'' , views . unlisted_queue_prelim , name = '' ) , url ( r'' , views . unlisted_list , name = '' ) , url ( r'' , views . eventlog , name = '' ) , url ( r'' , views . eventlog_detail , name = '' ) , url ( r'' , views . reviewlog , name = '' ) , url ( r'' , views . beta_signed_log , name = '' ) , url ( r'' % ADDON_ID , views . queue_version_notes , name = '' ) , url ( r'' , views . queue_viewing , name = '' ) , url ( r'' , views . review_viewing , name = '' ) , url ( r'' % ADDON_ID , views . review , name = '' ) , url ( r'' , views . performance , name = '' ) , url ( r'' , views . motd , name = '' ) , url ( r'' , views . save_motd , name = '' ) , url ( r'' % ADDON_ID , views . abuse_reports , name = '' ) , url ( r'' , views . leaderboard , name = '' ) , url ( r'' % ADDON_ID , views . whiteboard , name = '' ) , url ( '' , views_themes . home , name = '' ) , url ( '' , views_themes . themes_list , name = '' ) , url ( '' , views_themes . themes_list , name = '' , kwargs = { '' : True } ) , url ( '' , views_themes . themes_list , ", "answer": "name = '' ,"}, {"prompt": " import pprint from uuid import uuid4 from twisted . internet . defer import Deferred , DeferredList , maybeDeferred from twisted . web . resource import Resource from twisted . internet import reactor from twisted . web import server from . base import BaseServer , LOGGER from . . resources import InterfaceResource , ExposedResource from . . aws import sdb_now from . . evaluateboolean import evaluateBoolean PRETTYPRINTER = pprint . PrettyPrinter ( indent = ) class InterfaceServer ( BaseServer ) : exposed_functions = [ ] exposed_function_resources = { } def __init__ ( self , aws_access_key_id , aws_secret_access_key , aws_sdb_reservation_domain , aws_s3_reservation_cache_bucket = None , aws_s3_http_cache_bucket = None , aws_s3_storage_bucket = None , aws_sdb_coordination_domain = None , max_simultaneous_requests = , max_requests_per_host_per_second = , max_simultaneous_requests_per_host = , port = , log_file = '' , log_directory = None , log_level = \"\" , name = None , time_offset = None ) : if name == None : name = \"\" % self . uuid resource = Resource ( ) interface_resource = InterfaceResource ( self ) resource . putChild ( \"\" , interface_resource ) self . function_resource = Resource ( ) resource . putChild ( \"\" , self . function_resource ) self . site_port = reactor . listenTCP ( port , server . Site ( resource ) ) BaseServer . __init__ ( self , aws_access_key_id , aws_secret_access_key , aws_s3_reservation_cache_bucket = aws_s3_reservation_cache_bucket , aws_s3_http_cache_bucket = aws_s3_http_cache_bucket , aws_sdb_reservation_domain = aws_sdb_reservation_domain , aws_s3_storage_bucket = aws_s3_storage_bucket , aws_sdb_coordination_domain = aws_sdb_coordination_domain , max_simultaneous_requests = max_simultaneous_requests , max_requests_per_host_per_second = max_requests_per_host_per_second , max_simultaneous_requests_per_host = max_simultaneous_requests_per_host , log_file = log_file , log_directory = log_directory , log_level = log_level , name = name , time_offset = time_offset , port = port ) def start ( self ) : reactor . callWhenRunning ( self . _start ) return self . start_deferred def _start ( self ) : deferreds = [ ] if self . time_offset is None : deferreds . append ( self . getTimeOffset ( ) ) d = DeferredList ( deferreds , consumeErrors = True ) d . addCallback ( self . _startCallback ) def _startCallback ( self , data ) : for row in data : if row [ ] == False : d = self . shutdown ( ) d . addCallback ( self . _startHandleError , row [ ] ) return d d = BaseServer . start ( self ) def shutdown ( self ) : deferreds = [ ] LOGGER . debug ( \"\" % self . name ) d = self . site_port . stopListening ( ) if isinstance ( d , Deferred ) : deferreds . append ( d ) if len ( deferreds ) > : d = DeferredList ( deferreds ) d . addCallback ( self . _shutdownCallback ) return d else : return self . _shutdownCallback ( None ) def _shutdownCallback ( self , data ) : return BaseServer . shutdown ( self ) def makeCallable ( self , func , interval = , name = None , expose = False ) : function_name = BaseServer . makeCallable ( self , func , interval = interval , name = name , expose = expose ) if expose : self . exposed_functions . append ( function_name ) er = ExposedResource ( self , function_name ) function_name_parts = function_name . split ( \"\" ) if len ( function_name_parts ) > : if function_name_parts [ ] in self . exposed_function_resources : r = self . exposed_function_resources [ function_name_parts [ ] ] else : r = Resource ( ) self . exposed_function_resources [ function_name_parts [ ] ] = r self . function_resource . putChild ( function_name_parts [ ] , r ) r . putChild ( function_name_parts [ ] , er ) else : self . function_resource . putChild ( function_name_parts [ ] , er ) LOGGER . info ( \"\" % function_name ) def createReservation ( self , function_name , ** kwargs ) : if not isinstance ( function_name , str ) : for key in self . functions : if self . functions [ key ] [ \"\" ] == function_name : function_name = key break if function_name not in self . functions : raise Exception ( \"\" % function_name ) function = self . functions [ function_name ] filtered_kwargs = { } for key in function [ \"\" ] : if key in kwargs : filtered_kwargs [ key ] = kwargs [ key ] else : raise Exception ( \"\" % ( key , function [ \"\" ] , function [ \"\" ] ) ) for key in function [ \"\" ] : if key in kwargs : filtered_kwargs [ key ] = kwargs [ key ] if function [ \"\" ] > : reserved_arguments = { } reserved_arguments [ \"\" ] = function_name reserved_arguments [ \"\" ] = sdb_now ( offset = self . time_offset ) reserved_arguments [ \"\" ] = reserved_arguments [ \"\" ] reserved_arguments [ \"\" ] = \"\" arguments = { } arguments . update ( reserved_arguments ) arguments . update ( filtered_kwargs ) uuid = uuid4 ( ) . hex LOGGER . debug ( \"\" % ( function_name , uuid ) ) a = self . sdb . putAttributes ( self . aws_sdb_reservation_domain , uuid , arguments ) a . addCallback ( self . _createReservationCallback , function_name , uuid ) a . addErrback ( self . _createReservationErrback , function_name , uuid ) if \"\" in kwargs and not evaluateBoolean ( kwargs [ \"\" ] ) : d = DeferredList ( [ a ] , consumeErrors = True ) else : LOGGER . debug ( \"\" % ( function_name , PRETTYPRINTER . pformat ( filtered_kwargs ) ) ) self . active_jobs [ uuid ] = True b = self . callExposedFunction ( function [ \"\" ] , filtered_kwargs , function_name , uuid = uuid ) d = DeferredList ( [ a , b ] , consumeErrors = True ) d . addCallback ( self . _createReservationCallback2 , function_name , uuid ) d . addErrback ( self . _createReservationErrback2 , function_name , uuid ) return d else : LOGGER . debug ( \"\" % ( function_name , PRETTYPRINTER . pformat ( filtered_kwargs ) ) ) d = self . callExposedFunction ( function [ \"\" ] , filtered_kwargs , function_name ) return d def _createReservationCallback ( self , data , function_name , uuid ) : LOGGER . error ( data ) LOGGER . debug ( \"\" % ( function_name , uuid ) ) return uuid def _createReservationErrback ( self , error , function_name , uuid ) : LOGGER . error ( \"\" % ( function_name , uuid , error ) ) return error def _createReservationCallback2 ( self , data , function_name , uuid ) : for row in data : if row [ ] == False : raise row [ ] if len ( data ) == : return { data [ ] [ ] : { } } else : return { data [ ] [ ] : data [ ] [ ] } def _createReservationErrback2 ( self , error , function_name , uuid ) : LOGGER . error ( \"\" % ( function_name , uuid , error ) ) return error def showReservation ( self , uuid ) : d = self . sdb . getAttributes ( self . aws_sdb_reservation_domain , uuid ) return d def executeReservation ( self , uuid ) : sql = \"\" % ( self . aws_sdb_reservation_domain , uuid ) LOGGER . debug ( \"\" % sql ) d = self . sdb . select ( sql ) d . addCallback ( self . _executeReservationCallback ) d . addErrback ( self . _executeReservationErrback ) return d def _executeReservationCallback ( self , data ) : if len ( data ) == : raise Exception ( \"\" ) uuid = data . keys ( ) [ ] ", "answer": "kwargs_raw = { }"}, {"prompt": " from __future__ import ( absolute_import , division , generators , nested_scopes , print_function , unicode_literals , with_statement ) import logging import select from pants . pantsd . pailgun_server import PailgunServer from pants . pantsd . service . pants_service import PantsService class PailgunService ( PantsService ) : \"\"\"\"\"\" def __init__ ( self , bind_addr , exiter_class , runner_class ) : \"\"\"\"\"\" super ( PailgunService , self ) . __init__ ( ) self . _logger = logging . getLogger ( __name__ ) self . _bind_addr = bind_addr self . _exiter_class = exiter_class self . _runner_class = runner_class self . _pailgun = None @ property def pailgun ( self ) : if not self . _pailgun : ", "answer": "self . _pailgun = self . _setup_pailgun ( )"}, {"prompt": " from flask import Flask , url_for from flaskext . odesk import odesk from mock import patch import unittest class ODeskTestCase ( unittest . TestCase ) : def setUp ( self ) : app = Flask ( __name__ ) app . config [ '' ] = '' app . config [ '' ] = '' app . config [ '' ] = '' app . register_module ( odesk , url_prefix = '' ) ctx = app . test_request_context ( ) ctx . push ( ) ", "answer": "self . app = app"}, {"prompt": " from pitchfork . setup_application import create_app from pitchfork . config import config from datetime import datetime from uuid import uuid4 import unittest import urlparse import re class PitchforkManageTests ( unittest . TestCase ) : def setUp ( self ) : check_db = re . search ( '' , config . MONGO_DATABASE ) if not check_db : test_db = '' % config . MONGO_DATABASE else : test_db = config . MONGO_DATABASE self . pitchfork , self . db = create_app ( test_db ) self . app = self . pitchfork . test_client ( ) self . app . get ( '' ) def tearDown ( self ) : self . db . sessions . remove ( ) self . db . settings . remove ( ) self . db . api_settings . remove ( ) self . db . history . remove ( ) self . db . forms . remove ( ) def setup_user_login ( self , session ) : session [ '' ] = '' session [ '' ] = uuid4 ( ) . hex session [ '' ] = '' session [ '' ] = '' session [ '' ] = True session [ '' ] = '' session [ '' ] = uuid4 ( ) . hex def setup_admin_login ( self , session ) : session [ '' ] = '' session [ '' ] = uuid4 ( ) . hex session [ '' ] = '' session [ '' ] = '' session [ '' ] = True session [ '' ] = '' session [ '' ] = uuid4 ( ) . hex def setup_useable_admin ( self ) : self . db . settings . update ( { } , { '' : { '' : { '' : '' , '' : '' , '' : '' } } } ) def setup_useable_history ( self ) : history = { '' : '' , '' : '' , '' : { '' : '' , '' : '' , '' : '' } , '' : '' , '' : datetime . now ( ) , '' : '' , '' : { '' : ( '' '' '' ) , '' : '' , '' : { '' : { '' : '' , '' : ( '' '' ) , '' : ( '' '' ) , '' : ( '' '' ) } } } , '' : { '' : { '' : { '' : '' , '' : , '' : ( '' '' ) , '' : ( '' '' ) } } , '' : { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' } , '' : } , '' : '' } self . db . history . insert ( history ) def setup_default_field ( self , form_name ) : data = { '' : '' , '' : True , '' : '' , '' : '' , '' : '' , '' : '' , '' : True , '' : None , '' : False , '' : '' , '' : } self . db . forms . update ( { '' : form_name } , { '' : { '' : data } } ) def retrieve_csrf_token ( self , data ) : temp = re . search ( '' , data ) if temp : token = re . search ( '' , temp . group ( ) ) if token : return token . group ( ) return '' \"\"\"\"\"\" def test_pf_history ( self ) : with self . app as c : with c . session_transaction ( ) as sess : self . setup_user_login ( sess ) response = c . get ( '' ) self . assertIn ( '' , response . data , '' ) self . assertIn ( '' , response . data , '' ) def test_pf_history_scrub ( self ) : self . setup_useable_history ( ) with self . app as c : with c . session_transaction ( ) as sess : self . setup_user_login ( sess ) response = c . get ( '' , follow_redirects = True ) self . assertIn ( '' , response . data , '' ) self . assertIn ( '' , response . data , '' ) history = self . db . history . find_one ( { '' : '' } ) assert history , '' def test_pf_history_scrub_no_history ( self ) : with self . app as c : with c . session_transaction ( ) as sess : self . setup_user_login ( sess ) response = c . get ( '' , follow_redirects = True ) self . assertIn ( '' , response . data , '' ) self . assertIn ( '' , response . data , '' ) def test_pf_favorites ( self ) : with self . app as c : with c . session_transaction ( ) as sess : self . setup_user_login ( sess ) response = c . get ( '' ) self . assertIn ( '' , response . data , '' ) \"\"\"\"\"\" def test_pf_manage_dcs_admin_perms ( self ) : with self . app as c : with c . session_transaction ( ) as sess : self . setup_admin_login ( sess ) response = c . get ( '' ) assert response . _status_code == , ( '' % response . _status_code ) self . assertIn ( '' , response . data , '' ) def test_pf_manage_dcs_user_perms ( self ) : with self . app as c : with c . session_transaction ( ) as sess : self . setup_user_login ( sess ) result = c . get ( '' ) assert result . _status_code == , ( '' % result . _status_code ) request_path = urlparse . urlparse ( result . headers . get ( '' ) ) . path self . assertEqual ( request_path , '' , '' % request_path ) \"\"\"\"\"\" def test_pf_manage_dcs_add ( self ) : with self . app as c : with c . session_transaction ( ) as sess : self . setup_admin_login ( sess ) response = c . get ( '' ) token = self . retrieve_csrf_token ( response . data ) data = { '' : token , '' : '' , '' : '' } response = c . post ( '' , data = data , follow_redirects = True ) self . assertIn ( '' , response . data , '' ) found_add = self . db . api_settings . find_one ( { '' : '' } ) assert found_add , '' def test_pf_manage_dcs_add_no_dcs ( self ) : self . db . api_settings . update ( { } , { '' : { '' : } } ) with self . app as c : with c . session_transaction ( ) as sess : self . setup_admin_login ( sess ) response = c . get ( '' ) token = self . retrieve_csrf_token ( response . data ) data = { '' : token , '' : '' , '' : '' } response = c . post ( '' , data = data , follow_redirects = True ) self . assertIn ( '' , response . data , '' ) found_add = self . db . api_settings . find_one ( { '' : '' } ) assert found_add , '' def test_pf_manage_dcs_add_dupe ( self ) : with self . app as c : with c . session_transaction ( ) as sess : self . setup_admin_login ( sess ) response = c . get ( '' ) token = self . retrieve_csrf_token ( response . data ) data = { '' : token , '' : '' , '' : '' } response = c . post ( '' , data = data , follow_redirects = True ) self . assertIn ( '' , response . data , '' ) self . assertIn ( '' , response . data , '' ) api_settings = self . db . api_settings . find_one ( ) dcs = api_settings . get ( '' ) count = for dc in dcs : if dc . get ( '' ) == '' : count += self . assertEquals ( count , , '' % count ) def test_pf_manage_dcs_add_bad_data ( self ) : with self . app as c : with c . session_transaction ( ) as sess : self . setup_admin_login ( sess ) response = c . get ( '' ) data = { '' : '' , '' : '' } response = c . post ( '' , data = data , follow_redirects = True ) self . assertIn ( ( '' '' ) , response . data , '' ) def test_pf_manage_dcs_remove ( self ) : with self . app as c : with c . session_transaction ( ) as sess : self . setup_admin_login ( sess ) response = c . get ( '' , follow_redirects = True ) self . assertIn ( '' , response . data , '' ) api_settings = self . db . api_settings . find_one ( ) dcs = api_settings . get ( '' ) count = for dc in dcs : if dc . get ( '' ) == '' : count += self . assertEquals ( count , , '' % count ) \"\"\"\"\"\" def test_pf_verbs_admin_perms ( self ) : with self . app as c : with c . session_transaction ( ) as sess : self . setup_admin_login ( sess ) response = c . get ( '' ) assert response . _status_code == , ( '' % response . _status_code ) self . assertIn ( '' , response . data , '' ) def test_pf_verbs_user_perms ( self ) : with self . app as c : with c . session_transaction ( ) as sess : self . setup_user_login ( sess ) result = c . get ( '' ) assert result . _status_code == , ( '' % result . _status_code ) request_path = urlparse . urlparse ( result . headers . get ( '' ) ) . path self . assertEqual ( request_path , '' , '' % request_path ) \"\"\"\"\"\" def test_pf_verbs_add ( self ) : with self . app as c : with c . session_transaction ( ) as sess : self . setup_admin_login ( sess ) response = c . get ( '' ) token = self . retrieve_csrf_token ( response . data ) data = { '' : token , '' : '' , '' : True } response = c . post ( '' , data = data , follow_redirects = True ) self . assertIn ( '' , response . data , '' ) found_add = self . db . api_settings . find_one ( { '' : '' } ) assert found_add , '' def test_pf_verbs_add_dupe ( self ) : with self . app as c : with c . session_transaction ( ) as sess : self . setup_admin_login ( sess ) response = c . get ( '' ) token = self . retrieve_csrf_token ( response . data ) data = { '' : token , '' : '' , '' : True } response = c . post ( '' , data = data , follow_redirects = True ) self . assertIn ( '' , response . data , '' ) api_settings = self . db . api_settings . find_one ( ) verbs = api_settings . get ( '' ) count = for verb in verbs : if verb . get ( '' ) == '' : count += self . assertEquals ( count , , ", "answer": "'' % count"}, {"prompt": " import itertools from oslo_config import cfg cells_opts = [ cfg . BoolOpt ( '' , default = False , help = \"\"\"\"\"\" ) , cfg . StrOpt ( '' , default = '' , help = \"\"\"\"\"\" ) , cfg . StrOpt ( '' , default = '' , help = \"\"\"\"\"\" , deprecated_for_removal = True ) , cfg . StrOpt ( '' , default = '' , help = \"\"\"\"\"\" ) , cfg . ListOpt ( '' , default = [ '' , '' ] , help = \"\"\"\"\"\" ) , cfg . IntOpt ( '' , default = , help = \"\"\"\"\"\" ) , cfg . FloatOpt ( '' , default = , help = \"\"\"\"\"\" ) , cfg . StrOpt ( '' , default = '' , choices = ( '' , '' ) , help = \"\"\"\"\"\" ) , cfg . IntOpt ( \"\" , default = , help = \"\"\"\"\"\" ) , cfg . IntOpt ( '' , default = , help = \"\"\"\"\"\" ) , cfg . IntOpt ( '' , default = , help = \"\"\"\"\"\" ) , ] mute_weigher_opts = [ cfg . FloatOpt ( '' , default = - , help = \"\"\"\"\"\" ) , ] ram_weigher_opts = [ cfg . FloatOpt ( '' , default = , help = \"\"\"\"\"\" ) , ] weigher_opts = [ cfg . FloatOpt ( '' , default = , help = \"\"\"\"\"\" ) , ] cell_manager_opts = [ cfg . StrOpt ( '' , default = '' , help = \"\"\"\"\"\" ) , cfg . IntOpt ( \"\" , default = , help = \"\"\"\"\"\" ) , cfg . IntOpt ( \"\" , default = , help = \"\"\"\"\"\" ) ] cell_messaging_opts = [ cfg . IntOpt ( '' , default = , help = \"\"\"\"\"\" ) , cfg . StrOpt ( '' , default = '' , help = \"\"\"\"\"\" ) ] cell_rpc_driver_opts = [ cfg . StrOpt ( '' , default = '' , help = \"\"\"\"\"\" ) ] ", "answer": "cell_scheduler_opts = ["}, {"prompt": " \"\"\"\"\"\" import os import sys __all__ = [ '' , '' , '' ] try : from imp import cache_from_source except ImportError : def cache_from_source ( py_file , debug = __debug__ ) : ext = debug and '' or '' return py_file + ext try : callable = callable except NameError : from collections import Callable def callable ( obj ) : return isinstance ( obj , Callable ) try : fsencode = os . fsencode except AttributeError : def fsencode ( filename ) : if isinstance ( filename , bytes ) : return filename ", "answer": "elif isinstance ( filename , str ) :"}, {"prompt": " \"\"\"\"\"\" from time import time from types import MethodType from inspect import getmembers , ismethod from re import match from threading import Lock from traceback import extract_stack from pyon . util import log class _Wrapper ( object ) : \"\"\"\"\"\" def __init__ ( self , timer , function , name , logger ) : self . _original = function self . _timer = timer self . _name = name self . _simultaneous = self . _log = logger def proxy ( self , * a , ** b ) : if self . _log : for frame in reversed ( extract_stack ( ) ) : file = frame [ ] if not file . endswith ( '' ) : line = frame [ ] self . _log . info ( self . _name + '' + file + '' + str ( line ) ) break tuple = extract_stack ( ) [ - ] self . _simultaneous += start = self . _timer . _start_timing ( ) try : return self . _original ( * a , ** b ) finally : self . _timer . _stop_timing ( self , start ) self . _simultaneous -= def __str__ ( self ) : return self . _name class _Call ( object ) : \"\"\"\"\"\" def __init__ ( self , index ) : self . proportional_time = self . _index = index def add_time ( self , elapsed ) : self . proportional_time += elapsed def start ( self , time ) : self . _start_time = time def stop ( self , time ) : self . clock_time = time - self . _start_time def __str__ ( self ) : return '' % self . _index def __repr__ ( self ) : return self . __str__ ( ) class MonkeyTimer ( object ) : \"\"\"\"\"\" def __init__ ( self , nooverlap = False ) : self . _proportional_time = { } self . _clock_time = { } self . _total_count = { } self . _lock = Lock ( ) self . _last_tick = None self . _currently_running = [ ] self . _max_simultaneous = self . _call_index = self . logger = None def set_logger ( self , logger ) : \"\"\"\"\"\" self . logger = logger def _add_time ( self , elapsed ) : running_count = len ( self . _currently_running ) if running_count : self . _max_simultaneous = max ( self . _max_simultaneous , running_count ) delta = elapsed / running_count for call in self . _currently_running : call . add_time ( delta ) def _start_timing ( self ) : self . _lock . acquire ( ) this_tick = time ( ) new_call = _Call ( self . _call_index ) self . _call_index += new_call . start ( this_tick ) if self . _last_tick : self . _add_time ( this_tick - self . _last_tick ) self . _last_tick = this_tick self . _currently_running . append ( new_call ) self . _lock . release ( ) return new_call ", "answer": "def _stop_timing ( self , wrapper , call ) :"}, {"prompt": " from functools import wraps import json import re import time import six import pyrax from pyrax . client import BaseClient from pyrax . cloudloadbalancers import CloudLoadBalancer import pyrax . exceptions as exc from pyrax . manager import BaseManager from pyrax . resource import BaseResource import pyrax . utils as utils DEFAULT_TIMEOUT = DEFAULT_DELAY = DEFAULT_RETRY = def assure_domain ( fnc ) : @ wraps ( fnc ) def _wrapped ( self , domain , * args , ** kwargs ) : if not isinstance ( domain , CloudDNSDomain ) : try : domain = self . _manager . get ( domain ) except exc . NotFound : domain = self . _manager . find ( name = domain ) return fnc ( self , domain , * args , ** kwargs ) return _wrapped class CloudDNSRecord ( BaseResource ) : \"\"\"\"\"\" GET_DETAILS = False type = None name = None data = None priority = None ttl = None comment = None def update ( self , data = None , priority = None , ttl = None , comment = None ) : \"\"\"\"\"\" return self . manager . update_record ( self . domain_id , self , data = data , priority = priority , ttl = ttl , comment = comment ) def get ( self ) : \"\"\"\"\"\" return self . manager . get_record ( self . domain_id , self ) def delete ( self ) : \"\"\"\"\"\" return self . manager . delete_record ( self . domain_id , self ) class CloudDNSDomain ( BaseResource ) : \"\"\"\"\"\" def delete ( self , delete_subdomains = False ) : \"\"\"\"\"\" self . manager . delete ( self , delete_subdomains = delete_subdomains ) def changes_since ( self , date_or_datetime ) : \"\"\"\"\"\" return self . manager . changes_since ( self , date_or_datetime ) def export ( self ) : \"\"\"\"\"\" return self . manager . export_domain ( self ) def update ( self , emailAddress = None , ttl = None , comment = None ) : \"\"\"\"\"\" return self . manager . update_domain ( self , emailAddress = emailAddress , ttl = ttl , comment = comment ) def list_subdomains ( self , limit = None , offset = None ) : \"\"\"\"\"\" return self . manager . list_subdomains ( self , limit = limit , offset = offset ) def list_records ( self , limit = None , offset = None ) : \"\"\"\"\"\" return self . manager . list_records ( self , limit = limit , offset = offset ) def search_records ( self , record_type , name = None , data = None ) : \"\"\"\"\"\" return self . manager . search_records ( self , record_type = record_type , name = name , data = data ) def find_record ( self , record_type , name = None , data = None ) : \"\"\"\"\"\" matches = self . manager . search_records ( self , record_type = record_type , name = name , data = data ) if not matches : raise exc . DomainRecordNotFound elif len ( matches ) > : raise exc . DomainRecordNotUnique return matches [ ] def add_records ( self , records ) : \"\"\"\"\"\" return self . manager . add_records ( self , records ) add_record = add_records def get_record ( self , record ) : \"\"\"\"\"\" return self . manager . get_record ( self , record ) def update_record ( self , record , data = None , priority = None , ttl = None , comment = None ) : \"\"\"\"\"\" return self . manager . update_record ( self , record , data = data , priority = priority , ttl = ttl , comment = comment ) def update_records ( self , records ) : \"\"\"\"\"\" return self . manager . update_records ( self , records ) def delete_record ( self , record ) : \"\"\"\"\"\" return self . manager . delete_record ( self , record ) class CloudDNSPTRRecord ( object ) : \"\"\"\"\"\" def __init__ ( self , data = None , device = None ) : self . type = self . id = self . data = self . name = None self . ttl = self . comment = None if data : for key , val in data . items ( ) : setattr ( self , key , val ) self . device = device def delete ( self ) : \"\"\"\"\"\" return pyrax . cloud_dns . delete_ptr_records ( self . device , self . data ) def __repr__ ( self ) : reprkeys = ( \"\" , \"\" , \"\" , \"\" ) info = \"\" . join ( \"\" % ( key , getattr ( self , key ) ) for key in reprkeys ) return \"\" % ( self . __class__ . __name__ , info ) class CloudDNSManager ( BaseManager ) : def __init__ ( self , api , resource_class = None , response_key = None , plural_response_key = None , uri_base = None ) : super ( CloudDNSManager , self ) . __init__ ( api , resource_class = resource_class , response_key = response_key , plural_response_key = plural_response_key , uri_base = uri_base ) self . _paging = { \"\" : { } , \"\" : { } , \"\" : { } } self . _reset_paging ( service = \"\" ) self . _timeout = DEFAULT_TIMEOUT self . _delay = DEFAULT_DELAY def _create_body ( self , name , emailAddress , ttl = , comment = None , subdomains = None , records = None ) : \"\"\"\"\"\" if subdomains is None : subdomains = [ ] if records is None : records = [ ] body = { \"\" : [ { \"\" : name , \"\" : emailAddress , \"\" : ttl , \"\" : comment , \"\" : { \"\" : subdomains } , \"\" : { \"\" : records } , } ] } return body def _set_timeout ( self , timeout ) : \"\"\"\"\"\" self . _timeout = timeout def _set_delay ( self , delay ) : \"\"\"\"\"\" self . _delay = delay def _reset_paging ( self , service , body = None ) : \"\"\"\"\"\" if service == \"\" : for svc in self . _paging . keys ( ) : svc_dct = self . _paging [ svc ] svc_dct [ \"\" ] = svc_dct [ \"\" ] = None svc_dct [ \"\" ] = None return svc_dct = self . _paging [ service ] svc_dct [ \"\" ] = svc_dct [ \"\" ] = None svc_dct [ \"\" ] = None if not body : return svc_dct [ \"\" ] = body . get ( \"\" ) links = body . get ( \"\" ) uri_base = self . uri_base if links : for link in links : href = link [ \"\" ] pos = href . index ( uri_base ) page_uri = href [ pos - : ] if link [ \"\" ] == \"\" : svc_dct [ \"\" ] = page_uri elif link [ \"\" ] == \"\" : svc_dct [ \"\" ] = page_uri def _get_pagination_qs ( self , limit , offset ) : pagination_items = [ ] if limit is not None : pagination_items . append ( \"\" % limit ) if offset is not None : pagination_items . append ( \"\" % offset ) qs = \"\" . join ( pagination_items ) qs = \"\" % qs if qs else \"\" return qs def list ( self , limit = None , offset = None ) : \"\"\"\"\"\" uri = \"\" % ( self . uri_base , self . _get_pagination_qs ( limit , offset ) ) return self . _list ( uri ) def _list ( self , uri , obj_class = None , list_all = False ) : \"\"\"\"\"\" resp , resp_body = self . _retry_get ( uri ) if obj_class is None : obj_class = self . resource_class data = resp_body [ self . plural_response_key ] ret = [ obj_class ( self , res , loaded = False ) for res in data if res ] self . _reset_paging ( \"\" , resp_body ) if list_all : dom_paging = self . _paging . get ( \"\" , { } ) while dom_paging . get ( \"\" ) : next_uri = dom_paging . get ( \"\" ) ret . extend ( self . _list ( uri = next_uri , obj_class = obj_class , list_all = False ) ) return ret def list_previous_page ( self ) : \"\"\"\"\"\" uri = self . _paging . get ( \"\" , { } ) . get ( \"\" ) if uri is None : raise exc . NoMoreResults ( \"\" \"\" ) return self . _list ( uri ) def list_next_page ( self ) : \"\"\"\"\"\" uri = self . _paging . get ( \"\" , { } ) . get ( \"\" ) if uri is None : raise exc . NoMoreResults ( \"\" \"\" ) return self . _list ( uri ) def _get ( self , uri ) : \"\"\"\"\"\" uri = \"\" % uri resp , body = self . _retry_get ( uri ) body [ \"\" ] = [ ] return self . resource_class ( self , body , loaded = True ) def _retry_get ( self , uri ) : \"\"\"\"\"\" for i in six . moves . range ( DEFAULT_RETRY ) : resp , body = self . api . method_get ( uri ) if body : return resp , body raise exc . ServiceResponseFailure ( \"\" \"\" ) def _async_call ( self , uri , body = None , method = \"\" , error_class = None , has_response = True , * args , ** kwargs ) : \"\"\"\"\"\" api_methods = { \"\" : self . _retry_get , \"\" : self . api . method_post , \"\" : self . api . method_put , \"\" : self . api . method_delete , } api_method = api_methods [ method ] try : if body is None : resp , resp_body = api_method ( uri , * args , ** kwargs ) else : resp , resp_body = api_method ( uri , body = body , * args , ** kwargs ) except Exception as e : if error_class : raise error_class ( e ) else : raise callbackURL = resp_body [ \"\" ] . split ( \"\" ) [ - ] massagedURL = \"\" % callbackURL start = time . time ( ) timed_out = False while ( resp_body [ \"\" ] == \"\" ) and not timed_out : resp_body = None while resp_body is None and not timed_out : resp , resp_body = self . _retry_get ( massagedURL ) if self . _timeout : timed_out = ( ( time . time ( ) - start ) > self . _timeout ) time . sleep ( self . _delay ) if timed_out : raise exc . DNSCallTimedOut ( \"\" \"\" % ( uri , self . _timeout ) ) if error_class and ( resp_body [ \"\" ] == \"\" ) : self . _process_async_error ( resp_body , error_class ) if has_response : ret = resp , resp_body [ \"\" ] else : ret = resp , resp_body try : resp_body = json . loads ( resp_body ) except Exception : pass return ret def _process_async_error ( self , resp_body , error_class ) : \"\"\"\"\"\" def _fmt_error ( err ) : details = err . get ( \"\" , \"\" ) . replace ( \"\" , \"\" ) if not details : details = err . get ( \"\" , \"\" ) return \"\" % ( details , err . get ( \"\" , \"\" ) ) error = resp_body . get ( \"\" , \"\" ) if \"\" in error : faults = error . get ( \"\" , { } ) . get ( \"\" , [ ] ) msgs = [ _fmt_error ( fault ) for fault in faults ] msg = \"\" . join ( msgs ) else : msg = _fmt_error ( error ) raise error_class ( msg ) def _create ( self , uri , body , records = None , subdomains = None , return_none = False , return_raw = False , ** kwargs ) : \"\"\"\"\"\" self . run_hooks ( \"\" , body , ** kwargs ) resp , resp_body = self . _async_call ( uri , body = body , method = \"\" , error_class = exc . DomainCreationFailed ) response_body = resp_body [ self . response_key ] [ ] return self . resource_class ( self , response_body ) def delete ( self , domain , delete_subdomains = False ) : \"\"\"\"\"\" uri = \"\" % ( self . uri_base , utils . get_id ( domain ) ) if delete_subdomains : uri = \"\" % uri resp , resp_body = self . _async_call ( uri , method = \"\" , error_class = exc . DomainDeletionFailed , has_response = False ) def findall ( self , ** kwargs ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " import logging import os import sys from nose2 . compat import unittest from nose2 import events , loader , runner , session , util log = logging . getLogger ( __name__ ) __unittest = True class PluggableTestProgram ( unittest . TestProgram ) : \"\"\"\"\"\" sessionClass = session . Session _currentSession = None loaderClass = loader . PluggableTestLoader runnerClass = runner . PluggableTestRunner defaultPlugins = ( '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , ) excludePlugins = ( ) def __init__ ( self , ** kw ) : plugins = kw . pop ( '' , [ ] ) exclude = kw . pop ( '' , [ ] ) hooks = kw . pop ( '' , [ ] ) self . defaultPlugins = list ( self . defaultPlugins ) self . excludePlugins = list ( self . excludePlugins ) self . extraHooks = hooks self . defaultPlugins . extend ( plugins ) self . excludePlugins . extend ( exclude ) super ( PluggableTestProgram , self ) . __init__ ( ** kw ) def parseArgs ( self , argv ) : \"\"\"\"\"\" self . session = self . sessionClass ( ) self . __class__ . _currentSession = self . session self . argparse = self . session . argparse self . testLoader = self . loaderClass ( self . session ) self . session . testLoader = self . testLoader self . setInitialArguments ( ) cfg_args , argv = self . argparse . parse_known_args ( argv [ : ] ) self . handleCfgArgs ( cfg_args ) self . argparse . add_argument ( '' , nargs = '' ) self . argparse . add_argument ( '' , '' , action = '' , help = ( '' ) ) args , argv = self . argparse . parse_known_args ( argv ) if argv : self . argparse . error ( \"\" % '' . join ( argv ) ) self . handleArgs ( args ) self . createTests ( ) def setInitialArguments ( self ) : \"\"\"\"\"\" self . argparse . add_argument ( '' , '' , default = None , help = \"\" ) self . argparse . add_argument ( '' , '' , '' , help = '' ) self . argparse . add_argument ( '' , '' , nargs = '' , action = '' , default = [ '' , '' ] , help = \"\" \"\" ) self . argparse . add_argument ( '' , action = '' , dest = '' , const = False , default = True , help = \"\" ) self . argparse . add_argument ( '' , action = '' , dest = '' , const = False , default = True , help = \"\" \"\" ) self . argparse . add_argument ( '' , action = '' , dest = '' , default = [ ] , help = \"\" ) self . argparse . add_argument ( '' , action = '' , dest = '' , default = [ ] , help = \"\" ) self . argparse . add_argument ( '' , '' , action = '' , default = , help = \"\" ) self . argparse . add_argument ( '' , action = '' , dest = '' , const = ) self . argparse . add_argument ( '' , default = logging . WARN , help = '' ) def handleCfgArgs ( self , cfg_args ) : \"\"\"\"\"\" self . session . logLevel = util . parse_log_level ( cfg_args . log_level ) logging . basicConfig ( level = self . session . logLevel ) log . debug ( '' , cfg_args . log_level ) if cfg_args . verbose : self . session . verbosity += cfg_args . verbose self . session . startDir = cfg_args . start_dir if cfg_args . top_level_directory : self . session . topLevelDir = cfg_args . top_level_directory self . session . loadConfigFiles ( * self . findConfigFiles ( cfg_args ) ) self . session . setStartDir ( ) self . session . prepareSysPath ( ) if cfg_args . load_plugins : self . defaultPlugins . extend ( cfg_args . plugins ) self . excludePlugins . extend ( cfg_args . exclude_plugins ) ", "answer": "self . loadPlugins ( )"}, {"prompt": " import unittest import tornado . testing from glob import glob def all ( ) : test_modules = list ( map ( lambda x : x . rstrip ( '' ) . replace ( '' , '' ) , glob ( '' ) + glob ( '' ) ) ) return unittest . defaultTestLoader . loadTestsFromNames ( test_modules ) ", "answer": "if __name__ == \"\" :"}, {"prompt": " import os , sys sys . path . insert ( , os . path . join ( sys . path [ ] , '' ) ) import pibrella if sys . version [ : ] == '' : import unittest2 as unittest else : import unittest class TestAASanity ( unittest . TestCase ) : def test_outputexists ( self ) : \"\"\"\"\"\" self . assertEqual ( isinstance ( pibrella . output . e , pibrella . Output ) , True ) self . assertEqual ( isinstance ( pibrella . output . f , pibrella . Output ) , True ) self . assertEqual ( isinstance ( pibrella . output . g , pibrella . Output ) , True ) self . assertEqual ( isinstance ( pibrella . output . h , pibrella . Output ) , True ) def test_output_index ( self ) : \"\"\"\"\"\" self . assertEqual ( pibrella . output . e , pibrella . output [ ] ) self . assertEqual ( pibrella . output . f , pibrella . output [ ] ) self . assertEqual ( pibrella . output . g , pibrella . output [ ] ) self . assertEqual ( pibrella . output . h , pibrella . output [ ] ) class TestBBInput ( unittest . TestCase ) : def test_outputwrite ( self ) : \"\"\"\"\"\" ", "answer": "pibrella . output . e . write ( )"}, {"prompt": " from __future__ import unicode_literals from django . utils import six from djblets . testing . decorators import add_fixtures from djblets . webapi . errors import DOES_NOT_EXIST , PERMISSION_DENIED from reviewboard . webapi . resources import resources from reviewboard . webapi . tests . base import BaseWebAPITestCase from reviewboard . webapi . tests . mimetypes import ( watched_review_group_item_mimetype , watched_review_group_list_mimetype ) from reviewboard . webapi . tests . mixins import BasicTestsMetaclass from reviewboard . webapi . tests . urls import ( get_review_group_item_url , ", "answer": "get_watched_review_group_item_url ,"}, {"prompt": " \"\"\"\"\"\" from cafe . drivers . unittest . decorators import tags from cloudcafe . compute . common . exceptions import ItemNotFound from cloudroast . compute . fixtures import ComputeFixture class ImagesMetadataNegativeTest ( ComputeFixture ) : @ tags ( type = '' , net = '' ) def test_list_image_metadata_for_nonexistent_image ( self ) : \"\"\"\"\"\" with self . assertRaises ( ItemNotFound ) : ", "answer": "self . images_client . list_image_metadata ( )"}, {"prompt": " from flask import Flask , url_for , request , render_template from app import app @ app . route ( '' ) def hello ( ) : url = url_for ( '' ) ; link = '' + url + '' ; return link ; @ app . route ( '' ) def about ( ) : ", "answer": "return '' ;"}, {"prompt": " from __future__ import ( absolute_import , division , generators , nested_scopes , print_function , unicode_literals , with_statement ) import os import subprocess from contextlib import contextmanager from shutil import rmtree from pants . base . build_environment import get_buildroot from pants_test . pants_run_integration_test import PantsRunIntegrationTest class Bundles ( object ) : \"\"\"\"\"\" phrase_path = '' bundle_dir_prefix = '' class Bundle ( object ) : def __init__ ( self , spec , text ) : self . spec = spec self . text = text def __hash__ ( self ) : return hash ( ( self . spec , self . text ) ) @ property def full_spec ( self ) : return '' . format ( project = Bundles . phrase_path , name = self . spec ) lesser_of_two = Bundle ( '' , \"\" ) once_upon_a_time = Bundle ( '' , \"\" ) ten_thousand = Bundle ( '' , \"\" ) there_was_a_duck = Bundle ( '' , \"\" ) all_bundles = [ lesser_of_two , once_upon_a_time , ten_thousand , there_was_a_duck ] class BundleIntegrationTest ( PantsRunIntegrationTest ) : \"\"\"\"\"\" def _bundle_path ( self , bundle ) : return os . path . join ( get_buildroot ( ) , '' , '' . format ( prefix = Bundles . bundle_dir_prefix , name = bundle ) ) @ contextmanager def _handle_bundles ( self , names ) : \"\"\"\"\"\" paths = [ self . _bundle_path ( name ) for name in names ] jars = [ '' . format ( name = name ) for name in names ] yield ( paths , jars ) missing = [ ] for path in paths : if os . path . exists ( path ) : rmtree ( path ) else : missing . append ( path ) self . assertFalse ( missing , \"\" . format ( missing = '' . join ( missing ) ) ) def _test_bundle_existences ( self , args , bundles , config = None ) : all_bundles = set ( bundle . spec for bundle in Bundles . all_bundles ) all_paths = [ self . _bundle_path ( bundle ) for bundle in all_bundles ] names = [ bundle . spec for bundle in bundles ] outputs = [ bundle . text for bundle in bundles ] for path in all_paths : if os . path . exists ( path ) : rmtree ( path ) with self . _handle_bundles ( names ) as ( paths , jars ) : with self . pants_results ( [ '' ] + args , config = config ) as pants_run : self . assert_success ( pants_run ) for path , jar , expected in zip ( paths , jars , outputs ) : java_run = subprocess . Popen ( [ '' , '' , jar ] , stdout = subprocess . PIPE , cwd = path ) java_retcode = java_run . wait ( ) java_out = java_run . stdout . read ( ) self . assertEquals ( java_retcode , ) self . assertTrue ( expected in java_out , \"\" . format ( output = expected , jar = jar , stdout = java_out ) ) lingering = [ path for path in all_paths if os . path . exists ( path ) ] self . assertTrue ( not lingering , \"\" . format ( bundles = '' . join ( lingering ) ) ) def test_single_run ( self ) : \"\"\"\"\"\" self . _test_bundle_existences ( [ Bundles . lesser_of_two . full_spec ] , [ Bundles . lesser_of_two ] , ) def test_double_run ( self ) : \"\"\"\"\"\" ", "answer": "self . _test_bundle_existences ("}, {"prompt": " \"\"\"\"\"\" from focus import common from focus . parser . lexer import SettingLexer from focus . parser . parser import SettingParser , ParseError __all__ = ( '' , '' , '' , '' ) def parse_config ( filename , header ) : \"\"\"\"\"\" parser = SettingParser ( filename ) if parser . header != header : header_value = parser . header or '' raise ParseError ( u\"\" ", "answer": ". format ( common . from_utf8 ( header_value ) , header ) )"}, {"prompt": " import copy import cgi import itertools import os from SimpleHTTPServer import SimpleHTTPRequestHandler from testrunner import testhelp from testutils import sock_utils from conary_test import recipes from conary_test . auth_helper import AuthHelper from conary import conarycfg , versions , trove from conary . build import use from conary . deps import deps from conary . lib import httputils from conary . repository import errors , netclient from conary . server . server import HTTPServer class AclTest ( AuthHelper ) : def testAddAcls ( self ) : label = versions . Label ( \"\" ) self . openRepository ( ) repos = self . getRepositoryClient ( ) self . addUserAndRole ( repos , label , \"\" , \"\" ) repos . addAcl ( label , \"\" , \"\" , label ) repos . setRoleCanMirror ( label , \"\" , True ) repos . setRoleCanMirror ( label , \"\" , False ) self . addUserAndRole ( repos , label , \"\" , \"\" ) repos . addAcl ( label , \"\" , \"\" , label , write = True ) repos . setRoleCanMirror ( label , \"\" , True ) repos . setRoleCanMirror ( label , \"\" , False ) self . addUserAndRole ( repos , label , \"\" , \"\" ) repos . addAcl ( label , \"\" , \"\" , label , write = True ) repos . addAcl ( label , \"\" , \"\" , label , write = True , remove = True ) repos . setRoleIsAdmin ( label , '' , True ) @ testhelp . context ( '' ) def testBasicAcls ( self ) : rootLabel = versions . Label ( \"\" ) branchLabel = versions . Label ( \"\" ) rootBranch = versions . VersionFromString ( '' ) self . makeSourceTrove ( '' , recipes . doubleRecipe1 ) p = self . build ( recipes . doubleRecipe1 , \"\" ) repos = self . getRepositoryClient ( ) limitedRepos = self . setupUser ( repos , rootLabel , '' , '' , '' , branchLabel ) repos . deleteUserByName ( rootLabel , '' ) branchRepos = self . setupEntitlement ( repos , \"\" , \"\" , rootLabel , None , branchLabel , withClass = True ) [ ] runtimeRepos = self . setupUser ( repos , rootLabel , '' , '' , '' , None ) repeatRepos = self . setupUser ( repos , rootLabel , '' , '' , '' , None ) repos . addAcl ( rootLabel , '' , '' , None , False , False ) self . addUserAndRole ( repos , rootLabel , '' , '' ) taRepos = self . getRepositoryClient ( user = '' , password = '' ) repos . addTroveAccess ( '' , [ p . getNameVersionFlavor ( ) ] ) both = [ '' , '' , '' ] runtime = [ '' ] assert ( set ( repos . troveNames ( rootLabel ) ) == set ( both ) ) assert ( limitedRepos . troveNames ( rootLabel ) == [ ] ) assert ( branchRepos . troveNames ( rootLabel ) == [ ] ) assert ( runtimeRepos . troveNames ( rootLabel ) == runtime ) assert ( repeatRepos . troveNames ( rootLabel ) == runtime ) assert ( taRepos . troveNames ( rootLabel ) == runtime ) self . mkbranch ( self . cfg . buildLabel , branchLabel , '' ) branchVersion = versions . VersionFromString ( '' ) oldLabel = self . cfg . buildLabel self . cfg . buildLabel = branchLabel self . updateSourceTrove ( '' , recipes . doubleRecipe1_1 ) double1_1 = self . build ( recipes . doubleRecipe1_1 , \"\" ) self . cfg . buildLabel = oldLabel repos . addTroveAccess ( '' , [ double1_1 . getNameVersionFlavor ( ) ] ) assert ( { } . fromkeys ( repos . troveNames ( branchLabel ) ) == { } . fromkeys ( both ) ) assert ( limitedRepos . troveNames ( branchLabel ) == runtime ) assert ( { } . fromkeys ( branchRepos . troveNames ( branchLabel ) ) == { } . fromkeys ( both ) ) assert ( runtimeRepos . troveNames ( branchLabel ) == runtime ) assert ( taRepos . troveNames ( rootLabel ) == runtime ) full = { '' : [ '' , '' , ] , '' : [ '' , '' , ] , '' : [ '' , '' , '' , ] , } d = repos . getTroveVersionList ( '' , { '' : None , '' : None , '' : None } ) self . cmpTroveVersionList ( d , full ) d = repos . getTroveVersionList ( '' , { None : None } ) self . cmpTroveVersionList ( d , full ) d = limitedRepos . getTroveVersionList ( '' , { '' : None , '' : None } ) self . cmpTroveVersionList ( d , { '' : full [ '' ] [ : ] } ) d = branchRepos . getTroveVersionList ( '' , { None : None } ) self . cmpTroveVersionList ( d , { '' : full [ '' ] [ : ] , '' : full [ '' ] [ : ] , '' : full [ '' ] [ : ] } ) d = runtimeRepos . getTroveVersionList ( '' , { None : None } ) self . cmpTroveVersionList ( d , { '' : full [ '' ] } ) d = repeatRepos . getTroveVersionList ( '' , { None : None } ) self . cmpTroveVersionList ( d , { '' : full [ '' ] } ) d = taRepos . getTroveVersionList ( '' , { None : None } ) self . cmpTroveVersionList ( d , { '' : full [ '' ] } ) full = { '' : [ '' ] , '' : [ '' ] , '' : [ '' ] } q = { None : { self . cfg . buildLabel : None } } d = repos . getTroveVersionsByLabel ( q ) self . cmpTroveVersionList ( d , full ) d = limitedRepos . getTroveVersionsByLabel ( q ) assert ( d == { } ) d = branchRepos . getTroveVersionsByLabel ( q ) assert ( d == { } ) d = runtimeRepos . getTroveVersionsByLabel ( q ) self . cmpTroveVersionList ( d , { '' : full [ '' ] } ) d = repeatRepos . getTroveVersionsByLabel ( q ) self . cmpTroveVersionList ( d , { '' : full [ '' ] } ) d = taRepos . getTroveVersionsByLabel ( q ) self . cmpTroveVersionList ( d , { '' : full [ '' ] } ) full = { '' : [ '' ] , '' : [ '' ] , '' : [ '' , '' ] } q = { None : { branchLabel : None } } d = repos . getTroveVersionsByLabel ( q ) self . cmpTroveVersionList ( d , full ) d = limitedRepos . getTroveVersionsByLabel ( q ) self . cmpTroveVersionList ( d , { '' : full [ '' ] } ) d = branchRepos . getTroveVersionsByLabel ( q ) self . cmpTroveVersionList ( d , full ) d = runtimeRepos . getTroveVersionsByLabel ( q ) self . cmpTroveVersionList ( d , { '' : full [ '' ] } ) d = repeatRepos . getTroveVersionsByLabel ( q ) self . cmpTroveVersionList ( d , { '' : full [ '' ] } ) d = taRepos . getTroveVersionsByLabel ( q ) self . cmpTroveVersionList ( d , { '' : full [ '' ] } ) full = { '' : [ '' , '' ] , '' : [ '' , '' ] , '' : [ '' , '' ] , } d = repos . getAllTroveLeaves ( '' , { None : None } ) self . cmpTroveVersionList ( d , full ) d = limitedRepos . getAllTroveLeaves ( '' , { None : None } ) self . cmpTroveVersionList ( d , { '' : full [ '' ] [ : ] } ) d = branchRepos . getAllTroveLeaves ( '' , { None : None } ) self . cmpTroveVersionList ( d , { '' : full [ '' ] [ : ] , '' : full [ '' ] [ : ] , '' : full [ '' ] [ : ] , } ) d = runtimeRepos . getAllTroveLeaves ( '' , { None : None } ) self . cmpTroveVersionList ( d , { '' : full [ '' ] } ) d = taRepos . getAllTroveLeaves ( '' , { None : None } ) self . cmpTroveVersionList ( d , { '' : full [ '' ] } ) full = { '' : [ '' ] , '' : [ '' ] , '' : [ '' ] , } qd = { None : { self . cfg . buildLabel : None } } d = repos . getTroveLeavesByLabel ( qd ) self . cmpTroveVersionList ( d , full ) d = limitedRepos . getTroveLeavesByLabel ( qd ) assert ( d == { } ) d = branchRepos . getTroveLeavesByLabel ( qd ) assert ( d == { } ) d = runtimeRepos . getTroveLeavesByLabel ( qd ) self . cmpTroveVersionList ( d , { '' : full [ '' ] } ) d = repeatRepos . getTroveLeavesByLabel ( qd ) self . cmpTroveVersionList ( d , { '' : full [ '' ] } ) d = taRepos . getTroveLeavesByLabel ( qd ) self . cmpTroveVersionList ( d , { '' : full [ '' ] } ) full = { '' : [ '' ] , '' : [ '' ] , '' : [ '' ] , } qd = { None : { branchLabel : None } } d = repos . getTroveLeavesByLabel ( qd ) self . cmpTroveVersionList ( d , full ) d = limitedRepos . getTroveLeavesByLabel ( qd ) self . cmpTroveVersionList ( d , { '' : full [ '' ] } ) d = branchRepos . getTroveLeavesByLabel ( qd ) self . cmpTroveVersionList ( d , full ) d = runtimeRepos . getTroveLeavesByLabel ( qd ) self . cmpTroveVersionList ( d , { '' : full [ '' ] } ) d = repeatRepos . getTroveLeavesByLabel ( qd ) self . cmpTroveVersionList ( d , { '' : full [ '' ] } ) d = taRepos . getTroveLeavesByLabel ( qd ) self . cmpTroveVersionList ( d , { '' : full [ '' ] } ) q = { '' : { branchVersion : None } , '' : { rootBranch : None } } full = { '' : [ '' ] , '' : [ '' ] } d = repos . getTroveLeavesByBranch ( q ) self . cmpTroveVersionList ( d , full ) d = limitedRepos . getTroveLeavesByBranch ( q ) assert ( d == { } ) d = branchRepos . getTroveLeavesByBranch ( q ) self . cmpTroveVersionList ( d , { '' : full [ '' ] } ) d = runtimeRepos . getTroveLeavesByBranch ( q ) self . cmpTroveVersionList ( d , { '' : full [ '' ] } ) d = repeatRepos . getTroveLeavesByBranch ( q ) self . cmpTroveVersionList ( d , { '' : full [ '' ] } ) d = taRepos . getTroveLeavesByBranch ( q ) self . cmpTroveVersionList ( d , { '' : full [ '' ] } ) q = { '' : { branchVersion : None } , '' : { rootBranch : None } } full = { '' : [ '' ] , '' : [ '' ] , } d = repos . getTroveVersionsByBranch ( q ) self . cmpTroveVersionList ( d , full ) d = limitedRepos . getTroveVersionsByBranch ( q ) assert ( d == { } ) d = branchRepos . getTroveVersionsByBranch ( q ) self . cmpTroveVersionList ( d , { '' : full [ '' ] } ) d = runtimeRepos . getTroveVersionsByBranch ( q ) self . cmpTroveVersionList ( d , { '' : full [ '' ] } ) d = repeatRepos . getTroveVersionsByBranch ( q ) self . cmpTroveVersionList ( d , { '' : full [ '' ] } ) d = taRepos . getTroveVersionsByBranch ( q ) self . cmpTroveVersionList ( d , { '' : full [ '' ] } ) versionList = [ '' , '' , ] versionDict = { } . fromkeys ( [ versions . VersionFromString ( x ) for x in versionList ] , [ None ] ) q = { '' : versionDict , '' : versionDict } full = { '' : versionList , '' : versionList , } d = repos . getTroveVersionFlavors ( q ) self . cmpTroveVersionList ( d , full ) d = limitedRepos . getTroveVersionFlavors ( q ) self . cmpTroveVersionList ( d , { '' : versionList [ : ] } ) d = branchRepos . getTroveVersionFlavors ( q ) self . cmpTroveVersionList ( d , { '' : versionList [ : ] , '' : versionList [ : ] } ) d = runtimeRepos . getTroveVersionFlavors ( q ) self . cmpTroveVersionList ( d , { '' : full [ '' ] } ) d = repeatRepos . getTroveVersionFlavors ( q ) self . cmpTroveVersionList ( d , { '' : full [ '' ] } ) d = taRepos . getTroveVersionFlavors ( q ) self . cmpTroveVersionList ( d , { '' : full [ '' ] } ) flavor = deps . Flavor ( ) if use . Arch . x86 : flavor . addDep ( deps . InstructionSetDependency , deps . Dependency ( '' , [ ( '' , deps . FLAG_SENSE_REQUIRED ) ] ) ) elif use . Arch . x86_64 : pass else : raise NotImplementedError , '' versionDict = { } . fromkeys ( [ versions . VersionFromString ( x ) for x in versionList ] , [ flavor ] ) q = { '' : versionDict , '' : versionDict } d = repos . getTroveVersionFlavors ( q ) self . cmpTroveVersionList ( d , full ) all = repos . getTroveVersionList ( '' , { None : None } ) all = list ( self . asSet ( all ) ) troves = dict ( itertools . izip ( all , repos . getTroves ( all ) ) ) for testRepos in ( limitedRepos , branchRepos , repeatRepos ) : canSee = testRepos . getTroveVersionList ( '' , { None : None } ) canSee = self . asSet ( canSee ) isPresent = testRepos . hasTroves ( all ) for trvInfo in all : if trvInfo == '' : files = [ ( x [ ] , x [ ] , x [ ] ) for x in troves [ trvInfo ] . iterFileList ( ) ] else : files = '' if trvInfo in canSee : assert ( isPresent [ trvInfo ] ) testRepos . getTrove ( * trvInfo ) if files : testRepos . getFileVersions ( files ) testRepos . getFileContents ( [ x [ : ] for x in files ] ) else : assert ( not isPresent [ trvInfo ] ) self . assertRaises ( errors . InsufficientPermission , testRepos . getTrove , * trvInfo ) if files : self . assertRaises ( errors . FileStreamMissing , testRepos . getFileVersions , files ) self . assertRaises ( errors . FileStreamNotFound , testRepos . getFileContents , [ x [ : ] for x in files ] ) new = testRepos . getNewTroveList ( '' , ) assert ( canSee == set ( [ x [ ] for x in new ] ) ) all = repos . getTroveVersionList ( '' , { None : None } ) del all [ \"\" ] all = list ( self . asSet ( all ) ) troves = dict ( itertools . izip ( all , repos . getTroves ( all ) ) ) infos = dict ( itertools . izip ( all , repos . getTroveInfo ( trove . _TROVEINFO_TAG_SOURCENAME , all ) ) ) for trv in all : assert ( troves [ trv ] . troveInfo . sourceName == infos [ trv ] ) infos = dict ( itertools . izip ( all , repos . getTroveInfo ( trove . _TROVEINFO_TAG_SIGS , all ) ) ) for trv in all : assert ( troves [ trv ] . troveInfo . sigs == infos [ trv ] ) self . assertRaises ( errors . TroveMissing , limitedRepos . getTroveInfo , trove . _TROVEINFO_TAG_SOURCENAME , all ) all . append ( ( '' , versions . VersionFromString ( '' ) , deps . Flavor ( ) ) ) self . assertRaises ( errors . TroveMissing , repos . getTroveInfo , trove . _TROVEINFO_TAG_SOURCENAME , all ) d = taRepos . getTroveVersionList ( '' , { None : None } ) for i in taRepos . getTroveInfo ( trove . _TROVEINFO_TAG_SOURCENAME , list ( self . asSet ( d ) ) ) : self . assertEqual ( i ( ) , \"\" ) def testCompoundAcls ( self ) : rootLabel = versions . Label ( \"\" ) branchLabel = versions . Label ( \"\" ) rootBranch = versions . VersionFromString ( '' ) self . makeSourceTrove ( '' , recipes . testSuiteRecipe ) self . build ( recipes . testSuiteRecipe , \"\" ) self . makeSourceTrove ( '' , recipes . doubleRecipe1 ) self . build ( recipes . doubleRecipe1 , \"\" ) repos = self . getRepositoryClient ( ) repos . deleteUserByName ( self . cfg . buildLabel , '' ) repeatRepos = self . setupUser ( repos , rootLabel , '' , '' , '' , None ) repos . addAcl ( rootLabel , '' , '' , None ) repos . addAcl ( rootLabel , '' , '' , None ) repos . addAcl ( rootLabel , '' , '' , None ) full = { '' : [ '' ] , '' : [ '' ] , '' : [ '' ] , '' : [ '' ] , '' : [ '' ] , '' : [ '' ] , '' : [ '' ] } qd = { None : { self . cfg . buildLabel : None } } d = repos . getTroveLeavesByLabel ( qd ) self . cmpTroveVersionList ( d , full ) d = repeatRepos . getTroveLeavesByLabel ( qd ) self . cmpTroveVersionList ( d , { '' : full [ '' ] , '' : full [ '' ] , '' : full [ '' ] , '' : full [ '' ] , } ) def testAclChanges ( self ) : rootLabel = versions . Label ( \"\" ) branchLabel = versions . Label ( \"\" ) rootBranch = versions . VersionFromString ( '' ) self . makeSourceTrove ( '' , recipes . doubleRecipe1 ) self . build ( recipes . doubleRecipe1 , \"\" ) repos = self . getRepositoryClient ( ) repos . deleteUserByName ( self . cfg . buildLabel , '' ) limitedRepos = self . setupUser ( repos , rootLabel , '' , '' , '' , branchLabel ) both = [ '' , '' , '' ] runtime = [ '' ] assert ( limitedRepos . troveNames ( branchLabel ) == [ ] ) self . mkbranch ( self . cfg . buildLabel , branchLabel , '' ) branchVersion = versions . VersionFromString ( '' ) oldLabel = self . cfg . buildLabel self . cfg . buildLabel = branchLabel self . updateSourceTrove ( '' , recipes . doubleRecipe1_1 ) double1_1 = self . build ( recipes . doubleRecipe1_1 , \"\" ) self . cfg . buildLabel = oldLabel assert ( limitedRepos . troveNames ( branchLabel ) == runtime ) full = { '' : [ '' , '' , ] , '' : [ '' , '' , ] , '' : [ '' , '' , '' , ] , } d = limitedRepos . getTroveVersionList ( '' , { '' : None , '' : None , '' : None } ) self . cmpTroveVersionList ( d , { '' : full [ '' ] [ : ] } ) try : limitedRepos . editAcl ( rootLabel , '' , '' , branchLabel , None , None , False ) except errors . InsufficientPermission : pass else : assert ( ) repos . editAcl ( rootLabel , '' , '' , branchLabel , None , None , False ) d = limitedRepos . getTroveVersionList ( '' , { '' : None , '' : None , '' : None } ) self . cmpTroveVersionList ( d , full ) assert repos . listAcls ( rootLabel , '' ) == [ dict ( label = '' , item = '' , canWrite = , canRemove = ) ] repos . deleteAcl ( rootLabel , '' , None , None ) assert repos . listAcls ( rootLabel , '' ) == [ ] d = limitedRepos . getTroveVersionList ( '' , { '' : None , '' : None , '' : None } ) self . cmpTroveVersionList ( d , { } ) repos . addAcl ( rootLabel , '' , '' , branchLabel ) assert repos . listAcls ( rootLabel , '' ) == [ dict ( label = branchLabel . asString ( ) , item = '' , canWrite = , canRemove = ) ] d = limitedRepos . getTroveVersionList ( '' , { '' : None , '' : None , '' : None } ) self . cmpTroveVersionList ( d , { '' : full [ '' ] [ : ] } ) repos . deleteAcl ( rootLabel , '' , '' , branchLabel ) assert repos . listAcls ( rootLabel , '' ) == [ ] d = limitedRepos . getTroveVersionList ( '' , { '' : None , '' : None , '' : None } ) self . cmpTroveVersionList ( d , { } ) repos . addAcl ( rootLabel , '' , '' , branchLabel . asString ( ) ) assert repos . listAcls ( rootLabel , '' ) == [ dict ( label = branchLabel . asString ( ) , item = '' , canWrite = , canRemove = ) ] d = limitedRepos . getTroveVersionList ( '' , { '' : None , '' : None , '' : None } ) self . cmpTroveVersionList ( d , { '' : full [ '' ] [ : ] } ) repos . editAcl ( rootLabel , '' , '' , branchLabel , '' , '' , False , False ) d = limitedRepos . getTroveVersionList ( '' , { '' : None , '' : None , '' : None } ) self . cmpTroveVersionList ( d , full ) repos . deleteAcl ( rootLabel , '' , '' , '' ) assert repos . listAcls ( rootLabel , '' ) == [ ] d = limitedRepos . getTroveVersionList ( '' , { '' : None , '' : None , '' : None } ) self . cmpTroveVersionList ( d , { } ) def testGetRoles ( self ) : repos = self . openRepository ( ) repos = self . getRepositoryClient ( ) l = versions . Label ( \"\" ) assert set ( repos . listRoles ( l ) ) == set ( [ '' , '' ] ) assert ( repos . getRoles ( l ) == [ '' ] ) repos . addRole ( l , '' ) assert set ( repos . listRoles ( l ) ) == set ( [ '' , '' , '' ] ) repos . updateRoleMembers ( l , '' , [ '' ] ) assert ( repos . getRoles ( l ) == [ '' , '' ] ) repos . updateRoleMembers ( l , '' , [ ] ) assert ( repos . getRoles ( l ) == [ '' ] ) repos . addRoleMember ( l , '' , '' ) self . assertEqual ( repos . getRoles ( l ) , [ '' , '' ] ) self . assertEqual ( repos . getRoleMembers ( l , '' ) , [ '' ] ) repos . updateRoleMembers ( l , '' , [ ] ) self . assertEqual ( repos . getRoleMembers ( l , '' ) , [ ] ) repos . updateRoleMembers ( l , '' , [ '' ] ) repos . deleteRole ( l , '' ) assert set ( repos . listRoles ( l ) ) == set ( [ '' , '' ] ) assert ( repos . getRoles ( l ) == [ '' ] ) def testBadUser ( self ) : repos = self . openRepository ( ) repos = self . getRepositoryClient ( user = '' , password = '' ) self . addComponent ( '' , '' ) results = repos . getTroveVersionList ( '' , { None : None } ) assert ( '' in results ) def testBadTrovepattern ( self ) : repos = self . openRepository ( ) user = '' l = versions . Label ( \"\" ) self . addUserAndRole ( repos , l , user , '' ) self . assertRaises ( errors . InvalidRegex , repos . addAcl , l , user , '' , '' , False , False ) repos . addAcl ( l , user , '' , '' , False , False ) self . assertRaises ( errors . InvalidRegex , repos . editAcl , l , user , '' , '' , '' , '' , False , False ) def testBadUserTriesToCommit ( self ) : user = '' password = '' bl = self . cfg . buildLabel repos = self . openRepository ( ) self . addUserAndRole ( repos , bl , user , password ) repos . addAcl ( bl , user , '' , bl , False , False ) repos . addAcl ( bl , user , '' , bl , True , False ) limitedRepos = self . getRepositoryClient ( user = user , password = password ) self . assertRaises ( errors . InsufficientPermission , self . addComponent , \"\" , \"\" , repos = limitedRepos ) def testFallbackThenNeedUser ( self ) : user = '' password = '' bl = self . cfg . buildLabel repos = self . openRepository ( ) self . addUserAndRole ( repos , bl , user , password ) repos . addAcl ( bl , user , '' , bl , write = True ) trv = self . addComponent ( '' , '' ) limitedRepos = self . getRepositoryClient ( user = user , password = password ) assert ( limitedRepos . getTrove ( * trv . getNameVersionFlavor ( ) ) ) self . addComponent ( \"\" , \"\" , repos = limitedRepos ) self . assertRaises ( errors . InsufficientPermission , self . addComponent , \"\" , \"\" , repos = limitedRepos ) def testNonExistingUserTriesToCommit ( self ) : user = '' password = '' repos = self . openRepository ( ) limited = self . getRepositoryClient ( user = user , password = password ) self . assertRaises ( errors . InsufficientPermission , self . addComponent , \"\" , \"\" , repos = limited ) def testUserPasswordQuoting ( self ) : repos = self . openRepository ( ) user = '' password = '' bl = self . cfg . buildLabel self . addUserAndRole ( repos , bl , user , password ) repos . addAcl ( bl , user , '' , bl , False , False ) repos . addAcl ( bl , user , '' , bl , True , False ) limitedRepos = self . getRepositoryClient ( user = user , password = password ) self . addComponent ( \"\" , \"\" , repos = limitedRepos ) l = repos . getTroveVersionList ( '' , { None : None } ) assert ( l . keys ( ) == [ '' ] ) @ testhelp . context ( '' ) def testExternalAuthChecks ( self ) : rootLabel = versions . Label ( \"\" ) self . stopRepository ( ) pwServer = AuthorizationServer ( PasswordHttpRequests ) entServer = AuthorizationServer ( EntitlementRequests ) try : repos = self . openRepository ( authCheck = pwServer . url ( ) + '' , entCheck = entServer . url ( ) + '' ) repos . deleteUserByName ( self . cfg . buildLabel , '' ) self . setupUser ( repos , rootLabel , '' , '' , None , None ) origEntClient = self . setupEntitlement ( repos , '' , '' , rootLabel , None , None , withClass = True ) [ ] pwClient = self . getRepositoryClient ( user = '' , password = '' ) pwClient . c [ '' ] . checkVersion ( ) self . assertRaises ( errors . CannotChangePassword , pwClient . changePassword , rootLabel , '' , '' ) pwClient = self . getRepositoryClient ( user = '' , password = '' ) self . assertRaises ( errors . InsufficientPermission , pwClient . c . __getitem__ , '' ) self . assertRaises ( errors . InsufficientPermission , origEntClient . c . __getitem__ , '' ) entClient = self . getEntitlementClient ( [ ( '' , '' , '' ) ] , withClass = True ) . getRepos ( ) entClient . c [ '' ] . checkVersion ( ) entClient = self . getEntitlementClient ( [ ( '' , '' , '' ) ] , withClass = False ) . getRepos ( ) entClient . c [ '' ] . checkVersion ( ) finally : pwServer . kill ( ) entServer . kill ( ) self . stopRepository ( ) @ testhelp . context ( '' ) def testThreadedEntitlementUpdates ( self ) : rootLabel = self . cfg . buildLabel repos = self . openRepository ( ) repos . deleteUserByName ( rootLabel , '' ) self . cfg . threaded = True origEntClient = self . setupEntitlement ( repos , '' , '' , rootLabel , None , None , onDisk = False ) [ ] self . cfg . threaded = False self . addComponent ( '' , '' ) self . addCollection ( '' , '' , [ '' ] ) self . addComponent ( '' , '' , filePrimer = ) self . addCollection ( '' , '' , [ '' ] ) self . checkUpdate ( [ '' , '' ] , [ '' , '' , '' , '' ] , client = origEntClient , apply = True ) def testPermissionRevoked ( self ) : self . openRepository ( ) tFoo = self . addComponent ( '' , '' ) tBar = self . addComponent ( '' , '' ) tBar1 = self . addComponent ( '' , '' ) self . updatePkg ( '' ) repos = self . openRepository ( ) repos . deleteUserByName ( versions . Label ( '' ) , '' ) limitedRepos = self . setupUser ( repos , versions . Label ( '' ) , '' , '' , None , versions . Label ( '' ) ) self . assertRaises ( errors . InsufficientPermission , limitedRepos . getTrove , '' , tFoo . getVersion ( ) , tFoo . getFlavor ( ) ) limitedRepos . createChangeSet ( [ ( '' , ( tFoo . getVersion ( ) , tFoo . getFlavor ( ) ) , ( tBar . getVersion ( ) , tBar . getFlavor ( ) ) , False ) ] ) limitedRepos . createChangeSet ( [ ( '' , ( tFoo . getVersion ( ) , tFoo . getFlavor ( ) ) , ( tBar1 . getVersion ( ) , tBar1 . getFlavor ( ) ) , False ) ] ) def testComplexRegexp ( self ) : self . addComponent ( '' , '' ) self . addComponent ( '' , '' ) self . addComponent ( '' , '' ) self . addCollection ( '' , '' , [ '' , '' ] ) self . addComponent ( '' , '' ) self . addComponent ( '' , '' ) self . addComponent ( '' , '' ) self . addComponent ( '' , '' ) self . addCollection ( '' , '' , [ '' , '' , '' ] ) repos = self . getRepositoryClient ( ) repos . deleteUserByName ( self . cfg . buildLabel , '' ) limitedRepos = self . setupUser ( repos , self . cfg . buildLabel , '' , '' , '' , self . cfg . buildLabel ) assert ( sorted ( limitedRepos . troveNames ( self . cfg . buildLabel ) ) == [ '' , '' , '' , '' , '' ] ) def testRecursiveGetChangeSetAcl ( self ) : def _missing ( cs , name , trv ) : trvCs = cs . getNewTroveVersion ( name , trv . getVersion ( ) , trv . getFlavor ( ) ) trv = trove . Trove ( trvCs ) return trv . isMissing ( ) repos = self . openRepository ( ) self . addComponent ( '' , '' ) debug = self . addComponent ( '' , '' ) trv = self . addCollection ( '' , '' , [ ( '' , True ) , ( '' , False ) ] ) label = versions . Label ( \"\" ) self . addUserAndRole ( repos , label , \"\" , \"\" ) repos . deleteUserByName ( label , '' ) repos . addAcl ( label , \"\" , \"\" , label ) repos . addAcl ( label , \"\" , \"\" , label ) self . addUserAndRole ( repos , self . cfg . buildLabel , '' , '' ) ta = self . getRepositoryClient ( user = '' , password = '' ) repos . addTroveAccess ( '' , [ trv . getNameVersionFlavor ( ) ] ) limited = self . getRepositoryClient ( user = '' , password = '' ) for rep in ( limited , ta ) : cs = rep . createChangeSet ( [ ( '' , ( None , None ) , ( trv . getVersion ( ) , trv . getFlavor ( ) ) , True ) ] ) if rep != ta : assert ( _missing ( cs , '' , trv ) ) assert ( not _missing ( cs , '' , trv ) ) cs = rep . createChangeSet ( [ ( '' , ( None , None ) , ( trv . getVersion ( ) , trv . getFlavor ( ) ) , ", "answer": "True ) ] )"}, {"prompt": " from pymongo . collection import Collection as PymongoCollection from mongokit . mongo_exceptions import MultipleResultsFound from mongokit . cursor import Cursor from warnings import warn class Collection ( PymongoCollection ) : def __init__ ( self , * args , ** kwargs ) : self . _documents = { } self . _collections = { } super ( Collection , self ) . __init__ ( * args , ** kwargs ) self . _registered_documents = self . database . connection . _registered_documents def __getattr__ ( self , key ) : if key in self . _registered_documents : if not key in self . _documents : self . _documents [ key ] = self . _registered_documents [ key ] ( collection = self ) if hasattr ( self . _documents [ key ] , \"\" ) and self . _documents [ key ] . i18n : self . _documents [ key ] ( ) if self . _documents [ key ] . indexes : warn ( '' '' % self . _documents [ key ] . _obj_class . __name__ , DeprecationWarning ) return self . _documents [ key ] else : newkey = u\"\" % ( self . name , key ) if not newkey in self . _collections : self . _collections [ newkey ] = Collection ( self . database , newkey ) return self . _collections [ newkey ] def __call__ ( self , * args , ** kwargs ) : if \"\" not in self . __name : raise TypeError ( \"\" \"\" \"\" \"\" % self . __name ) name = self . __name . split ( \"\" ) [ - ] raise TypeError ( \"\" \"\" ", "answer": "\"\""}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import from google . appengine . api import memcache try : from ndb import model except ImportError : from google . appengine . ext . ndb import model try : from ndb . model import PickleProperty except ImportError : try : from google . appengine . ext . ndb . model import PickleProperty except ImportError : import pickle ", "answer": "class PickleProperty ( model . BlobProperty ) :"}, {"prompt": " import unittest2 as unittest from slimta . envelope import Envelope from slimta . bounce import Bounce from slimta . smtp . reply import Reply class TestBounce ( unittest . TestCase ) : def test_bounce ( self ) : env = Envelope ( '' , [ '' , '' ] ) env . parse ( b\"\"\"\"\"\" ) reply = Reply ( '' , '' ) Bounce . header_template = \"\"\"\"\"\" Bounce . footer_template = \"\"\"\"\"\" bounce = Bounce ( env , reply ) self . assertEqual ( '' , bounce . sender ) self . assertEqual ( [ '' ] , bounce . recipients ) self . assertEqual ( '' , bounce . headers [ '' ] ) self . assertEqual ( '' , bounce . headers [ '' ] ) self . assertEqual ( '' , bounce . headers [ '' ] ) self . assertEqual ( b\"\"\"\"\"\" . replace ( b'' , b'' ) , bounce . message ) def test_bounce_headersonly ( self ) : env = Envelope ( '' , [ '' , '' ] ) env . parse ( b\"\"\"\"\"\" ) reply = Reply ( '' , '' ) Bounce . header_template = \"\"\"\"\"\" Bounce . footer_template = \"\"\"\"\"\" ", "answer": "bounce = Bounce ( env , reply , headers_only = True )"}, {"prompt": " import numpy as np from matplotlib import lines from ... viewer . canvastools . base import CanvasToolBase , ToolHandles __all__ = [ '' , '' ] class LineTool ( CanvasToolBase ) : \"\"\"\"\"\" def __init__ ( self , manager , on_move = None , on_release = None , on_enter = None , maxdist = , line_props = None , handle_props = None , ** kwargs ) : super ( LineTool , self ) . __init__ ( manager , on_move = on_move , on_enter = on_enter , on_release = on_release , ** kwargs ) props = dict ( color = '' , linewidth = , alpha = , solid_capstyle = '' ) props . update ( line_props if line_props is not None else { } ) self . linewidth = props [ '' ] self . maxdist = maxdist ", "answer": "self . _active_pt = None"}, {"prompt": " from __future__ import absolute_import import os from salttesting import skipIf , TestCase from salttesting . helpers import ensure_in_syspath from salttesting . mock import NO_MOCK , NO_MOCK_REASON , MagicMock , patch ensure_in_syspath ( '' ) from salt . modules import pip from salt . exceptions import CommandExecutionError pip . __salt__ = { '' : lambda _ : '' } @ skipIf ( NO_MOCK , NO_MOCK_REASON ) class PipTestCase ( TestCase ) : def test_fix4361 ( self ) : mock = MagicMock ( return_value = { '' : , '' : '' } ) with patch . dict ( pip . __salt__ , { '' : mock } ) : pip . install ( requirements = '' ) expected_cmd = [ '' , '' , '' , '' ] mock . assert_called_once_with ( expected_cmd , saltenv = '' , runas = None , use_vt = False , python_shell = False , ) def test_install_editable_without_egg_fails ( self ) : mock = MagicMock ( return_value = { '' : , '' : '' } ) with patch . dict ( pip . __salt__ , { '' : mock } ) : self . assertRaises ( CommandExecutionError , pip . install , editable = '' ) def test_install_multiple_editable ( self ) : editables = [ '' , '' ] expected = [ '' , '' ] for item in editables : expected . extend ( [ '' , item ] ) mock = MagicMock ( return_value = { '' : , '' : '' } ) with patch . dict ( pip . __salt__ , { '' : mock } ) : pip . install ( editable = editables ) mock . assert_called_once_with ( expected , saltenv = '' , runas = None , use_vt = False , python_shell = False , ) mock = MagicMock ( return_value = { '' : , '' : '' } ) with patch . dict ( pip . __salt__ , { '' : mock } ) : pip . install ( editable = '' . join ( editables ) ) mock . assert_called_once_with ( expected , saltenv = '' , runas = None , use_vt = False , python_shell = False , ) def test_install_multiple_pkgs_and_editables ( self ) : pkgs = [ '' , '' ] editables = [ '' , '' ] expected = [ '' , '' ] + pkgs for item in editables : expected . extend ( [ '' , item ] ) mock = MagicMock ( return_value = { '' : , '' : '' } ) with patch . dict ( pip . __salt__ , { '' : mock } ) : pip . install ( pkgs = pkgs , editable = editables ) mock . assert_called_once_with ( expected , saltenv = '' , runas = None , use_vt = False , python_shell = False , ) mock = MagicMock ( return_value = { '' : , '' : '' } ) with patch . dict ( pip . __salt__ , { '' : mock } ) : pip . install ( pkgs = '' . join ( pkgs ) , editable = '' . join ( editables ) ) mock . assert_called_once_with ( expected , saltenv = '' , runas = None , use_vt = False , python_shell = False , ) mock = MagicMock ( return_value = { '' : , '' : '' } ) with patch . dict ( pip . __salt__ , { '' : mock } ) : pip . install ( pkgs = pkgs [ ] , editable = editables [ ] ) mock . assert_called_once_with ( [ '' , '' , pkgs [ ] , '' , editables [ ] ] , saltenv = '' , runas = None , use_vt = False , python_shell = False , ) def test_issue5940_install_multiple_pip_mirrors ( self ) : mirrors = [ '' , '' , '' ] expected = [ '' , '' , '' ] for item in mirrors : expected . extend ( [ '' , item ] ) mock = MagicMock ( return_value = { '' : , '' : '' } ) with patch . dict ( pip . __salt__ , { '' : mock } ) : pip . install ( mirrors = mirrors ) mock . assert_called_once_with ( expected , saltenv = '' , runas = None , use_vt = False , python_shell = False , ) mock = MagicMock ( return_value = { '' : , '' : '' } ) with patch . dict ( pip . __salt__ , { '' : mock } ) : pip . install ( mirrors = '' . join ( mirrors ) ) mock . assert_called_once_with ( expected , saltenv = '' , runas = None , use_vt = False , python_shell = False , ) mock = MagicMock ( return_value = { '' : , '' : '' } ) with patch . dict ( pip . __salt__ , { '' : mock } ) : pip . install ( mirrors = mirrors [ ] ) mock . assert_called_once_with ( [ '' , '' , '' , '' , mirrors [ ] ] , saltenv = '' , runas = None , use_vt = False , python_shell = False , ) def test_install_with_multiple_find_links ( self ) : find_links = [ '' , '' , '' ] pkg = '' expected = [ '' , '' ] for item in find_links : expected . extend ( [ '' , item ] ) expected . append ( pkg ) mock = MagicMock ( return_value = { '' : , '' : '' } ) with patch . dict ( pip . __salt__ , { '' : mock } ) : pip . install ( pkg , find_links = find_links ) mock . assert_called_once_with ( expected , saltenv = '' , runas = None , use_vt = False , python_shell = False , ) mock = MagicMock ( return_value = { '' : , '' : '' } ) with patch . dict ( pip . __salt__ , { '' : mock } ) : pip . install ( pkg , find_links = '' . join ( find_links ) ) mock . assert_called_once_with ( expected , saltenv = '' , runas = None , use_vt = False , python_shell = False , ) mock = MagicMock ( return_value = { '' : , '' : '' } ) with patch . dict ( pip . __salt__ , { '' : mock } ) : pip . install ( pkg , find_links = find_links [ ] ) mock . assert_called_once_with ( [ '' , '' , '' , find_links [ ] , pkg ] , saltenv = '' , runas = None , use_vt = False , python_shell = False , ) mock = MagicMock ( return_value = { '' : , '' : '' } ) with patch . dict ( pip . __salt__ , { '' : mock } ) : self . assertRaises ( CommandExecutionError , pip . install , '' + pkg + '' , find_links = '' ) mock = MagicMock ( return_value = { '' : , '' : '' } ) with patch . dict ( pip . __salt__ , { '' : mock } ) : pip . install ( pkg , find_links = find_links ) mock . assert_called_once_with ( expected , saltenv = '' , runas = None , use_vt = False , python_shell = False , ) def test_install_no_index_with_index_url_or_extra_index_url_raises ( self ) : mock = MagicMock ( return_value = { '' : , '' : '' } ) with patch . dict ( pip . __salt__ , { '' : mock } ) : self . assertRaises ( CommandExecutionError , pip . install , no_index = True , index_url = '' ) mock = MagicMock ( return_value = { '' : , '' : '' } ) with patch . dict ( pip . __salt__ , { '' : mock } ) : self . assertRaises ( CommandExecutionError , pip . install , no_index = True , extra_index_url = '' ) @ patch ( '' ) def test_install_failed_cached_requirements ( self , get_cached_requirements ) : get_cached_requirements . return_value = False ret = pip . install ( requirements = '' ) self . assertEqual ( False , ret [ '' ] ) self . assertIn ( '' , ret [ '' ] ) @ patch ( '' ) def test_install_cached_requirements_used ( self , get_cached_requirements ) : get_cached_requirements . return_value = '' mock = MagicMock ( return_value = { '' : , '' : '' } ) with patch . dict ( pip . __salt__ , { '' : mock } ) : pip . install ( requirements = '' ) expected = [ '' , '' , '' , '' ] mock . assert_called_once_with ( expected , saltenv = '' , runas = None , use_vt = False , python_shell = False , ) @ patch ( '' ) def test_install_venv ( self , mock_path ) : mock_path . is_file . return_value = True mock_path . isdir . return_value = True pkg = '' venv_path = '' def join ( * args ) : return '' . join ( args ) mock_path . join = join mock = MagicMock ( return_value = { '' : , '' : '' } ) with patch . dict ( pip . __salt__ , { '' : mock } ) : pip . install ( pkg , bin_env = venv_path ) mock . assert_called_once_with ( [ os . path . join ( venv_path , '' , '' ) , '' , pkg ] , env = { '' : '' } , saltenv = '' , runas = None , use_vt = False , python_shell = False , ) @ patch ( '' ) def test_install_log_argument_in_resulting_command ( self , mock_path ) : pkg = '' log_path = '' mock = MagicMock ( return_value = { '' : , '' : '' } ) with patch . dict ( pip . __salt__ , { '' : mock } ) : pip . install ( pkg , log = log_path ) mock . assert_called_once_with ( [ '' , '' , '' , log_path , pkg ] , saltenv = '' , runas = None , use_vt = False , python_shell = False , ) @ patch ( '' ) def test_non_writeable_log ( self , mock_path ) : pkg = '' log_path = '' mock_path . exists . side_effect = IOError ( '' ) mock = MagicMock ( return_value = { '' : , '' : '' } ) with patch . dict ( pip . __salt__ , { '' : mock } ) : self . assertRaises ( IOError , pip . install , pkg , log = log_path ) def test_install_timeout_argument_in_resulting_command ( self ) : pkg = '' expected_prefix = [ '' , '' , '' ] mock = MagicMock ( return_value = { '' : , '' : '' } ) with patch . dict ( pip . __salt__ , { '' : mock } ) : pip . install ( pkg , timeout = ) mock . assert_called_once_with ( expected_prefix + [ , pkg ] , saltenv = '' , runas = None , use_vt = False , python_shell = False , ) mock = MagicMock ( return_value = { '' : , '' : '' } ) with patch . dict ( pip . __salt__ , { '' : mock } ) : pip . install ( pkg , timeout = '' ) mock . assert_called_once_with ( expected_prefix + [ '' , pkg ] , saltenv = '' , runas = None , use_vt = False , python_shell = False , ) mock = MagicMock ( return_value = { '' : , '' : '' } ) with patch . dict ( pip . __salt__ , { '' : mock } ) : self . assertRaises ( ValueError , pip . install , pkg , timeout = '' ) def test_install_index_url_argument_in_resulting_command ( self ) : pkg = '' index_url = '' mock = MagicMock ( return_value = { '' : , '' : '' } ) with patch . dict ( pip . __salt__ , { '' : mock } ) : pip . install ( pkg , index_url = index_url ) mock . assert_called_once_with ( [ '' , '' , '' , index_url , pkg ] , saltenv = '' , runas = None , use_vt = False , python_shell = False , ) def test_install_extra_index_url_argument_in_resulting_command ( self ) : pkg = '' extra_index_url = '' mock = MagicMock ( return_value = { '' : , '' : '' } ) with patch . dict ( pip . __salt__ , { '' : mock } ) : pip . install ( pkg , extra_index_url = extra_index_url ) mock . assert_called_once_with ( [ '' , '' , '' , extra_index_url , pkg ] , saltenv = '' , runas = None , use_vt = False , python_shell = False , ) def test_install_no_index_argument_in_resulting_command ( self ) : pkg = '' mock = MagicMock ( return_value = { '' : , '' : '' } ) with patch . dict ( pip . __salt__ , { '' : mock } ) : pip . install ( pkg , no_index = True ) mock . assert_called_once_with ( [ '' , '' , '' , pkg ] , saltenv = '' , runas = None , use_vt = False , python_shell = False , ) def test_install_build_argument_in_resulting_command ( self ) : pkg = '' build = '' mock = MagicMock ( return_value = { '' : , '' : '' } ) with patch . dict ( pip . __salt__ , { '' : mock } ) : pip . install ( pkg , build = build ) mock . assert_called_once_with ( [ '' , '' , '' , build , pkg ] , saltenv = '' , runas = None , use_vt = False , python_shell = False , ) def test_install_target_argument_in_resulting_command ( self ) : pkg = '' target = '' mock = MagicMock ( return_value = { '' : , '' : '' } ) with patch . dict ( pip . __salt__ , { '' : mock } ) : pip . install ( pkg , target = target ) mock . assert_called_once_with ( [ '' , '' , '' , target , pkg ] , saltenv = '' , runas = None , use_vt = False , python_shell = False , ) def test_install_download_argument_in_resulting_command ( self ) : pkg = '' download = '' mock = MagicMock ( return_value = { '' : , '' : '' } ) with patch . dict ( pip . __salt__ , { '' : mock } ) : pip . install ( pkg , download = download ) mock . assert_called_once_with ( [ '' , '' , '' , download , pkg ] , saltenv = '' , runas = None , use_vt = False , python_shell = False , ) def test_install_no_download_argument_in_resulting_command ( self ) : pkg = '' mock = MagicMock ( return_value = { '' : , '' : '' } ) with patch . dict ( pip . __salt__ , { '' : mock } ) : pip . install ( pkg , no_download = True ) mock . assert_called_once_with ( [ '' , '' , '' , pkg ] , saltenv = '' , runas = None , use_vt = False , python_shell = False , ) def test_install_download_cache_argument_in_resulting_command ( self ) : pkg = '' download_cache = '' mock = MagicMock ( return_value = { '' : , '' : '' } ) with patch . dict ( pip . __salt__ , { '' : mock } ) : pip . install ( pkg , download_cache = '' ) mock . assert_called_once_with ( [ '' , '' , '' , download_cache , pkg ] , saltenv = '' , runas = None , use_vt = False , python_shell = False , ) def test_install_source_argument_in_resulting_command ( self ) : pkg = '' source = '' mock = MagicMock ( return_value = { '' : , '' : '' } ) with patch . dict ( pip . __salt__ , { '' : mock } ) : pip . install ( pkg , source = source ) mock . assert_called_once_with ( [ '' , '' , '' , source , pkg ] , saltenv = '' , runas = None , use_vt = False , python_shell = False , ) def test_install_exists_action_argument_in_resulting_command ( self ) : pkg = '' for action in ( '' , '' , '' , '' ) : mock = MagicMock ( return_value = { '' : , '' : '' } ) with patch . dict ( pip . __salt__ , { '' : mock } ) : pip . install ( '' , exists_action = action ) mock . assert_called_once_with ( [ '' , '' , '' , action , pkg ] , saltenv = '' , runas = None , use_vt = False , python_shell = False , ) mock = MagicMock ( return_value = { '' : , '' : '' } ) with patch . dict ( pip . __salt__ , { '' : mock } ) : self . assertRaises ( CommandExecutionError , pip . install , pkg , exists_action = '' ) def test_install_install_options_argument_in_resulting_command ( self ) : install_options = [ '' , '' ] pkg = '' ", "answer": "expected = [ '' , '' ]"}, {"prompt": " from __future__ import absolute_import from datetime import datetime from nose . tools import * from modularodm . exceptions import ValidationValueError , ValidationTypeError from framework . auth import Auth from tests . base import OsfTestCase from tests . factories import UserFactory , CommentFactory class TestSpamMixin ( OsfTestCase ) : def setUp ( self ) : super ( TestSpamMixin , self ) . setUp ( ) self . comment = CommentFactory ( ) self . auth = Auth ( user = self . comment . user ) def test_report_abuse ( self ) : user = UserFactory ( ) time = datetime . utcnow ( ) self . comment . report_abuse ( user , date = time , category = '' , text = '' , save = True ) ", "answer": "assert_equal ( self . comment . spam_status , self . comment . FLAGGED )"}, {"prompt": " import urllib , httplib2 from django . template import loader from django . core . cache import cache from django . utils . translation import ugettext as _ from xadmin . sites import site from xadmin . models import UserSettings from xadmin . views import BaseAdminPlugin , BaseAdminView from xadmin . util import static , json THEME_CACHE_KEY = '' class ThemePlugin ( BaseAdminPlugin ) : enable_themes = False user_themes = None use_bootswatch = False default_theme = static ( '' ) bootstrap2_theme = static ( '' ) def init_request ( self , * args , ** kwargs ) : return self . enable_themes def _get_theme ( self ) : if self . user : try : return UserSettings . objects . get ( user = self . user , key = \"\" ) . value except Exception : pass if '' in self . request . COOKIES : return urllib . unquote ( self . request . COOKIES [ '' ] ) return self . default_theme def get_context ( self , context ) : context [ '' ] = self . _get_theme ( ) return context def get_media ( self , media ) : return media + self . vendor ( '' , '' ) def block_top_navmenu ( self , context , nodes ) : themes = [ { '' : _ ( u\"\" ) , '' : _ ( u\"\" ) , '' : self . default_theme } , { '' : _ ( u\"\" ) , '' : _ ( u\"\" ) , '' : self . bootstrap2_theme } ] select_css = context . get ( '' , self . default_theme ) if self . user_themes : themes . extend ( self . user_themes ) if self . use_bootswatch : ex_themes = cache . get ( THEME_CACHE_KEY ) if ex_themes : themes . extend ( json . loads ( ex_themes ) ) else : ex_themes = [ ] try : h = httplib2 . Http ( ) resp , content = h . request ( \"\" , '' , \"\" , headers = { \"\" : \"\" , \"\" : self . request . META [ '' ] } ) watch_themes = json . loads ( content ) [ '' ] ex_themes . extend ( [ { '' : t [ '' ] , '' : t [ '' ] , '' : t [ '' ] , '' : t [ '' ] } for t in watch_themes ] ) except Exception , e : ", "answer": "print e"}, {"prompt": " \"\"\"\"\"\" from __future__ import print_function import os , sys from apigen import ApiDocWriter from distutils . version import LooseVersion as V def abort ( error ) : print ( '' % error ) exit ( ) def assert_source_and_install_match ( package ) : \"\"\"\"\"\" module = sys . modules [ package ] installed_version = V ( module . version . version ) setup_lines = open ( '' ) . readlines ( ) for l in setup_lines : if l . startswith ( '' ) : source_version = V ( l . split ( \"\" ) [ ] ) break if source_version != installed_version : abort ( \"\" ) if __name__ == '' : package = '' try : __import__ ( package ) except ImportError as e : abort ( \"\" ) outdir = '' docwriter = ApiDocWriter ( package ) docwriter . package_skip_patterns += [ r'' , r'' , ] docwriter . write_api_docs ( outdir ) docwriter . write_index ( outdir , '' , relative_to = '' ) ", "answer": "print ( '' % len ( docwriter . written_modules ) ) "}, {"prompt": " '''''' import time class CallbackModule ( object ) : \"\"\"\"\"\" def __init__ ( self ) : self . stats = { } self . current = None def playbook_on_task_start ( self , name , is_conditional ) : \"\"\"\"\"\" ", "answer": "if self . current is not None :"}, {"prompt": " __appname__ = \"\" __version__ = \"\" __author__ = \"\" __license__ = \"\" __doc__ = '''''' import getopt import sys import logging import re import t411 try : import tpb except : print ( \"\" ) print ( \"\" ) sys . exit ( ) try : import tvdb_api except : tvdbapi_tag = False else : tvdbapi_tag = True try : import transmissionrpc except : transmissionrpc_tag = False else : transmissionrpc_tag = True ", "answer": "tpb_url = \"\""}, {"prompt": " \"\"\"\"\"\" from scipy import stats from matplotlib import pyplot as plt import statsmodels . api as sm data = sm . datasets . longley . load ( ) data . exog = sm . add_constant ( data . exog , prepend = True ) mod_fit = sm . OLS ( data . endog , data . exog ) . fit ( ) res = mod_fit . resid left = - fig = plt . figure ( ) ax = fig . add_subplot ( , , ) sm . graphics . qqplot ( res , ax = ax ) top = ax . get_ylim ( ) [ ] * txt = ax . text ( left , top , '' , verticalalignment = '' ) txt . set_bbox ( dict ( facecolor = '' , alpha = ) ) ax = fig . add_subplot ( , , ) sm . graphics . qqplot ( res , line = '' , ax = ax ) top = ax . get_ylim ( ) [ ] * txt = ax . text ( left , top , \"\" , verticalalignment = '' ) txt . set_bbox ( dict ( facecolor = '' , alpha = ) ) ax = fig . add_subplot ( , , ) sm . graphics . qqplot ( res , line = '' , fit = True , ax = ax ) ax . set_xlim ( - , ) top = ax . get_ylim ( ) [ ] * txt = ax . text ( left , top , \"\" , verticalalignment = '' ) txt . set_bbox ( dict ( facecolor = '' , alpha = ) ) ", "answer": "ax = fig . add_subplot ( , , )"}, {"prompt": " import pytest from thefuck . rules . git_pull import match , get_new_command ", "answer": "from tests . utils import Command"}, {"prompt": " from . TextReporter import TextReporter from . JsonReporter import JsonReporter from . XMLReporter import XMLReporter class ReporterUtil ( ) : @ staticmethod def getReporter ( reporterType , checker ) : if reporterType == '' : ", "answer": "return TextReporter ( checker )"}, {"prompt": " from pymongo import ASCENDING from django . core . management . base import BaseCommand from tasks . models import Tasks from tasks . jobs import create_task class Command ( BaseCommand ) : help = '' def handle ( self , * args , ** kwargs ) : ", "answer": "for task in Tasks . find ( { } , sort = [ ( '' , ASCENDING ) ] ) :"}, {"prompt": " import json import requests from io import BytesIO from time import sleep , time from zipfile import ZipFile , BadZipfile from logging import getLogger from requests . exceptions import RequestException try : from types import NoneType except ImportError : NoneType = type ( None ) from . exceptions import BadCredentials , BadRequest log = getLogger ( __name__ ) class Client ( object ) : API_VERSION = \"\" def __init__ ( self , environment , account_id = None , access_token = None , json_options = None ) : self . domain , self . domain_stream = environment self . access_token = access_token self . account_id = account_id self . json_options = json_options or { } if account_id and not self . get_credentials ( ) : raise BadCredentials ( ) def get_credentials ( self ) : \"\"\"\"\"\" ", "answer": "url = \"\" . format ("}, {"prompt": " from setuptools import setup , find_packages setup ( name = '' , version = '' , packages = find_packages ( ) , ", "answer": "install_requires = [ '' , ] ,"}, {"prompt": " \"\"\"\"\"\" from django . core import mail from django . core . exceptions import ImproperlyConfigured from django . db import models from django . utils . encoding import smart_str import urllib from django . db . models . manager import EmptyManager from google . appengine . api import users from google . appengine . ext import db from appengine_django . models import BaseModel class User ( BaseModel ) : \"\"\"\"\"\" user = db . UserProperty ( required = True ) username = db . StringProperty ( required = True ) first_name = db . StringProperty ( ) last_name = db . StringProperty ( ) email = db . EmailProperty ( ) ", "answer": "password = db . StringProperty ( )"}, {"prompt": " from __future__ import absolute_import from __future__ import print_function import autograd . numpy as np import matplotlib . pyplot as plt from autograd import grad from builtins import range , map def fun ( x ) : return np . sin ( x ) d_fun = grad ( fun ) dd_fun = grad ( d_fun ) x = np . linspace ( - , , ) plt . plot ( x , list ( map ( fun , x ) ) , x , list ( map ( d_fun , x ) ) , x , list ( map ( dd_fun , x ) ) ) plt . xlim ( [ - , ] ) plt . ylim ( [ - , ] ) plt . axis ( '' ) plt . savefig ( \"\" ) plt . clf ( ) def fun ( x ) : currterm = x ans = currterm for i in range ( ) : print ( i , end = '' ) currterm = - currterm * x ** / ( ( * i + ) * ( * i + ) ) ans = ans + currterm if np . abs ( currterm ) < : break return ans d_fun = grad ( fun ) dd_fun = grad ( d_fun ) ", "answer": "x = np . linspace ( - , , )"}, {"prompt": " \"\"\"\"\"\" from __future__ import print_function import subprocess import sys def _parse_lines ( lines ) : \"\"\"\"\"\" results = [ ] acc = [ ] ", "answer": "for line in lines :"}, {"prompt": " from django . core . urlresolvers import reverse from django . template import defaultfilters as filters from django . utils . translation import ugettext_lazy as _ from django . utils . translation import ungettext_lazy from horizon import tables from openstack_dashboard import policy class AddRuleLink ( tables . LinkAction ) : name = \"\" verbose_name = _ ( \"\" ) url = \"\" classes = ( \"\" , ) icon = \"\" policy_rules = ( ( \"\" , \"\" ) , ) class AddPolicyLink ( tables . LinkAction ) : name = \"\" verbose_name = _ ( \"\" ) url = \"\" classes = ( \"\" , \"\" , ) policy_rules = ( ( \"\" , \"\" ) , ) class AddFirewallLink ( tables . LinkAction ) : name = \"\" verbose_name = _ ( \"\" ) url = \"\" classes = ( \"\" , ) icon = \"\" policy_rules = ( ( \"\" , \"\" ) , ) class DeleteRuleLink ( policy . PolicyTargetMixin , tables . DeleteAction ) : name = \"\" @ staticmethod def action_present ( count ) : return ungettext_lazy ( u\"\" , u\"\" , count ) @ staticmethod def action_past ( count ) : return ungettext_lazy ( u\"\" , u\"\" , count ) policy_rules = ( ( \"\" , \"\" ) , ) class DeletePolicyLink ( policy . PolicyTargetMixin , tables . DeleteAction ) : name = \"\" @ staticmethod def action_present ( count ) : return ungettext_lazy ( u\"\" , u\"\" , count ) @ staticmethod def action_past ( count ) : return ungettext_lazy ( u\"\" , u\"\" , count ) policy_rules = ( ( \"\" , \"\" ) , ) class DeleteFirewallLink ( policy . PolicyTargetMixin , tables . DeleteAction ) : name = \"\" @ staticmethod ", "answer": "def action_present ( count ) :"}, {"prompt": " from __future__ import unicode_literals from django . db import models , migrations class Migration ( migrations . Migration ) : dependencies = [ ( '' , '' ) , ] operations = [ migrations . AlterField ( model_name = '' , name = '' , ", "answer": "field = models . TextField ( blank = True , default = '' ) ,"}, {"prompt": " from django . test import TestCase from django . test . client import Client ", "answer": "try :"}, {"prompt": " '''''' ", "answer": "from shovel import task"}, {"prompt": " '''''' from os import name ", "answer": "from pypomvisualiser . display . TKinterDisplay import TKinterDisplay"}, {"prompt": " import os from test import CollectorTestCase from test import get_collector_config from test import unittest from mock import Mock from mock import patch from diamond . collector import Collector from ksm import KSMCollector class TestKSMCollector ( CollectorTestCase ) : def setUp ( self ) : config = get_collector_config ( '' , { '' : , '' : os . path . dirname ( __file__ ) + '' } ) self . collector = KSMCollector ( config , None ) ", "answer": "def test_import ( self ) :"}, {"prompt": " from __future__ import unicode_literals from . common import InfoExtractor from . . utils import ExtractorError class FreeVideoIE ( InfoExtractor ) : _VALID_URL = r'' _TEST = { '' : '' , '' : { '' : '' , '' : '' , \"\" : \"\" , \"\" : , } , '' : '' , } def _real_extract ( self , url ) : video_id = self . _match_id ( url ) webpage , handle = self . _download_webpage_handle ( url , video_id ) if '' in handle . geturl ( ) : ", "answer": "raise ExtractorError ("}, {"prompt": " from twisted . spread import pb from twisted . internet import reactor class Two ( pb . Referenceable ) : def remote_print ( self , arg ) : print \"\" , arg class One ( pb . Root ) : def __init__ ( self , two ) : self . two = two def remote_getTwo ( self ) : print \"\" , self . two return self . two def remote_checkTwo ( self , newtwo ) : ", "answer": "print \"\" , self . two"}, {"prompt": " from . errors import APIError from . auth import Credentials ", "answer": "from . hub import Hub"}, {"prompt": " import os import os . path import sys import string import getopt import re import socket import time import threading import traceback import types import subprocess import macosxSupport import linecache from code import InteractiveInterpreter try : from Tkinter import * except ImportError : print >> sys . __stderr__ , \"\" \"\" sys . exit ( ) import tkMessageBox from EditorWindow import EditorWindow , fixwordbreaks from FileList import FileList from ColorDelegator import ColorDelegator from UndoDelegator import UndoDelegator from OutputWindow import OutputWindow from configHandler import idleConf from utils import tb_print_list import idlever import rpc import Debugger import RemoteDebugger IDENTCHARS = string . ascii_letters + string . digits + \"\" HOST = '' PORT = global warning_stream warning_stream = sys . __stderr__ try : import warnings except ImportError : pass else : def idle_showwarning ( message , category , filename , lineno , file = None , line = None ) : if file is None : file = warning_stream try : file . write ( warnings . formatwarning ( message , category , filename , lineno , file = file , line = line ) ) except IOError : pass warnings . showwarning = idle_showwarning def idle_formatwarning ( message , category , filename , lineno , line = None ) : \"\"\"\"\"\" s = \"\" s += '' % ( filename , lineno ) if line is None : line = linecache . getline ( filename , lineno ) line = line . strip ( ) if line : s += \"\" % line s += \"\" % ( category . __name__ , message ) return s warnings . formatwarning = idle_formatwarning def extended_linecache_checkcache ( filename = None , orig_checkcache = linecache . checkcache ) : \"\"\"\"\"\" cache = linecache . cache save = { } for key in list ( cache ) : if key [ : ] + key [ - : ] == '' : save [ key ] = cache . pop ( key ) orig_checkcache ( filename ) cache . update ( save ) linecache . checkcache = extended_linecache_checkcache class PyShellEditorWindow ( EditorWindow ) : \"\" def __init__ ( self , * args ) : self . breakpoints = [ ] EditorWindow . __init__ ( self , * args ) self . text . bind ( \"\" , self . set_breakpoint_here ) self . text . bind ( \"\" , self . clear_breakpoint_here ) self . text . bind ( \"\" , self . flist . open_shell ) self . breakpointPath = os . path . join ( idleConf . GetUserCfgDir ( ) , '' ) if self . io . filename : self . restore_file_breaks ( ) def filename_changed_hook ( old_hook = self . io . filename_change_hook , self = self ) : self . restore_file_breaks ( ) old_hook ( ) self . io . set_filename_change_hook ( filename_changed_hook ) rmenu_specs = [ ( \"\" , \"\" , \"\" ) , ( \"\" , \"\" , \"\" ) , ( \"\" , \"\" , \"\" ) , ( None , None , None ) , ( \"\" , \"\" , None ) , ( \"\" , \"\" , None ) ] def set_breakpoint ( self , lineno ) : text = self . text filename = self . io . filename text . tag_add ( \"\" , \"\" % lineno , \"\" % ( lineno + ) ) try : i = self . breakpoints . index ( lineno ) except ValueError : self . breakpoints . append ( lineno ) try : debug = self . flist . pyshell . interp . debugger debug . set_breakpoint_here ( filename , lineno ) except : pass def set_breakpoint_here ( self , event = None ) : text = self . text filename = self . io . filename if not filename : text . bell ( ) return lineno = int ( float ( text . index ( \"\" ) ) ) self . set_breakpoint ( lineno ) def clear_breakpoint_here ( self , event = None ) : text = self . text filename = self . io . filename if not filename : text . bell ( ) return lineno = int ( float ( text . index ( \"\" ) ) ) try : self . breakpoints . remove ( lineno ) except : pass text . tag_remove ( \"\" , \"\" , \"\" ) try : debug = self . flist . pyshell . interp . debugger debug . clear_breakpoint_here ( filename , lineno ) except : pass def clear_file_breaks ( self ) : if self . breakpoints : text = self . text filename = self . io . filename if not filename : text . bell ( ) return self . breakpoints = [ ] text . tag_remove ( \"\" , \"\" , END ) try : debug = self . flist . pyshell . interp . debugger debug . clear_file_breaks ( filename ) except : pass def store_file_breaks ( self ) : \"\" breaks = self . breakpoints filename = self . io . filename try : lines = open ( self . breakpointPath , \"\" ) . readlines ( ) except IOError : lines = [ ] new_file = open ( self . breakpointPath , \"\" ) for line in lines : if not line . startswith ( filename + '' ) : new_file . write ( line ) self . update_breakpoints ( ) breaks = self . breakpoints if breaks : new_file . write ( filename + '' + str ( breaks ) + '' ) ", "answer": "new_file . close ( )"}, {"prompt": " '''''' import base64 import unittest import zlib from StringIO import StringIO import numpy as np from cellprofiler . preferences import set_headless set_headless ( ) import cellprofiler . workspace as cpw import cellprofiler . cpgridinfo as cpg import cellprofiler . cpimage as cpi import cellprofiler . cpmodule as cpm import cellprofiler . objects as cpo import cellprofiler . measurements as cpmeas import cellprofiler . pipeline as cpp import cellprofiler . modules . displaydataonimage as D from centrosome . cpmorphology import centers_of_labels INPUT_IMAGE_NAME = '' OUTPUT_IMAGE_NAME = '' OBJECTS_NAME = '' MEASUREMENT_NAME = '' class TestDisplayDataOnImage ( unittest . TestCase ) : def test_01_00_load_matlab ( self ) : data = ( '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' ) pipeline = cpp . Pipeline ( ) def callback ( caller , event ) : self . assertFalse ( isinstance ( event , cpp . LoadExceptionEvent ) ) pipeline . add_listener ( callback ) pipeline . load ( StringIO ( zlib . decompress ( base64 . b64decode ( data ) ) ) ) self . assertEqual ( len ( pipeline . modules ( ) ) , ) module = pipeline . modules ( ) [ - ] self . assertTrue ( isinstance ( module , D . DisplayDataOnImage ) ) self . assertEqual ( module . image_name , \"\" ) self . assertEqual ( module . text_color , \"\" ) self . assertEqual ( module . objects_or_image , D . OI_IMAGE ) self . assertEqual ( module . display_image , \"\" ) self . assertEqual ( module . saved_image_contents , \"\" ) def test_01_01_load_v1 ( self ) : data = ( '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' ) pipeline = cpp . Pipeline ( ) def callback ( caller , event ) : self . assertFalse ( isinstance ( event , cpp . LoadExceptionEvent ) ) pipeline . add_listener ( callback ) pipeline . load ( StringIO ( zlib . decompress ( base64 . b64decode ( data ) ) ) ) self . assertEqual ( len ( pipeline . modules ( ) ) , ) module = pipeline . modules ( ) [ - ] self . assertTrue ( isinstance ( module , D . DisplayDataOnImage ) ) self . assertEqual ( module . objects_or_image , D . OI_OBJECTS ) self . assertEqual ( module . objects_name , \"\" ) self . assertEqual ( module . measurement , \"\" ) self . assertEqual ( module . image_name , \"\" ) self . assertEqual ( module . text_color , \"\" ) self . assertEqual ( module . display_image , \"\" ) self . assertEqual ( module . saved_image_contents , \"\" ) def test_01_04_load_v4 ( self ) : data = r\"\"\"\"\"\" pipeline = cpp . Pipeline ( ) def callback ( caller , event ) : self . assertFalse ( isinstance ( event , cpp . LoadExceptionEvent ) ) pipeline . add_listener ( callback ) pipeline . load ( StringIO ( data ) ) self . assertEqual ( len ( pipeline . modules ( ) ) , ) module = pipeline . modules ( ) [ ] self . assertTrue ( isinstance ( module , D . DisplayDataOnImage ) ) self . assertEqual ( module . objects_or_image , D . OI_OBJECTS ) self . assertEqual ( module . measurement , \"\" ) self . assertEqual ( module . image_name , \"\" ) self . assertEqual ( module . text_color , \"\" ) self . assertEqual ( module . objects_name , \"\" ) self . assertEqual ( module . display_image , \"\" ) self . assertEqual ( module . font_size , ) self . assertEqual ( module . decimals , ) self . assertEqual ( module . saved_image_contents , D . E_AXES ) self . assertEqual ( module . offset , ) self . assertEqual ( module . color_or_text , D . CT_COLOR ) self . assertEqual ( module . colormap , \"\" ) self . assertTrue ( module . wants_image ) def test_01_04_load_v5 ( self ) : data = r\"\"\"\"\"\" pipeline = cpp . Pipeline ( ) def callback ( caller , event ) : self . assertFalse ( isinstance ( event , cpp . LoadExceptionEvent ) ) pipeline . add_listener ( callback ) pipeline . load ( StringIO ( data ) ) self . assertEqual ( len ( pipeline . modules ( ) ) , ) module = pipeline . modules ( ) [ ] self . assertTrue ( isinstance ( module , D . DisplayDataOnImage ) ) self . assertEqual ( module . objects_or_image , D . OI_OBJECTS ) self . assertEqual ( module . measurement , \"\" ) self . assertEqual ( module . image_name , \"\" ) self . assertEqual ( module . text_color , \"\" ) self . assertEqual ( module . objects_name , \"\" ) self . assertEqual ( module . display_image , \"\" ) self . assertEqual ( module . font_size , ) self . assertEqual ( module . decimals , ) self . assertEqual ( module . saved_image_contents , D . E_AXES ) self . assertEqual ( module . offset , ) self . assertEqual ( module . color_or_text , D . CT_COLOR ) self . assertEqual ( module . colormap , \"\" ) self . assertFalse ( module . wants_image ) self . assertEqual ( module . color_map_scale_choice , D . CMS_USE_MEASUREMENT_RANGE ) self . assertEqual ( module . color_map_scale . min , ) self . assertEqual ( module . color_map_scale . max , ) def test_01_06_load_v6 ( self ) : data = r\"\"\"\"\"\" pipeline = cpp . Pipeline ( ) def callback ( caller , event ) : self . assertFalse ( isinstance ( event , cpp . LoadExceptionEvent ) ) pipeline . add_listener ( callback ) pipeline . load ( StringIO ( data ) ) self . assertEqual ( len ( pipeline . modules ( ) ) , ) module = pipeline . modules ( ) [ ] self . assertTrue ( isinstance ( module , D . DisplayDataOnImage ) ) self . assertEqual ( module . objects_or_image , D . OI_OBJECTS ) self . assertEqual ( module . objects_name , \"\" ) self . assertEqual ( module . measurement , \"\" ) ", "answer": "self . assertEqual ( module . image_name , \"\" )"}, {"prompt": " class BaseRepository ( object ) : def __init__ ( self , path , ** kwargs ) : \"\"\"\"\"\" self . path = path ", "answer": "self . extra = kwargs"}, {"prompt": " \"\"\"\"\"\" import warnings from . volumeutils import array_from_file , apply_read_scaling from . fileslice import fileslice from . keywordonly import kw_only_meth from . openers import ImageOpener class ArrayProxy ( object ) : \"\"\"\"\"\" order = '' @ kw_only_meth ( ) def __init__ ( self , file_like , header , mmap = True ) : \"\"\"\"\"\" if mmap not in ( True , False , '' , '' ) : raise ValueError ( \"\" ) self . file_like = file_like self . _shape = header . get_data_shape ( ) self . _dtype = header . get_data_dtype ( ) self . _offset = header . get_data_offset ( ) self . _slope , self . _inter = header . get_slope_inter ( ) self . _slope = if self . _slope is None else self . _slope self . _inter = if self . _inter is None else self . _inter self . _mmap = mmap self . _header = header . copy ( ) @ property def header ( self ) : warnings . warn ( '' , FutureWarning , ", "answer": "stacklevel = )"}, {"prompt": " import glob import time import os import numpy as np import hickle as hkl from proc_load import crop_and_mirror def proc_configs ( config ) : if not os . path . exists ( config [ '' ] ) : os . makedirs ( config [ '' ] ) print \"\" + config [ '' ] return config def unpack_configs ( config , ext_data = '' , ext_label = '' ) : flag_para_load = config [ '' ] train_folder = config [ '' ] val_folder = config [ '' ] label_folder = config [ '' ] train_filenames = sorted ( glob . glob ( train_folder + '' + ext_data ) ) val_filenames = sorted ( glob . glob ( val_folder + '' + ext_data ) ) train_labels = np . load ( label_folder + '' + ext_label ) val_labels = np . load ( label_folder + '' + ext_label ) img_mean = np . load ( config [ '' ] ) img_mean = img_mean [ : , : , : , np . newaxis ] . astype ( '' ) return ( flag_para_load , train_filenames , val_filenames , train_labels , val_labels , img_mean ) def adjust_learning_rate ( config , epoch , step_idx , val_record , learning_rate ) : if config [ '' ] == '' : if epoch == config [ '' ] [ step_idx ] : learning_rate . set_value ( np . float32 ( learning_rate . get_value ( ) / ) ) step_idx += if step_idx >= len ( config [ '' ] ) : step_idx = print '' , learning_rate . get_value ( ) if config [ '' ] == '' : ", "answer": "if ( epoch > ) and ( val_record [ - ] - val_record [ - ] <"}, {"prompt": " \"\"\"\"\"\" from __pypy__ import tproxy from types import MethodType _dummy = object ( ) origtype = type def make_proxy ( controller , type = _dummy , obj = _dummy ) : \"\"\"\"\"\" if type is _dummy : if obj is _dummy : raise TypeError ( \"\" ) type = origtype ( obj ) ", "answer": "def perform ( opname , * args , ** kwargs ) :"}, {"prompt": " import os import logging import logging . handlers import shelve from socket import inet_aton from struct import pack import tornado . web import binascii try : from ConfigParser import RawConfigParser from httplib import responses except ImportError : from configparser import RawConfigParser from http . client import responses CONFIG_PATH = os . path . expanduser ( '' ) DB_PATH = os . path . expanduser ( '' ) LOG_PATH = os . path . expanduser ( '' ) PEER_INCREASE_LIMIT = DEFAULT_ALLOWED_PEERS = MAX_ALLOWED_PEERS = INFO_HASH_LEN = * PEER_ID_LEN = INVALID_REQUEST_TYPE = MISSING_INFO_HASH = MISSING_PEER_ID = MISSING_PORT = INVALID_INFO_HASH = INVALID_PEER_ID = INVALID_NUMWANT = GENERIC_ERROR = PYTT_RESPONSE_MESSAGES = { INVALID_REQUEST_TYPE : '' , MISSING_INFO_HASH : '' , MISSING_PEER_ID : '' , MISSING_PORT : '' , INVALID_INFO_HASH : '' % INFO_HASH_LEN , INVALID_PEER_ID : '' % PEER_ID_LEN , INVALID_NUMWANT : '' % MAX_ALLOWED_PEERS , GENERIC_ERROR : '' , } responses . update ( PYTT_RESPONSE_MESSAGES ) logger = logging . getLogger ( '' ) def setup_logging ( debug = False ) : \"\"\"\"\"\" if debug : level = logging . DEBUG else : level = logging . INFO log_handler = logging . handlers . RotatingFileHandler ( LOG_PATH , maxBytes = * , backupCount = ) root_logger = logging . getLogger ( '' ) root_logger . setLevel ( level ) format = '' formatter = logging . Formatter ( format ) log_handler . setFormatter ( formatter ) root_logger . addHandler ( log_handler ) def create_config ( path ) : \"\"\"\"\"\" logging . info ( '' % CONFIG_PATH ) config = RawConfigParser ( ) config . add_section ( '' ) config . set ( '' , '' , '' ) config . set ( '' , '' , '' ) config . set ( '' , '' , '' ) with open ( path , '' ) as f : config . write ( f ) def create_pytt_dirs ( ) : \"\"\"\"\"\" logging . info ( '' ) for path in [ CONFIG_PATH , DB_PATH , LOG_PATH ] : dirname = os . path . dirname ( path ) if not os . path . exists ( dirname ) : os . makedirs ( dirname ) if not os . path . exists ( CONFIG_PATH ) : create_config ( CONFIG_PATH ) class BaseHandler ( tornado . web . RequestHandler ) : \"\"\"\"\"\" def decode_argument ( self , value , name ) : if name == '' : value = binascii . hexlify ( value ) return super ( BaseHandler , self ) . decode_argument ( value , name ) class ConfigError ( Exception ) : \"\"\"\"\"\" class Config : \"\"\"\"\"\" __shared_state = { } def __init__ ( self ) : \"\"\"\"\"\" self . __dict__ = self . __shared_state def get ( self ) : \"\"\"\"\"\" if not hasattr ( self , '' ) : self . __config = RawConfigParser ( ) if self . __config . read ( CONFIG_PATH ) == [ ] : raise ConfigError ( '' % CONFIG_PATH ) return self . __config def close ( self ) : \"\"\"\"\"\" if not hasattr ( self , '' ) : return del self . __config class Database : \"\"\"\"\"\" __shared_state = { } def __init__ ( self ) : \"\"\"\"\"\" self . __dict__ = self . __shared_state def get ( self ) : \"\"\"\"\"\" if not hasattr ( self , '' ) : self . __db = shelve . open ( DB_PATH , writeback = True ) return self . __db def close ( self ) : \"\"\"\"\"\" if not hasattr ( self , '' ) : return self . __db . close ( ) del self . __db def get_config ( ) : \"\"\"\"\"\" return Config ( ) . get ( ) def get_db ( ) : \"\"\"\"\"\" return Database ( ) . get ( ) def close_db ( ) : \"\"\"\"\"\" Database ( ) . close ( ) def no_of_seeders ( info_hash ) : \"\"\"\"\"\" db = get_db ( ) count = if info_hash in db : for peer_info in db [ info_hash ] : if peer_info [ ] == '' : count += return count def no_of_leechers ( info_hash ) : \"\"\"\"\"\" db = get_db ( ) count = if info_hash in db : for peer_info in db [ info_hash ] : if peer_info [ ] == '' : count += return count def store_peer_info ( info_hash , peer_id , ip , port , status ) : \"\"\"\"\"\" db = get_db ( ) if info_hash in db : if ( peer_id , ip , port , status ) not in db [ info_hash ] : db [ info_hash ] . append ( ( peer_id , ip , port , status ) ) else : db [ info_hash ] = [ ( peer_id , ip , port , status ) ] def get_peer_list ( info_hash , numwant , compact , no_peer_id ) : \"\"\"\"\"\" db = get_db ( ) if compact : byteswant = numwant * compact_peers = b'' if info_hash in db : for peer_info in db [ info_hash ] : ip = inet_aton ( peer_info [ ] ) port = pack ( '' , int ( peer_info [ ] ) ) compact_peers += ( ip + port ) logging . debug ( '' % compact_peers [ : byteswant ] ) ", "answer": "return compact_peers [ : byteswant ]"}, {"prompt": " \"\"\"\"\"\" import calendar import time from cloudcafe . common . tools . datagen import rand_name from cloudcafe . glance . common . constants import Messages from cloudcafe . glance . common . types import ImageMemberStatus from cloudroast . glance . fixtures import ImagesFixture class ListImageMembers ( ImagesFixture ) : @ classmethod def setUpClass ( cls ) : super ( ListImageMembers , cls ) . setUpClass ( ) cls . alt_member_id = cls . images_alt_one . auth . tenant_id cls . alt_two_member_id = cls . images_alt_two . auth . tenant_id created_images = cls . images . behaviors . create_images_via_task ( image_properties = { '' : rand_name ( '' ) } , count = ) cls . shared_image = created_images . pop ( ) cls . images . client . create_image_member ( cls . shared_image . id_ , cls . alt_member_id ) cls . images . client . create_image_member ( cls . shared_image . id_ , cls . alt_two_member_id ) cls . image_member_created_at_time_in_sec = ( calendar . timegm ( time . gmtime ( ) ) ) cls . alt_shared_image = created_images . pop ( ) cls . images . client . create_image_member ( cls . alt_shared_image . id_ , cls . alt_member_id ) cls . images . client . create_image_member ( cls . alt_shared_image . id_ , cls . alt_two_member_id ) cls . no_access_image = created_images . pop ( ) cls . delete_image = created_images . pop ( ) cls . images . client . delete_image ( cls . delete_image . id_ ) cls . deactivated_image = created_images . pop ( ) cls . images . client . create_image_member ( cls . deactivated_image . id_ , cls . alt_member_id ) cls . images_admin . client . deactivate_image ( cls . deactivated_image . id_ ) cls . reactivated_image = created_images . pop ( ) cls . images . client . create_image_member ( cls . reactivated_image . id_ , cls . alt_member_id ) cls . images_admin . client . deactivate_image ( cls . reactivated_image . id_ ) cls . images_admin . client . reactivate_image ( cls . reactivated_image . id_ ) @ classmethod def tearDownClass ( cls ) : cls . images . behaviors . resources . release ( ) super ( ListImageMembers , cls ) . tearDownClass ( ) def test_list_image_members_all_member_statuses ( self ) : \"\"\"\"\"\" status = { '' : ImageMemberStatus . ALL } resp = self . images . client . list_image_members ( image_id = self . shared_image . id_ , params = status ) self . assertEqual ( resp . status_code , , Messages . STATUS_CODE_MSG . format ( , resp . status_code ) ) listed_image_members = resp . entity self . assertEqual ( len ( listed_image_members ) , , msg = ( '' '' ) . format ( len ( listed_image_members ) ) ) def test_list_image_members_using_deactivated_image ( self ) : \"\"\"\"\"\" image_member_ids = [ ] errors = [ ] resp = self . images . client . list_image_members ( self . deactivated_image . id_ ) self . assertEqual ( resp . status_code , , Messages . STATUS_CODE_MSG . format ( , resp . status_code ) ) listed_image_members = resp . entity self . assertEqual ( len ( listed_image_members ) , , msg = ( '' '' ) . format ( len ( listed_image_members ) ) ) [ image_member_ids . append ( image_member . member_id ) for image_member in listed_image_members ] self . assertIn ( self . alt_member_id , image_member_ids , msg = ( '' '' '' ) . format ( self . alt_member_id , image_member_ids ) ) for image_member in listed_image_members : errors = self . images . behaviors . validate_image_member ( image_member ) self . assertEqual ( errors , [ ] , msg = ( '' '' '' ) . format ( self . deactivated_image . id_ , errors ) ) def test_list_image_members_using_reactivated_image ( self ) : \"\"\"\"\"\" image_member_ids = [ ] errors = [ ] resp = self . images . client . list_image_members ( self . reactivated_image . id_ ) self . assertEqual ( resp . status_code , , Messages . STATUS_CODE_MSG . format ( , resp . status_code ) ) listed_image_members = resp . entity self . assertEqual ( len ( listed_image_members ) , , msg = ( '' '' ) . format ( len ( listed_image_members ) ) ) [ image_member_ids . append ( image_member . member_id ) for image_member in listed_image_members ] self . assertIn ( self . alt_member_id , image_member_ids , msg = ( '' '' '' ) . format ( self . alt_member_id , image_member_ids ) ) for image_member in listed_image_members : errors = self . images . behaviors . validate_image_member ( image_member ) self . assertEqual ( errors , [ ] , msg = ( '' '' '' ) . format ( self . reactivated_image . id_ , errors ) ) def test_list_image_members_using_invalid_image_id ( self ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " '''''' from __future__ import absolute_import import code import sys from optparse import OptionParser import cpa import cpa . properties import cpa . dbconnect ", "answer": "parser = OptionParser ( \"\" )"}, {"prompt": " class BaseError ( Exception ) : def __init__ ( self , message , * args , ** kwargs ) : self . message = message super ( BaseError , self ) . __init__ ( message , * args , ** kwargs ) class WrongInputDataError ( BaseError ) : pass class WrongPartitionSchemeError ( BaseError ) : pass class WrongPartitionPolicyError ( BaseError ) : pass class PartitionSchemeMismatchError ( BaseError ) : pass class HardwarePartitionSchemeCannotBeReadError ( BaseError ) : pass class WrongPartitionLabelError ( BaseError ) : pass class PartitionNotFoundError ( BaseError ) : pass class DiskNotFoundError ( BaseError ) : pass class NotEnoughSpaceError ( BaseError ) : pass class PVAlreadyExistsError ( BaseError ) : pass class PVNotFoundError ( BaseError ) : pass class PVBelongsToVGError ( BaseError ) : pass class VGAlreadyExistsError ( BaseError ) : pass class VGNotFoundError ( BaseError ) : pass class LVAlreadyExistsError ( BaseError ) : pass class LVNotFoundError ( BaseError ) : pass class MDAlreadyExistsError ( BaseError ) : pass class MDNotFoundError ( BaseError ) : pass class MDDeviceDuplicationError ( BaseError ) : pass class MDWrongSpecError ( BaseError ) : pass class MDRemovingError ( BaseError ) : pass class WrongConfigDriveDataError ( BaseError ) : pass class WrongImageDataError ( BaseError ) : pass class TemplateWriteError ( BaseError ) : pass class ProcessExecutionError ( BaseError ) : def __init__ ( self , stdout = None , stderr = None , exit_code = None , cmd = None , description = None ) : self . exit_code = exit_code self . stderr = stderr self . stdout = stdout self . cmd = cmd self . description = description if description is None : description = ( \"\" ) if exit_code is None : exit_code = '' message = ( '' '' '' '' '' ) % { '' : description , '' : cmd , '' : exit_code , '' : stdout , '' : stderr } super ( ProcessExecutionError , self ) . __init__ ( message ) class GrubUtilsError ( BaseError ) : pass class FsUtilsError ( BaseError ) : pass class HttpUrlConnectionError ( BaseError ) : pass class HttpUrlInvalidContentLength ( BaseError ) : pass class ImageChecksumMismatchError ( BaseError ) : pass class NoFreeLoopDevices ( BaseError ) : pass class WrongRepositoryError ( BaseError ) : pass ", "answer": "class WrongDeviceError ( BaseError ) :"}, {"prompt": " from input_algorithms . errors import BadSpec , BadSpecValue from delfick_error import DelfickError , ProgrammerError class HarpoonError ( DelfickError ) : pass BadSpec = BadSpec BadSpecValue = BadSpecValue ProgrammerError = ProgrammerError class BadConfiguration ( HarpoonError ) : desc = \"\" class BadOptionFormat ( HarpoonError ) : desc = \"\" class BadTask ( HarpoonError ) : desc = \"\" class BadOption ( HarpoonError ) : desc = \"\" class NoSuchKey ( HarpoonError ) : desc = \"\" class NoSuchImage ( HarpoonError ) : desc = \"\" class BadCommand ( HarpoonError ) : desc = \"\" class BadImage ( HarpoonError ) : desc = \"\" class CouldntKill ( HarpoonError ) : desc = \"\" class FailedImage ( HarpoonError ) : desc = \"\" class BadYaml ( HarpoonError ) : desc = \"\" class BadResult ( HarpoonError ) : desc = \"\" class UserQuit ( HarpoonError ) : desc = \"\" class BadDockerConnection ( HarpoonError ) : ", "answer": "desc = \"\""}, {"prompt": " class FatalCatastrophyException ( RuntimeError ) : ROBOT_EXIT_ON_FAILURE = True class ContinuableApocalypseException ( RuntimeError ) : ROBOT_CONTINUE_ON_FAILURE = True def exit_on_failure ( ) : raise FatalCatastrophyException ( ) ", "answer": "def raise_continuable_failure ( msg = '' ) :"}, {"prompt": " import os extensions = [ '' , '' , '' , '' , '' , '' ] templates_path = [ '' ] source_suffix = '' master_doc = '' project = u'' copyright = u'' ", "answer": "version = ''"}, {"prompt": " \"\"\"\"\"\" from threading import Event , Lock from errors import * try : from json import JSONDecoder , JSONEncoder except ImportError , e : from simplejson import JSONDecoder , JSONEncoder class JSONRPCEncoder ( JSONEncoder ) : def default ( self , obj ) : if isinstance ( obj , JSONRPCError ) : return obj . __class__ . __name__ else : return JSONEncoder . default ( self , obj ) class Timeout ( Exception ) : pass class ResponseEvent : \"\"\"\"\"\" def __init__ ( self ) : self . __evt = Event ( ) def waiting ( self ) : return not self . __evt . isSet ( ) def waitForResponse ( self , timeOut = None ) : \"\"\"\"\"\" self . __evt . wait ( timeOut ) if self . waiting ( ) : raise Timeout ( ) else : if self . response [ \"\" ] : raise Exception ( self . response [ \"\" ] ) else : return self . response [ \"\" ] def handleResponse ( self , resp ) : self . response = resp self . __evt . set ( ) class SimpleMessageHandler : def __init__ ( self , DecoderClass = JSONDecoder , EncoderClass = JSONRPCEncoder , messageDelimiter = \"\" ) : self . decoder = DecoderClass ( ) self . encoder = EncoderClass ( ) self . partialData = \"\" self . respEvents = { } self . respLock = Lock ( ) self . messageDelimiter = messageDelimiter def close ( self ) : pass def send ( self , data ) : pass def sendMessage ( self , msg ) : self . send ( self . encoder . encode ( msg ) + self . messageDelimiter ) def handlePartialData ( self , data ) : data = self . partialData + data . replace ( \"\" , \"\" ) . replace ( \"\" , \"\" ) msgs = [ ] while data != \"\" : pos = data . find ( \"\" ) if ( pos > - ) : data = data [ pos : ] try : ( obj , pos ) = self . decoder . raw_decode ( data ) data = data [ pos : ] msgs . append ( obj ) except : break else : break self . partialData = data self . handleMessages ( msgs ) def sendNotify ( self , name , args ) : \"\"\"\"\"\" self . sendMessage ( { \"\" : name , \"\" : args } ) def sendRequest ( self , name , args ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " \"\"\"\"\"\" import time from google . appengine . api . memcache import Client class MemcacheClient ( object ) : client = Client ( ) def __init__ ( self , request , default_time_expire = ) : self . request = request self . default_time_expire = default_time_expire def __call__ ( self , key , f , time_expire = None , ) : if time_expire is None : time_expire = self . default_time_expire key = '' % ( self . request . application , key ) value = None obj = self . client . get ( key ) if obj : value = obj [ ] elif f is not None : value = f ( ) self . client . set ( key , ( time . time ( ) , value ) , time = time_expire ) return value def increment ( self , key , value = ) : key = '' % ( self . request . application , key ) obj = self . client . get ( key ) if obj : value = obj [ ] + value self . client . set ( key , ( time . time ( ) , value ) ) return value def incr ( self , key , value = ) : return self . increment ( key , value ) def clear ( self , key = None ) : if key : key = '' % ( self . request . application , key ) self . client . delete ( key ) else : self . client . flush_all ( ) def delete ( self , * a , ** b ) : ", "answer": "return self . client . delete ( * a , ** b )"}, {"prompt": " INTERNET_INVALID_PORT_NUMBER = INTERNET_DEFAULT_FTP_PORT = INTERNET_DEFAULT_GOPHER_PORT = INTERNET_DEFAULT_HTTP_PORT = INTERNET_DEFAULT_HTTPS_PORT = INTERNET_DEFAULT_SOCKS_PORT = INTERNET_MAX_HOST_NAME_LENGTH = INTERNET_MAX_USER_NAME_LENGTH = INTERNET_MAX_PASSWORD_LENGTH = INTERNET_MAX_PORT_NUMBER_LENGTH = INTERNET_MAX_PORT_NUMBER_VALUE = INTERNET_MAX_PATH_LENGTH = INTERNET_MAX_SCHEME_LENGTH = INTERNET_KEEP_ALIVE_ENABLED = INTERNET_KEEP_ALIVE_DISABLED = INTERNET_REQFLAG_FROM_CACHE = INTERNET_REQFLAG_ASYNC = INTERNET_REQFLAG_VIA_PROXY = INTERNET_REQFLAG_NO_HEADERS = INTERNET_REQFLAG_PASSIVE = INTERNET_REQFLAG_CACHE_WRITE_DISABLED = INTERNET_REQFLAG_NET_TIMEOUT = INTERNET_FLAG_RELOAD = ( - ) INTERNET_FLAG_RAW_DATA = INTERNET_FLAG_EXISTING_CONNECT = INTERNET_FLAG_ASYNC = INTERNET_FLAG_PASSIVE = INTERNET_FLAG_NO_CACHE_WRITE = INTERNET_FLAG_DONT_CACHE = INTERNET_FLAG_NO_CACHE_WRITE INTERNET_FLAG_MAKE_PERSISTENT = INTERNET_FLAG_FROM_CACHE = INTERNET_FLAG_OFFLINE = INTERNET_FLAG_FROM_CACHE INTERNET_FLAG_SECURE = INTERNET_FLAG_KEEP_CONNECTION = INTERNET_FLAG_NO_AUTO_REDIRECT = INTERNET_FLAG_READ_PREFETCH = INTERNET_FLAG_NO_COOKIES = INTERNET_FLAG_NO_AUTH = INTERNET_FLAG_RESTRICTED_ZONE = INTERNET_FLAG_CACHE_IF_NET_FAIL = INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP = INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS = INTERNET_FLAG_IGNORE_CERT_DATE_INVALID = INTERNET_FLAG_IGNORE_CERT_CN_INVALID = INTERNET_FLAG_RESYNCHRONIZE = INTERNET_FLAG_HYPERLINK = INTERNET_FLAG_NO_UI = INTERNET_FLAG_PRAGMA_NOCACHE = INTERNET_FLAG_CACHE_ASYNC = INTERNET_FLAG_FORMS_SUBMIT = INTERNET_FLAG_FWD_BACK = INTERNET_FLAG_NEED_FILE = INTERNET_FLAG_MUST_CACHE_REQUEST = INTERNET_FLAG_NEED_FILE SECURITY_INTERNET_MASK = ( INTERNET_FLAG_IGNORE_CERT_CN_INVALID | INTERNET_FLAG_IGNORE_CERT_DATE_INVALID | INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS | INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP ) INTERNET_ERROR_MASK_INSERT_CDROM = INTERNET_ERROR_MASK_COMBINED_SEC_CERT = INTERNET_ERROR_MASK_NEED_MSN_SSPI_PKG = INTERNET_ERROR_MASK_LOGIN_FAILURE_DISPLAY_ENTITY_BODY = WININET_API_FLAG_ASYNC = WININET_API_FLAG_SYNC = WININET_API_FLAG_USE_CONTEXT = INTERNET_NO_CALLBACK = IDSI_FLAG_KEEP_ALIVE = IDSI_FLAG_SECURE = IDSI_FLAG_PROXY = IDSI_FLAG_TUNNEL = INTERNET_PER_CONN_FLAGS = INTERNET_PER_CONN_PROXY_SERVER = INTERNET_PER_CONN_PROXY_BYPASS = INTERNET_PER_CONN_AUTOCONFIG_URL = INTERNET_PER_CONN_AUTODISCOVERY_FLAGS = INTERNET_PER_CONN_AUTOCONFIG_SECONDARY_URL = INTERNET_PER_CONN_AUTOCONFIG_RELOAD_DELAY_MINS = INTERNET_PER_CONN_AUTOCONFIG_LAST_DETECT_TIME = INTERNET_PER_CONN_AUTOCONFIG_LAST_DETECT_URL = PROXY_TYPE_DIRECT = PROXY_TYPE_PROXY = PROXY_TYPE_AUTO_PROXY_URL = PROXY_TYPE_AUTO_DETECT = AUTO_PROXY_FLAG_USER_SET = AUTO_PROXY_FLAG_ALWAYS_DETECT = AUTO_PROXY_FLAG_DETECTION_RUN = AUTO_PROXY_FLAG_MIGRATED = AUTO_PROXY_FLAG_DONT_CACHE_PROXY_RESULT = AUTO_PROXY_FLAG_CACHE_INIT_RUN = AUTO_PROXY_FLAG_DETECTION_SUSPECT = ISO_FORCE_DISCONNECTED = INTERNET_RFC1123_FORMAT = INTERNET_RFC1123_BUFSIZE = ICU_ESCAPE = ( - ) ICU_USERNAME = ICU_NO_ENCODE = ICU_DECODE = ICU_NO_META = ICU_ENCODE_SPACES_ONLY = ICU_BROWSER_MODE = ICU_ENCODE_PERCENT = INTERNET_OPEN_TYPE_PRECONFIG = INTERNET_OPEN_TYPE_DIRECT = INTERNET_OPEN_TYPE_PROXY = INTERNET_OPEN_TYPE_PRECONFIG_WITH_NO_AUTOPROXY = PRE_CONFIG_INTERNET_ACCESS = INTERNET_OPEN_TYPE_PRECONFIG LOCAL_INTERNET_ACCESS = INTERNET_OPEN_TYPE_DIRECT CERN_PROXY_INTERNET_ACCESS = INTERNET_OPEN_TYPE_PROXY INTERNET_SERVICE_FTP = INTERNET_SERVICE_GOPHER = INTERNET_SERVICE_HTTP = IRF_ASYNC = WININET_API_FLAG_ASYNC IRF_SYNC = WININET_API_FLAG_SYNC IRF_USE_CONTEXT = WININET_API_FLAG_USE_CONTEXT IRF_NO_WAIT = ISO_GLOBAL = ISO_REGISTRY = ISO_VALID_FLAGS = ( ISO_GLOBAL | ISO_REGISTRY ) INTERNET_OPTION_CALLBACK = INTERNET_OPTION_CONNECT_TIMEOUT = INTERNET_OPTION_CONNECT_RETRIES = INTERNET_OPTION_CONNECT_BACKOFF = INTERNET_OPTION_SEND_TIMEOUT = INTERNET_OPTION_CONTROL_SEND_TIMEOUT = INTERNET_OPTION_SEND_TIMEOUT INTERNET_OPTION_RECEIVE_TIMEOUT = INTERNET_OPTION_CONTROL_RECEIVE_TIMEOUT = INTERNET_OPTION_RECEIVE_TIMEOUT INTERNET_OPTION_DATA_SEND_TIMEOUT = INTERNET_OPTION_DATA_RECEIVE_TIMEOUT = INTERNET_OPTION_HANDLE_TYPE = INTERNET_OPTION_LISTEN_TIMEOUT = INTERNET_OPTION_READ_BUFFER_SIZE = INTERNET_OPTION_WRITE_BUFFER_SIZE = INTERNET_OPTION_ASYNC_ID = INTERNET_OPTION_ASYNC_PRIORITY = INTERNET_OPTION_PARENT_HANDLE = INTERNET_OPTION_KEEP_CONNECTION = INTERNET_OPTION_REQUEST_FLAGS = INTERNET_OPTION_EXTENDED_ERROR = INTERNET_OPTION_OFFLINE_MODE = INTERNET_OPTION_CACHE_STREAM_HANDLE = INTERNET_OPTION_USERNAME = INTERNET_OPTION_PASSWORD = INTERNET_OPTION_ASYNC = INTERNET_OPTION_SECURITY_FLAGS = INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT = INTERNET_OPTION_DATAFILE_NAME = INTERNET_OPTION_URL = INTERNET_OPTION_SECURITY_CERTIFICATE = INTERNET_OPTION_SECURITY_KEY_BITNESS = INTERNET_OPTION_REFRESH = INTERNET_OPTION_PROXY = INTERNET_OPTION_SETTINGS_CHANGED = INTERNET_OPTION_VERSION = INTERNET_OPTION_USER_AGENT = INTERNET_OPTION_END_BROWSER_SESSION = INTERNET_OPTION_PROXY_USERNAME = INTERNET_OPTION_PROXY_PASSWORD = INTERNET_OPTION_CONTEXT_VALUE = INTERNET_OPTION_CONNECT_LIMIT = INTERNET_OPTION_SECURITY_SELECT_CLIENT_CERT = INTERNET_OPTION_POLICY = INTERNET_OPTION_DISCONNECTED_TIMEOUT = INTERNET_OPTION_CONNECTED_STATE = INTERNET_OPTION_IDLE_STATE = INTERNET_OPTION_OFFLINE_SEMANTICS = INTERNET_OPTION_SECONDARY_CACHE_KEY = INTERNET_OPTION_CALLBACK_FILTER = INTERNET_OPTION_CONNECT_TIME = INTERNET_OPTION_SEND_THROUGHPUT = INTERNET_OPTION_RECEIVE_THROUGHPUT = INTERNET_OPTION_REQUEST_PRIORITY = INTERNET_OPTION_HTTP_VERSION = INTERNET_OPTION_RESET_URLCACHE_SESSION = INTERNET_OPTION_ERROR_MASK = INTERNET_OPTION_FROM_CACHE_TIMEOUT = INTERNET_OPTION_BYPASS_EDITED_ENTRY = INTERNET_OPTION_DIAGNOSTIC_SOCKET_INFO = INTERNET_OPTION_CODEPAGE = INTERNET_OPTION_CACHE_TIMESTAMPS = INTERNET_OPTION_DISABLE_AUTODIAL = INTERNET_OPTION_MAX_CONNS_PER_SERVER = INTERNET_OPTION_MAX_CONNS_PER_1_0_SERVER = INTERNET_OPTION_PER_CONNECTION_OPTION = INTERNET_OPTION_DIGEST_AUTH_UNLOAD = INTERNET_OPTION_IGNORE_OFFLINE = INTERNET_OPTION_IDENTITY = INTERNET_OPTION_REMOVE_IDENTITY = INTERNET_OPTION_ALTER_IDENTITY = INTERNET_OPTION_SUPPRESS_BEHAVIOR = INTERNET_OPTION_AUTODIAL_MODE = INTERNET_OPTION_AUTODIAL_CONNECTION = INTERNET_OPTION_CLIENT_CERT_CONTEXT = INTERNET_OPTION_AUTH_FLAGS = INTERNET_OPTION_COOKIES_3RD_PARTY = INTERNET_OPTION_DISABLE_PASSPORT_AUTH = INTERNET_OPTION_SEND_UTF8_SERVERNAME_TO_PROXY = INTERNET_OPTION_EXEMPT_CONNECTION_LIMIT = INTERNET_OPTION_ENABLE_PASSPORT_AUTH = INTERNET_OPTION_HIBERNATE_INACTIVE_WORKER_THREADS = INTERNET_OPTION_ACTIVATE_WORKER_THREADS = INTERNET_OPTION_RESTORE_WORKER_THREAD_DEFAULTS = INTERNET_OPTION_SOCKET_SEND_BUFFER_LENGTH = INTERNET_OPTION_PROXY_SETTINGS_CHANGED = INTERNET_FIRST_OPTION = INTERNET_OPTION_CALLBACK INTERNET_LAST_OPTION = INTERNET_OPTION_PROXY_SETTINGS_CHANGED INTERNET_PRIORITY_FOREGROUND = INTERNET_HANDLE_TYPE_INTERNET = INTERNET_HANDLE_TYPE_CONNECT_FTP = INTERNET_HANDLE_TYPE_CONNECT_GOPHER = INTERNET_HANDLE_TYPE_CONNECT_HTTP = INTERNET_HANDLE_TYPE_FTP_FIND = INTERNET_HANDLE_TYPE_FTP_FIND_HTML = INTERNET_HANDLE_TYPE_FTP_FILE = INTERNET_HANDLE_TYPE_FTP_FILE_HTML = INTERNET_HANDLE_TYPE_GOPHER_FIND = INTERNET_HANDLE_TYPE_GOPHER_FIND_HTML = INTERNET_HANDLE_TYPE_GOPHER_FILE = INTERNET_HANDLE_TYPE_GOPHER_FILE_HTML = INTERNET_HANDLE_TYPE_HTTP_REQUEST = INTERNET_HANDLE_TYPE_FILE_REQUEST = AUTH_FLAG_DISABLE_NEGOTIATE = AUTH_FLAG_ENABLE_NEGOTIATE = SECURITY_FLAG_SECURE = SECURITY_FLAG_STRENGTH_WEAK = SECURITY_FLAG_STRENGTH_MEDIUM = SECURITY_FLAG_STRENGTH_STRONG = SECURITY_FLAG_UNKNOWNBIT = ( - ) SECURITY_FLAG_FORTEZZA = SECURITY_FLAG_NORMALBITNESS = SECURITY_FLAG_STRENGTH_WEAK SECURITY_FLAG_SSL = SECURITY_FLAG_SSL3 = SECURITY_FLAG_PCT = SECURITY_FLAG_PCT4 = SECURITY_FLAG_IETFSSL4 = SECURITY_FLAG_40BIT = SECURITY_FLAG_STRENGTH_WEAK SECURITY_FLAG_128BIT = SECURITY_FLAG_STRENGTH_STRONG SECURITY_FLAG_56BIT = SECURITY_FLAG_STRENGTH_MEDIUM SECURITY_FLAG_IGNORE_REVOCATION = SECURITY_FLAG_IGNORE_UNKNOWN_CA = SECURITY_FLAG_IGNORE_WRONG_USAGE = SECURITY_FLAG_IGNORE_CERT_CN_INVALID = INTERNET_FLAG_IGNORE_CERT_CN_INVALID SECURITY_FLAG_IGNORE_CERT_DATE_INVALID = INTERNET_FLAG_IGNORE_CERT_DATE_INVALID SECURITY_FLAG_IGNORE_REDIRECT_TO_HTTPS = INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS SECURITY_FLAG_IGNORE_REDIRECT_TO_HTTP = INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP SECURITY_SET_MASK = ( SECURITY_FLAG_IGNORE_REVOCATION | SECURITY_FLAG_IGNORE_UNKNOWN_CA | SECURITY_FLAG_IGNORE_CERT_CN_INVALID | SECURITY_FLAG_IGNORE_CERT_DATE_INVALID | SECURITY_FLAG_IGNORE_WRONG_USAGE ) AUTODIAL_MODE_NEVER = AUTODIAL_MODE_ALWAYS = AUTODIAL_MODE_NO_NETWORK_PRESENT = INTERNET_STATUS_RESOLVING_NAME = INTERNET_STATUS_NAME_RESOLVED = INTERNET_STATUS_CONNECTING_TO_SERVER = INTERNET_STATUS_CONNECTED_TO_SERVER = INTERNET_STATUS_SENDING_REQUEST = INTERNET_STATUS_REQUEST_SENT = INTERNET_STATUS_RECEIVING_RESPONSE = INTERNET_STATUS_RESPONSE_RECEIVED = INTERNET_STATUS_CTL_RESPONSE_RECEIVED = INTERNET_STATUS_PREFETCH = INTERNET_STATUS_CLOSING_CONNECTION = INTERNET_STATUS_CONNECTION_CLOSED = INTERNET_STATUS_HANDLE_CREATED = INTERNET_STATUS_HANDLE_CLOSING = INTERNET_STATUS_DETECTING_PROXY = INTERNET_STATUS_REQUEST_COMPLETE = INTERNET_STATUS_REDIRECT = INTERNET_STATUS_INTERMEDIATE_RESPONSE = INTERNET_STATUS_USER_INPUT_REQUIRED = INTERNET_STATUS_STATE_CHANGE = INTERNET_STATUS_COOKIE_SENT = INTERNET_STATUS_COOKIE_RECEIVED = INTERNET_STATUS_PRIVACY_IMPACTED = INTERNET_STATUS_P3P_HEADER = INTERNET_STATUS_P3P_POLICYREF = INTERNET_STATUS_COOKIE_HISTORY = INTERNET_STATE_CONNECTED = INTERNET_STATE_DISCONNECTED = INTERNET_STATE_DISCONNECTED_BY_USER = INTERNET_STATE_IDLE = INTERNET_STATE_BUSY = FTP_TRANSFER_TYPE_UNKNOWN = FTP_TRANSFER_TYPE_ASCII = FTP_TRANSFER_TYPE_BINARY = FTP_TRANSFER_TYPE_MASK = ( FTP_TRANSFER_TYPE_ASCII | FTP_TRANSFER_TYPE_BINARY ) MAX_GOPHER_DISPLAY_TEXT = MAX_GOPHER_SELECTOR_TEXT = MAX_GOPHER_HOST_NAME = INTERNET_MAX_HOST_NAME_LENGTH MAX_GOPHER_LOCATOR_LENGTH = ( + MAX_GOPHER_DISPLAY_TEXT + + MAX_GOPHER_SELECTOR_TEXT + + MAX_GOPHER_HOST_NAME + + INTERNET_MAX_PORT_NUMBER_LENGTH + + + ) GOPHER_TYPE_TEXT_FILE = GOPHER_TYPE_DIRECTORY = GOPHER_TYPE_CSO = GOPHER_TYPE_ERROR = GOPHER_TYPE_MAC_BINHEX = GOPHER_TYPE_DOS_ARCHIVE = GOPHER_TYPE_UNIX_UUENCODED = GOPHER_TYPE_INDEX_SERVER = GOPHER_TYPE_TELNET = GOPHER_TYPE_BINARY = GOPHER_TYPE_REDUNDANT = GOPHER_TYPE_TN3270 = GOPHER_TYPE_GIF = GOPHER_TYPE_IMAGE = GOPHER_TYPE_BITMAP = GOPHER_TYPE_MOVIE = GOPHER_TYPE_SOUND = GOPHER_TYPE_HTML = GOPHER_TYPE_PDF = GOPHER_TYPE_CALENDAR = GOPHER_TYPE_INLINE = GOPHER_TYPE_UNKNOWN = GOPHER_TYPE_ASK = GOPHER_TYPE_GOPHER_PLUS = ( - ) GOPHER_TYPE_FILE_MASK = ( GOPHER_TYPE_TEXT_FILE | GOPHER_TYPE_MAC_BINHEX | GOPHER_TYPE_DOS_ARCHIVE | GOPHER_TYPE_UNIX_UUENCODED | GOPHER_TYPE_BINARY | GOPHER_TYPE_GIF | GOPHER_TYPE_IMAGE | GOPHER_TYPE_BITMAP | GOPHER_TYPE_MOVIE | GOPHER_TYPE_SOUND | GOPHER_TYPE_HTML | GOPHER_TYPE_PDF | GOPHER_TYPE_CALENDAR | GOPHER_TYPE_INLINE ) MAX_GOPHER_CATEGORY_NAME = MAX_GOPHER_ATTRIBUTE_NAME = MIN_GOPHER_ATTRIBUTE_LENGTH = GOPHER_ATTRIBUTE_ID_BASE = ( - ) GOPHER_CATEGORY_ID_ALL = ( GOPHER_ATTRIBUTE_ID_BASE + ) GOPHER_CATEGORY_ID_INFO = ( GOPHER_ATTRIBUTE_ID_BASE + ) GOPHER_CATEGORY_ID_ADMIN = ( GOPHER_ATTRIBUTE_ID_BASE + ) GOPHER_CATEGORY_ID_VIEWS = ( GOPHER_ATTRIBUTE_ID_BASE + ) GOPHER_CATEGORY_ID_ABSTRACT = ( GOPHER_ATTRIBUTE_ID_BASE + ) GOPHER_CATEGORY_ID_VERONICA = ( GOPHER_ATTRIBUTE_ID_BASE + ) GOPHER_CATEGORY_ID_ASK = ( GOPHER_ATTRIBUTE_ID_BASE + ) GOPHER_CATEGORY_ID_UNKNOWN = ( GOPHER_ATTRIBUTE_ID_BASE + ) GOPHER_ATTRIBUTE_ID_ALL = ( GOPHER_ATTRIBUTE_ID_BASE + ) GOPHER_ATTRIBUTE_ID_ADMIN = ( GOPHER_ATTRIBUTE_ID_BASE + ) GOPHER_ATTRIBUTE_ID_MOD_DATE = ( GOPHER_ATTRIBUTE_ID_BASE + ) GOPHER_ATTRIBUTE_ID_TTL = ( GOPHER_ATTRIBUTE_ID_BASE + ) GOPHER_ATTRIBUTE_ID_SCORE = ( GOPHER_ATTRIBUTE_ID_BASE + ) GOPHER_ATTRIBUTE_ID_RANGE = ( GOPHER_ATTRIBUTE_ID_BASE + ) GOPHER_ATTRIBUTE_ID_SITE = ( GOPHER_ATTRIBUTE_ID_BASE + ) GOPHER_ATTRIBUTE_ID_ORG = ( GOPHER_ATTRIBUTE_ID_BASE + ) GOPHER_ATTRIBUTE_ID_LOCATION = ( GOPHER_ATTRIBUTE_ID_BASE + ) GOPHER_ATTRIBUTE_ID_GEOG = ( GOPHER_ATTRIBUTE_ID_BASE + ) GOPHER_ATTRIBUTE_ID_TIMEZONE = ( GOPHER_ATTRIBUTE_ID_BASE + ) GOPHER_ATTRIBUTE_ID_PROVIDER = ( GOPHER_ATTRIBUTE_ID_BASE + ) GOPHER_ATTRIBUTE_ID_VERSION = ( GOPHER_ATTRIBUTE_ID_BASE + ) GOPHER_ATTRIBUTE_ID_ABSTRACT = ( GOPHER_ATTRIBUTE_ID_BASE + ) GOPHER_ATTRIBUTE_ID_VIEW = ( GOPHER_ATTRIBUTE_ID_BASE + ) GOPHER_ATTRIBUTE_ID_TREEWALK = ( GOPHER_ATTRIBUTE_ID_BASE + ) GOPHER_ATTRIBUTE_ID_UNKNOWN = ( GOPHER_ATTRIBUTE_ID_BASE + ) HTTP_MAJOR_VERSION = HTTP_MINOR_VERSION = HTTP_VERSIONA = \"\" HTTP_VERSION = HTTP_VERSIONA HTTP_QUERY_MIME_VERSION = HTTP_QUERY_CONTENT_TYPE = HTTP_QUERY_CONTENT_TRANSFER_ENCODING = HTTP_QUERY_CONTENT_ID = HTTP_QUERY_CONTENT_DESCRIPTION = HTTP_QUERY_CONTENT_LENGTH = HTTP_QUERY_CONTENT_LANGUAGE = HTTP_QUERY_ALLOW = HTTP_QUERY_PUBLIC = HTTP_QUERY_DATE = HTTP_QUERY_EXPIRES = HTTP_QUERY_LAST_MODIFIED = HTTP_QUERY_MESSAGE_ID = HTTP_QUERY_URI = HTTP_QUERY_DERIVED_FROM = HTTP_QUERY_COST = HTTP_QUERY_LINK = HTTP_QUERY_PRAGMA = HTTP_QUERY_VERSION = HTTP_QUERY_STATUS_CODE = HTTP_QUERY_STATUS_TEXT = HTTP_QUERY_RAW_HEADERS = HTTP_QUERY_RAW_HEADERS_CRLF = HTTP_QUERY_CONNECTION = HTTP_QUERY_ACCEPT = HTTP_QUERY_ACCEPT_CHARSET = HTTP_QUERY_ACCEPT_ENCODING = HTTP_QUERY_ACCEPT_LANGUAGE = HTTP_QUERY_AUTHORIZATION = HTTP_QUERY_CONTENT_ENCODING = HTTP_QUERY_FORWARDED = HTTP_QUERY_FROM = HTTP_QUERY_IF_MODIFIED_SINCE = HTTP_QUERY_LOCATION = HTTP_QUERY_ORIG_URI = HTTP_QUERY_REFERER = HTTP_QUERY_RETRY_AFTER = HTTP_QUERY_SERVER = HTTP_QUERY_TITLE = HTTP_QUERY_USER_AGENT = HTTP_QUERY_WWW_AUTHENTICATE = HTTP_QUERY_PROXY_AUTHENTICATE = HTTP_QUERY_ACCEPT_RANGES = HTTP_QUERY_SET_COOKIE = HTTP_QUERY_COOKIE = HTTP_QUERY_REQUEST_METHOD = HTTP_QUERY_REFRESH = HTTP_QUERY_CONTENT_DISPOSITION = HTTP_QUERY_AGE = HTTP_QUERY_CACHE_CONTROL = HTTP_QUERY_CONTENT_BASE = HTTP_QUERY_CONTENT_LOCATION = HTTP_QUERY_CONTENT_MD5 = HTTP_QUERY_CONTENT_RANGE = HTTP_QUERY_ETAG = HTTP_QUERY_HOST = HTTP_QUERY_IF_MATCH = HTTP_QUERY_IF_NONE_MATCH = HTTP_QUERY_IF_RANGE = HTTP_QUERY_IF_UNMODIFIED_SINCE = HTTP_QUERY_MAX_FORWARDS = HTTP_QUERY_PROXY_AUTHORIZATION = HTTP_QUERY_RANGE = HTTP_QUERY_TRANSFER_ENCODING = HTTP_QUERY_UPGRADE = HTTP_QUERY_VARY = HTTP_QUERY_VIA = HTTP_QUERY_WARNING = HTTP_QUERY_EXPECT = HTTP_QUERY_PROXY_CONNECTION = HTTP_QUERY_UNLESS_MODIFIED_SINCE = HTTP_QUERY_ECHO_REQUEST = HTTP_QUERY_ECHO_REPLY = HTTP_QUERY_ECHO_HEADERS = HTTP_QUERY_ECHO_HEADERS_CRLF = HTTP_QUERY_PROXY_SUPPORT = HTTP_QUERY_AUTHENTICATION_INFO = HTTP_QUERY_PASSPORT_URLS = HTTP_QUERY_PASSPORT_CONFIG = HTTP_QUERY_MAX = HTTP_QUERY_CUSTOM = HTTP_QUERY_FLAG_REQUEST_HEADERS = ( - ) HTTP_QUERY_FLAG_SYSTEMTIME = HTTP_QUERY_FLAG_NUMBER = HTTP_QUERY_FLAG_COALESCE = HTTP_QUERY_MODIFIER_FLAGS_MASK = ( HTTP_QUERY_FLAG_REQUEST_HEADERS | HTTP_QUERY_FLAG_SYSTEMTIME | HTTP_QUERY_FLAG_NUMBER | HTTP_QUERY_FLAG_COALESCE ) HTTP_QUERY_HEADER_MASK = ( ~ HTTP_QUERY_MODIFIER_FLAGS_MASK ) HTTP_STATUS_CONTINUE = HTTP_STATUS_SWITCH_PROTOCOLS = HTTP_STATUS_OK = HTTP_STATUS_CREATED = HTTP_STATUS_ACCEPTED = HTTP_STATUS_PARTIAL = HTTP_STATUS_NO_CONTENT = HTTP_STATUS_RESET_CONTENT = HTTP_STATUS_PARTIAL_CONTENT = HTTP_STATUS_AMBIGUOUS = HTTP_STATUS_MOVED = HTTP_STATUS_REDIRECT = HTTP_STATUS_REDIRECT_METHOD = HTTP_STATUS_NOT_MODIFIED = HTTP_STATUS_USE_PROXY = HTTP_STATUS_REDIRECT_KEEP_VERB = HTTP_STATUS_BAD_REQUEST = HTTP_STATUS_DENIED = HTTP_STATUS_PAYMENT_REQ = HTTP_STATUS_FORBIDDEN = HTTP_STATUS_NOT_FOUND = HTTP_STATUS_BAD_METHOD = HTTP_STATUS_NONE_ACCEPTABLE = HTTP_STATUS_PROXY_AUTH_REQ = HTTP_STATUS_REQUEST_TIMEOUT = HTTP_STATUS_CONFLICT = HTTP_STATUS_GONE = HTTP_STATUS_LENGTH_REQUIRED = HTTP_STATUS_PRECOND_FAILED = HTTP_STATUS_REQUEST_TOO_LARGE = HTTP_STATUS_URI_TOO_LONG = HTTP_STATUS_UNSUPPORTED_MEDIA = HTTP_STATUS_RETRY_WITH = HTTP_STATUS_SERVER_ERROR = HTTP_STATUS_NOT_SUPPORTED = HTTP_STATUS_BAD_GATEWAY = HTTP_STATUS_SERVICE_UNAVAIL = HTTP_STATUS_GATEWAY_TIMEOUT = HTTP_STATUS_VERSION_NOT_SUP = HTTP_STATUS_FIRST = HTTP_STATUS_CONTINUE HTTP_STATUS_LAST = HTTP_STATUS_VERSION_NOT_SUP HTTP_ADDREQ_INDEX_MASK = HTTP_ADDREQ_FLAGS_MASK = ( - ) HTTP_ADDREQ_FLAG_ADD_IF_NEW = HTTP_ADDREQ_FLAG_ADD = HTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA = HTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON = HTTP_ADDREQ_FLAG_COALESCE = HTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA HTTP_ADDREQ_FLAG_REPLACE = ( - ) HSR_ASYNC = WININET_API_FLAG_ASYNC HSR_SYNC = WININET_API_FLAG_SYNC HSR_USE_CONTEXT = WININET_API_FLAG_USE_CONTEXT HSR_INITIATE = HSR_DOWNLOAD = HSR_CHUNKED = INTERNET_COOKIE_IS_SECURE = INTERNET_COOKIE_IS_SESSION = INTERNET_COOKIE_THIRD_PARTY = INTERNET_COOKIE_PROMPT_REQUIRED = INTERNET_COOKIE_EVALUATE_P3P = INTERNET_COOKIE_APPLY_P3P = INTERNET_COOKIE_P3P_ENABLED = INTERNET_COOKIE_IS_RESTRICTED = INTERNET_COOKIE_IE6 = INTERNET_COOKIE_IS_LEGACY = FLAG_ICC_FORCE_CONNECTION = FLAGS_ERROR_UI_FILTER_FOR_ERRORS = FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS = FLAGS_ERROR_UI_FLAGS_GENERATE_DATA = FLAGS_ERROR_UI_FLAGS_NO_UI = FLAGS_ERROR_UI_SERIALIZE_DIALOGS = INTERNET_ERROR_BASE = ERROR_INTERNET_OUT_OF_HANDLES = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_TIMEOUT = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_EXTENDED_ERROR = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_INTERNAL_ERROR = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_INVALID_URL = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_UNRECOGNIZED_SCHEME = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_NAME_NOT_RESOLVED = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_PROTOCOL_NOT_FOUND = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_INVALID_OPTION = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_BAD_OPTION_LENGTH = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_OPTION_NOT_SETTABLE = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_SHUTDOWN = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_INCORRECT_USER_NAME = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_INCORRECT_PASSWORD = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_LOGIN_FAILURE = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_INVALID_OPERATION = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_OPERATION_CANCELLED = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_INCORRECT_HANDLE_TYPE = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_INCORRECT_HANDLE_STATE = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_NOT_PROXY_REQUEST = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_REGISTRY_VALUE_NOT_FOUND = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_BAD_REGISTRY_PARAMETER = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_NO_DIRECT_ACCESS = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_NO_CONTEXT = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_NO_CALLBACK = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_REQUEST_PENDING = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_INCORRECT_FORMAT = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_ITEM_NOT_FOUND = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_CANNOT_CONNECT = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_CONNECTION_ABORTED = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_CONNECTION_RESET = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_FORCE_RETRY = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_INVALID_PROXY_REQUEST = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_NEED_UI = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_HANDLE_EXISTS = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_SEC_CERT_DATE_INVALID = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_SEC_CERT_CN_INVALID = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_HTTP_TO_HTTPS_ON_REDIR = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_HTTPS_TO_HTTP_ON_REDIR = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_MIXED_SECURITY = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_CHG_POST_IS_NON_SECURE = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_POST_IS_NON_SECURE = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_CLIENT_AUTH_CERT_NEEDED = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_INVALID_CA = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_CLIENT_AUTH_NOT_SETUP = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_ASYNC_THREAD_FAILED = ( INTERNET_ERROR_BASE + ) ERROR_INTERNET_REDIRECT_SCHEME_CHANGE = ( INTERNET_ERROR_BASE + ) ", "answer": "ERROR_INTERNET_DIALOG_PENDING = ( INTERNET_ERROR_BASE + )"}, {"prompt": " '''''' from __future__ import absolute_import from salttesting import TestCase , skipIf from salttesting . helpers import ensure_in_syspath from salttesting . mock import ( MagicMock , patch , NO_MOCK , NO_MOCK_REASON ) ensure_in_syspath ( '' ) from salt . states import group group . __salt__ = { } group . __opts__ = { } @ skipIf ( NO_MOCK , NO_MOCK_REASON ) class GroupTestCase ( TestCase ) : '''''' def test_present ( self ) : '''''' ret = { '' : '' , '' : { } , '' : True , '' : { } } ret . update ( { '' : '' '' , '' : None } ) ", "answer": "self . assertDictEqual ( group . present ( \"\" , delusers = True ,"}, {"prompt": " \"\"\"\"\"\" import six from django . contrib import admin from django . test import TestCase class TestAdminSite ( TestCase ) : def test_search_fields ( self ) : \"\"\"\"\"\" for model , model_admin in six . iteritems ( admin . site . _registry ) : for search_field in getattr ( model_admin , '' , [ ] ) : model_name = model_admin . model . __name__ self . assertFalse ( search_field . startswith ( '' . format ( table_name = model_name . lower ( ) ) ) , '' . format ( ", "answer": "search_field = search_field , model_name = model_name ) ) "}, {"prompt": " import collectd import json import urllib2 import socket import collections PREFIX = \"\" MESOS_INSTANCE = \"\" MESOS_HOST = \"\" MESOS_PORT = MESOS_VERSION = \"\" MESOS_URL = \"\" VERBOSE_LOGGING = False CONFIGS = [ ] Stat = collections . namedtuple ( '' , ( '' , '' ) ) STATS_MESOS = { '' : Stat ( \"\" , \"\" ) , '' : Stat ( \"\" , \"\" ) , '' : Stat ( \"\" , \"\" ) , '' : Stat ( \"\" , \"\" ) , '' : Stat ( \"\" , \"\" ) , '' : Stat ( \"\" , \"\" ) , '' : Stat ( \"\" , \"\" ) , '' : Stat ( \"\" , \"\" ) , '' : Stat ( \"\" , \"\" ) , '' : Stat ( \"\" , \"\" ) , '' : Stat ( \"\" , \"\" ) , '' : Stat ( \"\" , \"\" ) , '' : Stat ( \"\" , \"\" ) , '' : Stat ( \"\" , \"\" ) , '' : Stat ( \"\" , \"\" ) , '' : Stat ( \"\" , \"\" ) , '' : Stat ( \"\" , \"\" ) , '' : Stat ( \"\" , \"\" ) , '' : Stat ( \"\" , \"\" ) , '' : Stat ( \"\" , \"\" ) , '' : Stat ( \"\" , \"\" ) } STATS_MESOS_019 = { } STATS_MESOS_020 = { '' : Stat ( \"\" , \"\" ) , '' : Stat ( \"\" , \"\" ) , '' : Stat ( \"\" , \"\" ) , '' : Stat ( \"\" , \"\" ) } STATS_MESOS_021 = { '' : Stat ( \"\" , \"\" ) , '' : Stat ( \"\" , \"\" ) , '' : Stat ( \"\" , \"\" ) , '' : Stat ( \"\" , \"\" ) , '' : Stat ( \"\" , \"\" ) , '' : Stat ( \"\" , \"\" ) , '' : Stat ( \"\" , \"\" ) , '' : Stat ( \"\" , \"\" ) , '' : Stat ( \"\" , \"\" ) , '' : Stat ( \"\" , \"\" ) , '' : Stat ( \"\" , \"\" ) , '' : Stat ( \"\" , \"\" ) , '' : Stat ( \"\" , \"\" ) } STATS_MESOS_022 = STATS_MESOS_021 . copy ( ) def get_stats_string ( version ) : if version == \"\" or version == \"\" : stats_cur = dict ( STATS_MESOS . items ( ) + STATS_MESOS_019 . items ( ) ) elif version == \"\" or version == \"\" : stats_cur = dict ( STATS_MESOS . items ( ) + STATS_MESOS_020 . items ( ) ) elif version == \"\" or version == \"\" : stats_cur = dict ( STATS_MESOS . items ( ) + STATS_MESOS_021 . items ( ) ) elif version == \"\" or version == \"\" : stats_cur = dict ( STATS_MESOS . items ( ) + STATS_MESOS_022 . items ( ) ) else : stats_cur = dict ( STATS_MESOS . items ( ) + STATS_MESOS_022 . items ( ) ) return stats_cur def lookup_stat ( stat , json , conf ) : val = dig_it_up ( json , get_stats_string ( conf [ '' ] ) [ stat ] . path ) if not isinstance ( val , bool ) : return val else : return None def configure_callback ( conf ) : \"\"\"\"\"\" host = MESOS_HOST port = MESOS_PORT verboseLogging = VERBOSE_LOGGING version = MESOS_VERSION instance = MESOS_INSTANCE for node in conf . children : if node . key == '' : host = node . values [ ] elif node . key == '' : port = int ( node . values [ ] ) elif node . key == '' : verboseLogging = bool ( node . values [ ] ) elif node . key == '' : version = node . values [ ] elif node . key == '' : instance = node . values [ ] else : collectd . warning ( '' % node . key ) continue log_verbose ( '' , '' % ( host , port , verboseLogging , version , instance ) ) CONFIGS . append ( { '' : host , '' : port , '' : \"\" + host + \"\" + str ( port ) + \"\" , '' : verboseLogging , '' : version , '' : instance , } ) def fetch_stats ( ) : for conf in CONFIGS : try : result = json . load ( urllib2 . urlopen ( conf [ '' ] , timeout = ) ) except urllib2 . URLError , e : collectd . error ( '' % ( conf [ '' ] , e ) ) return None parse_stats ( conf , result ) def parse_stats ( conf , json ) : \"\"\"\"\"\" for name , key in get_stats_string ( conf [ '' ] ) . iteritems ( ) : result = lookup_stat ( name , json , conf ) dispatch_stat ( result , name , key , conf ) def dispatch_stat ( result , name , key , conf ) : \"\"\"\"\"\" if result is None : collectd . warning ( '' % name ) return estype = key . type value = result log_verbose ( conf [ '' ] , '' % ( estype , name , value , conf [ '' ] ) ) val = collectd . Values ( plugin = '' ) val . type = estype val . type_instance = name val . values = [ value ] val . plugin_instance = conf [ '' ] val . meta = { '' : True } val . dispatch ( ) ", "answer": "def read_callback ( ) :"}, {"prompt": " import os class SentryLogger ( object ) : def __init__ ( self ) : try : import raven self . enabled = True dsn = os . environ [ '' ] if dsn . startswith ( '' ) : dsn = dsn . replace ( '' , '' ) self . client = raven . Client ( dsn ) except ( ImportError , KeyError ) : self . enabled = False def capture ( self , failure ) : if self . enabled : ", "answer": "self . client . captureException ( ( failure . type , failure . value , failure . getTracebackObject ( ) ) )"}, {"prompt": " \"\"\"\"\"\" from django . contrib import admin from open_connect . groups . models import Category class CategoryAdmin ( admin . ModelAdmin ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " \"\"\"\"\"\" import sys , time , os . path try : try : from cProfile import Profile except ImportError : from profile import Profile from pstats import Stats available = True except ImportError : available = False class MergeStream ( object ) : \"\"\"\"\"\" def __init__ ( self , * streams ) : if not streams : raise TypeError ( '' ) self . streams = streams def write ( self , data ) : for stream in self . streams : stream . write ( data ) class ProfilerMiddleware ( object ) : \"\"\"\"\"\" def __init__ ( self , app , stream = None , sort_by = ( '' , '' ) , restrictions = ( ) , profile_dir = None ) : if not available : raise RuntimeError ( '' '' ) self . _app = app self . _stream = stream or sys . stdout self . _sort_by = sort_by self . _restrictions = restrictions self . _profile_dir = profile_dir def __call__ ( self , environ , start_response ) : response_body = [ ] def catching_start_response ( status , headers , exc_info = None ) : start_response ( status , headers , exc_info ) return response_body . append def runapp ( ) : appiter = self . _app ( environ , catching_start_response ) response_body . extend ( appiter ) if hasattr ( appiter , '' ) : appiter . close ( ) p = Profile ( ) start = time . time ( ) p . runcall ( runapp ) body = b'' . join ( response_body ) elapsed = time . time ( ) - start if self . _profile_dir is not None : prof_filename = os . path . join ( self . _profile_dir , '' % ( environ [ '' ] , environ . get ( '' ) . strip ( '' ) . replace ( '' , '' ) or '' , elapsed * , time . time ( ) ) ) p . dump_stats ( prof_filename ) else : stats = Stats ( p , stream = self . _stream ) stats . sort_stats ( * self . _sort_by ) self . _stream . write ( '' * ) self . _stream . write ( '' % environ . get ( '' ) ) stats . print_stats ( * self . _restrictions ) self . _stream . write ( '' * + '' ) return [ body ] ", "answer": "def make_action ( app_factory , hostname = '' , port = ,"}, {"prompt": " import numpy as np from sklearn . utils . optimize import newton_cg from scipy . optimize import fmin_ncg from sklearn . utils . testing import assert_array_almost_equal def test_newton_cg ( ) : rng = np . random . RandomState ( ) ", "answer": "A = rng . normal ( size = ( , ) )"}, {"prompt": " \"\"\"\"\"\" import itertools import math import random import networkx as nx __author__ = \"\"\"\"\"\" . join ( [ '' , '' , '' '' ] ) __all__ = [ '' , '' , '' , '' , '' , '' , '' ] def caveman_graph ( l , k ) : \"\"\"\"\"\" G = nx . empty_graph ( l * k ) G . name = \"\" % ( l * k , k ) if k > : for start in range ( , l * k , k ) : edges = itertools . combinations ( range ( start , start + k ) , ) G . add_edges_from ( edges ) return G def connected_caveman_graph ( l , k ) : \"\"\"\"\"\" G = nx . caveman_graph ( l , k ) G . name = \"\" % ( l , k ) for start in range ( , l * k , k ) : G . remove_edge ( start , start + ) G . add_edge ( start , ( start - ) % ( l * k ) ) return G def relaxed_caveman_graph ( l , k , p , seed = None ) : \"\"\"\"\"\" if not seed is None : random . seed ( seed ) G = nx . caveman_graph ( l , k ) nodes = list ( G ) G . name = \"\" % ( l , k , p ) for ( u , v ) in G . edges ( ) : if random . random ( ) < p : x = random . choice ( nodes ) if G . has_edge ( u , x ) : continue G . remove_edge ( u , v ) G . add_edge ( u , x ) return G def random_partition_graph ( sizes , p_in , p_out , seed = None , directed = False ) : \"\"\"\"\"\" if not seed is None : random . seed ( seed ) if not <= p_in <= : raise nx . NetworkXError ( \"\" ) if not <= p_out <= : raise nx . NetworkXError ( \"\" ) if directed : G = nx . DiGraph ( ) else : G = nx . Graph ( ) G . graph [ '' ] = [ ] n = sum ( sizes ) G . add_nodes_from ( range ( n ) ) next_group = { } start = group = for n in sizes : edges = ( ( u + start , v + start ) for u , v in nx . fast_gnp_random_graph ( n , p_in , directed = directed ) . edges ( ) ) G . add_edges_from ( edges ) next_group . update ( dict . fromkeys ( range ( start , start + n ) , start + n ) ) G . graph [ '' ] . append ( set ( range ( start , start + n ) ) ) group += start += n if p_out == : return G if p_out == : for n in next_group : targets = range ( next_group [ n ] , len ( G ) ) G . add_edges_from ( zip ( [ n ] * len ( targets ) , targets ) ) if directed : G . add_edges_from ( zip ( targets , [ n ] * len ( targets ) ) ) return G lp = math . log ( - p_out ) n = len ( G ) if directed : for u in range ( n ) : v = while v < n : lr = math . log ( - random . random ( ) ) v += int ( lr / lp ) if next_group . get ( v , n ) == next_group [ u ] : v = next_group [ u ] if v < n : G . add_edge ( u , v ) v += else : for u in range ( n - ) : v = next_group [ u ] while v < n : lr = math . log ( - random . random ( ) ) v += int ( lr / lp ) if v < n : G . add_edge ( u , v ) v += return G def planted_partition_graph ( l , k , p_in , p_out , seed = None , directed = False ) : \"\"\"\"\"\" return random_partition_graph ( [ k ] * l , p_in , p_out , seed , directed ) def gaussian_random_partition_graph ( n , s , v , p_in , p_out , directed = False , seed = None ) : \"\"\"\"\"\" if s > n : raise nx . NetworkXError ( \"\" ) assigned = sizes = [ ] while True : size = int ( random . normalvariate ( s , float ( s ) / v + ) ) if size < : continue ", "answer": "if assigned + size >= n :"}, {"prompt": " \"\"\"\"\"\" import os import sys import re import logging from optparse import OptionParser from taolib . CoreLib . Parser import * from taolib . CoreLib . BasicStat . Prob import normal_cdf_inv logging . basicConfig ( level = , format = '' , datefmt = '' , stream = sys . stderr , filemode = \"\" ) error = logging . critical warn = logging . warning debug = logging . debug info = logging . info def main ( ) : usage = \"\" description = \"\" optparser = OptionParser ( version = \"\" , description = description , usage = usage , add_help_option = False ) optparser . add_option ( \"\" , \"\" , action = \"\" , help = \"\" ) optparser . add_option ( \"\" , \"\" , dest = \"\" , type = \"\" , help = \"\" ) optparser . add_option ( \"\" , \"\" , dest = \"\" , type = \"\" , help = \"\" ) optparser . add_option ( \"\" , \"\" , dest = \"\" , type = \"\" , help = \"\" , default = ) optparser . add_option ( \"\" , \"\" , dest = \"\" , type = \"\" , help = \"\" , default = ) optparser . add_option ( \"\" , \"\" , dest = \"\" , type = \"\" , help = \"\" , default = ) optparser . add_option ( \"\" , dest = \"\" , action = \"\" , help = \"\" , default = True ) optparser . add_option ( \"\" , dest = \"\" , action = \"\" , help = \"\" , default = True ) optparser . add_option ( \"\" , dest = \"\" , type = \"\" , default = , help = \"\" ) ( options , args ) = optparser . parse_args ( ) if not options . wfile or not options . bfile or not options . cutoff : optparser . print_help ( ) sys . exit ( ) f = options . wfile if not os . path . isfile ( f ) : error ( \"\" % f ) sys . exit ( ) try : fhd = open ( f ) except : error ( \"\" % f ) sys . exit ( ) try : bfhd = open ( options . bfile , \"\" ) except : error ( \"\" % options . bfile ) sys . exit ( ) info ( \"\" ) wio = WiggleIO . WiggleIO ( fhd ) info ( \"\" ) wtrack = wio . build_wigtrack ( ) if options . normalize : info ( \"\" ) ( sum_v , max_v , min_v , mean_v , std_v ) = wtrack . normalize ( null = options . nullmodel , sample_percent = options . samplepercent ) if options . nullmodel : info ( \"\" ) info ( \"\" % mean_v ) info ( \"\" % std_v ) info ( \"\" ) else : info ( \"\" ) info ( \"\" % mean_v ) info ( \"\" % std_v ) info ( \"\" ) if options . nullmodel : ( sum_v , max_v , min_v , mean_v , std_v ) = wtrack . null_model_summary ( sample = options . samplepercent ) else : ( sum_v , max_v , min_v , mean_v , std_v ) = wtrack . summary ( ) info ( \"\" % mean_v ) info ( \"\" % std_v ) info ( \"\" ) scorecutoff = normal_cdf_inv ( options . cutoff , mu = mean_v , sigma2 = std_v , lower = False ) ", "answer": "info ( \"\" % scorecutoff )"}, {"prompt": " from __future__ import absolute_import import os import os . path import tempfile from salttesting import TestCase from salttesting . mock import patch , MagicMock from salttesting . helpers import ensure_in_syspath ensure_in_syspath ( '' ) import integration import salt . config from salt . state import HighState from salt . utils . odict import OrderedDict , DefaultOrderedDict class HighStateTestCase ( TestCase ) : def setUp ( self ) : self . root_dir = tempfile . mkdtemp ( dir = integration . TMP ) self . state_tree_dir = os . path . join ( self . root_dir , '' ) self . cache_dir = os . path . join ( self . root_dir , '' ) if not os . path . isdir ( self . root_dir ) : os . makedirs ( self . root_dir ) if not os . path . isdir ( self . state_tree_dir ) : os . makedirs ( self . state_tree_dir ) if not os . path . isdir ( self . cache_dir ) : os . makedirs ( self . cache_dir ) self . config = salt . config . minion_config ( None ) self . config [ '' ] = self . root_dir self . config [ '' ] = False self . config [ '' ] = '' self . config [ '' ] = '' self . config [ '' ] = dict ( base = [ self . state_tree_dir ] ) self . config [ '' ] = self . cache_dir self . config [ '' ] = False self . highstate = HighState ( self . config ) self . highstate . push_active ( ) def tearDown ( self ) : self . highstate . pop_active ( ) def test_top_matches_with_list ( self ) : top = { '' : { '' : [ '' , '' ] , '' : [ '' ] } } matches = self . highstate . top_matches ( top ) self . assertEqual ( matches , { '' : [ '' , '' ] } ) def test_top_matches_with_string ( self ) : top = { '' : { '' : '' , '' : '' } } matches = self . highstate . top_matches ( top ) self . assertEqual ( matches , { '' : [ '' ] } ) def test_matches_whitelist ( self ) : matches = { '' : [ '' , '' , '' ] } matches = self . highstate . matches_whitelist ( matches , [ '' ] ) self . assertEqual ( matches , { '' : [ '' ] } ) def test_matches_whitelist_with_string ( self ) : matches = { '' : [ '' , '' , '' ] } matches = self . highstate . matches_whitelist ( matches , '' ) self . assertEqual ( matches , { '' : [ '' , '' ] } ) class TopFileMergeTestCase ( TestCase ) : '''''' def setUp ( self ) : '''''' self . env1 = { '' : { '' : [ '' , '' , '' ] } } self . env2 = { '' : { '' : [ '' , '' , '' ] } } self . env3 = { '' : { '' : [ '' , '' , '' ] } } self . config = self . _make_default_config ( ) self . highstate = HighState ( self . config ) def _make_default_config ( self ) : config = salt . config . minion_config ( None ) root_dir = tempfile . mkdtemp ( dir = integration . TMP ) state_tree_dir = os . path . join ( root_dir , '' ) cache_dir = os . path . join ( root_dir , '' ) config [ '' ] = root_dir config [ '' ] = False config [ '' ] = '' config [ '' ] = '' config [ '' ] = dict ( base = [ state_tree_dir ] ) config [ '' ] = cache_dir config [ '' ] = False return config def _get_tops ( self ) : '''''' tops = DefaultOrderedDict ( list ) tops [ '' ] . append ( self . env1 ) tops [ '' ] . append ( self . env2 ) tops [ '' ] . append ( self . env3 ) return tops def test_basic_merge ( self ) : '''''' merged_tops = self . highstate . merge_tops ( self . _get_tops ( ) ) expected_merge = DefaultOrderedDict ( OrderedDict ) ", "answer": "expected_merge [ '' ] [ '' ] = [ '' , '' , '' ]"}, {"prompt": " import unittest import Mariana . layers as ML import Mariana . initializations as MI import Mariana . costs as MC import Mariana . regularizations as MR import Mariana . scenari as MS import Mariana . activations as MA import theano . tensor as tt import numpy class MLPTests ( unittest . TestCase ) : def setUp ( self ) : self . xor_ins = [ [ , ] , [ , ] , [ , ] , [ , ] ] self . xor_outs = [ , , , ] def tearDown ( self ) : pass def trainMLP_xor ( self ) : ls = MS . GradientDescent ( lr = ) cost = MC . NegativeLogLikelihood ( ) i = ML . Input ( , '' ) h = ML . Hidden ( , activation = MA . ReLU ( ) , regularizations = [ MR . L1 ( ) , MR . L2 ( ) ] , name = \"\" ) o = ML . SoftmaxClassifier ( , learningScenario = ls , costObject = cost , name = \"\" ) mlp = i > h > o self . xor_ins = numpy . array ( self . xor_ins ) self . xor_outs = numpy . array ( self . xor_outs ) for i in xrange ( ) : mlp . train ( o , inp = self . xor_ins , targets = self . xor_outs ) return mlp def test_xor ( self ) : mlp = self . trainMLP_xor ( ) o = mlp . outputs . values ( ) [ ] pa = mlp . predictionAccuracy ( o , inp = self . xor_ins , targets = self . xor_outs ) [ ] self . assertEqual ( pa , ) pc = mlp . classificationAccuracy ( o , inp = self . xor_ins , targets = self . xor_outs ) [ ] self . assertEqual ( pc , ) self . assertEqual ( mlp . classify ( o , inp = [ self . xor_ins [ ] ] ) [ ] , ) self . assertEqual ( mlp . classify ( o , inp = [ self . xor_ins [ ] ] ) [ ] , ) self . assertEqual ( mlp . classify ( o , inp = [ self . xor_ins [ ] ] ) [ ] , ) self . assertEqual ( mlp . classify ( o , inp = [ self . xor_ins [ ] ] ) [ ] , ) def test_save_load_pickle ( self ) : import cPickle , os import Mariana . network as MN mlp = self . trainMLP_xor ( ) mlp . save ( \"\" ) mlp2 = MN . loadModel ( \"\" ) o = mlp . outputs . values ( ) [ ] o2 = mlp2 . outputs . values ( ) [ ] for i in xrange ( len ( self . xor_ins ) ) : v1 = mlp . propagate ( o , inp = [ self . xor_ins [ i ] ] ) [ ] [ ] v2 = mlp2 . propagate ( o2 , inp = [ self . xor_ins [ i ] ] ) [ ] [ ] for j in xrange ( len ( v1 ) ) : self . assertEqual ( v1 [ j ] , v2 [ j ] ) os . remove ( '' ) def test_ae ( self ) : data = [ ] for i in xrange ( ) : zeros = numpy . zeros ( ) zeros [ i ] = data . append ( zeros ) ls = MS . GradientDescent ( lr = ) cost = MC . MeanSquaredError ( ) i = ML . Input ( , name = '' ) h = ML . Hidden ( , activation = MA . ReLU ( ) , name = \"\" ) o = ML . Regression ( , activation = MA . ReLU ( ) , learningScenario = ls , costObject = cost , name = \"\" ) ae = i > h > o miniBatchSize = for e in xrange ( ) : for i in xrange ( , len ( data ) , miniBatchSize ) : ae . train ( o , inp = data [ i : i + miniBatchSize ] , targets = data [ i : i + miniBatchSize ] ) res = ae . propagate ( o , inp = data ) [ ] for i in xrange ( len ( res ) ) : self . assertEqual ( numpy . argmax ( data [ i ] ) , numpy . argmax ( res [ i ] ) ) def test_composite ( self ) : ls = MS . GradientDescent ( lr = ) cost = MC . NegativeLogLikelihood ( ) inp = ML . Input ( , '' ) h1 = ML . Hidden ( , activation = MA . Tanh ( ) , name = \"\" ) h2 = ML . Hidden ( , activation = MA . Tanh ( ) , name = \"\" ) o = ML . SoftmaxClassifier ( , learningScenario = ls , costObject = cost , name = \"\" ) c = ML . Composite ( name = \"\" ) inp > h1 > c inp > h2 > c mlp = c > o self . xor_ins = numpy . array ( self . xor_ins ) self . xor_outs = numpy . array ( self . xor_outs ) for i in xrange ( ) : ii = i % len ( self . xor_ins ) mlp . train ( o , inp = [ self . xor_ins [ ii ] ] , targets = [ self . xor_outs [ ii ] ] ) self . assertEqual ( mlp . predict ( o , inp = [ self . xor_ins [ ] ] ) [ ] , ) self . assertEqual ( mlp . predict ( o , inp = [ self . xor_ins [ ] ] ) [ ] , ) self . assertEqual ( mlp . predict ( o , inp = [ self . xor_ins [ ] ] ) [ ] , ) self . assertEqual ( mlp . predict ( o , inp = [ self . xor_ins [ ] ] ) [ ] , ) def test_embedding ( self ) : \"\"\"\"\"\" ", "answer": "data = [ [ ] , [ ] , [ ] , [ ] , [ ] , [ ] ]"}, {"prompt": " \"\"\"\"\"\" from nose . tools import * from tests . base import OsfTestCase from website . addons . forward . tests . factories import ForwardSettingsFactory from website . addons . forward import utils class TestUtils ( OsfTestCase ) : def test_serialize_settings ( self ) : node_settings = ForwardSettingsFactory ( ) serialized = utils . serialize_settings ( node_settings ) assert_equal ( serialized , { '' : node_settings . url , '' : node_settings . label , '' : node_settings . redirect_bool , '' : node_settings . redirect_secs , } ) def test_settings_complete_true ( self ) : node_settings = ForwardSettingsFactory ( ) assert_true ( utils . settings_complete ( node_settings ) ) def test_settings_complete_true_no_redirect ( self ) : \"\"\"\"\"\" node_settings = ForwardSettingsFactory ( redirect_bool = False ) assert_true ( utils . settings_complete ( node_settings ) ) def test_settings_complete_false ( self ) : ", "answer": "node_settings = ForwardSettingsFactory ( url = None )"}, {"prompt": " from . client import * ", "answer": "from . server import * "}, {"prompt": " import os from flask import abort , Flask , jsonify , redirect , render_template , request from . filekeeper import delete_files , insert_link_to_latest , parse_docfiles , unpack_project from . import getconfig ", "answer": "app = Flask ( __name__ )"}, {"prompt": " import time import uuid from pika import spec from pika . compat import as_bytes import pika . connection import pika . frame import pika . spec from async_test_base import ( AsyncTestCase , BoundQueueTestCase , AsyncAdapters ) class TestA_Connect ( AsyncTestCase , AsyncAdapters ) : DESCRIPTION = \"\" def begin ( self , channel ) : self . stop ( ) class TestConfirmSelect ( AsyncTestCase , AsyncAdapters ) : DESCRIPTION = \"\" def begin ( self , channel ) : channel . _on_selectok = self . on_complete channel . confirm_delivery ( ) def on_complete ( self , frame ) : self . assertIsInstance ( frame . method , spec . Confirm . SelectOk ) self . stop ( ) class TestBlockingNonBlockingBlockingRPCWontStall ( AsyncTestCase , AsyncAdapters ) : DESCRIPTION = ( \"\" \"\" ) def begin ( self , channel ) : self . _expected_queue_params = ( ( \"\" + uuid . uuid1 ( ) . hex , False ) , ( \"\" + uuid . uuid1 ( ) . hex , True ) , ( \"\" + uuid . uuid1 ( ) . hex , False ) ) self . _declared_queue_names = [ ] for queue , nowait in self . _expected_queue_params : channel . queue_declare ( callback = self . _queue_declare_ok_cb if not nowait else None , queue = queue , auto_delete = True , nowait = nowait , arguments = { '' : self . TIMEOUT * } ) def _queue_declare_ok_cb ( self , declare_ok_frame ) : self . _declared_queue_names . append ( declare_ok_frame . method . queue ) if len ( self . _declared_queue_names ) == : self . channel . queue_declare ( callback = self . _queue_declare_ok_cb , queue = self . _expected_queue_params [ ] [ ] , passive = True , nowait = False ) elif len ( self . _declared_queue_names ) == : self . assertSequenceEqual ( sorted ( self . _declared_queue_names ) , sorted ( item [ ] for item in self . _expected_queue_params ) ) self . stop ( ) class TestConsumeCancel ( AsyncTestCase , AsyncAdapters ) : DESCRIPTION = \"\" def begin ( self , channel ) : self . queue_name = self . __class__ . __name__ + '' + uuid . uuid1 ( ) . hex channel . queue_declare ( self . on_queue_declared , queue = self . queue_name ) def on_queue_declared ( self , frame ) : for i in range ( , ) : msg_body = '' . format ( self . __class__ . __name__ , i , time . time ( ) ) self . channel . basic_publish ( '' , self . queue_name , msg_body ) self . ctag = self . channel . basic_consume ( self . on_message , queue = self . queue_name , no_ack = True ) def on_message ( self , _channel , _frame , _header , body ) : self . channel . basic_cancel ( self . on_cancel , self . ctag ) def on_cancel ( self , _frame ) : self . channel . queue_delete ( self . on_deleted , self . queue_name ) def on_deleted ( self , _frame ) : self . stop ( ) class TestExchangeDeclareAndDelete ( AsyncTestCase , AsyncAdapters ) : DESCRIPTION = \"\" X_TYPE = '' def begin ( self , channel ) : self . name = self . __class__ . __name__ + '' + uuid . uuid1 ( ) . hex channel . exchange_declare ( self . on_exchange_declared , self . name , exchange_type = self . X_TYPE , passive = False , durable = False , auto_delete = True ) def on_exchange_declared ( self , frame ) : self . assertIsInstance ( frame . method , spec . Exchange . DeclareOk ) self . channel . exchange_delete ( self . on_exchange_delete , self . name ) def on_exchange_delete ( self , frame ) : self . assertIsInstance ( frame . method , spec . Exchange . DeleteOk ) self . stop ( ) class TestExchangeRedeclareWithDifferentValues ( AsyncTestCase , AsyncAdapters ) : DESCRIPTION = \"\" X_TYPE1 = '' X_TYPE2 = '' def begin ( self , channel ) : self . name = self . __class__ . __name__ + '' + uuid . uuid1 ( ) . hex self . channel . add_on_close_callback ( self . on_channel_closed ) channel . exchange_declare ( self . on_exchange_declared , self . name , exchange_type = self . X_TYPE1 , passive = False , durable = False , auto_delete = True ) def on_cleanup_channel ( self , channel ) : channel . exchange_delete ( None , self . name , nowait = True ) self . stop ( ) def on_channel_closed ( self , channel , reply_code , reply_text ) : self . connection . channel ( self . on_cleanup_channel ) def on_exchange_declared ( self , frame ) : self . channel . exchange_declare ( self . on_bad_result , self . name , exchange_type = self . X_TYPE2 , passive = False , durable = False , auto_delete = True ) def on_bad_result ( self , frame ) : self . channel . exchange_delete ( None , self . name , nowait = True ) raise AssertionError ( \"\" ) class TestQueueDeclareAndDelete ( AsyncTestCase , AsyncAdapters ) : DESCRIPTION = \"\" def begin ( self , channel ) : channel . queue_declare ( self . on_queue_declared , passive = False , durable = False , exclusive = True , auto_delete = False , nowait = False , arguments = { '' : self . TIMEOUT * } ) def on_queue_declared ( self , frame ) : self . assertIsInstance ( frame . method , spec . Queue . DeclareOk ) self . channel . queue_delete ( self . on_queue_delete , frame . method . queue ) def on_queue_delete ( self , frame ) : self . assertIsInstance ( frame . method , spec . Queue . DeleteOk ) self . stop ( ) class TestQueueNameDeclareAndDelete ( AsyncTestCase , AsyncAdapters ) : DESCRIPTION = \"\" def begin ( self , channel ) : self . _q_name = self . __class__ . __name__ + '' + uuid . uuid1 ( ) . hex channel . queue_declare ( self . on_queue_declared , self . _q_name , passive = False , durable = False , exclusive = True , auto_delete = True , nowait = False , arguments = { '' : self . TIMEOUT * } ) def on_queue_declared ( self , frame ) : self . assertIsInstance ( frame . method , spec . Queue . DeclareOk ) self . assertEqual ( frame . method . queue , self . _q_name ) self . channel . queue_delete ( self . on_queue_delete , frame . method . queue ) def on_queue_delete ( self , frame ) : self . assertIsInstance ( frame . method , spec . Queue . DeleteOk ) self . stop ( ) class TestQueueRedeclareWithDifferentValues ( AsyncTestCase , AsyncAdapters ) : DESCRIPTION = \"\" def begin ( self , channel ) : self . _q_name = self . __class__ . __name__ + '' + uuid . uuid1 ( ) . hex self . channel . add_on_close_callback ( self . on_channel_closed ) channel . queue_declare ( self . on_queue_declared , self . _q_name , passive = False , durable = False , exclusive = True , auto_delete = True , nowait = False , arguments = { '' : self . TIMEOUT * } ) def on_channel_closed ( self , channel , reply_code , reply_text ) : self . stop ( ) def on_queue_declared ( self , frame ) : self . channel . queue_declare ( self . on_bad_result , self . _q_name , passive = False , durable = True , exclusive = False , auto_delete = True , nowait = False , arguments = { '' : self . TIMEOUT * } ) def on_bad_result ( self , frame ) : self . channel . queue_delete ( None , self . _q_name , nowait = True ) raise AssertionError ( \"\" ) class TestTX1_Select ( AsyncTestCase , AsyncAdapters ) : DESCRIPTION = \"\" def begin ( self , channel ) : channel . tx_select ( self . on_complete ) def on_complete ( self , frame ) : self . assertIsInstance ( frame . method , spec . Tx . SelectOk ) self . stop ( ) class TestTX2_Commit ( AsyncTestCase , AsyncAdapters ) : DESCRIPTION = \"\" def begin ( self , channel ) : channel . tx_select ( self . on_selectok ) def on_selectok ( self , frame ) : self . assertIsInstance ( frame . method , spec . Tx . SelectOk ) self . channel . tx_commit ( self . on_commitok ) def on_commitok ( self , frame ) : self . assertIsInstance ( frame . method , spec . Tx . CommitOk ) self . stop ( ) class TestTX2_CommitFailure ( AsyncTestCase , AsyncAdapters ) : DESCRIPTION = \"\" def begin ( self , channel ) : self . channel . add_on_close_callback ( self . on_channel_closed ) self . channel . tx_commit ( self . on_commitok ) def on_channel_closed ( self , channel , reply_code , reply_text ) : self . stop ( ) def on_selectok ( self , frame ) : self . assertIsInstance ( frame . method , spec . Tx . SelectOk ) @ staticmethod def on_commitok ( frame ) : raise AssertionError ( \"\" ) class TestTX3_Rollback ( AsyncTestCase , AsyncAdapters ) : DESCRIPTION = \"\" def begin ( self , channel ) : channel . tx_select ( self . on_selectok ) def on_selectok ( self , frame ) : self . assertIsInstance ( frame . method , spec . Tx . SelectOk ) self . channel . tx_rollback ( self . on_rollbackok ) def on_rollbackok ( self , frame ) : self . assertIsInstance ( frame . method , spec . Tx . RollbackOk ) self . stop ( ) class TestTX3_RollbackFailure ( AsyncTestCase , AsyncAdapters ) : DESCRIPTION = \"\" def begin ( self , channel ) : self . channel . add_on_close_callback ( self . on_channel_closed ) self . channel . tx_rollback ( self . on_commitok ) def on_channel_closed ( self , channel , reply_code , reply_text ) : self . stop ( ) @ staticmethod def on_commitok ( frame ) : raise AssertionError ( \"\" ) class TestZ_PublishAndConsume ( BoundQueueTestCase , AsyncAdapters ) : DESCRIPTION = \"\" ", "answer": "def on_ready ( self , frame ) :"}, {"prompt": " \"\"\"\"\"\" ", "answer": "from __future__ import absolute_import , print_function"}, {"prompt": " from PyQt4 import QtCore , QtGui class Ui_MainWindow ( object ) : def setupUi ( self , MainWindow ) : MainWindow . setObjectName ( \"\" ) MainWindow . resize ( , ) icon = QtGui . QIcon ( ) icon . addPixmap ( QtGui . QPixmap ( \"\" ) , QtGui . QIcon . Normal , QtGui . QIcon . Off ) MainWindow . setWindowIcon ( icon ) self . centralWidget = QtGui . QWidget ( MainWindow ) self . centralWidget . setObjectName ( \"\" ) self . horizontalLayout_3 = QtGui . QHBoxLayout ( self . centralWidget ) self . horizontalLayout_3 . setMargin ( ) self . horizontalLayout_3 . setObjectName ( \"\" ) self . tabs = QtGui . QTabWidget ( self . centralWidget ) sizePolicy = QtGui . QSizePolicy ( QtGui . QSizePolicy . Expanding , QtGui . QSizePolicy . Expanding ) sizePolicy . setHorizontalStretch ( ) sizePolicy . setVerticalStretch ( ) sizePolicy . setHeightForWidth ( self . tabs . sizePolicy ( ) . hasHeightForWidth ( ) ) self . tabs . setSizePolicy ( sizePolicy ) self . tabs . setObjectName ( \"\" ) self . tab = QtGui . QWidget ( ) self . tab . setObjectName ( \"\" ) self . horizontalLayout = QtGui . QHBoxLayout ( self . tab ) self . horizontalLayout . setMargin ( ) self . horizontalLayout . setObjectName ( \"\" ) self . text = CodeEditor ( self . tab ) font = QtGui . QFont ( ) font . setFamily ( \"\" ) self . text . setFont ( font ) self . text . setFrameShape ( QtGui . QFrame . NoFrame ) self . text . setFrameShadow ( QtGui . QFrame . Plain ) self . text . setLineWidth ( ) self . text . setObjectName ( \"\" ) self . horizontalLayout . addWidget ( self . text ) self . tabs . addTab ( self . tab , \"\" ) self . tab_2 = QtGui . QWidget ( ) self . tab_2 . setObjectName ( \"\" ) self . horizontalLayout_2 = QtGui . QHBoxLayout ( self . tab_2 ) self . horizontalLayout_2 . setMargin ( ) self . horizontalLayout_2 . setObjectName ( \"\" ) self . style = CodeEditor ( self . tab_2 ) font = QtGui . QFont ( ) font . setFamily ( \"\" ) self . style . setFont ( font ) self . style . setFrameShape ( QtGui . QFrame . NoFrame ) self . style . setObjectName ( \"\" ) self . horizontalLayout_2 . addWidget ( self . style ) self . tabs . addTab ( self . tab_2 , \"\" ) self . horizontalLayout_3 . addWidget ( self . tabs ) MainWindow . setCentralWidget ( self . centralWidget ) self . statusBar = QtGui . QStatusBar ( MainWindow ) self . statusBar . setObjectName ( \"\" ) MainWindow . setStatusBar ( self . statusBar ) self . menuBar = QtGui . QMenuBar ( MainWindow ) self . menuBar . setGeometry ( QtCore . QRect ( , , , ) ) self . menuBar . setObjectName ( \"\" ) self . menuText = QtGui . QMenu ( self . menuBar ) self . menuText . setObjectName ( \"\" ) self . menuView = QtGui . QMenu ( self . menuBar ) self . menuView . setObjectName ( \"\" ) self . menuEdit = QtGui . QMenu ( self . menuBar ) self . menuEdit . setObjectName ( \"\" ) self . menuHelp = QtGui . QMenu ( self . menuBar ) self . menuHelp . setObjectName ( \"\" ) MainWindow . setMenuBar ( self . menuBar ) self . toolBar = QtGui . QToolBar ( MainWindow ) self . toolBar . setObjectName ( \"\" ) MainWindow . addToolBar ( QtCore . Qt . TopToolBarArea , self . toolBar ) self . pdfbar = QtGui . QToolBar ( MainWindow ) self . pdfbar . setObjectName ( \"\" ) MainWindow . addToolBar ( QtCore . Qt . TopToolBarArea , self . pdfbar ) self . dock = QtGui . QDockWidget ( MainWindow ) icon1 = QtGui . QIcon ( ) icon1 . addPixmap ( QtGui . QPixmap ( \"\" ) , QtGui . QIcon . Normal , QtGui . QIcon . Off ) self . dock . setWindowIcon ( icon1 ) self . dock . setObjectName ( \"\" ) self . dockWidgetContents = QtGui . QWidget ( ) self . dockWidgetContents . setObjectName ( \"\" ) self . verticalLayout = QtGui . QVBoxLayout ( self . dockWidgetContents ) self . verticalLayout . setMargin ( ) self . verticalLayout . setObjectName ( \"\" ) self . dockLayout = QtGui . QVBoxLayout ( ) self . dockLayout . setSpacing ( ) self . dockLayout . setSizeConstraint ( QtGui . QLayout . SetNoConstraint ) self . dockLayout . setContentsMargins ( - , - , - , ) self . dockLayout . setObjectName ( \"\" ) self . verticalLayout . addLayout ( self . dockLayout ) self . dock . setWidget ( self . dockWidgetContents ) MainWindow . addDockWidget ( QtCore . Qt . DockWidgetArea ( ) , self . dock ) self . editbar = QtGui . QToolBar ( MainWindow ) self . editbar . setObjectName ( \"\" ) MainWindow . addToolBar ( QtCore . Qt . TopToolBarArea , self . editbar ) self . searchbar = QtGui . QToolBar ( MainWindow ) self . searchbar . setMovable ( False ) self . searchbar . setAllowedAreas ( QtCore . Qt . BottomToolBarArea ) self . searchbar . setFloatable ( False ) self . searchbar . setObjectName ( \"\" ) MainWindow . addToolBar ( QtCore . Qt . BottomToolBarArea , self . searchbar ) self . structure = QtGui . QDockWidget ( MainWindow ) self . structure . setObjectName ( \"\" ) self . dockWidgetContents_2 = QtGui . QWidget ( ) self . dockWidgetContents_2 . setObjectName ( \"\" ) self . verticalLayout_3 = QtGui . QVBoxLayout ( self . dockWidgetContents_2 ) self . verticalLayout_3 . setMargin ( ) self . verticalLayout_3 . setObjectName ( \"\" ) self . verticalLayout_2 = QtGui . QVBoxLayout ( ) self . verticalLayout_2 . setObjectName ( \"\" ) self . tree = QtGui . QTreeWidget ( self . dockWidgetContents_2 ) self . tree . setEditTriggers ( QtGui . QAbstractItemView . NoEditTriggers ) self . tree . setProperty ( \"\" , QtCore . QVariant ( False ) ) self . tree . setAlternatingRowColors ( True ) self . tree . setHeaderHidden ( False ) self . tree . setObjectName ( \"\" ) self . tree . header ( ) . setVisible ( True ) self . tree . header ( ) . setStretchLastSection ( False ) self . verticalLayout_2 . addWidget ( self . tree ) self . verticalLayout_3 . addLayout ( self . verticalLayout_2 ) self . structure . setWidget ( self . dockWidgetContents_2 ) MainWindow . addDockWidget ( QtCore . Qt . DockWidgetArea ( ) , self . structure ) self . actionLoad_Text = QtGui . QAction ( MainWindow ) icon2 = QtGui . QIcon ( ) icon2 . addPixmap ( QtGui . QPixmap ( \"\" ) , QtGui . QIcon . Normal , QtGui . QIcon . Off ) self . actionLoad_Text . setIcon ( icon2 ) self . actionLoad_Text . setObjectName ( \"\" ) self . actionLoad_Style = QtGui . QAction ( MainWindow ) self . actionLoad_Style . setIcon ( icon2 ) self . actionLoad_Style . setObjectName ( \"\" ) self . actionRender = QtGui . QAction ( MainWindow ) self . actionRender . setIcon ( icon1 ) self . actionRender . setObjectName ( \"\" ) self . actionSave_Text = QtGui . QAction ( MainWindow ) icon3 = QtGui . QIcon ( ) icon3 . addPixmap ( QtGui . QPixmap ( \"\" ) , QtGui . QIcon . Normal , QtGui . QIcon . Off ) self . actionSave_Text . setIcon ( icon3 ) self . actionSave_Text . setObjectName ( \"\" ) self . actionSave_Style = QtGui . QAction ( MainWindow ) self . actionSave_Style . setIcon ( icon3 ) self . actionSave_Style . setObjectName ( \"\" ) self . actionSave_PDF = QtGui . QAction ( MainWindow ) self . actionSave_PDF . setIcon ( icon1 ) self . actionSave_PDF . setObjectName ( \"\" ) self . actionSaveAs_Text = QtGui . QAction ( MainWindow ) self . actionSaveAs_Text . setIcon ( icon3 ) self . actionSaveAs_Text . setObjectName ( \"\" ) self . actionSaveAs_Style = QtGui . QAction ( MainWindow ) self . actionSaveAs_Style . setIcon ( icon3 ) self . actionSaveAs_Style . setObjectName ( \"\" ) self . actionSaveAs_PDF = QtGui . QAction ( MainWindow ) self . actionSaveAs_PDF . setIcon ( icon1 ) self . actionSaveAs_PDF . setObjectName ( \"\" ) self . actionUndo1 = QtGui . QAction ( MainWindow ) self . actionUndo1 . setEnabled ( False ) icon4 = QtGui . QIcon ( ) icon4 . addPixmap ( QtGui . QPixmap ( \"\" ) , QtGui . QIcon . Normal , QtGui . QIcon . Off ) self . actionUndo1 . setIcon ( icon4 ) self . actionUndo1 . setObjectName ( \"\" ) ", "answer": "self . actionRedo1 = QtGui . QAction ( MainWindow )"}, {"prompt": " \"\"\"\"\"\" import imp import six from social . utils import handle_http_errors from social . backends . oauth import BaseOAuth2 from social . exceptions import AuthFailed , AuthCanceled class ShopifyOAuth2 ( BaseOAuth2 ) : \"\"\"\"\"\" name = '' ID_KEY = '' EXTRA_DATA = [ ( '' , '' ) , ( '' , '' ) , ( '' , '' ) ] REDIRECT_STATE = False @ property def shopifyAPI ( self ) : if not hasattr ( self , '' ) : fp , pathname , description = imp . find_module ( '' ) self . _shopify_api = imp . load_module ( '' , fp , pathname , description ) return self . _shopify_api def get_user_details ( self , response ) : \"\"\"\"\"\" return { '' : six . text_type ( response . get ( '' , '' ) ) . replace ( '' , '' ) } def extra_data ( self , user , uid , response , details = None , * args , ** kwargs ) : \"\"\"\"\"\" data = super ( ShopifyOAuth2 , self ) . extra_data ( user , uid , response , details , * args , ** kwargs ) session = self . shopifyAPI . Session ( self . data . get ( '' ) . strip ( ) ) token = session . request_token ( data [ '' ] ) data [ '' ] = token return dict ( data ) def auth_url ( self ) : key , secret = self . get_key_and_secret ( ) self . shopifyAPI . Session . setup ( api_key = key , secret = secret ) scope = self . get_scope ( ) state = self . state_token ( ) self . strategy . session_set ( self . name + '' , state ) redirect_uri = self . get_redirect_uri ( state ) session = self . shopifyAPI . Session ( self . data . get ( '' ) . strip ( ) ) return session . create_permission_url ( scope = scope , redirect_uri = redirect_uri ) @ handle_http_errors def auth_complete ( self , * args , ** kwargs ) : \"\"\"\"\"\" self . process_error ( self . data ) access_token = None key , secret = self . get_key_and_secret ( ) ", "answer": "try :"}, {"prompt": " from django . test import TestCase import mocker import health class CheckItem ( TestCase ) : def test_call_must_be_implemented ( self ) : class CheckIt ( health . CheckItem ) : pass check = CheckIt ( ) self . assertRaises ( NotImplementedError , check ) class CheckListTests ( mocker . MockerTestCase ) : def test_refresh_in_minutes ( self ) : import datetime check_list = health . CheckList ( refresh = ) self . assertEqual ( datetime . timedelta ( minutes = ) , ", "answer": "check_list . _refresh_rate )"}, {"prompt": " \"\"\"\"\"\" def function ( receiver ) : \"\"\"\"\"\" if hasattr ( receiver , '' ) : if hasattr ( receiver . __call__ , '' ) or hasattr ( receiver . __call__ , '' ) : receiver = receiver . __call__ if hasattr ( receiver , '' ) : return receiver , receiver . im_func . func_code , elif not hasattr ( receiver , '' ) : raise ValueError ( '' % ( receiver , type ( receiver ) ) ) return receiver , receiver . func_code , def robustApply ( receiver , * arguments , ** named ) : \"\"\"\"\"\" ", "answer": "receiver , codeObject , startIndex = function ( receiver )"}, {"prompt": " \"\"\"\"\"\" import cStringIO import json from google . appengine . ext import ndb import logging from lib . crud import crud_handler from lib . crud import crud_model from lib . crud import crud_test class SampleNdb ( crud_model . CrudNdbModel ) : ", "answer": "name = ndb . StringProperty ( )"}, {"prompt": " import cd , CD class Error ( Exception ) : pass class _Stop ( Exception ) : pass def _doatime ( self , cb_type , data ) : if ( ( data [ ] * ) + data [ ] ) * + data [ ] > self . end : raise _Stop func , arg = self . callbacks [ cb_type ] if func : func ( arg , cb_type , data ) def _dopnum ( self , cb_type , data ) : if data > self . end : raise _Stop func , arg = self . callbacks [ cb_type ] if func : func ( arg , cb_type , data ) class Readcd : def __init__ ( self , * arg ) : if len ( arg ) == : self . player = cd . open ( ) elif len ( arg ) == : self . player = cd . open ( arg [ ] ) elif len ( arg ) == : self . player = cd . open ( arg [ ] , arg [ ] ) else : raise Error , '' self . list = [ ] self . callbacks = [ ( None , None ) ] * self . parser = cd . createparser ( ) self . playing = self . end = self . status = None self . trackinfo = None def eject ( self ) : self . player . eject ( ) self . list = [ ] self . end = self . listindex = self . status = None self . trackinfo = None if self . playing : raise _Stop def pmsf2msf ( self , track , min , sec , frame ) : if not self . status : self . cachestatus ( ) if track < self . status [ ] or track > self . status [ ] : raise Error , '' if not self . trackinfo : self . cacheinfo ( ) start , total = self . trackinfo [ track ] start = ( ( start [ ] * ) + start [ ] ) * + start [ ] total = ( ( total [ ] * ) + total [ ] ) * + total [ ] block = ( ( min * ) + sec ) * + frame if block > total : raise Error , '' block = start + block min , block = divmod ( block , * ) sec , frame = divmod ( block , ) return min , sec , frame def reset ( self ) : self . list = [ ] def appendtrack ( self , track ) : self . appendstretch ( track , track ) def appendstretch ( self , start , end ) : if not self . status : self . cachestatus ( ) if not start : start = if not end : end = self . status [ ] if type ( end ) == type ( ) : if end < self . status [ ] or end > self . status [ ] : raise Error , '' else : l = len ( end ) if l == : prog , min , sec , frame = end if prog < self . status [ ] or prog > self . status [ ] : raise Error , '' end = self . pmsf2msf ( prog , min , sec , frame ) elif l != : raise Error , '' if type ( start ) == type ( ) : if start < self . status [ ] or start > self . status [ ] : raise Error , '' if len ( self . list ) > : s , e = self . list [ - ] if type ( e ) == type ( ) : if start == e + : start = s del self . list [ - ] else : l = len ( start ) if l == : prog , min , sec , frame = start if prog < self . status [ ] or prog > self . status [ ] : raise Error , '' start = self . pmsf2msf ( prog , min , sec , frame ) elif l != : raise Error , '' ", "answer": "self . list . append ( ( start , end ) )"}, {"prompt": " from ants . webservice import JsonRpcResource class CrawlerResource ( JsonRpcResource ) : ws_name = '' ", "answer": "def __init__ ( self , crawler ) :"}, {"prompt": " \"\"\"\"\"\" import logging import netaddr from compass . actions import util from compass . db . api import database from compass . db . api import switch as switch_api from compass . db . api import user as user_api from compass . hdsdiscovery . hdmanager import HDManager def _poll_switch ( ip_addr , credentials , req_obj = '' , oper = \"\" ) : \"\"\"\"\"\" under_monitoring = '' unreachable = '' polling_error = '' hdmanager = HDManager ( ) vendor , state , err_msg = hdmanager . get_vendor ( ip_addr , credentials ) if not vendor : logging . info ( \"\" , err_msg ) logging . error ( '' , ip_addr ) return ( { '' : vendor , '' : state , '' : err_msg } , { } ) logging . debug ( '' , ip_addr ) results = [ ] try : results = hdmanager . learn ( ip_addr , credentials , vendor , req_obj , oper ) except Exception as error : logging . exception ( error ) state = unreachable err_msg = ( '' ) return ( { '' : vendor , '' : state , '' : err_msg } , { } ) logging . info ( \"\" , ip_addr , results ) if not results : logging . error ( '' , ip_addr ) state = polling_error err_msg = '' return ( { '' : vendor , '' : state , '' : err_msg } , { } ) logging . info ( '' % str ( results ) ) machine_dicts = { } for machine in results : mac = machine [ '' ] port = machine [ '' ] vlan = int ( machine [ '' ] ) if vlan : vlans = [ vlan ] else : vlans = [ ] if mac not in machine_dicts : machine_dicts [ mac ] = { '' : mac , '' : port , '' : vlans } else : machine_dicts [ mac ] [ '' ] = port machine_dicts [ mac ] [ '' ] . extend ( vlans ) logging . debug ( '' , ip_addr ) state = under_monitoring return ( { '' : vendor , '' : state , '' : err_msg } , machine_dicts . values ( ) ) def poll_switch ( poller_email , ip_addr , credentials , req_obj = '' , oper = \"\" ) : \"\"\"\"\"\" poller = user_api . get_user_object ( poller_email ) ip_int = long ( netaddr . IPAddress ( ip_addr ) ) with util . lock ( '' % ip_addr , timeout = ) as lock : if not lock : raise Exception ( '' % ip_addr ) logging . debug ( '' , ip_addr ) switch_dict , machine_dicts = _poll_switch ( ip_addr , credentials , req_obj = req_obj , oper = oper ) switches = switch_api . list_switches ( ip_int = ip_int , user = poller ) if not switches : logging . error ( '' , ip_addr ) return for switch in switches : for machine_dict in machine_dicts : logging . debug ( '' , machine_dict ) switch_api . add_switch_machine ( switch [ '' ] , False , user = poller , ** machine_dict ) switch_api . update_switch ( switch [ '' ] , ", "answer": "user = poller ,"}, {"prompt": " from gym . envs . registration import registry , register , make , spec register ( id = '' , entry_point = '' , timestep_limit = , reward_threshold = , ) register ( id = '' , entry_point = '' , timestep_limit = , reward_threshold = , ) register ( id = '' , entry_point = '' , kwargs = { '' : } , timestep_limit = , reward_threshold = , ) register ( id = '' , entry_point = '' , kwargs = { '' : } , timestep_limit = , reward_threshold = , ) register ( id = '' , entry_point = '' , timestep_limit = , reward_threshold = , ) register ( id = '' , entry_point = '' , timestep_limit = , reward_threshold = , ) register ( id = '' , entry_point = '' , timestep_limit = , reward_threshold = , ) register ( id = '' , entry_point = '' , timestep_limit = , ) register ( id = '' , entry_point = '' , timestep_limit = , ", "answer": ")"}, {"prompt": " import os import sys ", "answer": "if __name__ == \"\" :"}, {"prompt": " from . foreign import StataReader , genfromdta , savetxt ", "answer": "from . table import SimpleTable , csv2st"}, {"prompt": " \"\"\"\"\"\" SUCCESS = API_ERROR = ", "answer": "CONFIG_FILE_PARSE_ERROR = "}, {"prompt": " from sahara . service . edp . oozie . workflow_creator import workflow_factory from sahara . utils import xmlutils def get_possible_hive_config_from ( file_name ) : '''''' config = { ", "answer": "'' : xmlutils . load_hadoop_xml_defaults ( file_name ) ,"}, {"prompt": " \"\"\"\"\"\" from twisted . trial import unittest from . . _levels import InvalidLogLevelError from . . _levels import LogLevel from . . _format import formatEvent from . . _logger import Logger from . . _global import globalLogPublisher class TestLogger ( Logger ) : \"\"\"\"\"\" def emit ( self , level , format = None , ** kwargs ) : def observer ( event ) : self . event = event globalLogPublisher . addObserver ( observer ) try : Logger . emit ( self , level , format , ** kwargs ) finally : globalLogPublisher . removeObserver ( observer ) self . emitted = { \"\" : level , \"\" : format , \"\" : kwargs , } class LogComposedObject ( object ) : \"\"\"\"\"\" log = TestLogger ( ) def __init__ ( self , state = None ) : self . state = state def __str__ ( self ) : return \"\" . format ( state = self . state ) class LoggerTests ( unittest . TestCase ) : \"\"\"\"\"\" def test_repr ( self ) : \"\"\"\"\"\" namespace = \"\" log = Logger ( namespace ) self . assertEqual ( repr ( log ) , \"\" . format ( repr ( namespace ) ) ) def test_namespaceDefault ( self ) : \"\"\"\"\"\" log = Logger ( ) self . assertEqual ( log . namespace , __name__ ) def test_namespaceAttribute ( self ) : \"\"\"\"\"\" obj = LogComposedObject ( ) expectedNamespace = \"\" . format ( obj . __module__ , obj . __class__ . __name__ , ) self . assertEqual ( obj . log . namespace , expectedNamespace ) self . assertEqual ( LogComposedObject . log . namespace , expectedNamespace ) self . assertIs ( LogComposedObject . log . source , LogComposedObject ) self . assertIs ( obj . log . source , obj ) self . assertIs ( Logger ( ) . source , None ) def test_descriptorObserver ( self ) : \"\"\"\"\"\" observed = [ ] class MyObject ( object ) : log = Logger ( observer = observed . append ) MyObject . log . info ( \"\" ) self . assertEqual ( len ( observed ) , ) self . assertEqual ( observed [ ] [ '' ] , \"\" ) def test_sourceAvailableForFormatting ( self ) : \"\"\"\"\"\" obj = LogComposedObject ( \"\" ) log = obj . log log . error ( \"\" ) self . assertIn ( \"\" , log . event ) self . assertEqual ( log . event [ \"\" ] , obj ) stuff = formatEvent ( log . event ) self . assertIn ( \"\" , stuff ) def test_basicLogger ( self ) : \"\"\"\"\"\" log = TestLogger ( ) for level in LogLevel . iterconstants ( ) : format = \"\" message = format . format ( level_name = level . name ) logMethod = getattr ( log , level . name ) logMethod ( format , junk = message , level_name = level . name ) self . assertEqual ( log . emitted [ \"\" ] , level ) self . assertEqual ( log . emitted [ \"\" ] , format ) self . assertEqual ( log . emitted [ \"\" ] [ \"\" ] , message ) self . assertTrue ( hasattr ( log , \"\" ) , \"\" ) self . assertEqual ( log . event [ \"\" ] , format ) self . assertEqual ( log . event [ \"\" ] , level ) self . assertEqual ( log . event [ \"\" ] , __name__ ) self . assertEqual ( log . event [ \"\" ] , None ) self . assertEqual ( log . event [ \"\" ] , message ) self . assertEqual ( formatEvent ( log . event ) , message ) def test_sourceOnClass ( self ) : \"\"\"\"\"\" def observer ( event ) : self . assertEqual ( event [ \"\" ] , Thingo ) class Thingo ( object ) : log = TestLogger ( observer = observer ) ", "answer": "Thingo . log . info ( )"}, {"prompt": " import json import zmq import pandas as pd import pylab def getstream ( address ) : c = zmq . Context ( ) s = c . socket ( zmq . SUB ) s . setsockopt ( zmq . SUBSCRIBE , '' ) s . connect ( address ) while True : yield s . recv ( ) def populate ( df , n , stream ) : m = df . shape [ ] while True : next ( stream ) j = next ( stream ) d = json . loads ( j ) . get ( '' ) if d : df . loc [ df . shape [ ] ] = d if df . shape [ ] >= n + m : break def plot_df ( df ) : for i in range ( df . shape [ ] ) : pylab . subplot ( df . shape [ ] , , i + ) ", "answer": "pylab . plot ( df [ i ] )"}, {"prompt": " import unittest ", "answer": "from geonamescache import GeonamesCache"}, {"prompt": " import copy import six import unittest2 from oslo_config import cfg from bareon . actions import partitioning from bareon . drivers . data import nailgun from bareon import objects from bareon . tests import test_nailgun if six . PY2 : import mock elif six . PY3 : import unittest . mock as mock CONF = cfg . CONF class TestPartitioningAction ( unittest2 . TestCase ) : @ mock . patch ( '' , return_value = { } ) @ mock . patch ( '' ) def setUp ( self , mock_lbd , mock_image_meta ) : super ( TestPartitioningAction , self ) . setUp ( ) mock_lbd . return_value = test_nailgun . LIST_BLOCK_DEVICES_SAMPLE self . drv = nailgun . Nailgun ( test_nailgun . PROVISION_SAMPLE_DATA ) self . action = partitioning . PartitioningAction ( self . drv ) @ mock . patch ( '' , return_value = { } ) @ mock . patch ( '' ) ", "answer": "@ mock . patch . object ( partitioning , '' , autospec = True )"}, {"prompt": " from commands import getstatusoutput print '' print '' print '' print '' status , output = getstatusoutput ( '' ) if status : print '' + output else : print output ", "answer": "print ''"}, {"prompt": " '''''' import xml . dom . minidom __all__ = ( '' , ) class XMLNode : \"\"\"\"\"\" def __init__ ( self ) : \"\"\"\"\"\" self . name = \"\" self . text = \"\" self . attrib = { } self . xml = None def __setitem__ ( self , key , item ) : \"\"\"\"\"\" self . attrib [ key ] = item def __getitem__ ( self , key ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " import sys from . PatchImporter import PatchImporter import wrapt from . log import * from recipyCommon . utils import * from recipyCommon . config import option_set class PatchSimple ( PatchImporter ) : \"\"\"\"\"\" def patch ( self , mod ) : \"\"\"\"\"\" if not self . _ignore_input ( ) : for f in self . input_functions : if option_set ( '' , '' ) : print ( '' % f ) patch_function ( mod , f , self . input_wrapper ) else : if option_set ( '' , '' ) : print ( '' % self . modulename ) if not self . _ignore_output ( ) : for f in self . output_functions : if option_set ( '' , '' ) : ", "answer": "print ( '' % f )"}, {"prompt": " from __future__ import absolute_import from . debug import ( DebugViewTests , ExceptionReporterTests , ExceptionReporterTests , PlainTextReportTests , ExceptionReporterFilterTests , AjaxResponseExceptionReporterFilter ) ", "answer": "from . defaults import DefaultsTests"}, {"prompt": " '''''' import os import string import re import time import tempfile import types from CGAT import Experiment as E from CGAT import CSV as CSV from CGAT import IOTools as IOTools import sqlite3 def executewait ( dbhandle , statement , error , retry = False , wait = , args = ( ) ) : '''''' cc = dbhandle . cursor ( ) i = while i > : try : cc . execute ( statement , args ) return cc except sqlite3 . OperationalError as e : msg = e . message E . warn ( \"\" % ( msg , statement ) ) if not retry : raise e if not re . search ( \"\" , str ( msg ) ) : raise e time . sleep ( wait ) i -= continue break raise sqlite3 . OperationalError ( \"\" ) def quoteRow ( row , take , map_column2type , missing_values , null = \"\" , string_value = \"\" ) : \"\"\"\"\"\" d = { } for t in take : v = row [ t ] if v == \"\" : d [ t ] = null elif v in missing_values : d [ t ] = null elif map_column2type [ t ] in ( types . IntType , types . FloatType ) : d [ t ] = str ( row [ t ] ) else : d [ t ] = string_value % row [ t ] return d def quoteTableName ( name , quote_char = \"\" , backend = \"\" ) : if backend == \"\" : if name [ ] in \"\" : name = \"\" + name return re . sub ( \"\" , \"\" , name ) elif backend in ( \"\" , \"\" ) : if name [ ] in \"\" : name = \"\" + name return re . sub ( \"\" , \"\" , name ) def createTable ( dbhandle , error , tablename , options , retry = True , ignore_empty = True , ignore_columns = [ ] , rename_columns = [ ] , lowercase = False , ignore_duplicates = True , indices = [ ] , rows = None , headers = None , first_column = None , existing_tables = set ( ) , append = False ) : if rows : map_column2type , ignored , max_values = CSV . getMapColumn2Type ( rows , ignore_empty = ignore_empty , get_max_values = True ) if ignored : E . info ( \"\" % str ( ignored ) ) headers = map_column2type . keys ( ) headers . sort ( ) elif headers : map_column2type = dict ( zip ( headers , [ None , ] * len ( headers ) ) ) ignored = columns_to_ignore = set ( [ x . lower ( ) for x in ignore_columns ] ) columns_to_rename = dict ( [ x . lower ( ) . split ( \"\" ) for x in rename_columns ] ) take = [ ] columns = [ ] present = { } for header_index , h in enumerate ( headers ) : hh = h if lowercase : hh = string . lower ( h ) if hh in columns_to_ignore : continue if hh in present : if ignore_duplicates : continue else : raise ValueError ( \"\" % hh ) present [ hh ] = take . append ( h ) if map_column2type [ h ] == int : max_value = max_values [ h ] if max_value > : t = \"\" elif max_value > : t = \"\" else : t = \"\" elif map_column2type [ h ] == float : t = \"\" else : if h in options . indices : t = options . index else : t = options . text if hh == \"\" : if first_column is not None and header_index == : hh = first_column else : raise ValueError ( \"\" % h ) hh = columns_to_rename . get ( hh , hh ) hh = re . sub ( '''''' , \"\" , hh ) hh = re . sub ( \"\" , \"\" , hh ) if hh [ ] in \"\" : hh = \"\" + hh columns . append ( \"\" % ( hh , t ) ) if not options . append : while : try : cc = dbhandle . cursor ( ) statement = \"\" % tablename E . debug ( statement ) cc . execute ( statement ) dbhandle . commit ( ) cc . close ( ) E . info ( \"\" % tablename ) except sqlite3 . OperationalError , msg : E . warn ( msg ) time . sleep ( ) continue except error , msg : E . warn ( \"\" % ( tablename , str ( msg ) ) ) dbhandle . rollback ( ) if not retry : raise error ( msg ) elif tablename in existing_tables : time . sleep ( ) continue else : break break statement = \"\" % ( tablename , \"\" . join ( columns ) ) E . debug ( \"\" % ( statement ) ) while : try : cc = dbhandle . cursor ( ) cc . execute ( statement ) cc . close ( ) dbhandle . commit ( ) except error , msg : E . warn ( \"\" % ( msg , statement ) ) if not retry : raise error ( msg ) if not re . search ( \"\" , str ( msg ) ) : raise error ( \"\" % ( msg , statement ) ) time . sleep ( ) continue break E . info ( \"\" % tablename ) return take , map_column2type , ignored def run ( infile , options , report_step = ) : options . tablename = quoteTableName ( options . tablename , backend = options . backend ) if options . map : m = { } for x in options . map : f , t = x . split ( \"\" ) m [ f ] = t options . map = m else : options . map = { } existing_tables = set ( ) quick_import_separator = \"\" if options . database_backend == \"\" : import psycopg2 raise NotImplementedError ( \"\" ) dbhandle = psycopg2 . connect ( options . psql_connection ) error = psycopg2 . Error options . null = \"\" options . string_value = \"\" options . text = \"\" options . index = \"\" if options . insert_quick : raise ValueError ( \"\" ) elif options . database_backend == \"\" : import MySQLdb dbhandle = MySQLdb . connect ( host = options . database_host , user = options . database_username , passwd = options . database_password , port = options . database_port , db = options . database_name ) error = Exception options . null = \"\" options . string_value = \"\" options . text = \"\" options . index = \"\" if options . insert_quick : raise ValueError ( \"\" ) elif options . backend == \"\" : import sqlite3 dbhandle = sqlite3 . connect ( options . database_name ) try : os . chmod ( options . database_name , ) except OSError , msg : E . warn ( \"\" % msg ) dbhandle . text_factory = str error = sqlite3 . OperationalError options . insert_many = True options . null = None options . text = \"\" options . index = \"\" options . string_value = \"\" statement = \"\" cc = executewait ( dbhandle , statement , error , options . retry ) existing_tables = set ( [ x [ ] for x in cc ] ) cc . close ( ) quick_import_statement = \"\" % ( options . database , options . tablename ) quick_import_separator = \"\" if options . header is not None : options . header = [ x . strip ( ) for x in options . header . split ( \"\" ) ] if options . utf : reader = CSV . UnicodeDictReader ( infile , dialect = options . dialect , fieldnames = options . header ) else : reader = CSV . DictReader ( infile , dialect = options . dialect , fieldnames = options . header ) if options . replace_header : try : reader . next ( ) except StopIteration : pass E . info ( \"\" % options . guess_size ) rows = [ ] for row in reader : if None in row : raise ValueError ( \"\" % row ) try : rows . append ( IOTools . convertDictionary ( row , map = options . map ) ) except TypeError , msg : E . warn ( \"\" \"\" % ( msg , str ( row ) ) ) except ValueError , msg : E . warn ( \"\" \"\" % ( msg , str ( row ) ) ) if len ( rows ) >= options . guess_size : break E . info ( \"\" % len ( rows ) ) E . info ( \"\" ) if len ( rows ) == : if options . allow_empty : if not reader . fieldnames : E . warn ( \"\" ) else : take , map_column2type , ignored = createTable ( dbhandle , error , options . tablename , options , retry = options . retry , headers = reader . fieldnames , ignore_empty = options . ignore_empty , ignore_columns = options . ignore_columns , rename_columns = options . rename_columns , lowercase = options . lowercase , ignore_duplicates = options . ignore_duplicates , indices = options . indices , first_column = options . first_column , existing_tables = existing_tables , append = options . append ) E . info ( \"\" ) return else : raise ValueError ( \"\" ) else : take , map_column2type , ignored = createTable ( dbhandle , error , options . tablename , options , rows = rows , retry = options . retry , headers = reader . fieldnames , ignore_empty = options . ignore_empty , ignore_columns = options . ignore_columns , rename_columns = options . rename_columns , lowercase = options . lowercase , ignore_duplicates = options . ignore_duplicates , indices = options . indices , first_column = options . first_column , existing_tables = existing_tables , append = options . append ) def row_iter ( rows , reader ) : for row in rows : yield quoteRow ( row , take , map_column2type , options . missing_values , null = options . null , string_value = options . string_value ) for data in reader : yield quoteRow ( IOTools . convertDictionary ( data , map = options . map ) , take , map_column2type , options . missing_values , null = options . null , string_value = options . string_value ) ninput = E . info ( \"\" ) if options . insert_quick : E . info ( \"\" ) outfile , filename = tempfile . mkstemp ( ) E . debug ( \"\" % filename ) for d in row_iter ( rows , reader ) : ninput += os . write ( outfile , quick_import_separator . join ( [ str ( d [ x ] ) for x in take ] ) + \"\" ) if ninput % report_step == : E . info ( \"\" % ninput ) os . close ( outfile ) statement = quick_import_statement % filename E . debug ( statement ) while : retcode = E . run ( statement , cwd = os . getcwd ( ) , close_fds = True ) if retcode != : E . warn ( \"\" % statement ) if not options . retry : raise ValueError ( \"\" % statement ) time . sleep ( ) continue break os . remove ( filename ) for column in take : executewait ( dbhandle , \"\" % ( options . tablename , column , column ) , error , options . retry ) elif options . insert_many : data = [ ] for d in row_iter ( rows , reader ) : ninput += data . append ( [ d [ x ] for x in take ] ) if ninput % report_step == : E . info ( \"\" % ninput ) statement = \"\" % ( options . tablename , \"\" . join ( \"\" * len ( take ) ) ) E . info ( \"\" % len ( data ) ) E . debug ( \"\" % statement ) while : try : dbhandle . executemany ( statement , data ) except error , msg : E . warn ( \"\" % ( msg , statement ) ) if not options . retry : raise error ( msg ) if not re . search ( \"\" , str ( msg ) ) : raise error ( msg ) time . sleep ( ) continue break else : statement = \"\" % ( options . tablename , '' . join ( take ) ) for d in row_iter ( rows , reader ) : ninput += E . debug ( \"\" % ( statement % d ) ) cc = executewait ( dbhandle , statement , error , retry = options . retry , args = d ) cc . close ( ) if ninput % report_step == : E . info ( \"\" % ninput ) E . info ( \"\" ) nindex = for index in options . indices : nindex += try : statement = \"\" % ( options . tablename , nindex , options . tablename , index ) cc = executewait ( dbhandle , statement , error , options . retry ) cc . close ( ) E . info ( \"\" % ( index ) ) ", "answer": "except error , msg :"}, {"prompt": " \"\"\"\"\"\" import os import os . path import re try : from urllib . parse import urlparse except ImportError : from urlparse import urlparse import logging class MapperError ( Exception ) : pass class Mapper ( ) : def __init__ ( self , mappings = None , use_default_path = False ) : self . logger = logging . getLogger ( '' ) self . mappings = [ ] if ( mappings ) : self . parse ( mappings , use_default_path ) def __len__ ( self ) : \"\"\"\"\"\" return ( len ( self . mappings ) ) def parse ( self , mappings , use_default_path = False ) : \"\"\"\"\"\" if ( use_default_path and len ( mappings ) == and re . search ( r\"\" , mappings [ ] ) == None ) : path = self . path_from_uri ( mappings [ ] ) self . logger . warning ( \"\" % ( mappings [ ] , path ) ) self . mappings . append ( Map ( mappings [ ] , path ) ) elif ( len ( mappings ) == and re . search ( r\"\" , mappings [ ] ) == None and re . search ( r\"\" , mappings [ ] ) == None ) : self . mappings . append ( Map ( mappings [ ] , mappings [ ] ) ) else : ", "answer": "for mapping in mappings :"}, {"prompt": " import json import os DEFAULT_JSON_OUTPUT = '' class GlobalCounter : def __init__ ( self ) : self . data = { } @ staticmethod def fqn ( class_name , method , lineno ) : name = method + '' + str ( lineno ) if class_name and class_name != '' : name = class_name + '' + name return name def count ( self , file , class_name = None , method = None , lineno = - ) : if file not in self . data : self . data [ file ] = { } d = self . data [ file ] name = GlobalCounter . fqn ( class_name , method , lineno ) if name not in d : d [ name ] = d [ name ] += ", "answer": "def to_json ( self , file_location = DEFAULT_JSON_OUTPUT ) :"}, {"prompt": " \"\"\"\"\"\" import sys import logging import optparse import time import urllib import urllib2 import httplib import re class Eutils : def __init__ ( self , options , logger ) : self . logger = logger self . base = \"\" self . query_string = options . query_string self . dbname = options . dbname if options . outname : self . outname = options . outname else : self . outname = '' + '' + self . dbname + '' self . ids = [ ] self . retmax_esearch = self . retmax_efetch = self . count = self . webenv = \"\" self . query_key = \"\" def retrieve ( self ) : \"\"\"\"\"\" self . get_count_value ( ) self . get_uids_list ( ) self . get_sequences ( ) def get_count_value ( self ) : \"\"\"\"\"\" self . logger . info ( \"\" % self . base ) self . logger . info ( \"\" % ( self . query_string , self . dbname ) ) querylog = self . esearch ( self . dbname , self . query_string , '' , '' , \"\" ) self . logger . debug ( \"\" ) for line in querylog : self . logger . debug ( line . rstrip ( ) ) if '' in line : self . count = int ( line [ line . find ( '' ) + len ( '' ) : line . find ( '' ) ] ) self . logger . info ( \"\" % self . count ) def get_uids_list ( self ) : \"\"\"\"\"\" retmax = self . retmax_esearch if ( self . count > retmax ) : num_batches = ( self . count / retmax ) + else : num_batches = self . logger . info ( \"\" % retmax ) self . logger . info ( \"\" % num_batches ) for n in range ( num_batches ) : querylog = self . esearch ( self . dbname , self . query_string , n * retmax , retmax , '' ) for line in querylog : if '' in line and '' in line : uid = ( line [ line . find ( '' ) + len ( '' ) : line . find ( '' ) ] ) self . ids . append ( uid ) self . logger . info ( \"\" % len ( self . ids ) ) def esearch ( self , db , term , retstart , retmax , rettype ) : url = self . base + \"\" self . logger . debug ( \"\" % url ) values = { '' : db , '' : term , '' : rettype , '' : retstart , '' : retmax } data = urllib . urlencode ( values ) self . logger . debug ( \"\" % str ( data ) ) req = urllib2 . Request ( url , data ) response = urllib2 . urlopen ( req ) querylog = response . readlines ( ) time . sleep ( ) return querylog def epost ( self , db , ids ) : url = self . base + \"\" self . logger . debug ( \"\" % url ) values = { '' : db , '' : ids } data = urllib . urlencode ( values ) req = urllib2 . Request ( url , data ) req = urllib2 . Request ( url , data ) serverResponse = False while not serverResponse : try : response = urllib2 . urlopen ( req ) serverResponse = True except : e = sys . exc_info ( ) [ ] self . logger . info ( \"\" % e ) self . logger . info ( \"\" ) time . sleep ( ) querylog = response . readlines ( ) self . logger . debug ( \"\" ) for line in querylog : self . logger . debug ( line . rstrip ( ) ) if '' in line : self . query_key = str ( line [ line . find ( '' ) + len ( '' ) : line . find ( '' ) ] ) if '' in line : self . webenv = str ( line [ line . find ( '' ) + len ( '' ) : line . find ( '' ) ] ) self . logger . debug ( \"\" ) self . logger . debug ( \"\" % self . query_key ) self . logger . debug ( \"\" % self . webenv ) time . sleep ( ) def efetch ( self , db , query_key , webenv ) : url = self . base + \"\" self . logger . debug ( \"\" % url ) values = { '' : db , '' : query_key , '' : webenv , '' : \"\" , '' : \"\" } data = urllib . urlencode ( values ) req = urllib2 . Request ( url , data ) self . logger . debug ( \"\" % str ( data ) ) req = urllib2 . Request ( url , data ) serverTransaction = False counter = while not serverTransaction : counter += self . logger . info ( \"\" % ( counter ) ) try : response = urllib2 . urlopen ( req ) fasta = response . read ( ) if ( \"\" in fasta ) or ( not fasta . startswith ( \">\" ) ) : serverTransaction = False else : serverTransaction = True except urllib2 . HTTPError as e : serverTransaction = False self . logger . info ( \"\" % ( e . code , e . read ( ) ) ) except httplib . IncompleteRead as e : serverTransaction = False self . logger . info ( \"\" % ( e . partial ) ) ", "answer": "fasta = self . sanitiser ( self . dbname , fasta )"}, {"prompt": " from mlxtend . tf_regressor import TfLinearRegression ", "answer": "from mlxtend . data import boston_housing_data"}, {"prompt": " from election_office_measure . models import CandidateCampaign from organization . models import Organization from position . models import PositionEntered from rest_framework import serializers class CandidateCampaignSerializer ( serializers . ModelSerializer ) : class Meta : model = CandidateCampaign fields = ( '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ) class OrganizationSerializer ( serializers . ModelSerializer ) : class Meta : model = Organization fields = ( '' , '' , '' ) class PositionSerializer ( serializers . ModelSerializer ) : ", "answer": "class Meta :"}, {"prompt": " from __future__ import unicode_literals from django . db import migrations , models class Migration ( migrations . Migration ) : dependencies = [ ( '' , '' ) , ] operations = [ migrations . AlterModelOptions ( name = '' , options = { '' : '' } , ) , ", "answer": "migrations . AlterField ("}, {"prompt": " from nova . api . validation import parameter_types associate_host = { '' : '' , '' : { '' : parameter_types . hostname } , ", "answer": "'' : [ '' ] ,"}, {"prompt": " import os import re import gc import six import logging import unicodedata from hashlib import sha1 from datetime import datetime , date from unidecode import unidecode from normality import slugify log = logging . getLogger ( __name__ ) COLLAPSE = re . compile ( r'' ) WS = '' CATEGORIES = { '' : '' , '' : '' , '' : WS , '' : '' , '' : WS } def checksum ( filename ) : \"\"\"\"\"\" hash = sha1 ( ) with open ( filename , '' ) as fh : while True : block = fh . read ( ** ) if not block : break hash . update ( block ) return hash . hexdigest ( ) def make_filename ( source , sep = '' ) : if source is not None : source = os . path . basename ( source ) slugs = [ slugify ( s , sep = sep ) for s in source . split ( '' ) ] source = '' . join ( slugs ) source = source . strip ( '' ) . strip ( sep ) return source def latinize_text ( text ) : if not isinstance ( text , six . text_type ) : return text text = unicode ( unidecode ( text ) ) text = text . replace ( '' , '' ) return text . lower ( ) def normalize_strong ( text ) : if not isinstance ( text , six . string_types ) : return if six . PY2 and not isinstance ( text , six . text_type ) : text = text . decode ( '' ) text = latinize_text ( text . lower ( ) ) text = unicodedata . normalize ( '' , text ) characters = [ ] for character in text : category = unicodedata . category ( character ) [ ] character = CATEGORIES . get ( category , character ) characters . append ( character ) text = u'' . join ( characters ) return COLLAPSE . sub ( WS , text ) . strip ( WS ) def string_value ( value , encoding = None ) : if encoding is None : encoding = '' try : if value is None : return if isinstance ( value , ( date , datetime ) ) : return value . isoformat ( ) elif isinstance ( value , float ) and not value . is_integer ( ) : ", "answer": "return unicode ( value )"}, {"prompt": " from __future__ import unicode_literals from django . db import models , migrations class Migration ( migrations . Migration ) : dependencies = [ ( '' , '' ) , ( '' , '' ) , ] operations = [ ", "answer": "migrations . RemoveField ("}, {"prompt": " \"\"\"\"\"\" __authors__ = [ '' , '' ] import json from tornado import gen from viewfinder . backend . base . exceptions import PermissionError from viewfinder . backend . db . accounting import AccountingAccumulator from viewfinder . backend . db . follower import Follower from viewfinder . backend . db . operation import Operation from viewfinder . backend . db . viewpoint import Viewpoint from viewfinder . backend . op . notification_manager import NotificationManager from viewfinder . backend . op . viewfinder_op import ViewfinderOperation class RemoveViewpointOperation ( ViewfinderOperation ) : \"\"\"\"\"\" def __init__ ( self , client , user_id , viewpoint_id ) : super ( RemoveViewpointOperation , self ) . __init__ ( client ) self . _op = Operation . GetCurrent ( ) self . _client = client self . _user_id = user_id self . _viewpoint_id = viewpoint_id @ classmethod @ gen . coroutine def Execute ( cls , client , user_id , viewpoint_id ) : \"\"\"\"\"\" yield RemoveViewpointOperation ( client , user_id , viewpoint_id ) . _RemoveViewpoint ( ) @ gen . coroutine def _RemoveViewpoint ( self ) : \"\"\"\"\"\" lock = yield gen . Task ( Viewpoint . AcquireLock , self . _client , self . _viewpoint_id ) try : if not ( yield self . _Check ( ) ) : return self . _client . CheckDBNotModified ( ) yield self . _Update ( ) yield self . _Account ( ) ", "answer": "yield Operation . TriggerFailpoint ( self . _client )"}, {"prompt": " \"\"\"\"\"\" import itertools import collections import networkx as nx from networkx . exception import NetworkXError from networkx . utils import not_implemented_for from networkx . algorithms . approximation import local_node_connectivity from networkx . algorithms . connectivity import local_node_connectivity as exact_local_node_connectivity from networkx . algorithms . connectivity import build_auxiliary_node_connectivity from networkx . algorithms . flow import build_residual_network __author__ = \"\"\"\"\"\" . join ( [ '' ] ) __all__ = [ '' ] not_implemented_for ( '' ) def k_components ( G , min_density = ) : r\"\"\"\"\"\" k_components = collections . defaultdict ( list ) node_connectivity = local_node_connectivity k_core = nx . k_core core_number = nx . core_number biconnected_components = nx . biconnected_components density = nx . density combinations = itertools . combinations for component in nx . connected_components ( G ) : comp = set ( component ) if len ( comp ) > : k_components [ ] . append ( comp ) for bicomponent in nx . biconnected_components ( G ) : bicomp = set ( bicomponent ) if len ( bicomp ) > : k_components [ ] . append ( bicomp ) g_cnumber = core_number ( G ) max_core = max ( g_cnumber . values ( ) ) for k in range ( , max_core + ) : C = k_core ( G , k , core_number = g_cnumber ) for nodes in biconnected_components ( C ) : if len ( nodes ) < k : continue SG = G . subgraph ( nodes ) H = _AntiGraph ( ) H . add_nodes_from ( SG . nodes ( ) ) for u , v in combinations ( SG , ) : K = node_connectivity ( SG , u , v , cutoff = k ) if k > K : H . add_edge ( u , v ) for h_nodes in biconnected_components ( H ) : if len ( h_nodes ) <= k : continue SH = H . subgraph ( h_nodes ) for Gc in _cliques_heuristic ( SG , SH , k , min_density ) : for k_nodes in biconnected_components ( Gc ) : Gk = nx . k_core ( SG . subgraph ( k_nodes ) , k ) if len ( Gk ) <= k : continue k_components [ k ] . append ( set ( Gk ) ) return k_components def _cliques_heuristic ( G , H , k , min_density ) : h_cnumber = nx . core_number ( H ) for i , c_value in enumerate ( sorted ( set ( h_cnumber . values ( ) ) , reverse = True ) ) : cands = set ( n for n , c in h_cnumber . items ( ) if c == c_value ) if i == : overlap = False else : overlap = set . intersection ( * [ set ( x for x in H [ n ] if x not in cands ) for n in cands ] ) if overlap and len ( overlap ) < k : SH = H . subgraph ( cands | overlap ) else : SH = H . subgraph ( cands ) sh_cnumber = nx . core_number ( SH ) SG = nx . k_core ( G . subgraph ( SH ) , k ) while not ( _same ( sh_cnumber ) and nx . density ( SH ) >= min_density ) : SH = H . subgraph ( SG ) if len ( SH ) <= k : break sh_cnumber = nx . core_number ( SH ) sh_deg = dict ( SH . degree ( ) ) min_deg = min ( sh_deg . values ( ) ) SH . remove_nodes_from ( n for n , d in sh_deg . items ( ) if d == min_deg ) SG = nx . k_core ( G . subgraph ( SH ) , k ) else : yield SG def _same ( measure , tol = ) : vals = set ( measure . values ( ) ) if ( max ( vals ) - min ( vals ) ) <= tol : return True return False class _AntiGraph ( nx . Graph ) : \"\"\"\"\"\" all_edge_dict = { '' : } def single_edge_dict ( self ) : return self . all_edge_dict edge_attr_dict_factory = single_edge_dict def __getitem__ ( self , n ) : \"\"\"\"\"\" all_edge_dict = self . all_edge_dict return dict ( ( node , all_edge_dict ) for node in set ( self . adj ) - set ( self . adj [ n ] ) - set ( [ n ] ) ) def neighbors ( self , n ) : \"\"\"\"\"\" try : return iter ( set ( self . adj ) - set ( self . adj [ n ] ) - set ( [ n ] ) ) except KeyError : raise NetworkXError ( \"\" % ( n , ) ) def degree ( self , nbunch = None , weight = None ) : \"\"\"\"\"\" if nbunch in self : nbrs = { v : self . all_edge_dict for v in set ( self . adj ) - set ( self . adj [ nbunch ] ) - set ( [ nbunch ] ) } if weight is None : return len ( nbrs ) + ( nbunch in nbrs ) return sum ( ( nbrs [ nbr ] . get ( weight , ) for nbr in nbrs ) ) + ( nbunch in nbrs and nbrs [ nbunch ] . get ( weight , ) ) if nbunch is None : nodes_nbrs = ( ( n , { v : self . all_edge_dict for v in set ( self . adj ) - set ( self . adj [ n ] ) - set ( [ n ] ) } ) for n in self . nodes ( ) ) else : nodes_nbrs = ( ( n , { v : self . all_edge_dict for v in set ( self . nodes ( ) ) - set ( self . adj [ n ] ) - set ( [ n ] ) } ) for n in self . nbunch_iter ( nbunch ) ) if weight is None : def d_iter ( ) : for n , nbrs in nodes_nbrs : yield ( n , len ( nbrs ) + ( n in nbrs ) ) else : def d_iter ( ) : ", "answer": "for n , nbrs in nodes_nbrs :"}, {"prompt": " from nameko . events import event_handler ", "answer": "from nameko . standalone . events import event_dispatcher"}, {"prompt": " from openstack import service_filter class ClusterService ( service_filter . ServiceFilter ) : \"\"\"\"\"\" valid_versions = [ service_filter . ValidVersion ( '' ) ] UNVERSIONED = None def __init__ ( self , version = None ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " \"\"\"\"\"\" from __future__ import print_function import argparse import logging import sys from oslo_utils import encodeutils from oslo_utils import importutils import six import senlinclient from senlinclient import cliargs from senlinclient import client as senlin_client from senlinclient . common import exc from senlinclient . common . i18n import _ from senlinclient . common import utils osprofiler_profiler = importutils . try_import ( \"\" ) USER_AGENT = '' LOG = logging . getLogger ( __name__ ) class HelpFormatter ( argparse . HelpFormatter ) : def start_section ( self , heading ) : heading = '' % ( heading [ ] . upper ( ) , heading [ : ] ) super ( HelpFormatter , self ) . start_section ( heading ) class SenlinShell ( object ) : def _setup_logging ( self , debug ) : log_lvl = logging . DEBUG if debug else logging . WARNING logging . basicConfig ( format = \"\" , level = log_lvl ) logging . getLogger ( '' ) . setLevel ( logging . WARNING ) logging . getLogger ( '' ) . setLevel ( logging . WARNING ) def _setup_verbose ( self , verbose ) : if verbose : exc . verbose = def _find_actions ( self , subparsers , actions_module ) : for attr in ( a for a in dir ( actions_module ) if a . startswith ( '' ) ) : command = attr [ : ] . replace ( '' , '' ) callback = getattr ( actions_module , attr ) desc = callback . __doc__ or '' help = desc . strip ( ) . split ( '' ) [ ] arguments = getattr ( callback , '' , [ ] ) subparser = subparsers . add_parser ( command , help = help , description = desc , add_help = False , formatter_class = HelpFormatter ) subparser . add_argument ( '' , '' , action = '' , help = argparse . SUPPRESS ) for ( args , kwargs ) in arguments : subparser . add_argument ( * args , ** kwargs ) subparser . set_defaults ( func = callback ) self . subcommands [ command ] = subparser def do_bash_completion ( self , args ) : \"\"\"\"\"\" commands = set ( ) options = set ( ) for sc_str , sc in self . subcommands . items ( ) : if sc_str == '' or sc_str == '' : continue commands . add ( sc_str ) for option in list ( sc . _optionals . _option_string_actions ) : options . add ( option ) print ( '' . join ( commands | options ) ) def add_profiler_args ( self , parser ) : ", "answer": "if osprofiler_profiler :"}, {"prompt": " from framework . dependency_management . dependency_resolver import ServiceLocator \"\"\"\"\"\" ", "answer": "DESCRIPTION = \"\""}, {"prompt": " \"\"\"\"\"\" __version__ = '' from datetime import datetime from datetime import timedelta import wikipedia as pywikibot import catlib from category import * redirect_templates = [ u'' , u'' , u'' , u'' , u'' , u'' , u'' , u'' ] move_message = u'' cooldown = def get_redirect_cat ( category = None ) : \"\"\"\"\"\" destination = None site = pywikibot . getSite ( u'' , u'' ) for template in category . templatesWithParams ( ) : if ( ( template [ ] in redirect_templates ) and ( len ( template [ ] ) > ) ) : destination = catlib . Category ( site , template [ ] [ ] ) if not destination . exists ( ) : return None return destination def readyToEdit ( old_category ) : \"\"\"\"\"\" dateformat = \"\" today = datetime . now ( ) deadline = today + timedelta ( days = - cooldown ) old_category . get ( ) return ( deadline . strftime ( dateformat ) > old_category . editTime ( ) ) def main ( ) : \"\"\"\"\"\" site = pywikibot . getSite ( u'' , u'' ) dirtycat = catlib . Category ( site , u'' ) destination = None catbot = None for old_category in dirtycat . subcategories ( ) : if ( readyToEdit ( old_category ) ) : destination = get_redirect_cat ( old_category ) if destination : pywikibot . output ( destination . title ( ) ) for page in old_category . articles ( ) : try : catlib . change_category ( page , old_category , destination , move_message % ( old_category . title ( ) , old_category . title ( withNamespace = False ) , destination . title ( ) , destination . title ( withNamespace = False ) ) ) ", "answer": "except pywikibot . IsRedirectPage :"}, {"prompt": " import requests import sys import unittest from httmock import ( all_requests , response , urlmatch , with_httmock , HTTMock , text_type , binary_type ) @ urlmatch ( scheme = '' ) def unmatched_scheme ( url , request ) : raise AssertionError ( '' ) @ urlmatch ( path = r'' ) def unmatched_path ( url , request ) : ", "answer": "raise AssertionError ( '' )"}, {"prompt": " from django . test import TestCase from datastores import TxRedisMapper from transifex . txcommon . log import logger class TestRedis ( TestCase ) : def setUp ( self ) : logger . critical ( \"\" ) self . r = TxRedisMapper ( db = ) def tearDown ( self ) : self . r . flushdb ( ) def test_json_suffix ( self ) : key = '' data = { '' : '' , '' : '' } res = self . r . lpush ( key , data = data ) ", "answer": "self . assertEquals ( res , )"}, {"prompt": " \"\"\"\"\"\" import json from six . moves . urllib . parse import quote , unquote from swift . common . ring import Ring from swift . common . utils import get_logger , split_path from swift . common . swob import Request , Response from swift . common . swob import HTTPBadRequest , HTTPMethodNotAllowed from swift . common . storage_policy import POLICIES from swift . proxy . controllers . base import get_container_info RESPONSE_VERSIONS = ( , ) class ListEndpointsMiddleware ( object ) : \"\"\"\"\"\" def __init__ ( self , app , conf ) : self . app = app self . logger = get_logger ( conf , log_route = '' ) self . swift_dir = conf . get ( '' , '' ) self . account_ring = Ring ( self . swift_dir , ring_name = '' ) self . container_ring = Ring ( self . swift_dir , ring_name = '' ) self . endpoints_path = conf . get ( '' , '' ) if not self . endpoints_path . endswith ( '' ) : self . endpoints_path += '' self . default_response_version = self . response_map = { : self . v1_format_response , : self . v2_format_response , } def get_object_ring ( self , policy_idx ) : \"\"\"\"\"\" return POLICIES . get_object_ring ( policy_idx , self . swift_dir ) def _parse_version ( self , raw_version ) : err_msg = '' % raw_version try : version = float ( raw_version . lstrip ( '' ) ) except ValueError : raise ValueError ( err_msg ) if not any ( version == v for v in RESPONSE_VERSIONS ) : raise ValueError ( err_msg ) return version def _parse_path ( self , request ) : \"\"\"\"\"\" clean_path = request . path [ len ( self . endpoints_path ) - : ] try : raw_version , rest = split_path ( clean_path , , , True ) except ValueError : raise ValueError ( '' ) try : version = self . _parse_version ( raw_version ) except ValueError : if raw_version . startswith ( '' ) and '' not in raw_version : raise version = self . default_response_version rest = clean_path else : rest = '' + rest if rest else '' try : account , container , obj = split_path ( rest , , , True ) except ValueError : raise ValueError ( '' ) return version , account , container , obj def v1_format_response ( self , req , endpoints , ** kwargs ) : return Response ( json . dumps ( endpoints ) , content_type = '' ) ", "answer": "def v2_format_response ( self , req , endpoints , storage_policy_index ,"}, {"prompt": " import io import re import json import pickle from os . path import join from functools import partial from acrylamid import core , utils , lib from acrylamid . compat import PY2K , iteritems , text_type as str from acrylamid . core import cache from acrylamid . utils import Struct from acrylamid . filters import Filter from acrylamid . lib import requests if PY2K : from urllib import urlencode from urlparse import urlparse , parse_qs import cPickle as pickle else : from urllib . parse import urlencode from urllib . parse import urlparse , parse_qs __img_re = r'' __img_re_title = r'' def blockquote ( header , body ) : \"\"\"\"\"\" def paragraphize ( text ) : return '' + text . strip ( ) . replace ( '' , '' ) . replace ( '' , '' ) + '' by , source , title = None , None , None m = re . match ( r'' , header , flags = re . I ) if m : by = m . group ( ) source = m . group ( ) + m . group ( ) title = m . group ( ) else : m = re . match ( r'' , header , re . I ) if m : by = m . group ( ) source = m . group ( ) + m . group ( ) else : m = re . match ( r'' , header ) if m : by = m . group ( ) title = m . group ( ) else : m = re . match ( r'' , header ) if m : by = m . group ( ) quote = paragraphize ( body ) author = '' % ( by . strip ( ) or '' ) if source : url = re . match ( r'' , source ) . group ( ) parts = [ ] for part in url . split ( '' ) : if not part or len ( '' . join ( parts + [ part ] ) ) >= : break parts . append ( part ) else : parts . append ( '' ) href = '' . join ( parts ) if source : cite = '' % ( source , ( title or href ) ) elif title : cite = '' % title if not author : blockquote = quote elif cite : blockquote = quote + \"\" % ( author + cite ) else : blockquote = quote + \"\" % author return \"\" % blockquote def img ( header , body = None ) : \"\"\"\"\"\" attrs = re . match ( __img_re , header ) . groupdict ( ) m = re . match ( __img_re_title , attrs [ '' ] ) if m : attrs [ '' ] = m . groupdict ( ) [ '' ] attrs [ '' ] = m . groupdict ( ) [ '' ] elif '' in attrs : attrs [ '' ] = attrs [ '' ] . replace ( '' , '' ) if '' in attrs : attrs [ '' ] = attrs [ '' ] . replace ( '' , '' ) if attrs : return '' + '' . join ( '' % ( k , v ) for k , v in iteritems ( attrs ) if v ) + '' return ( \"\" \"\" \"\" ) def youtube ( header , body = None ) : if header . startswith ( ( '' , '' ) ) : header = parse_qs ( urlparse ( header ) . query ) [ '' ] [ ] return '' + '' % header + '' def pullquote ( header , body ) : \"\"\"\"\"\" align = '' if '' in header . lower ( ) else '' m = re . search ( r'' , body , re . MULTILINE | re . DOTALL ) if m : return '' . format ( align , m . group ( ) , re . sub ( r'' , '' , body ) ) return \"\" def tweet ( header , body = None ) : \"\"\"\"\"\" oembed = '' args = list ( map ( str . strip , re . split ( r'' , header ) ) ) params = Struct ( url = args . pop ( ) ) for arg in args : k , v = list ( map ( str . strip , arg . split ( '' ) ) ) if k and v : v = v . strip ( '' ) params [ k ] = v try : with io . open ( join ( core . cache . cache_dir , '' ) , '' ) as fp : cache = pickle . load ( fp ) except ( IOError , pickle . PickleError ) : cache = { } if params in cache : body = cache [ params ] else : try : body = json . loads ( requests . get ( oembed + '' + urlencode ( params ) ) . read ( ) ) [ '' ] except ( requests . HTTPError , requests . URLError ) : log . exception ( '' ) body = \"\" except ( ValueError , KeyError ) : log . exception ( '' ) body = \"\" else : cache [ params ] = body try : with io . open ( join ( core . cache . cache_dir , '' ) , '' ) as fp : pickle . dump ( cache , fp , pickle . HIGHEST_PROTOCOL ) except ( IOError , pickle . PickleError ) : log . exception ( '' ) return \"\" % body class Liquid ( Filter ) : match = [ re . compile ( '' , re . I ) ] priority = directives = { '' : blockquote , '' : pullquote , '' : img , '' : tweet , '' : youtube } def block ( self , tag ) : return re . compile ( '' . join ( [ r'' % tag , '' , '' , r'' % tag , ", "answer": "'' ] ) , re . MULTILINE | re . DOTALL )"}, {"prompt": " \"\"\"\"\"\" import json __all__ = [ '' , '' ] _INVALID_ENUM_TEMPLATE = '' class RequestRejectionError ( Exception ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " from pypy . interpreter . baseobjspace import ObjSpace from pypy . interpreter . error import OperationError from pypy . objspace . descroperation import DescrOperation from pypy . objspace . std . multimethod import FailedToImplement from pypy . objspace . std . boolobject import W_BoolObject from pypy . tool . sourcetools import func_with_new_name METHODS_WITH_SHORTCUT = dict . fromkeys ( [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , ] ) KNOWN_MISSING = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , ] for _name , _ , _ , _specialmethods in ObjSpace . MethodTable : ", "answer": "if _specialmethods :"}, {"prompt": " \"\"\"\"\"\" from __future__ import division , print_function from time import time import os import re import shutil import traceback import glob import sys import gzip import posixpath try : from StringIO import StringIO import cPickle as pickle import urllib2 as urllib from urllib2 import HTTPError , URLError except : from io import StringIO import pickle import urllib . request import urllib . error import urllib . parse from urllib . error import HTTPError , URLError try : execfile except NameError : def execfile ( filename , global_vars = None , local_vars = None ) : with open ( filename , encoding = '' ) as f : code = compile ( f . read ( ) , filename , '' ) exec ( code , global_vars , local_vars ) try : basestring except NameError : basestring = str try : from PIL import Image except : import Image import matplotlib matplotlib . use ( '' ) import token import tokenize import numpy as np class Tee ( object ) : def __init__ ( self , file1 , file2 ) : self . file1 = file1 self . file2 = file2 def write ( self , data ) : self . file1 . write ( data ) self . file2 . write ( data ) def flush ( self ) : self . file1 . flush ( ) self . file2 . flush ( ) def get_data ( url ) : \"\"\"\"\"\" if url . startswith ( '' ) : resp = urllib . urlopen ( url ) encoding = resp . headers . dict . get ( '' , '' ) data = resp . read ( ) if encoding == '' : pass elif encoding == '' : data = StringIO ( data ) data = gzip . GzipFile ( fileobj = data ) . read ( ) else : raise RuntimeError ( '' ) else : with open ( url , '' ) as fid : data = fid . read ( ) fid . close ( ) return data def parse_sphinx_searchindex ( searchindex ) : \"\"\"\"\"\" def _select_block ( str_in , start_tag , end_tag ) : \"\"\"\"\"\" start_pos = str_in . find ( start_tag ) if start_pos < : raise ValueError ( '' ) depth = for pos in range ( start_pos , len ( str_in ) ) : if str_in [ pos ] == start_tag : depth += elif str_in [ pos ] == end_tag : depth -= if depth == : break sel = str_in [ start_pos + : pos ] return sel def _parse_dict_recursive ( dict_str ) : \"\"\"\"\"\" dict_out = dict ( ) pos_last = pos = dict_str . find ( '' ) while pos >= : key = dict_str [ pos_last : pos ] if dict_str [ pos + ] == '' : pos_tmp = dict_str . find ( '' , pos + ) if pos_tmp < : raise RuntimeError ( '' ) value = dict_str [ pos + : pos_tmp ] . split ( '' ) for i in range ( len ( value ) ) : try : value [ i ] = int ( value [ i ] ) except ValueError : pass elif dict_str [ pos + ] == '' : subdict_str = _select_block ( dict_str [ pos : ] , '' , '' ) value = _parse_dict_recursive ( subdict_str ) pos_tmp = pos + len ( subdict_str ) else : raise ValueError ( '' ) key = key . strip ( '' ) if len ( key ) > : dict_out [ key ] = value pos_last = dict_str . find ( '' , pos_tmp ) if pos_last < : break pos_last += pos = dict_str . find ( '' , pos_last ) return dict_out query = '' pos = searchindex . find ( query ) if pos < : raise ValueError ( '' ) sel = _select_block ( searchindex [ pos : ] , '' , '' ) objects = _parse_dict_recursive ( sel ) query = '' pos = searchindex . find ( query ) if pos < : raise ValueError ( '' ) filenames = searchindex [ pos + len ( query ) + : ] filenames = filenames [ : filenames . find ( '' ) ] filenames = [ f . strip ( '' ) for f in filenames . split ( '' ) ] return filenames , objects class SphinxDocLinkResolver ( object ) : \"\"\"\"\"\" def __init__ ( self , doc_url , searchindex = '' , extra_modules_test = None , relative = False ) : self . doc_url = doc_url self . relative = relative self . _link_cache = { } self . extra_modules_test = extra_modules_test self . _page_cache = { } if doc_url . startswith ( '' ) : if relative : raise ValueError ( '' '' ) searchindex_url = doc_url + '' + searchindex else : searchindex_url = os . path . join ( doc_url , searchindex ) if os . name . lower ( ) == '' and not doc_url . startswith ( '' ) : if not relative : raise ValueError ( '' '' ) self . _is_windows = True else : self . _is_windows = False sindex = get_data ( searchindex_url ) filenames , objects = parse_sphinx_searchindex ( sindex ) self . _searchindex = dict ( filenames = filenames , objects = objects ) def _get_link ( self , cobj ) : \"\"\"\"\"\" fname_idx = None full_name = cobj [ '' ] + '' + cobj [ '' ] if full_name in self . _searchindex [ '' ] : value = self . _searchindex [ '' ] [ full_name ] if isinstance ( value , dict ) : value = value [ value . keys ( ) [ ] ] fname_idx = value [ ] elif cobj [ '' ] in self . _searchindex [ '' ] : value = self . _searchindex [ '' ] [ cobj [ '' ] ] if cobj [ '' ] in value . keys ( ) : fname_idx = value [ cobj [ '' ] ] [ ] if fname_idx is not None : fname = self . _searchindex [ '' ] [ fname_idx ] + '' if self . _is_windows : fname = fname . replace ( '' , '' ) link = os . path . join ( self . doc_url , fname ) else : link = posixpath . join ( self . doc_url , fname ) if link in self . _page_cache : html = self . _page_cache [ link ] else : html = get_data ( link ) self . _page_cache [ link ] = html comb_names = [ cobj [ '' ] + '' + cobj [ '' ] ] if self . extra_modules_test is not None : for mod in self . extra_modules_test : comb_names . append ( mod + '' + cobj [ '' ] ) url = False for comb_name in comb_names : if html . find ( comb_name ) >= : url = link + '' + comb_name link = url else : link = False return link def resolve ( self , cobj , this_url ) : \"\"\"\"\"\" full_name = cobj [ '' ] + '' + cobj [ '' ] link = self . _link_cache . get ( full_name , None ) if link is None : link = self . _get_link ( cobj ) self . _link_cache [ full_name ] = link if link is False or link is None : return None if self . relative : link = os . path . relpath ( link , start = this_url ) if self . _is_windows : link = link . replace ( '' , '' ) link = link [ : ] return link rst_template = \"\"\"\"\"\" plot_rst_template = \"\"\"\"\"\" HLIST_HEADER = \"\"\"\"\"\" HLIST_IMAGE_TEMPLATE = \"\"\"\"\"\" SINGLE_IMAGE = \"\"\"\"\"\" def extract_docstring ( filename , ignore_heading = False ) : \"\"\"\"\"\" if sys . version_info >= ( , ) : lines = open ( filename , encoding = '' ) . readlines ( ) else : lines = open ( filename ) . readlines ( ) start_row = if lines [ ] . startswith ( '' ) : lines . pop ( ) start_row = docstring = '' first_par = '' line_iterator = iter ( lines ) tokens = tokenize . generate_tokens ( lambda : next ( line_iterator ) ) for tok_type , tok_content , _ , ( erow , _ ) , _ in tokens : tok_type = token . tok_name [ tok_type ] if tok_type in ( '' , '' , '' , '' , '' ) : continue elif tok_type == '' : docstring = eval ( tok_content ) paragraphs = '' . join ( line . rstrip ( ) for line in docstring . split ( '' ) ) . split ( '' ) if paragraphs : if ignore_heading : if len ( paragraphs ) > : first_par = re . sub ( '' , '' , paragraphs [ ] ) first_par = ( ( first_par [ : ] + '' ) if len ( first_par ) > else first_par ) else : raise ValueError ( \"\" , \"\" , \"\" ) else : first_par = paragraphs [ ] break return docstring , first_par , erow + + start_row def generate_example_rst ( app ) : \"\"\"\"\"\" root_dir = os . path . join ( app . builder . srcdir , '' ) ", "answer": "example_dir = os . path . abspath ( app . builder . srcdir + '' + '' )"}, {"prompt": " \"\"\"\"\"\" import Bcfg2 . Server . Plugin class POSIXCompat ( Bcfg2 . Server . Plugin . Plugin , Bcfg2 . Server . Plugin . GoalValidator ) : \"\"\"\"\"\" create = False def __init__ ( self , core ) : Bcfg2 . Server . Plugin . Plugin . __init__ ( self , core ) Bcfg2 . Server . Plugin . GoalValidator . __init__ ( self ) def validate_goals ( self , metadata , goals ) : \"\"\"\"\"\" if metadata . version_info and metadata . version_info >= ( , , , '' , ) : return for goal in goals : ", "answer": "for entry in goal . getchildren ( ) :"}, {"prompt": " \"\"\"\"\"\" from muntjac . data . util . object_property import ObjectProperty from muntjac . ui . abstract_field import AbstractField from muntjac . data import property as prop class ProgressIndicator ( AbstractField , prop . IValueChangeListener , prop . IProperty , prop . IViewer ) : \"\"\"\"\"\" CLIENT_WIDGET = None CONTENT_TEXT = CONTENT_PREFORMATTED = def __init__ ( self , * args ) : \"\"\"\"\"\" super ( ProgressIndicator , self ) . __init__ ( ) self . _indeterminate = False self . _dataSource = None self . _pollingInterval = nargs = len ( args ) if nargs == : self . setPropertyDataSource ( ObjectProperty ( , float ) ) elif nargs == : if isinstance ( args [ ] , prop . IProperty ) : contentSource , = args self . setPropertyDataSource ( contentSource ) else : value , = args self . setPropertyDataSource ( ObjectProperty ( value , float ) ) else : raise ValueError , '' def setReadOnly ( self , readOnly ) : \"\"\"\"\"\" if self . _dataSource is None : raise ValueError , '' self . _dataSource . setReadOnly ( readOnly ) def isReadOnly ( self ) : \"\"\"\"\"\" if self . _dataSource is None : raise ValueError , '' return self . _dataSource . isReadOnly ( ) def paintContent ( self , target ) : \"\"\"\"\"\" target . addAttribute ( '' , self . _indeterminate ) target . addAttribute ( '' , self . _pollingInterval ) target . addAttribute ( '' , str ( self . getValue ( ) ) ) def getValue ( self ) : \"\"\"\"\"\" if self . _dataSource is None : raise ValueError , '' return self . _dataSource . getValue ( ) def setValue ( self , newValue , repaintIsNotNeeded = None ) : \"\"\"\"\"\" if repaintIsNotNeeded is None : if self . _dataSource is None : raise ValueError , '' self . _dataSource . setValue ( newValue ) else : super ( ProgressIndicator , self ) . setValue ( newValue , repaintIsNotNeeded ) def __str__ ( self ) : \"\"\"\"\"\" if self . _dataSource is None : raise ValueError , '' return str ( self . _dataSource ) def getType ( self ) : \"\"\"\"\"\" ", "answer": "if self . _dataSource is None :"}, {"prompt": " import time import unittest from tipfy import Tipfy , Request , Response from tipfy . sessions import SessionStore , SecureCookieStore , SecureCookieSession import test_utils class TestSecureCookie ( test_utils . BaseTestCase ) : def _get_app ( self ) : return Tipfy ( config = { '' : { '' : '' , } } ) def test_get_cookie_no_cookie ( self ) : store = SecureCookieStore ( '' ) request = Request . from_values ( '' ) self . assertEqual ( store . get_cookie ( request , '' ) , None ) def test_get_cookie_invalid_parts ( self ) : store = SecureCookieStore ( '' ) request = Request . from_values ( '' , headers = [ ( '' , '' ) ] ) self . assertEqual ( store . get_cookie ( request , '' ) , None ) def test_get_cookie_invalid_signature ( self ) : store = SecureCookieStore ( '' ) request = Request . from_values ( '' , headers = [ ( '' , '' ) ] ) self . assertEqual ( store . get_cookie ( request , '' ) , None ) def test_get_cookie_expired ( self ) : store = SecureCookieStore ( '' ) request = Request . from_values ( '' , headers = [ ( '' , '' ) ] ) self . assertEqual ( store . get_cookie ( request , '' , max_age = - ) , None ) def test_get_cookie_badly_encoded ( self ) : store = SecureCookieStore ( '' ) timestamp = str ( int ( time . time ( ) ) ) value = '' signature = store . _get_signature ( '' , value , timestamp ) cookie_value = '' . join ( [ value , timestamp , signature ] ) request = Request . from_values ( '' , headers = [ ( '' , '' % cookie_value ) ] ) self . assertEqual ( store . get_cookie ( request , '' ) , None ) def test_get_cookie_valid ( self ) : ", "answer": "store = SecureCookieStore ( '' )"}, {"prompt": " from django . conf . urls import * urlpatterns = patterns ( '' , url ( r'' , ", "answer": "view = '' ,"}, {"prompt": " import logging import os import time from will . utils import sizeof_fmt class FileStorageException ( Exception ) : \"\"\"\"\"\" pass class FileStorage ( object ) : \"\"\"\"\"\" def __init__ ( self , settings ) : self . dirname = os . path . abspath ( os . path . expanduser ( settings . FILE_DIR ) ) self . dotfile = os . path . join ( self . dirname , \"\" ) logging . debug ( \"\" , self . dirname ) if not os . path . exists ( self . dirname ) : os . makedirs ( self . dirname , mode = ) elif not os . path . exists ( self . dotfile ) : if len ( self . _all_setting_files ( ) ) > : raise FileStorageException ( \"\" \"\" \"\" % ( self . dirname , ) ) os . chmod ( self . dirname , ) with open ( self . dotfile , '' ) : os . utime ( self . dotfile , None ) def _all_setting_files ( self ) : ", "answer": "return ["}, {"prompt": " from robot . model import SuiteVisitor class ResultVisitor ( SuiteVisitor ) : def visit_result ( self , result ) : if self . start_result ( result ) is not False : result . suite . visit ( self ) result . statistics . visit ( self ) result . errors . visit ( self ) self . end_result ( result ) def start_result ( self , result ) : pass def end_result ( self , result ) : pass def visit_statistics ( self , stats ) : if self . start_statistics ( stats ) is not False : stats . total . visit ( self ) stats . tags . visit ( self ) stats . suite . visit ( self ) self . end_statistics ( stats ) def start_statistics ( self , stats ) : pass def end_statistics ( self , stats ) : pass def visit_total_statistics ( self , stats ) : if self . start_total_statistics ( stats ) is not False : for stat in stats : stat . visit ( self ) self . end_total_statistics ( stats ) def start_total_statistics ( self , stats ) : pass def end_total_statistics ( self , stats ) : pass ", "answer": "def visit_tag_statistics ( self , stats ) :"}, {"prompt": " \"\"\"\"\"\" from cloudcafe . compute . common . composites import BaseComputeComposite from cloudcafe . compute . extensions . rescue_api . client import RescueClient class RescueComposite ( BaseComputeComposite ) : def __init__ ( self , auth_composite ) : super ( RescueComposite , self ) . __init__ ( auth_composite ) ", "answer": "self . client = RescueClient ( ** self . compute_auth_composite . client_args ) "}, {"prompt": " from google . net . proto import ProtocolBuffer import array import dummy_thread as thread __pychecker__ = \"\"\"\"\"\" if hasattr ( ProtocolBuffer , '' ) : _extension_runtime = True _ExtendableProtocolMessage = ProtocolBuffer . ExtendableProtocolMessage else : _extension_runtime = False _ExtendableProtocolMessage = ProtocolBuffer . ProtocolMessage class MemcacheServiceError ( ProtocolBuffer . ProtocolMessage ) : OK = UNSPECIFIED_ERROR = NAMESPACE_NOT_SET = PERMISSION_DENIED = INVALID_VALUE = UNAVAILABLE = _ErrorCode_NAMES = { : \"\" , : \"\" , : \"\" , : \"\" , : \"\" , : \"\" , } def ErrorCode_Name ( cls , x ) : return cls . _ErrorCode_NAMES . get ( x , \"\" ) ErrorCode_Name = classmethod ( ErrorCode_Name ) def __init__ ( self , contents = None ) : pass if contents is not None : self . MergeFromString ( contents ) def MergeFrom ( self , x ) : assert x is not self def Equals ( self , x ) : if x is self : return return def IsInitialized ( self , debug_strs = None ) : initialized = return initialized def ByteSize ( self ) : n = return n def ByteSizePartial ( self ) : n = return n def Clear ( self ) : pass def OutputUnchecked ( self , out ) : pass def OutputPartial ( self , out ) : pass def TryMerge ( self , d ) : while d . avail ( ) > : tt = d . getVarInt32 ( ) if ( tt == ) : raise ProtocolBuffer . ProtocolBufferDecodeError d . skipData ( tt ) def __str__ ( self , prefix = \"\" , printElemNumber = ) : res = \"\" return res def _BuildTagLookupTable ( sparse , maxtag , default = None ) : return tuple ( [ sparse . get ( i , default ) for i in xrange ( , + maxtag ) ] ) _TEXT = _BuildTagLookupTable ( { : \"\" , } , ) _TYPES = _BuildTagLookupTable ( { : ProtocolBuffer . Encoder . NUMERIC , } , , ProtocolBuffer . Encoder . MAX_TYPE ) _STYLE = \"\"\"\"\"\" _STYLE_CONTENT_TYPE = \"\"\"\"\"\" _PROTO_DESCRIPTOR_NAME = '' class AppOverride ( ProtocolBuffer . ProtocolMessage ) : has_app_id_ = app_id_ = \"\" has_num_memcacheg_backends_ = num_memcacheg_backends_ = has_ignore_shardlock_ = ignore_shardlock_ = has_memcache_pool_hint_ = memcache_pool_hint_ = \"\" has_memcache_sharding_strategy_ = memcache_sharding_strategy_ = \"\" def __init__ ( self , contents = None ) : if contents is not None : self . MergeFromString ( contents ) def app_id ( self ) : return self . app_id_ def set_app_id ( self , x ) : self . has_app_id_ = self . app_id_ = x def clear_app_id ( self ) : if self . has_app_id_ : self . has_app_id_ = self . app_id_ = \"\" def has_app_id ( self ) : return self . has_app_id_ def num_memcacheg_backends ( self ) : return self . num_memcacheg_backends_ def set_num_memcacheg_backends ( self , x ) : self . has_num_memcacheg_backends_ = self . num_memcacheg_backends_ = x def clear_num_memcacheg_backends ( self ) : if self . has_num_memcacheg_backends_ : self . has_num_memcacheg_backends_ = self . num_memcacheg_backends_ = def has_num_memcacheg_backends ( self ) : return self . has_num_memcacheg_backends_ def ignore_shardlock ( self ) : return self . ignore_shardlock_ def set_ignore_shardlock ( self , x ) : self . has_ignore_shardlock_ = self . ignore_shardlock_ = x def clear_ignore_shardlock ( self ) : if self . has_ignore_shardlock_ : self . has_ignore_shardlock_ = self . ignore_shardlock_ = def has_ignore_shardlock ( self ) : return self . has_ignore_shardlock_ def memcache_pool_hint ( self ) : return self . memcache_pool_hint_ def set_memcache_pool_hint ( self , x ) : self . has_memcache_pool_hint_ = self . memcache_pool_hint_ = x def clear_memcache_pool_hint ( self ) : if self . has_memcache_pool_hint_ : self . has_memcache_pool_hint_ = self . memcache_pool_hint_ = \"\" def has_memcache_pool_hint ( self ) : return self . has_memcache_pool_hint_ def memcache_sharding_strategy ( self ) : return self . memcache_sharding_strategy_ def set_memcache_sharding_strategy ( self , x ) : self . has_memcache_sharding_strategy_ = self . memcache_sharding_strategy_ = x def clear_memcache_sharding_strategy ( self ) : if self . has_memcache_sharding_strategy_ : self . has_memcache_sharding_strategy_ = self . memcache_sharding_strategy_ = \"\" def has_memcache_sharding_strategy ( self ) : return self . has_memcache_sharding_strategy_ def MergeFrom ( self , x ) : assert x is not self if ( x . has_app_id ( ) ) : self . set_app_id ( x . app_id ( ) ) if ( x . has_num_memcacheg_backends ( ) ) : self . set_num_memcacheg_backends ( x . num_memcacheg_backends ( ) ) if ( x . has_ignore_shardlock ( ) ) : self . set_ignore_shardlock ( x . ignore_shardlock ( ) ) if ( x . has_memcache_pool_hint ( ) ) : self . set_memcache_pool_hint ( x . memcache_pool_hint ( ) ) if ( x . has_memcache_sharding_strategy ( ) ) : self . set_memcache_sharding_strategy ( x . memcache_sharding_strategy ( ) ) def Equals ( self , x ) : if x is self : return if self . has_app_id_ != x . has_app_id_ : return if self . has_app_id_ and self . app_id_ != x . app_id_ : return if self . has_num_memcacheg_backends_ != x . has_num_memcacheg_backends_ : return if self . has_num_memcacheg_backends_ and self . num_memcacheg_backends_ != x . num_memcacheg_backends_ : return if self . has_ignore_shardlock_ != x . has_ignore_shardlock_ : return if self . has_ignore_shardlock_ and self . ignore_shardlock_ != x . ignore_shardlock_ : return if self . has_memcache_pool_hint_ != x . has_memcache_pool_hint_ : return if self . has_memcache_pool_hint_ and self . memcache_pool_hint_ != x . memcache_pool_hint_ : return if self . has_memcache_sharding_strategy_ != x . has_memcache_sharding_strategy_ : return if self . has_memcache_sharding_strategy_ and self . memcache_sharding_strategy_ != x . memcache_sharding_strategy_ : return return def IsInitialized ( self , debug_strs = None ) : initialized = if ( not self . has_app_id_ ) : initialized = if debug_strs is not None : debug_strs . append ( '' ) return initialized def ByteSize ( self ) : n = n += self . lengthString ( len ( self . app_id_ ) ) if ( self . has_num_memcacheg_backends_ ) : n += + self . lengthVarInt64 ( self . num_memcacheg_backends_ ) if ( self . has_ignore_shardlock_ ) : n += if ( self . has_memcache_pool_hint_ ) : n += + self . lengthString ( len ( self . memcache_pool_hint_ ) ) if ( self . has_memcache_sharding_strategy_ ) : n += + self . lengthString ( len ( self . memcache_sharding_strategy_ ) ) return n + def ByteSizePartial ( self ) : n = if ( self . has_app_id_ ) : n += n += self . lengthString ( len ( self . app_id_ ) ) if ( self . has_num_memcacheg_backends_ ) : n += + self . lengthVarInt64 ( self . num_memcacheg_backends_ ) if ( self . has_ignore_shardlock_ ) : n += if ( self . has_memcache_pool_hint_ ) : n += + self . lengthString ( len ( self . memcache_pool_hint_ ) ) if ( self . has_memcache_sharding_strategy_ ) : n += + self . lengthString ( len ( self . memcache_sharding_strategy_ ) ) return n def Clear ( self ) : self . clear_app_id ( ) self . clear_num_memcacheg_backends ( ) self . clear_ignore_shardlock ( ) self . clear_memcache_pool_hint ( ) self . clear_memcache_sharding_strategy ( ) def OutputUnchecked ( self , out ) : out . putVarInt32 ( ) out . putPrefixedString ( self . app_id_ ) if ( self . has_num_memcacheg_backends_ ) : out . putVarInt32 ( ) out . putVarInt32 ( self . num_memcacheg_backends_ ) if ( self . has_ignore_shardlock_ ) : out . putVarInt32 ( ) out . putBoolean ( self . ignore_shardlock_ ) if ( self . has_memcache_pool_hint_ ) : out . putVarInt32 ( ) out . putPrefixedString ( self . memcache_pool_hint_ ) if ( self . has_memcache_sharding_strategy_ ) : out . putVarInt32 ( ) out . putPrefixedString ( self . memcache_sharding_strategy_ ) def OutputPartial ( self , out ) : if ( self . has_app_id_ ) : out . putVarInt32 ( ) out . putPrefixedString ( self . app_id_ ) if ( self . has_num_memcacheg_backends_ ) : out . putVarInt32 ( ) out . putVarInt32 ( self . num_memcacheg_backends_ ) if ( self . has_ignore_shardlock_ ) : out . putVarInt32 ( ) out . putBoolean ( self . ignore_shardlock_ ) if ( self . has_memcache_pool_hint_ ) : out . putVarInt32 ( ) out . putPrefixedString ( self . memcache_pool_hint_ ) if ( self . has_memcache_sharding_strategy_ ) : out . putVarInt32 ( ) out . putPrefixedString ( self . memcache_sharding_strategy_ ) def TryMerge ( self , d ) : while d . avail ( ) > : tt = d . getVarInt32 ( ) if tt == : self . set_app_id ( d . getPrefixedString ( ) ) continue if tt == : self . set_num_memcacheg_backends ( d . getVarInt32 ( ) ) continue if tt == : self . set_ignore_shardlock ( d . getBoolean ( ) ) continue if tt == : self . set_memcache_pool_hint ( d . getPrefixedString ( ) ) continue if tt == : self . set_memcache_sharding_strategy ( d . getPrefixedString ( ) ) continue if ( tt == ) : raise ProtocolBuffer . ProtocolBufferDecodeError d . skipData ( tt ) def __str__ ( self , prefix = \"\" , printElemNumber = ) : res = \"\" if self . has_app_id_ : res += prefix + ( \"\" % self . DebugFormatString ( self . app_id_ ) ) if self . has_num_memcacheg_backends_ : res += prefix + ( \"\" % self . DebugFormatInt32 ( self . num_memcacheg_backends_ ) ) if self . has_ignore_shardlock_ : res += prefix + ( \"\" % self . DebugFormatBool ( self . ignore_shardlock_ ) ) if self . has_memcache_pool_hint_ : res += prefix + ( \"\" % self . DebugFormatString ( self . memcache_pool_hint_ ) ) if self . has_memcache_sharding_strategy_ : res += prefix + ( \"\" % self . DebugFormatString ( self . memcache_sharding_strategy_ ) ) return res def _BuildTagLookupTable ( sparse , maxtag , default = None ) : return tuple ( [ sparse . get ( i , default ) for i in xrange ( , + maxtag ) ] ) kapp_id = knum_memcacheg_backends = kignore_shardlock = kmemcache_pool_hint = kmemcache_sharding_strategy = _TEXT = _BuildTagLookupTable ( { : \"\" , : \"\" , : \"\" , : \"\" , : \"\" , : \"\" , } , ) _TYPES = _BuildTagLookupTable ( { : ProtocolBuffer . Encoder . NUMERIC , : ProtocolBuffer . Encoder . STRING , : ProtocolBuffer . Encoder . NUMERIC , : ProtocolBuffer . Encoder . NUMERIC , : ProtocolBuffer . Encoder . STRING , : ProtocolBuffer . Encoder . STRING , } , , ProtocolBuffer . Encoder . MAX_TYPE ) _STYLE = \"\"\"\"\"\" _STYLE_CONTENT_TYPE = \"\"\"\"\"\" _PROTO_DESCRIPTOR_NAME = '' class MemcacheGetRequest ( ProtocolBuffer . ProtocolMessage ) : has_name_space_ = name_space_ = \"\" has_for_cas_ = for_cas_ = has_override_ = override_ = None def __init__ ( self , contents = None ) : self . key_ = [ ] self . lazy_init_lock_ = thread . allocate_lock ( ) if contents is not None : self . MergeFromString ( contents ) def key_size ( self ) : return len ( self . key_ ) def key_list ( self ) : return self . key_ def key ( self , i ) : return self . key_ [ i ] def set_key ( self , i , x ) : self . key_ [ i ] = x def add_key ( self , x ) : self . key_ . append ( x ) def clear_key ( self ) : self . key_ = [ ] def name_space ( self ) : return self . name_space_ def set_name_space ( self , x ) : self . has_name_space_ = self . name_space_ = x def clear_name_space ( self ) : if self . has_name_space_ : self . has_name_space_ = self . name_space_ = \"\" def has_name_space ( self ) : return self . has_name_space_ def for_cas ( self ) : return self . for_cas_ def set_for_cas ( self , x ) : self . has_for_cas_ = self . for_cas_ = x def clear_for_cas ( self ) : if self . has_for_cas_ : self . has_for_cas_ = self . for_cas_ = def has_for_cas ( self ) : return self . has_for_cas_ def override ( self ) : if self . override_ is None : self . lazy_init_lock_ . acquire ( ) try : if self . override_ is None : self . override_ = AppOverride ( ) finally : self . lazy_init_lock_ . release ( ) return self . override_ def mutable_override ( self ) : self . has_override_ = ; return self . override ( ) def clear_override ( self ) : if self . has_override_ : self . has_override_ = ; if self . override_ is not None : self . override_ . Clear ( ) def has_override ( self ) : return self . has_override_ def MergeFrom ( self , x ) : assert x is not self for i in xrange ( x . key_size ( ) ) : self . add_key ( x . key ( i ) ) if ( x . has_name_space ( ) ) : self . set_name_space ( x . name_space ( ) ) if ( x . has_for_cas ( ) ) : self . set_for_cas ( x . for_cas ( ) ) if ( x . has_override ( ) ) : self . mutable_override ( ) . MergeFrom ( x . override ( ) ) def Equals ( self , x ) : if x is self : return if len ( self . key_ ) != len ( x . key_ ) : return for e1 , e2 in zip ( self . key_ , x . key_ ) : if e1 != e2 : return if self . has_name_space_ != x . has_name_space_ : return if self . has_name_space_ and self . name_space_ != x . name_space_ : return if self . has_for_cas_ != x . has_for_cas_ : return if self . has_for_cas_ and self . for_cas_ != x . for_cas_ : return if self . has_override_ != x . has_override_ : return if self . has_override_ and self . override_ != x . override_ : return return def IsInitialized ( self , debug_strs = None ) : initialized = if ( self . has_override_ and not self . override_ . IsInitialized ( debug_strs ) ) : initialized = return initialized def ByteSize ( self ) : n = n += * len ( self . key_ ) for i in xrange ( len ( self . key_ ) ) : n += self . lengthString ( len ( self . key_ [ i ] ) ) if ( self . has_name_space_ ) : n += + self . lengthString ( len ( self . name_space_ ) ) if ( self . has_for_cas_ ) : n += if ( self . has_override_ ) : n += + self . lengthString ( self . override_ . ByteSize ( ) ) return n def ByteSizePartial ( self ) : n = n += * len ( self . key_ ) for i in xrange ( len ( self . key_ ) ) : n += self . lengthString ( len ( self . key_ [ i ] ) ) if ( self . has_name_space_ ) : n += + self . lengthString ( len ( self . name_space_ ) ) if ( self . has_for_cas_ ) : n += if ( self . has_override_ ) : n += + self . lengthString ( self . override_ . ByteSizePartial ( ) ) return n def Clear ( self ) : self . clear_key ( ) self . clear_name_space ( ) self . clear_for_cas ( ) self . clear_override ( ) def OutputUnchecked ( self , out ) : for i in xrange ( len ( self . key_ ) ) : out . putVarInt32 ( ) out . putPrefixedString ( self . key_ [ i ] ) if ( self . has_name_space_ ) : out . putVarInt32 ( ) out . putPrefixedString ( self . name_space_ ) if ( self . has_for_cas_ ) : out . putVarInt32 ( ) out . putBoolean ( self . for_cas_ ) if ( self . has_override_ ) : out . putVarInt32 ( ) out . putVarInt32 ( self . override_ . ByteSize ( ) ) self . override_ . OutputUnchecked ( out ) def OutputPartial ( self , out ) : for i in xrange ( len ( self . key_ ) ) : out . putVarInt32 ( ) out . putPrefixedString ( self . key_ [ i ] ) if ( self . has_name_space_ ) : out . putVarInt32 ( ) out . putPrefixedString ( self . name_space_ ) if ( self . has_for_cas_ ) : out . putVarInt32 ( ) out . putBoolean ( self . for_cas_ ) if ( self . has_override_ ) : out . putVarInt32 ( ) out . putVarInt32 ( self . override_ . ByteSizePartial ( ) ) self . override_ . OutputPartial ( out ) def TryMerge ( self , d ) : while d . avail ( ) > : tt = d . getVarInt32 ( ) if tt == : self . add_key ( d . getPrefixedString ( ) ) continue if tt == : self . set_name_space ( d . getPrefixedString ( ) ) continue if tt == : self . set_for_cas ( d . getBoolean ( ) ) continue if tt == : length = d . getVarInt32 ( ) tmp = ProtocolBuffer . Decoder ( d . buffer ( ) , d . pos ( ) , d . pos ( ) + length ) d . skip ( length ) self . mutable_override ( ) . TryMerge ( tmp ) continue if ( tt == ) : raise ProtocolBuffer . ProtocolBufferDecodeError d . skipData ( tt ) def __str__ ( self , prefix = \"\" , printElemNumber = ) : res = \"\" cnt = for e in self . key_ : elm = \"\" if printElemNumber : elm = \"\" % cnt res += prefix + ( \"\" % ( elm , self . DebugFormatString ( e ) ) ) cnt += if self . has_name_space_ : res += prefix + ( \"\" % self . DebugFormatString ( self . name_space_ ) ) if self . has_for_cas_ : res += prefix + ( \"\" % self . DebugFormatBool ( self . for_cas_ ) ) if self . has_override_ : res += prefix + \"\" res += self . override_ . __str__ ( prefix + \"\" , printElemNumber ) res += prefix + \"\" return res def _BuildTagLookupTable ( sparse , maxtag , default = None ) : return tuple ( [ sparse . get ( i , default ) for i in xrange ( , + maxtag ) ] ) kkey = kname_space = kfor_cas = koverride = _TEXT = _BuildTagLookupTable ( { : \"\" , : \"\" , : \"\" , : \"\" , : \"\" , } , ) _TYPES = _BuildTagLookupTable ( { : ProtocolBuffer . Encoder . NUMERIC , : ProtocolBuffer . Encoder . STRING , : ProtocolBuffer . Encoder . STRING , : ProtocolBuffer . Encoder . NUMERIC , : ProtocolBuffer . Encoder . STRING , } , , ProtocolBuffer . Encoder . MAX_TYPE ) _STYLE = \"\"\"\"\"\" _STYLE_CONTENT_TYPE = \"\"\"\"\"\" _PROTO_DESCRIPTOR_NAME = '' class MemcacheGetResponse_Item ( ProtocolBuffer . ProtocolMessage ) : has_key_ = key_ = \"\" has_value_ = value_ = \"\" has_flags_ = flags_ = has_cas_id_ = cas_id_ = has_expires_in_seconds_ = expires_in_seconds_ = def __init__ ( self , contents = None ) : if contents is not None : self . MergeFromString ( contents ) def key ( self ) : return self . key_ def set_key ( self , x ) : self . has_key_ = self . key_ = x def clear_key ( self ) : if self . has_key_ : self . has_key_ = self . key_ = \"\" def has_key ( self ) : return self . has_key_ def value ( self ) : return self . value_ def set_value ( self , x ) : self . has_value_ = self . value_ = x def clear_value ( self ) : if self . has_value_ : self . has_value_ = self . value_ = \"\" def has_value ( self ) : return self . has_value_ def flags ( self ) : return self . flags_ def set_flags ( self , x ) : self . has_flags_ = self . flags_ = x def clear_flags ( self ) : if self . has_flags_ : self . has_flags_ = self . flags_ = def has_flags ( self ) : return self . has_flags_ def cas_id ( self ) : return self . cas_id_ def set_cas_id ( self , x ) : self . has_cas_id_ = self . cas_id_ = x def clear_cas_id ( self ) : if self . has_cas_id_ : self . has_cas_id_ = self . cas_id_ = def has_cas_id ( self ) : return self . has_cas_id_ def expires_in_seconds ( self ) : return self . expires_in_seconds_ def set_expires_in_seconds ( self , x ) : self . has_expires_in_seconds_ = self . expires_in_seconds_ = x def clear_expires_in_seconds ( self ) : if self . has_expires_in_seconds_ : self . has_expires_in_seconds_ = self . expires_in_seconds_ = def has_expires_in_seconds ( self ) : return self . has_expires_in_seconds_ def MergeFrom ( self , x ) : assert x is not self if ( x . has_key ( ) ) : self . set_key ( x . key ( ) ) if ( x . has_value ( ) ) : self . set_value ( x . value ( ) ) if ( x . has_flags ( ) ) : self . set_flags ( x . flags ( ) ) if ( x . has_cas_id ( ) ) : self . set_cas_id ( x . cas_id ( ) ) if ( x . has_expires_in_seconds ( ) ) : self . set_expires_in_seconds ( x . expires_in_seconds ( ) ) def Equals ( self , x ) : if x is self : return if self . has_key_ != x . has_key_ : return if self . has_key_ and self . key_ != x . key_ : return if self . has_value_ != x . has_value_ : return if self . has_value_ and self . value_ != x . value_ : return if self . has_flags_ != x . has_flags_ : return if self . has_flags_ and self . flags_ != x . flags_ : return if self . has_cas_id_ != x . has_cas_id_ : return if self . has_cas_id_ and self . cas_id_ != x . cas_id_ : return if self . has_expires_in_seconds_ != x . has_expires_in_seconds_ : return if self . has_expires_in_seconds_ and self . expires_in_seconds_ != x . expires_in_seconds_ : return return def IsInitialized ( self , debug_strs = None ) : initialized = if ( not self . has_key_ ) : initialized = if debug_strs is not None : debug_strs . append ( '' ) if ( not self . has_value_ ) : initialized = if debug_strs is not None : debug_strs . append ( '' ) return initialized def ByteSize ( self ) : n = n += self . lengthString ( len ( self . key_ ) ) n += self . lengthString ( len ( self . value_ ) ) if ( self . has_flags_ ) : n += if ( self . has_cas_id_ ) : n += if ( self . has_expires_in_seconds_ ) : n += + self . lengthVarInt64 ( self . expires_in_seconds_ ) return n + def ByteSizePartial ( self ) : n = if ( self . has_key_ ) : n += n += self . lengthString ( len ( self . key_ ) ) if ( self . has_value_ ) : n += n += self . lengthString ( len ( self . value_ ) ) if ( self . has_flags_ ) : n += if ( self . has_cas_id_ ) : n += if ( self . has_expires_in_seconds_ ) : n += + self . lengthVarInt64 ( self . expires_in_seconds_ ) return n def Clear ( self ) : self . clear_key ( ) self . clear_value ( ) self . clear_flags ( ) self . clear_cas_id ( ) self . clear_expires_in_seconds ( ) def OutputUnchecked ( self , out ) : out . putVarInt32 ( ) out . putPrefixedString ( self . key_ ) out . putVarInt32 ( ) out . putPrefixedString ( self . value_ ) if ( self . has_flags_ ) : out . putVarInt32 ( ) out . put32 ( self . flags_ ) if ( self . has_cas_id_ ) : out . putVarInt32 ( ) out . put64 ( self . cas_id_ ) if ( self . has_expires_in_seconds_ ) : out . putVarInt32 ( ) out . putVarInt32 ( self . expires_in_seconds_ ) def OutputPartial ( self , out ) : if ( self . has_key_ ) : out . putVarInt32 ( ) out . putPrefixedString ( self . key_ ) if ( self . has_value_ ) : out . putVarInt32 ( ) out . putPrefixedString ( self . value_ ) if ( self . has_flags_ ) : out . putVarInt32 ( ) out . put32 ( self . flags_ ) if ( self . has_cas_id_ ) : out . putVarInt32 ( ) out . put64 ( self . cas_id_ ) if ( self . has_expires_in_seconds_ ) : out . putVarInt32 ( ) out . putVarInt32 ( self . expires_in_seconds_ ) def TryMerge ( self , d ) : while : tt = d . getVarInt32 ( ) if tt == : break if tt == : self . set_key ( d . getPrefixedString ( ) ) continue if tt == : self . set_value ( d . getPrefixedString ( ) ) continue if tt == : self . set_flags ( d . get32 ( ) ) continue if tt == : self . set_cas_id ( d . get64 ( ) ) continue if tt == : self . set_expires_in_seconds ( d . getVarInt32 ( ) ) continue if ( tt == ) : raise ProtocolBuffer . ProtocolBufferDecodeError d . skipData ( tt ) def __str__ ( self , prefix = \"\" , printElemNumber = ) : res = \"\" if self . has_key_ : res += prefix + ( \"\" % self . DebugFormatString ( self . key_ ) ) if self . has_value_ : res += prefix + ( \"\" % self . DebugFormatString ( self . value_ ) ) if self . has_flags_ : res += prefix + ( \"\" % self . DebugFormatFixed32 ( self . flags_ ) ) if self . has_cas_id_ : res += prefix + ( \"\" % self . DebugFormatFixed64 ( self . cas_id_ ) ) if self . has_expires_in_seconds_ : res += prefix + ( \"\" % self . DebugFormatInt32 ( self . expires_in_seconds_ ) ) return res class MemcacheGetResponse ( ProtocolBuffer . ProtocolMessage ) : def __init__ ( self , contents = None ) : self . item_ = [ ] if contents is not None : self . MergeFromString ( contents ) def item_size ( self ) : return len ( self . item_ ) def item_list ( self ) : return self . item_ def item ( self , i ) : return self . item_ [ i ] def mutable_item ( self , i ) : return self . item_ [ i ] def add_item ( self ) : x = MemcacheGetResponse_Item ( ) self . item_ . append ( x ) return x def clear_item ( self ) : self . item_ = [ ] def MergeFrom ( self , x ) : assert x is not self for i in xrange ( x . item_size ( ) ) : self . add_item ( ) . CopyFrom ( x . item ( i ) ) def Equals ( self , x ) : if x is self : return if len ( self . item_ ) != len ( x . item_ ) : return for e1 , e2 in zip ( self . item_ , x . item_ ) : if e1 != e2 : return return def IsInitialized ( self , debug_strs = None ) : initialized = for p in self . item_ : if not p . IsInitialized ( debug_strs ) : initialized = return initialized def ByteSize ( self ) : n = n += * len ( self . item_ ) for i in xrange ( len ( self . item_ ) ) : n += self . item_ [ i ] . ByteSize ( ) return n def ByteSizePartial ( self ) : n = n += * len ( self . item_ ) for i in xrange ( len ( self . item_ ) ) : n += self . item_ [ i ] . ByteSizePartial ( ) return n def Clear ( self ) : self . clear_item ( ) def OutputUnchecked ( self , out ) : for i in xrange ( len ( self . item_ ) ) : out . putVarInt32 ( ) self . item_ [ i ] . OutputUnchecked ( out ) out . putVarInt32 ( ) def OutputPartial ( self , out ) : for i in xrange ( len ( self . item_ ) ) : out . putVarInt32 ( ) self . item_ [ i ] . OutputPartial ( out ) out . putVarInt32 ( ) def TryMerge ( self , d ) : while d . avail ( ) > : tt = d . getVarInt32 ( ) if tt == : self . add_item ( ) . TryMerge ( d ) continue if ( tt == ) : raise ProtocolBuffer . ProtocolBufferDecodeError d . skipData ( tt ) def __str__ ( self , prefix = \"\" , printElemNumber = ) : res = \"\" cnt = for e in self . item_ : elm = \"\" if printElemNumber : elm = \"\" % cnt res += prefix + ( \"\" % elm ) res += e . __str__ ( prefix + \"\" , printElemNumber ) res += prefix + \"\" cnt += return res def _BuildTagLookupTable ( sparse , maxtag , default = None ) : return tuple ( [ sparse . get ( i , default ) for i in xrange ( , + maxtag ) ] ) kItemGroup = kItemkey = kItemvalue = kItemflags = kItemcas_id = kItemexpires_in_seconds = _TEXT = _BuildTagLookupTable ( { : \"\" , : \"\" , : \"\" , : \"\" , : \"\" , : \"\" , : \"\" , } , ) _TYPES = _BuildTagLookupTable ( { : ProtocolBuffer . Encoder . NUMERIC , : ProtocolBuffer . Encoder . STARTGROUP , : ProtocolBuffer . Encoder . STRING , : ProtocolBuffer . Encoder . STRING , : ProtocolBuffer . Encoder . FLOAT , : ProtocolBuffer . Encoder . DOUBLE , : ProtocolBuffer . Encoder . NUMERIC , } , , ProtocolBuffer . Encoder . MAX_TYPE ) _STYLE = \"\"\"\"\"\" _STYLE_CONTENT_TYPE = \"\"\"\"\"\" _PROTO_DESCRIPTOR_NAME = '' class MemcacheSetRequest_Item ( ProtocolBuffer . ProtocolMessage ) : has_key_ = key_ = \"\" has_value_ = value_ = \"\" has_flags_ = flags_ = has_set_policy_ = set_policy_ = has_expiration_time_ = expiration_time_ = has_cas_id_ = cas_id_ = has_for_cas_ = for_cas_ = def __init__ ( self , contents = None ) : if contents is not None : self . MergeFromString ( contents ) def key ( self ) : return self . key_ def set_key ( self , x ) : self . has_key_ = self . key_ = x def clear_key ( self ) : if self . has_key_ : self . has_key_ = self . key_ = \"\" def has_key ( self ) : return self . has_key_ def value ( self ) : return self . value_ def set_value ( self , x ) : self . has_value_ = self . value_ = x def clear_value ( self ) : if self . has_value_ : self . has_value_ = self . value_ = \"\" def has_value ( self ) : return self . has_value_ def flags ( self ) : return self . flags_ def set_flags ( self , x ) : self . has_flags_ = self . flags_ = x def clear_flags ( self ) : if self . has_flags_ : self . has_flags_ = self . flags_ = def has_flags ( self ) : return self . has_flags_ def set_policy ( self ) : return self . set_policy_ def set_set_policy ( self , x ) : self . has_set_policy_ = self . set_policy_ = x def clear_set_policy ( self ) : if self . has_set_policy_ : self . has_set_policy_ = self . set_policy_ = def has_set_policy ( self ) : return self . has_set_policy_ def expiration_time ( self ) : return self . expiration_time_ def set_expiration_time ( self , x ) : self . has_expiration_time_ = self . expiration_time_ = x def clear_expiration_time ( self ) : if self . has_expiration_time_ : self . has_expiration_time_ = self . expiration_time_ = def has_expiration_time ( self ) : return self . has_expiration_time_ def cas_id ( self ) : return self . cas_id_ def set_cas_id ( self , x ) : self . has_cas_id_ = self . cas_id_ = x def clear_cas_id ( self ) : if self . has_cas_id_ : self . has_cas_id_ = self . cas_id_ = def has_cas_id ( self ) : return self . has_cas_id_ def for_cas ( self ) : return self . for_cas_ def set_for_cas ( self , x ) : self . has_for_cas_ = self . for_cas_ = x def clear_for_cas ( self ) : if self . has_for_cas_ : self . has_for_cas_ = self . for_cas_ = def has_for_cas ( self ) : return self . has_for_cas_ def MergeFrom ( self , x ) : assert x is not self if ( x . has_key ( ) ) : self . set_key ( x . key ( ) ) if ( x . has_value ( ) ) : self . set_value ( x . value ( ) ) if ( x . has_flags ( ) ) : self . set_flags ( x . flags ( ) ) if ( x . has_set_policy ( ) ) : self . set_set_policy ( x . set_policy ( ) ) if ( x . has_expiration_time ( ) ) : self . set_expiration_time ( x . expiration_time ( ) ) if ( x . has_cas_id ( ) ) : self . set_cas_id ( x . cas_id ( ) ) if ( x . has_for_cas ( ) ) : self . set_for_cas ( x . for_cas ( ) ) def Equals ( self , x ) : if x is self : return if self . has_key_ != x . has_key_ : return if self . has_key_ and self . key_ != x . key_ : return if self . has_value_ != x . has_value_ : return if self . has_value_ and self . value_ != x . value_ : return if self . has_flags_ != x . has_flags_ : return if self . has_flags_ and self . flags_ != x . flags_ : return if self . has_set_policy_ != x . has_set_policy_ : return if self . has_set_policy_ and self . set_policy_ != x . set_policy_ : return if self . has_expiration_time_ != x . has_expiration_time_ : return if self . has_expiration_time_ and self . expiration_time_ != x . expiration_time_ : return if self . has_cas_id_ != x . has_cas_id_ : return if self . has_cas_id_ and self . cas_id_ != x . cas_id_ : return if self . has_for_cas_ != x . has_for_cas_ : return if self . has_for_cas_ and self . for_cas_ != x . for_cas_ : return return def IsInitialized ( self , debug_strs = None ) : initialized = if ( not self . has_key_ ) : initialized = if debug_strs is not None : debug_strs . append ( '' ) if ( not self . has_value_ ) : initialized = if debug_strs is not None : debug_strs . append ( '' ) return initialized def ByteSize ( self ) : n = n += self . lengthString ( len ( self . key_ ) ) n += self . lengthString ( len ( self . value_ ) ) if ( self . has_flags_ ) : n += if ( self . has_set_policy_ ) : n += + self . lengthVarInt64 ( self . set_policy_ ) if ( self . has_expiration_time_ ) : n += if ( self . has_cas_id_ ) : n += if ( self . has_for_cas_ ) : n += return n + def ByteSizePartial ( self ) : n = if ( self . has_key_ ) : n += n += self . lengthString ( len ( self . key_ ) ) if ( self . has_value_ ) : n += n += self . lengthString ( len ( self . value_ ) ) if ( self . has_flags_ ) : n += if ( self . has_set_policy_ ) : n += + self . lengthVarInt64 ( self . set_policy_ ) if ( self . has_expiration_time_ ) : n += if ( self . has_cas_id_ ) : n += if ( self . has_for_cas_ ) : n += return n def Clear ( self ) : self . clear_key ( ) self . clear_value ( ) self . clear_flags ( ) self . clear_set_policy ( ) self . clear_expiration_time ( ) self . clear_cas_id ( ) self . clear_for_cas ( ) def OutputUnchecked ( self , out ) : out . putVarInt32 ( ) out . putPrefixedString ( self . key_ ) out . putVarInt32 ( ) out . putPrefixedString ( self . value_ ) if ( self . has_flags_ ) : out . putVarInt32 ( ) out . put32 ( self . flags_ ) if ( self . has_set_policy_ ) : out . putVarInt32 ( ) out . putVarInt32 ( self . set_policy_ ) if ( self . has_expiration_time_ ) : out . putVarInt32 ( ) out . put32 ( self . expiration_time_ ) if ( self . has_cas_id_ ) : out . putVarInt32 ( ) out . put64 ( self . cas_id_ ) if ( self . has_for_cas_ ) : out . putVarInt32 ( ) out . putBoolean ( self . for_cas_ ) def OutputPartial ( self , out ) : if ( self . has_key_ ) : out . putVarInt32 ( ) out . putPrefixedString ( self . key_ ) if ( self . has_value_ ) : out . putVarInt32 ( ) out . putPrefixedString ( self . value_ ) if ( self . has_flags_ ) : out . putVarInt32 ( ) out . put32 ( self . flags_ ) if ( self . has_set_policy_ ) : out . putVarInt32 ( ) out . putVarInt32 ( self . set_policy_ ) if ( self . has_expiration_time_ ) : out . putVarInt32 ( ) out . put32 ( self . expiration_time_ ) if ( self . has_cas_id_ ) : out . putVarInt32 ( ) out . put64 ( self . cas_id_ ) if ( self . has_for_cas_ ) : out . putVarInt32 ( ) out . putBoolean ( self . for_cas_ ) def TryMerge ( self , d ) : while : tt = d . getVarInt32 ( ) if tt == : break if tt == : self . set_key ( d . getPrefixedString ( ) ) continue if tt == : self . set_value ( d . getPrefixedString ( ) ) continue if tt == : self . set_flags ( d . get32 ( ) ) continue if tt == : self . set_set_policy ( d . getVarInt32 ( ) ) continue if tt == : self . set_expiration_time ( d . get32 ( ) ) continue if tt == : self . set_cas_id ( d . get64 ( ) ) continue if tt == : self . set_for_cas ( d . getBoolean ( ) ) continue if ( tt == ) : raise ProtocolBuffer . ProtocolBufferDecodeError d . skipData ( tt ) def __str__ ( self , prefix = \"\" , printElemNumber = ) : res = \"\" if self . has_key_ : res += prefix + ( \"\" % self . DebugFormatString ( self . key_ ) ) if self . has_value_ : res += prefix + ( \"\" % self . DebugFormatString ( self . value_ ) ) if self . has_flags_ : res += prefix + ( \"\" % self . DebugFormatFixed32 ( self . flags_ ) ) if self . has_set_policy_ : res += prefix + ( \"\" % self . DebugFormatInt32 ( self . set_policy_ ) ) if self . has_expiration_time_ : res += prefix + ( \"\" % self . DebugFormatFixed32 ( self . expiration_time_ ) ) if self . has_cas_id_ : res += prefix + ( \"\" % self . DebugFormatFixed64 ( self . cas_id_ ) ) ", "answer": "if self . has_for_cas_ : res += prefix + ( \"\" % self . DebugFormatBool ( self . for_cas_ ) )"}, {"prompt": " from __future__ import unicode_literals from django . contrib . auth . models import AnonymousUser from django . db . models import Q from djblets . util . templatetags . djblets_utils import user_displayname from haystack import indexes from reviewboard . reviews . models import ReviewRequest from reviewboard . search . indexes import BaseSearchIndex class ReviewRequestIndex ( BaseSearchIndex , indexes . Indexable ) : \"\"\"\"\"\" model = ReviewRequest local_site_attr = '' review_request_id = indexes . IntegerField ( model_attr = '' ) summary = indexes . CharField ( model_attr = '' ) ", "answer": "description = indexes . CharField ( model_attr = '' )"}, {"prompt": " \"\"\"\"\"\" __authors__ = [ '' ] import json import mock from tornado import options from viewfinder . backend . base import constants , util from viewfinder . backend . base . exceptions import TooManyRetriesError from viewfinder . backend . base . testing import async_test from viewfinder . backend . db . guess import Guess from viewfinder . backend . db . short_url import ShortURL from viewfinder . backend . www import base from viewfinder . backend . www . short_url_base import ShortURLBaseHandler from viewfinder . backend . www . test import service_base_test class TestShortURLBaseHandler ( ShortURLBaseHandler , base . BaseHandler ) : \"\"\"\"\"\" _MAX_GUESSES = def _HandleGet ( self , short_url , arg1 , arg2 ) : self . write ( { '' : '' , '' : short_url . group_id , '' : short_url . random_key , '' : short_url . timestamp , '' : short_url . expires , '' : arg1 , '' : arg2 } ) self . finish ( ) def _HandlePost ( self , short_url , arg1 , arg2 ) : self . write ( { '' : '' , '' : short_url . group_id , '' : short_url . random_key , '' : short_url . timestamp , '' : short_url . expires , '' : arg1 , '' : arg2 } ) self . finish ( ) class ShortURLTestCase ( service_base_test . ServiceBaseTestCase ) : \"\"\"\"\"\" def setUp ( self ) : super ( ShortURLTestCase , self ) . setUp ( ) self . _app . add_handlers ( r'' , [ ( r'' , TestShortURLBaseHandler ) ] ) self . _short_url = self . _RunAsync ( ShortURL . Create , self . _client , group_id = '' , timestamp = util . _TEST_TIME , expires = util . _TEST_TIME + constants . SECONDS_PER_DAY , arg1 = , arg2 = '' ) self . _url = self . get_url ( '' % ( self . _short_url . group_id , self . _short_url . random_key ) ) def testShortURLGet ( self ) : \"\"\"\"\"\" response = self . _RunAsync ( self . http_client . fetch , self . _url , method = '' ) self . assertEqual ( response . code , ) self . assertEqual ( json . loads ( response . body ) , { '' : '' , '' : '' , '' : self . _short_url . random_key , '' : util . _TEST_TIME , '' : util . _TEST_TIME + constants . SECONDS_PER_DAY , '' : , '' : '' } ) def testShortURLPost ( self ) : \"\"\"\"\"\" response = self . _RunAsync ( self . http_client . fetch , self . _url , method = '' , headers = { '' : '' , '' : '' } , body = '' ) self . assertEqual ( response . code , ) self . assertEqual ( json . loads ( response . body ) , { '' : '' , '' : '' , '' : self . _short_url . random_key , '' : util . _TEST_TIME , '' : util . _TEST_TIME + constants . SECONDS_PER_DAY , '' : , '' : '' } ) @ mock . patch . object ( TestShortURLBaseHandler , '' , ) def testMaxGuesses ( self ) : \"\"\"\"\"\" url = self . get_url ( '' ) response = self . _RunAsync ( self . http_client . fetch , url , method = '' ) self . assertEqual ( response . code , ) response = self . _RunAsync ( self . http_client . fetch , url , method = '' ) self . assertEqual ( response . code , ) response = self . _RunAsync ( self . http_client . fetch , self . _url , method = '' ) self . assertEqual ( response . code , ) url = self . get_url ( '' ) response = self . _RunAsync ( self . http_client . fetch , url , method = '' ) self . assertEqual ( response . code , ) util . _TEST_TIME += constants . SECONDS_PER_DAY response = self . _RunAsync ( self . http_client . fetch , url , method = '' ) self . assertEqual ( response . code , ) def testExpire ( self ) : \"\"\"\"\"\" self . _RunAsync ( self . _short_url . Expire , self . _client ) response = self . _RunAsync ( self . http_client . fetch , self . _url , method = '' ) self . assertEqual ( response . code , ) def testShortURLErrors ( self ) : \"\"\"\"\"\" url = self . get_url ( '' ) response = self . _RunAsync ( self . http_client . fetch , url , method = '' ) self . assertEqual ( response . code , ) url = self . get_url ( '' ) response = self . _RunAsync ( self . http_client . fetch , url , method = '' ) self . assertEqual ( response . code , ) util . _TEST_TIME += constants . SECONDS_PER_DAY response = self . _RunAsync ( self . http_client . fetch , self . _url , method = '' ) ", "answer": "self . assertEqual ( response . code , )"}, {"prompt": " \"\"\"\"\"\" import ctypes from ctypes_support import standard_c_lib as _c open_osfhandle = _c . _open_osfhandle open_osfhandle . argtypes = [ ctypes . c_int , ctypes . c_int ] open_osfhandle . restype = ctypes . c_int get_osfhandle = _c . _get_osfhandle get_osfhandle . argtypes = [ ctypes . c_int ] get_osfhandle . restype = ctypes . c_int ", "answer": "setmode = _c . _setmode"}, {"prompt": " '''''' def foo ( ) : print ( \"\" ) __pluginInfo__ = { '' : '' , '' : '' , ", "answer": "'' : \"\" ,"}, {"prompt": " \"\"\"\"\"\" from pyjamas . media . Media import Media from pyjamas import DOM \"\"\"\"\"\" class Audio ( Media ) : def __init__ ( self , src = None , ** kwargs ) : self . setElement ( DOM . createElement ( \"\" ) ) if src : ", "answer": "self . setSrc ( src )"}, {"prompt": " \"\"\"\"\"\" from fabric . api import env from mock import patch from prestoadmin import coordinator from prestoadmin . util . exception import ConfigurationError from tests . base_test_case import BaseTestCase class TestCoordinator ( BaseTestCase ) : def test_build_all_defaults ( self ) : env . roledefs [ '' ] = '' env . roledefs [ '' ] = [ '' , '' ] actual_default = coordinator . Coordinator ( ) . build_all_defaults ( ) expected = { '' : { '' : '' , '' : '' , '' : '' , '' : '' } , '' : [ '' , '' , '' , '' , '' , '' , '' , '' , '' ] , '' : { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' } } self . assertEqual ( actual_default , expected ) def test_defaults_coord_is_worker ( self ) : env . roledefs [ '' ] = [ '' ] env . roledefs [ '' ] = [ '' , '' , '' ] actual_default = coordinator . Coordinator ( ) . build_all_defaults ( ) expected = { '' : { '' : '' , '' : '' , '' : '' , '' : '' } , '' : [ '' , '' , '' , '' , '' , '' , '' , '' , '' ] , '' : { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' } } self . assertEqual ( actual_default , expected ) def test_validate_valid ( self ) : conf = { '' : { } , '' : [ ] , '' : { '' : '' , '' : '' } } self . assertEqual ( conf , coordinator . Coordinator . validate ( conf ) ) def test_validate_default ( self ) : env . roledefs [ '' ] = '' env . roledefs [ '' ] = [ '' ] conf = coordinator . Coordinator ( ) . build_all_defaults ( ) self . assertEqual ( conf , coordinator . Coordinator . validate ( conf ) ) ", "answer": "def test_invalid_conf ( self ) :"}, {"prompt": " import unittest from marmot . features . target_token_feature_extractor import TargetTokenFeatureExtractor class AlignmentFeatureExtractorTests ( unittest . TestCase ) : def test_get_features ( self ) : obj = { '' : u'' , '' : , '' : [ u'' , u'' , u'' , u'' , u'' ] , '' : [ u'' , u'' , u'' , u'' , u'' ] , '' : [ '' , '' , '' , '' , '' ] , '' : [ '' , '' , '' , '' , '' ] , '' : [ [ ] , [ ] , [ ] , [ ] , [ ] ] } extractor = TargetTokenFeatureExtractor ( ) [ token , left , right ] = extractor . get_features ( obj ) self . assertEqual ( token , u'' ) self . assertEqual ( left , u'' ) self . assertEqual ( right , u'' ) def test_get_features_two_words ( self ) : obj = { '' : u'' , '' : , '' : [ u'' , u'' , u'' , u'' , u'' ] , '' : [ u'' , u'' , u'' , u'' , u'' ] , '' : [ '' , '' , '' , '' , '' ] , '' : [ '' , '' , '' , '' , '' ] , '' : [ [ ] , [ ] , [ ] , [ ] , [ ] ] } extractor = TargetTokenFeatureExtractor ( context_size = ) [ token , left , right ] = extractor . get_features ( obj ) self . assertEqual ( token , u'' ) self . assertEqual ( left , u'' ) self . assertEqual ( right , u'' ) def test_first_el ( self ) : obj = { '' : u'' , '' : , '' : [ u'' , u'' , u'' , u'' , u'' ] , '' : [ u'' , u'' , u'' , u'' , u'' ] , '' : [ '' , '' , '' , '' , '' ] , '' : [ '' , '' , '' , '' , '' ] , '' : [ [ ] , [ ] , [ ] , [ ] , [ ] ] } extractor = TargetTokenFeatureExtractor ( context_size = ) [ token , left , right ] = extractor . get_features ( obj ) self . assertEqual ( token , u'' ) ", "answer": "self . assertEqual ( left , u'' )"}, {"prompt": " \"\"\"\"\"\" __all__ = [ '' , '' , '' ] ", "answer": "__revision__ = \"\" "}, {"prompt": " import os DIRNAME = os . path . dirname ( __file__ ) DEBUG = True DATABASES = { ", "answer": "'' : {"}, {"prompt": " from __future__ import absolute_import from sys import version_info as v if any ( [ v < ( , ) , ( , ) < v < ( , ) ] ) : raise Exception ( \"\" \"\" % v [ : ] ) import os from os . path import abspath import sys from setuptools import setup , Extension , find_packages from setuptools . command . build_ext import build_ext __builtins__ . __NUMPY_SETUP__ = False class BuildExtNumpyInc ( build_ext ) : def build_extensions ( self ) : ", "answer": "from numpy . distutils . misc_util import get_numpy_include_dirs"}, {"prompt": " import djgunicorn from setuptools import setup , find_packages version = djgunicorn . __version__ with open ( '' ) as f : readme = f . read ( ) with open ( '' ) as f : history = f . read ( ) with open ( '' ) as f : install_requires = f . read ( ) . strip ( ) . splitlines ( ) setup ( name = '' , version = version , description = \"\"\"\"\"\" , long_description = readme + '' + history , author = '' , author_email = '' , url = '' , ", "answer": "packages = find_packages ( ) ,"}, {"prompt": " from south . utils import datetime_utils as datetime from south . db import db from south . v2 import SchemaMigration from django . db import models class Migration ( SchemaMigration ) : def forwards ( self , orm ) : db . delete_unique ( u'' , [ '' , '' ] ) db . add_column ( u'' , '' , self . gf ( '' ) ( max_length = , null = True ) , keep_default = False ) db . alter_column ( u'' , '' , self . gf ( '' ) ( null = True ) ) def backwards ( self , orm ) : db . delete_column ( u'' , '' ) db . alter_column ( u'' , '' , self . gf ( '' ) ( default = ) ) db . create_unique ( u'' , [ '' , '' ] ) models = { u'' : { '' : { '' : '' } , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : u\"\" , '' : '' , '' : '' } ) } , u'' : { '' : { '' : \"\" , '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : u\"\" } ) , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , u'' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : u\"\" } ) , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) } , u'' : { '' : { '' : \"\" , '' : \"\" , '' : '' , '' : \"\" } , '' : ( '' , [ ] , { '' : '' } ) , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : \"\" } ) , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , ", "answer": "'' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) ,"}, {"prompt": " from getpass import getpass try : get_input = raw_input except NameError : get_input = input def get_user_details ( argv ) : if len ( argv ) > : host = argv [ ] else : host = get_input ( \"\" ) if len ( argv ) > : username = argv [ ] else : username = get_input ( \"\" ) if len ( argv ) > : password = argv [ ] ", "answer": "else :"}, {"prompt": " import inspect from . import fields from . utils import fn_name_to_pretty_label class BaseActions ( object ) : \"\"\"\"\"\" @ classmethod def get_all_actions ( cls ) : methods = inspect . getmembers ( cls ) ", "answer": "return [ { '' : m [ ] ,"}, {"prompt": " from abc import ABCMeta , abstractmethod from urlparse import urlsplit import sys from splunklib . client import Service from splunklib . modularinput . event_writer import EventWriter from splunklib . modularinput . input_definition import InputDefinition from splunklib . modularinput . validation_definition import ValidationDefinition try : import xml . etree . cElementTree as ET except ImportError : import xml . etree . ElementTree as ET class Script ( object ) : \"\"\"\"\"\" __metaclass__ = ABCMeta def __init__ ( self ) : self . _input_definition = None self . _service = None def run ( self , args ) : \"\"\"\"\"\" return self . run_script ( args , EventWriter ( ) , sys . stdin ) def run_script ( self , args , event_writer , input_stream ) : \"\"\"\"\"\" try : if len ( args ) == : self . _input_definition = InputDefinition . parse ( input_stream ) self . stream_events ( self . _input_definition , event_writer ) event_writer . close ( ) return elif str ( args [ ] ) . lower ( ) == \"\" : scheme = self . get_scheme ( ) if scheme is None : event_writer . log ( EventWriter . FATAL , \"\" ) return else : event_writer . write_xml_document ( scheme . to_xml ( ) ) return elif args [ ] . lower ( ) == \"\" : ", "answer": "validation_definition = ValidationDefinition . parse ( input_stream )"}, {"prompt": " from __future__ import ( ", "answer": "absolute_import ,"}, {"prompt": " from __future__ import absolute_import , print_function , division import tokenize import string from numba import utils def parse_signature ( sig ) : '''''' def stripws ( s ) : return '' . join ( c for c in s if c not in string . whitespace ) def tokenizer ( src ) : def readline ( ) : yield src gen = readline ( ) return tokenize . generate_tokens ( lambda : next ( gen ) ) def parse ( src ) : tokgen = tokenizer ( src ) while True : tok = next ( tokgen ) ", "answer": "if tok [ ] == '' :"}, {"prompt": " import logging from django . utils . translation import ugettext_lazy as _ from horizon import exceptions from horizon import tabs from openstack_dashboard . api import network from openstack_dashboard . api import nova from openstack_dashboard . api import sahara as saharaclient LOG = logging . getLogger ( __name__ ) class GeneralTab ( tabs . Tab ) : name = _ ( \"\" ) slug = \"\" template_name = ( \"\" ) def get_context_data ( self , request ) : template_id = self . tab_group . kwargs [ '' ] try : template = saharaclient . nodegroup_template_get ( request , template_id ) ", "answer": "except Exception :"}, {"prompt": " from runtime import * ", "answer": "\"\"\"\"\"\""}, {"prompt": " from mock import Mock from pyquery import PyQuery from olympia import amo ", "answer": "from olympia . amo . tests import TestCase"}, {"prompt": " from datetime import time , date , datetime from unittest import TestCase from django import forms from django . conf import settings from django . utils . translation import activate , deactivate class LocalizedTimeTests ( TestCase ) : def setUp ( self ) : self . old_TIME_INPUT_FORMATS = settings . TIME_INPUT_FORMATS self . old_USE_L10N = settings . USE_L10N settings . TIME_INPUT_FORMATS = [ \"\" , \"\" ] settings . USE_L10N = True activate ( '' ) def tearDown ( self ) : settings . TIME_INPUT_FORMATS = self . old_TIME_INPUT_FORMATS settings . USE_L10N = self . old_USE_L10N deactivate ( ) def test_timeField ( self ) : \"\" f = forms . TimeField ( ) self . assertRaises ( forms . ValidationError , f . clean , '' ) result = f . clean ( '' ) self . assertEqual ( result , time ( , , ) ) text = f . widget . _format_value ( result ) self . assertEqual ( text , '' ) result = f . clean ( '' ) self . assertEqual ( result , time ( , , ) ) text = f . widget . _format_value ( result ) self . assertEqual ( text , \"\" ) def test_localized_timeField ( self ) : \"\" f = forms . TimeField ( localize = True ) self . assertRaises ( forms . ValidationError , f . clean , '' ) result = f . clean ( '' ) self . assertEqual ( result , time ( , , ) ) ", "answer": "text = f . widget . _format_value ( result )"}, {"prompt": " import re import functools import redis from multiprocessing . dummy import Pool as ThreadPool from redis . client import Lock from redis . sentinel import Sentinel from . commands import SHARD_METHODS from . _compat import basestring , iteritems from . hashring import HashRing from . helpers import format_servers from . pipeline import Pipeline from . sentinel import SentinelRedis _findhash = re . compile ( '' , re . I ) def list_or_args ( keys , args ) : try : iter ( keys ) if isinstance ( keys , basestring ) : keys = [ keys ] except TypeError : keys = [ keys ] if args : keys . extend ( args ) return keys class RedisShardAPI ( object ) : def __init__ ( self , servers , hash_method = '' , sentinel = None , strict_redis = False ) : self . nodes = [ ] ", "answer": "self . connections = { }"}, {"prompt": " \"\"\"\"\"\" import unittest import mock from perfkitbenchmarker import benchmark_spec from perfkitbenchmarker import context from perfkitbenchmarker import disk from perfkitbenchmarker import virtual_machine from perfkitbenchmarker . configs import benchmark_config_spec from perfkitbenchmarker . providers . aws import aws_disk from perfkitbenchmarker . providers . aws import aws_virtual_machine from perfkitbenchmarker . providers . azure import azure_disk from perfkitbenchmarker . providers . azure import flags as azure_flags from perfkitbenchmarker . providers . azure import azure_virtual_machine from perfkitbenchmarker . providers . gcp import gce_disk from tests import mock_flags _BENCHMARK_NAME = '' _BENCHMARK_UID = '' _COMPONENT = '' class _DiskMetadataTestCase ( unittest . TestCase ) : def setUp ( self ) : self . addCleanup ( context . SetThreadBenchmarkSpec , None ) config_spec = benchmark_config_spec . BenchmarkConfigSpec ( _BENCHMARK_NAME , flag_values = mock_flags . MockFlags ( ) , vm_groups = { } ) self . benchmark_spec = benchmark_spec . BenchmarkSpec ( config_spec , _BENCHMARK_NAME , _BENCHMARK_UID ) class GcpDiskMetadataTest ( _DiskMetadataTestCase ) : def testPDStandard ( self ) : disk_spec = disk . BaseDiskSpec ( _COMPONENT , disk_size = , disk_type = gce_disk . PD_STANDARD ) disk_obj = gce_disk . GceDisk ( disk_spec , '' , '' , '' ) self . assertEquals ( disk_obj . metadata , { disk . MEDIA : disk . HDD , disk . REPLICATION : disk . ZONE , disk . LEGACY_DISK_TYPE : disk . STANDARD } ) class AwsDiskMetadataTest ( _DiskMetadataTestCase ) : def doAwsDiskTest ( self , disk_type , machine_type , goal_media , goal_replication , goal_legacy_disk_type ) : disk_spec = aws_disk . AwsDiskSpec ( _COMPONENT , disk_size = , disk_type = disk_type ) vm_spec = virtual_machine . BaseVmSpec ( '' , zone = '' , machine_type = machine_type ) vm = aws_virtual_machine . DebianBasedAwsVirtualMachine ( vm_spec ) vm . CreateScratchDisk ( disk_spec ) self . assertEqual ( vm . scratch_disks [ ] . metadata , { disk . MEDIA : goal_media , disk . REPLICATION : goal_replication , disk . LEGACY_DISK_TYPE : goal_legacy_disk_type } ) def testLocalSSD ( self ) : self . doAwsDiskTest ( disk . LOCAL , '' , disk . SSD , disk . NONE , disk . LOCAL ) def testLocalHDD ( self ) : self . doAwsDiskTest ( disk . LOCAL , '' , disk . HDD , disk . NONE , disk . LOCAL ) class AzureDiskMetadataTest ( _DiskMetadataTestCase ) : def doAzureDiskTest ( self , storage_type , disk_type , machine_type , goal_media , goal_replication , goal_legacy_disk_type ) : with mock . patch ( azure_disk . __name__ + '' ) as disk_flags : disk_flags . azure_storage_type = storage_type disk_spec = disk . BaseDiskSpec ( _COMPONENT , disk_size = , ", "answer": "disk_type = disk_type )"}, {"prompt": " import json from api . view import ApiView from popong_models . statement import Statement class StatementApi ( ApiView ) : model = Statement kind_single = '' kind_list = '' def _search ( self ) : return super ( StatementApi , self ) . _search ( fieldname = '' ) def to_dict ( self , statement ) : ", "answer": "d = {"}, {"prompt": " from setuptools import setup import os def read ( filename ) : return open ( filename ) . read ( ) setup ( name = '' , version = '' , description = '' , long_description = read ( '' ) , url = '' , author = '' , ", "answer": "author_email = '' ,"}, {"prompt": " import distutils , os from setuptools import Command from setuptools . compat import basestring from distutils . util import convert_path from distutils import log from distutils . errors import * class rotate ( Command ) : \"\"\"\"\"\" description = \"\" user_options = [ ( '' , '' , \"\" ) , ( '' , '' , \"\" ) , ( '' , '' , \"\" ) , ] boolean_options = [ ] def initialize_options ( self ) : self . match = None self . dist_dir = None self . keep = None def finalize_options ( self ) : if self . match is None : raise DistutilsOptionError ( \"\" \"\" ) if self . keep is None : raise DistutilsOptionError ( \"\" ) try : self . keep = int ( self . keep ) except ValueError : raise DistutilsOptionError ( \"\" ) if isinstance ( self . match , basestring ) : self . match = [ convert_path ( p . strip ( ) ) for p in self . match . split ( '' ) ] self . set_undefined_options ( '' , ( '' , '' ) ) def run ( self ) : self . run_command ( \"\" ) ", "answer": "from glob import glob"}, {"prompt": " from __future__ import unicode_literals from djblets . util . decorators import augment_method_from from reviewboard . webapi . decorators import webapi_check_local_site from reviewboard . webapi . resources import resources from reviewboard . webapi . resources . base_watched_object import BaseWatchedObjectResource class WatchedReviewRequestResource ( BaseWatchedObjectResource ) : \"\"\"\"\"\" name = '' uri_name = '' profile_field = '' star_function = '' unstar_function = '' @ property def watched_resource ( self ) : \"\"\"\"\"\" return resources . review_request @ webapi_check_local_site @ augment_method_from ( BaseWatchedObjectResource ) def get ( self , * args , ** kwargs ) : \"\"\"\"\"\" pass @ webapi_check_local_site @ augment_method_from ( BaseWatchedObjectResource ) def get_list ( self , * args , ** kwargs ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " from __future__ import unicode_literals from datetime import date , time , datetime from decimal import Decimal import json class JSONEncoder ( json . JSONEncoder ) : def default ( self , obj ) : if isinstance ( obj , ( datetime , date , time ) ) : return obj . isoformat ( ) ", "answer": "if isinstance ( obj , Decimal ) :"}, {"prompt": " import basic_container class SwiftContainer ( basic_container . BasicContainer ) : def __init__ ( self ) : super ( self . __class__ , self ) . __init__ ( ) self . image = \"\" self . command = \"\" ", "answer": "self . file_extension = \"\" "}, {"prompt": " from . sub_resource import SubResource class VpnClientRootCertificate ( SubResource ) : \"\"\"\"\"\" ", "answer": "_attribute_map = {"}, {"prompt": " \"\"\"\"\"\" from uuid import uuid4 from pyrsistent import pmap , pvector , pset from eliot import Message from twisted . internet import reactor from twisted . python . filepath import FilePath from . . import ( NodeLocalState , P2PManifestationDeployer , ApplicationNodeDeployer , sequentially ) from ... common import loop_until from ... control . _model import ( Deployment , Application , DockerImage , Node , AttachedVolume , Link , Manifestation , Dataset , DeploymentState , NodeState , PersistentState , ) from . . _docker import DockerClient from . . testtools import wait_for_unit_state , if_docker_configured from ... testtools import ( random_name , DockerImageBuilder , assertContainsAll , flaky , AsyncTestCase , ) from ... volume . testtools import create_volume_service from ... route import make_memory_network from . . import run_state_change from ... control . testtools import InMemoryStatePersister class P2PNodeDeployer ( object ) : \"\"\"\"\"\" def __init__ ( self , hostname , volume_service , docker_client = None , network = None , node_uuid = None ) : self . manifestations_deployer = P2PManifestationDeployer ( hostname , volume_service , node_uuid = node_uuid ) self . applications_deployer = ApplicationNodeDeployer ( hostname , docker_client , network , node_uuid = node_uuid ) self . hostname = hostname self . node_uuid = node_uuid self . volume_service = self . manifestations_deployer . volume_service self . docker_client = self . applications_deployer . docker_client self . network = self . applications_deployer . network def discover_state ( self , cluster_state , persistent_state ) : d = self . manifestations_deployer . discover_state ( cluster_state , persistent_state = persistent_state ) def got_manifestations_state ( manifestations_local_state ) : manifestations_state = manifestations_local_state . node_state app_discovery = self . applications_deployer . discover_state ( DeploymentState ( nodes = { manifestations_state } ) , persistent_state = PersistentState ( ) , ) def got_app_local_state ( app_local_state ) : app_state = app_local_state . node_state new_app_local_state = NodeLocalState ( node_state = ( app_state . evolver ( ) . set ( \"\" , manifestations_state . manifestations ) . set ( \"\" , manifestations_state . paths ) . set ( \"\" , manifestations_state . devices ) . persistent ( ) ) ) return new_app_local_state app_discovery . addCallback ( got_app_local_state ) return app_discovery d . addCallback ( got_manifestations_state ) return d def calculate_changes ( self , configuration , cluster_state , local_state ) : \"\"\"\"\"\" return sequentially ( changes = [ self . applications_deployer . calculate_changes ( configuration , cluster_state , local_state ) , self . manifestations_deployer . calculate_changes ( configuration , cluster_state , local_state ) , ] ) def change_node_state ( deployer , desired_configuration ) : \"\"\"\"\"\" state_persister = InMemoryStatePersister ( ) def converge ( ) : d = deployer . discover_state ( DeploymentState ( nodes = { NodeState ( hostname = deployer . hostname , uuid = deployer . node_uuid , applications = [ ] , manifestations = { } , paths = { } , devices = { } ) , } ) , persistent_state = state_persister . get_state ( ) , ) def got_changes ( local_state ) : changes = local_state . shared_state_changes ( ) cluster_state = DeploymentState ( ) for change in changes : cluster_state = change . update_cluster_state ( cluster_state ) return deployer . calculate_changes ( desired_configuration , cluster_state , local_state ) d . addCallback ( got_changes ) d . addCallback ( lambda change : run_state_change ( change , deployer = deployer , state_persister = state_persister ) ) return d result = converge ( ) result . addCallback ( lambda _ : converge ( ) ) result . addCallback ( lambda _ : converge ( ) ) return result def find_unit ( units , unit_name ) : Message . new ( message_type = \"\" , units = list ( unit . name for unit in units ) , desired_unit = unit_name ) . write ( ) for unit in units : if unit . name == unit_name : return unit class DeployerTests ( AsyncTestCase ) : \"\"\"\"\"\" @ if_docker_configured def test_environment ( self ) : \"\"\"\"\"\" expected_variables = frozenset ( { '' : '' , '' : '' , } . items ( ) ) docker_dir = FilePath ( __file__ ) . sibling ( '' ) volume_service = create_volume_service ( self ) image = DockerImageBuilder ( test = self , source_dir = docker_dir ) d = image . build ( ) def image_built ( image_name ) : application_name = random_name ( self ) docker_client = DockerClient ( ) self . addCleanup ( docker_client . remove , application_name ) deployer = P2PNodeDeployer ( u\"\" , volume_service , docker_client , make_memory_network ( ) , node_uuid = uuid4 ( ) ) dataset = Dataset ( dataset_id = unicode ( uuid4 ( ) ) , metadata = pmap ( { \"\" : application_name } ) ) manifestation = Manifestation ( dataset = dataset , primary = True ) desired_state = Deployment ( nodes = frozenset ( [ Node ( uuid = deployer . node_uuid , applications = frozenset ( [ Application ( name = application_name , image = DockerImage . from_string ( image_name ) , environment = expected_variables , volume = AttachedVolume ( manifestation = manifestation , mountpoint = FilePath ( '' ) , ) , links = frozenset ( ) , ) ] ) , manifestations = { manifestation . dataset_id : manifestation } ) ] ) ) return change_node_state ( deployer , desired_state ) d . addCallback ( image_built ) d . addCallback ( lambda _ : volume_service . enumerate ( ) ) d . addCallback ( lambda volumes : list ( volumes ) [ ] . get_filesystem ( ) . get_path ( ) . child ( b'' ) ) def got_result_path ( result_path ) : d = loop_until ( reactor , result_path . exists ) d . addCallback ( lambda _ : result_path ) return d d . addCallback ( got_result_path ) def started ( result_path ) : contents = result_path . getContent ( ) assertContainsAll ( haystack = contents , test_case = self , needles = [ '' . format ( k , v ) for k , v in expected_variables ] ) d . addCallback ( started ) return d @ if_docker_configured def test_links ( self ) : \"\"\"\"\"\" expected_variables = frozenset ( { '' : '' , '' : '' , '' : '' , '' : '' , } . items ( ) ) volume_service = create_volume_service ( self ) docker_dir = FilePath ( __file__ ) . sibling ( '' ) image = DockerImageBuilder ( test = self , source_dir = docker_dir ) d = image . build ( ) def image_built ( image_name ) : application_name = random_name ( self ) docker_client = DockerClient ( ) self . addCleanup ( docker_client . remove , application_name ) deployer = P2PNodeDeployer ( u\"\" , volume_service , docker_client , make_memory_network ( ) , node_uuid = uuid4 ( ) ) link = Link ( alias = u\"\" , local_port = , remote_port = ) dataset = Dataset ( dataset_id = unicode ( uuid4 ( ) ) , metadata = pmap ( { \"\" : application_name } ) ) manifestation = Manifestation ( dataset = dataset , primary = True ) desired_state = Deployment ( nodes = frozenset ( [ Node ( uuid = deployer . node_uuid , applications = frozenset ( [ Application ( name = application_name , image = DockerImage . from_string ( image_name ) , links = frozenset ( [ link ] ) , volume = AttachedVolume ( manifestation = manifestation , mountpoint = FilePath ( '' ) , ) , ) ] ) , manifestations = { manifestation . dataset_id : manifestation } ) ] ) ) return change_node_state ( deployer , desired_state ) d . addCallback ( image_built ) d . addCallback ( lambda _ : volume_service . enumerate ( ) ) ", "answer": "d . addCallback ( lambda volumes :"}, {"prompt": " import re from importlib import import_module from django . contrib . contenttypes . models import ContentType from django . forms import CharField , ChoiceField , Textarea from django . forms . models import ModelForm from django . utils . translation import ugettext_lazy as _ from . models import StyledLink , STYLEDLINK_MODELS class StyledLinkForm ( ModelForm ) : \"\"\"\"\"\" class Meta : model = StyledLink fields = ( '' , '' , ", "answer": "'' ,"}, {"prompt": " '''''' import hashlib import hmac import struct from collections import namedtuple from datetime import datetime from itertools import izip import OpenSSL from Crypto . Cipher import AES from Crypto . Util import asn1 , Counter from oppy . cell . cell import Cell from oppy . cell . definitions import RECOGNIZED , EMPTY_DIGEST from oppy . cell . fixedlen import EncryptedCell class UnrecognizedCell ( Exception ) : pass RelayCrypto = namedtuple ( \"\" , ( \"\" , \"\" , \"\" , \"\" ) ) def constantStrEqual ( str1 , str2 ) : '''''' try : from hmac import compare_digest return compare_digest ( str1 , str2 ) except ImportError : pass if len ( str1 ) != len ( str2 ) : res = comp1 = bytearray ( str2 ) comp2 = bytearray ( str2 ) else : res = comp1 = bytearray ( str1 ) comp2 = bytearray ( str2 ) for a , b in izip ( comp1 , comp2 ) : res |= a ^ b return res == def constantStrAllZero ( s ) : '''''' return constantStrEqual ( s , '' * len ( s ) ) def makeAES128CTRCipher ( key , initial_value = ) : '''''' ctr = Counter . new ( , initial_value = initial_value ) return AES . new ( key , AES . MODE_CTR , counter = ctr ) def makeHMACSHA256 ( msg , key ) : '''''' t = hmac . new ( msg = msg , key = key , digestmod = hashlib . sha256 ) return t . digest ( ) def _makePayloadWithDigest ( payload , digest = EMPTY_DIGEST ) : '''''' assert len ( payload ) >= and len ( digest ) == DIGEST_START = DIGEST_END = return payload [ : DIGEST_START ] + digest + payload [ DIGEST_END : ] def encryptCell ( cell , crypt_path , early = False ) : '''''' assert cell . rheader . digest == EMPTY_DIGEST crypt_path [ - ] . forward_digest . update ( cell . getPayload ( ) ) cell . rheader . digest = crypt_path [ - ] . forward_digest . digest ( ) [ : ] payload = cell . getPayload ( ) for node in reversed ( crypt_path ) : payload = node . forward_cipher . encrypt ( payload ) return EncryptedCell . make ( cell . header . circ_id , payload , early = early ) def _cellRecognized ( payload , relay_crypto ) : '''''' if len ( payload ) < or payload [ : ] != RECOGNIZED : return False digest = payload [ : ] test_payload = _makePayloadWithDigest ( payload ) test_digest = relay_crypto . backward_digest . copy ( ) test_digest . update ( test_payload ) return test_digest . digest ( ) [ : ] == digest def decryptCell ( cell , crypt_path ) : '''''' origin = recognized = False ", "answer": "payload = cell . getPayload ( )"}, {"prompt": " from setuptools import setup import stallion import sys install_requirements = [ '' , '' , '' , '' , '' , '' , ] try : import json except ImportError : install_requirements . append ( '' ) def long_description ( ) : if sys . version_info >= ( , , ) : f = open ( \"\" , mode = \"\" , encoding = \"\" ) else : f = open ( \"\" , mode = \"\" ) return f . read ( ) setup ( name = '' , version = stallion . __version__ , url = '' , license = '' , author = stallion . __author__ , ", "answer": "author_email = '' ,"}, {"prompt": " laboratory_assigned_experiments = { '' : { '' : '' , '' : ( ) } , '' : { '' : '' , '' : ( ) } , '' : { '' : '' , '' : ( ) } , '' : { '' : '' , '' : ( ) , } , '' : { '' : '' , '' : ( ) , } , '' : { '' : '' , '' : ( ) , } , '' : { '' : '' , '' : ( ) , } , '' : { '' : '' , '' : ( ) } , '' : { '' : '' , '' : ( ) } , '' : { '' : '' , '' : ( ) } , '' : { '' : '' , '' : ( ) } , '' : { '' : '' , '' : ( ) } , '' : { '' : '' , '' : ( ) } , '' : { '' : '' , '' : ( ) } , '' : { '' : '' , '' : ( ) } , '' : { '' : '' , '' : ( ) } , '' : { '' : '' , '' : ( ) } , '' : { '' : '' , '' : ( ) } , '' : { '' : '' , '' : ( ) } , '' : { '' : '' , '' : ( ) } , '' : { '' : '' , '' : ( ) } , '' : { '' : '' , '' : ( ) } , '' : { '' : '' , '' : ( ) } , '' : { '' : '' , '' : ( ) } , '' : { '' : '' , '' : ( ) } , '' : { '' : '' , '' : ( ) } , '' : { '' : '' , '' : ( ) } , '' : { '' : '' , '' : ( ) } , '' : { '' : '' , '' : ( ) } , '' : { '' : '' , '' : ( ) } , '' : { '' : '' , '' : ( ) } , '' : { '' : '' , '' : ( ) } , '' : { '' : '' , '' : ( ) } , '' : { '' : '' , '' : ( ) } , '' : { '' : '' , '' : ( ) } , '' : { '' : '' , '' : ( ) } , '' : { '' : '' , '' : ( ) } , '' : { '' : '' , '' : ( ) } , '' : { '' : '' , '' : ( ) } , '' : { '' : '' , '' : ( ) } , '' : { '' : '' , '' : ( ) } , '' : { '' : '' , '' : ( ) } , '' : { '' : '' , '' : ( ) } , '' : { '' : '' , '' : ( ) } , '' : { '' : '' , '' : ( ) } , '' : { '' : '' , '' : ( ) } , '' : { '' : '' , '' : ( ) } , '' : { '' : '' , '' : ( ) } , '' : { ", "answer": "'' : '' ,"}, {"prompt": " from __future__ import with_statement import sys import re DEBUG = True class Annotation ( object ) : def __init__ ( self , id_ , type_ ) : self . id_ = id_ self . type_ = type_ def map_ids ( self , idmap ) : self . id_ = idmap [ self . id_ ] class Textbound ( Annotation ) : def __init__ ( self , id_ , type_ , offsets , text ) : Annotation . __init__ ( self , id_ , type_ ) self . offsets = offsets self . text = text def map_ids ( self , idmap ) : Annotation . map_ids ( self , idmap ) def __str__ ( self ) : return \"\" % ( self . id_ , self . type_ , '' . join ( self . offsets ) , self . text ) class ArgAnnotation ( Annotation ) : def __init__ ( self , id_ , type_ , args ) : Annotation . __init__ ( self , id_ , type_ ) self . args = args ", "answer": "def map_ids ( self , idmap ) :"}, {"prompt": " import abc import logging import operator import os import subprocess import tempfile import warnings from luigi import six import luigi import luigi . contrib . hadoop from luigi . target import FileAlreadyExists , FileSystemTarget from luigi . task import flatten if six . PY3 : unicode = str logger = logging . getLogger ( '' ) class HiveCommandError ( RuntimeError ) : def __init__ ( self , message , out = None , err = None ) : super ( HiveCommandError , self ) . __init__ ( message , out , err ) self . message = message self . out = out self . err = err def load_hive_cmd ( ) : return luigi . configuration . get_config ( ) . get ( '' , '' , '' ) . split ( '' ) def get_hive_syntax ( ) : return luigi . configuration . get_config ( ) . get ( '' , '' , '' ) def run_hive ( args , check_return_code = True ) : \"\"\"\"\"\" cmd = load_hive_cmd ( ) + args p = subprocess . Popen ( cmd , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) stdout , stderr = p . communicate ( ) if check_return_code and p . returncode != : raise HiveCommandError ( \"\" . format ( \"\" . join ( cmd ) , p . returncode ) , stdout , stderr ) return stdout def run_hive_cmd ( hivecmd , check_return_code = True ) : \"\"\"\"\"\" return run_hive ( [ '' , hivecmd ] , check_return_code ) def run_hive_script ( script ) : \"\"\"\"\"\" if not os . path . isfile ( script ) : raise RuntimeError ( \"\" . format ( script ) ) return run_hive ( [ '' , script ] ) @ six . add_metaclass ( abc . ABCMeta ) class HiveClient ( object ) : @ abc . abstractmethod def table_location ( self , table , database = '' , partition = None ) : \"\"\"\"\"\" pass @ abc . abstractmethod def table_schema ( self , table , database = '' ) : \"\"\"\"\"\" pass @ abc . abstractmethod def table_exists ( self , table , database = '' , partition = None ) : \"\"\"\"\"\" pass @ abc . abstractmethod def partition_spec ( self , partition ) : \"\"\"\"\"\" pass class HiveCommandClient ( HiveClient ) : \"\"\"\"\"\" def table_location ( self , table , database = '' , partition = None ) : cmd = \"\" . format ( database , table ) if partition is not None : cmd += \"\" . format ( self . partition_spec ( partition ) ) stdout = run_hive_cmd ( cmd ) for line in stdout . split ( \"\" ) : if \"\" in line : return line . split ( \"\" ) [ ] def table_exists ( self , table , database = '' , partition = None ) : if partition is None : stdout = run_hive_cmd ( '' . format ( database , table ) ) return stdout and table . lower ( ) in stdout else : stdout = run_hive_cmd ( \"\"\"\"\"\" % ( database , table , self . partition_spec ( partition ) ) ) if stdout : return True else : return False def table_schema ( self , table , database = '' ) : describe = run_hive_cmd ( \"\" . format ( database , table ) ) if not describe or \"\" in describe : return None return [ tuple ( [ x . strip ( ) for x in line . strip ( ) . split ( \"\" ) ] ) for line in describe . strip ( ) . split ( \"\" ) ] def partition_spec ( self , partition ) : \"\"\"\"\"\" return '' . join ( [ \"\" . format ( k , v ) for ( k , v ) in sorted ( six . iteritems ( partition ) , key = operator . itemgetter ( ) ) ] ) class ApacheHiveCommandClient ( HiveCommandClient ) : \"\"\"\"\"\" def table_schema ( self , table , database = '' ) : describe = run_hive_cmd ( \"\" . format ( database , table ) , False ) if not describe or \"\" in describe : return None return [ tuple ( [ x . strip ( ) for x in line . strip ( ) . split ( \"\" ) ] ) for line in describe . strip ( ) . split ( \"\" ) ] class MetastoreClient ( HiveClient ) : def table_location ( self , table , database = '' , partition = None ) : with HiveThriftContext ( ) as client : if partition is not None : try : import hive_metastore . ttypes partition_str = self . partition_spec ( partition ) thrift_table = client . get_partition_by_name ( database , table , partition_str ) except hive_metastore . ttypes . NoSuchObjectException : return '' else : thrift_table = client . get_table ( database , table ) return thrift_table . sd . location def table_exists ( self , table , database = '' , partition = None ) : with HiveThriftContext ( ) as client : if partition is None : return table in client . get_all_tables ( database ) else : return partition in self . _existing_partitions ( table , database , client ) def _existing_partitions ( self , table , database , client ) : def _parse_partition_string ( partition_string ) : partition_def = { } for part in partition_string . split ( \"\" ) : name , value = part . split ( \"\" ) partition_def [ name ] = value return partition_def partition_strings = client . get_partition_names ( database , table , - ) return [ _parse_partition_string ( existing_partition ) for existing_partition in partition_strings ] def table_schema ( self , table , database = '' ) : with HiveThriftContext ( ) as client : return [ ( field_schema . name , field_schema . type ) for field_schema in client . get_schema ( database , table ) ] def partition_spec ( self , partition ) : return \"\" . join ( \"\" % ( k , v ) for ( k , v ) in sorted ( six . iteritems ( partition ) , key = operator . itemgetter ( ) ) ) class HiveThriftContext ( object ) : \"\"\"\"\"\" def __enter__ ( self ) : try : from thrift . transport import TSocket from thrift . transport import TTransport from thrift . protocol import TBinaryProtocol from hive_metastore import ThriftHiveMetastore config = luigi . configuration . get_config ( ) host = config . get ( '' , '' ) port = config . getint ( '' , '' ) transport = TSocket . TSocket ( host , port ) transport = TTransport . TBufferedTransport ( transport ) protocol = TBinaryProtocol . TBinaryProtocol ( transport ) transport . open ( ) self . transport = transport return ThriftHiveMetastore . Client ( protocol ) except ImportError as e : raise Exception ( '' + str ( e ) ) def __exit__ ( self , exc_type , exc_val , exc_tb ) : self . transport . close ( ) def get_default_client ( ) : syntax = get_hive_syntax ( ) if syntax == \"\" : return ApacheHiveCommandClient ( ) elif syntax == \"\" : return MetastoreClient ( ) else : return HiveCommandClient ( ) client = get_default_client ( ) class HiveQueryTask ( luigi . contrib . hadoop . BaseHadoopJobTask ) : \"\"\"\"\"\" n_reduce_tasks = None bytes_per_reducer = None reducers_max = None @ abc . abstractmethod def query ( self ) : \"\"\"\"\"\" raise RuntimeError ( \"\" ) def hiverc ( self ) : \"\"\"\"\"\" return luigi . configuration . get_config ( ) . get ( '' , '' , default = None ) def hiveconfs ( self ) : \"\"\"\"\"\" jcs = { } jcs [ '' ] = \"\" + self . task_id + \"\" if self . n_reduce_tasks is not None : jcs [ '' ] = self . n_reduce_tasks if self . pool is not None : scheduler_type = luigi . configuration . get_config ( ) . get ( '' , '' , '' ) if scheduler_type == '' : jcs [ '' ] = self . pool elif scheduler_type == '' : jcs [ '' ] = self . pool if self . bytes_per_reducer is not None : jcs [ '' ] = self . bytes_per_reducer if self . reducers_max is not None : jcs [ '' ] = self . reducers_max return jcs def job_runner ( self ) : return HiveQueryRunner ( ) class HiveQueryRunner ( luigi . contrib . hadoop . JobRunner ) : \"\"\"\"\"\" def prepare_outputs ( self , job ) : \"\"\"\"\"\" outputs = flatten ( job . output ( ) ) for o in outputs : if isinstance ( o , FileSystemTarget ) : parent_dir = os . path . dirname ( o . path ) if parent_dir and not o . fs . exists ( parent_dir ) : logger . info ( \"\" , parent_dir ) try : o . fs . mkdir ( parent_dir ) except FileAlreadyExists : pass ", "answer": "def run_job ( self , job , tracking_url_callback = None ) :"}, {"prompt": " \"\"\"\"\"\" import os from . import unittest , mock from architect . databases . postgresql . partition import Partition , RangePartition from architect . exceptions import ( PartitionConstraintError , PartitionRangeSubtypeError ) class BasePartitionTestCase ( object ) : def setUp ( self ) : model = mock . Mock ( __name__ = '' ) defaults = { '' : None , '' : None , '' : None , '' : None } self . partition = Partition ( model , ** defaults ) ", "answer": "self . range_partition = RangePartition ( model , ** dict ( constraint = '' , subtype = '' , ** defaults ) )"}, {"prompt": " \"\"\"\"\"\" from pyherc . aspects import log_debug from pyherc . generators . utils import BSPSection from pyherc . generators . level . partitioners import ( section_width , section_height , section_floor , section_wall ) class CatacombsGenerator ( ) : \"\"\"\"\"\" @ log_debug def __init__ ( self , floor_tile , empty_tile , level_types , rng ) : \"\"\"\"\"\" self . floor_tile = floor_tile self . empty_tile = empty_tile self . room_width = None self . room_height = None self . level_types = level_types self . rng = rng def __call__ ( self , section ) : \"\"\"\"\"\" ", "answer": "self . generate_room ( section )"}, {"prompt": " import os from datetime import datetime from flask import Flask , request , flash , url_for , redirect , render_template , abort import pg import json app = Flask ( __name__ ) app . config . from_pyfile ( '' ) print dir ( app . config ) db = pg . connect ( app . config [ '' ] , app . config [ '' ] , app . config [ '' ] , None , None , app . config [ '' ] , app . config [ '' ] ) @ app . route ( '' ) def index ( ) : return render_template ( '' ) @ app . route ( \"\" ) def parks ( ) : table_name = app . config [ '' ] result = db . query ( '' + table_name + \"\" ) return str ( json . dumps ( list ( result . dictresult ( ) ) ) ) @ app . route ( \"\" ) def within ( ) : ", "answer": "table_name = app . config [ '' ]"}, {"prompt": " \"\"\"\"\"\" import json from django . test import TestCase from django . test . client import Client from django . test . utils import override_settings from django . core . urlresolvers import reverse from django . contrib . auth . models import User as DjangoUser from treeio . core . models import User , Group , Perspective , ModuleSetting , Object from treeio . knowledge . models import KnowledgeFolder , KnowledgeItem , KnowledgeCategory @ override_settings ( HARDTREE_API_AUTH_ENGINE = '' ) class KnowledgeViewsTest ( TestCase ) : \"\" username = \"\" password = \"\" prepared = False authentication_headers = { \"\" : \"\" , \"\" : \"\" } content_type = '' prepared = False def setUp ( self ) : \"\" if not self . prepared : Object . objects . all ( ) . delete ( ) try : self . group = Group . objects . get ( name = '' ) except Group . DoesNotExist : Group . objects . all ( ) . delete ( ) self . group = Group ( name = '' ) self . group . save ( ) try : self . user = DjangoUser . objects . get ( username = self . username ) self . user . set_password ( self . password ) try : self . profile = self . user . profile except Exception : User . objects . all ( ) . delete ( ) self . user = DjangoUser ( username = self . username , password = '' ) self . user . set_password ( self . password ) self . user . save ( ) except DjangoUser . DoesNotExist : User . objects . all ( ) . delete ( ) self . user = DjangoUser ( username = self . username , password = '' ) self . user . set_password ( self . password ) self . user . save ( ) try : perspective = Perspective . objects . get ( name = '' ) except Perspective . DoesNotExist : Perspective . objects . all ( ) . delete ( ) perspective = Perspective ( name = '' ) perspective . set_default_user ( ) perspective . save ( ) ModuleSetting . set ( '' , perspective . id ) self . folder = KnowledgeFolder ( name = '' , treepath = '' ) self . folder . set_default_user ( ) self . folder . save ( ) self . category = KnowledgeCategory ( name = '' , treepath = '' ) self . category . set_default_user ( ) self . category . save ( ) self . item = KnowledgeItem ( name = '' , folder = self . folder , category = self . category , treepath = '' ) self . item . set_default_user ( ) self . item . save ( ) self . parent = KnowledgeFolder ( name = '' , treepath = '' ) self . parent . set_default_user ( ) self . parent . save ( ) self . client = Client ( ) self . prepared = True def test_unauthenticated_access ( self ) : \"\" response = self . client . get ( '' ) self . assertEquals ( response . status_code , ) def test_get_folders_list ( self ) : \"\"\"\"\"\" response = self . client . get ( path = reverse ( '' ) , ** self . authentication_headers ) self . assertEquals ( response . status_code , ) def test_get_folder ( self ) : response = self . client . get ( path = reverse ( '' , kwargs = { '' : self . folder . id } ) , ** self . authentication_headers ) self . assertEquals ( response . status_code , ) def test_update_folder ( self ) : updates = { '' : '' , '' : self . parent . id , '' : '' } response = self . client . put ( path = reverse ( '' , kwargs = { '' : self . folder . id } ) , content_type = self . content_type , data = json . dumps ( updates ) , ", "answer": "** self . authentication_headers )"}, {"prompt": " \"\"\"\"\"\" from django . conf import settings UNFRIENDLY_ENABLE_FILTER = getattr ( settings , '' , True ) ", "answer": "UNFRIENDLY_SECRET = getattr ( settings , '' ,"}, {"prompt": " from debug import * from defaults import * from generic . create_update import * from generic . date_based import * from generic . object_list import * ", "answer": "from generic . simple import *"}, {"prompt": " from setuptools import setup setup ( name = '' , install_requires = [ '' , ", "answer": "'' ,"}, {"prompt": " \"\"\"\"\"\" from struct import pack from struct import unpack from exabgp . protocol . ip import NoNextHop from exabgp . protocol . family import AFI from exabgp . protocol . family import SAFI from exabgp . bgp . message . direction import OUT from exabgp . bgp . message . notification import Notify from exabgp . bgp . message . update . nlri . cidr import CIDR from exabgp . protocol import Protocol from exabgp . protocol . ip . icmp import ICMPType from exabgp . protocol . ip . icmp import ICMPCode from exabgp . protocol . ip . fragment import Fragment from exabgp . protocol . ip . tcp . flag import TCPFlag from exabgp . bgp . message . update . nlri . nlri import NLRI from exabgp . bgp . message . update . nlri . qualifier import RouteDistinguisher class IComponent ( object ) : FLAG = False class CommonOperator ( object ) : power = { : , : , : , : , } rewop = { : , : , : , : , } len_position = EOL = AND = LEN = NOP = OPERATOR = ^ ( EOL | LEN ) @ staticmethod def eol ( data ) : return data & CommonOperator . EOL @ staticmethod def operator ( data ) : return data & CommonOperator . OPERATOR @ staticmethod def length ( data ) : return << ( ( data & CommonOperator . LEN ) >> ) class NumericOperator ( CommonOperator ) : LT = GT = EQ = class BinaryOperator ( CommonOperator ) : NOT = MATCH = INCLUDE = def _len_to_bit ( value ) : return NumericOperator . rewop [ value ] << def _bit_to_len ( value ) : return NumericOperator . power [ ( value & CommonOperator . len_position ) >> ] def _number ( string ) : value = for c in string : value = ( value << ) + ord ( c ) return value class IPv4 ( object ) : afi = AFI . ipv4 class IPv6 ( object ) : afi = AFI . ipv6 class IPrefix ( object ) : pass class IPrefix4 ( IPrefix , IComponent , IPv4 ) : CODE = - NAME = '' operations = def __init__ ( self , raw , netmask ) : self . cidr = CIDR ( raw , netmask ) def pack ( self ) : raw = self . cidr . pack_nlri ( ) return \"\" % ( chr ( self . ID ) , raw ) def __str__ ( self ) : return str ( self . cidr ) @ classmethod def make ( cls , bgp ) : prefix , mask = CIDR . decode ( AFI . ipv4 , bgp ) return cls ( prefix , mask ) , bgp [ CIDR . size ( mask ) + : ] class IPrefix6 ( IPrefix , IComponent , IPv6 ) : CODE = - NAME = '' operations = def __init__ ( self , raw , netmask , offset ) : self . cidr = CIDR ( raw , netmask ) self . offset = offset def pack ( self ) : return \"\" % ( chr ( self . ID ) , chr ( self . cidr . mask ) , chr ( self . offset ) , self . cidr . pack_ip ( ) ) def __str__ ( self ) : return \"\" % ( self . cidr , self . offset ) @ classmethod def make ( cls , bgp ) : offset = ord ( bgp [ ] ) prefix , mask = CIDR . decode ( AFI . ipv6 , bgp [ ] + bgp [ : ] ) return cls ( prefix , mask , offset ) , bgp [ CIDR . size ( mask ) + : ] class IOperation ( IComponent ) : def __init__ ( self , operations , value ) : self . operations = operations self . value = value self . first = None def pack ( self ) : l , v = self . encode ( self . value ) op = self . operations | _len_to_bit ( l ) return \"\" % ( chr ( op ) , v ) def encode ( self , value ) : raise NotImplementedError ( '' ) def decode ( self , value ) : raise NotImplementedError ( '' ) class IOperationByte ( IOperation ) : def encode ( self , value ) : return , chr ( value ) def decode ( self , bgp ) : return ord ( bgp [ ] ) , bgp [ : ] class IOperationByteShort ( IOperation ) : def encode ( self , value ) : if value < ( << ) : return , chr ( value ) return , pack ( '' , value ) def decode ( self , bgp ) : return unpack ( '' , bgp [ : ] ) [ ] , bgp [ : ] class NumericString ( object ) : OPERATION = '' operations = None value = None _string = { NumericOperator . LT : '' , NumericOperator . GT : '>' , NumericOperator . EQ : '' , NumericOperator . LT | NumericOperator . EQ : '' , NumericOperator . GT | NumericOperator . EQ : '' , NumericOperator . AND | NumericOperator . LT : '' , NumericOperator . AND | NumericOperator . GT : '' , NumericOperator . AND | NumericOperator . EQ : '' , NumericOperator . AND | NumericOperator . LT | NumericOperator . EQ : '' , NumericOperator . AND | NumericOperator . GT | NumericOperator . EQ : '' , } def __str__ ( self ) : return \"\" % ( self . _string [ self . operations & ( CommonOperator . EOL ^ ) ] , self . value ) class BinaryString ( object ) : OPERATION = '' operations = None value = None _string = { BinaryOperator . INCLUDE : '' , BinaryOperator . NOT : '' , BinaryOperator . MATCH : '' , BinaryOperator . AND | BinaryOperator . NOT : '' , BinaryOperator . AND | BinaryOperator . MATCH : '' , } def __str__ ( self ) : return \"\" % ( self . _string [ self . operations & ( CommonOperator . EOL ^ ) ] , self . value ) def converter ( function , klass = None ) : def _integer ( value ) : if klass is None : return function ( value ) try : return klass ( value ) except ValueError : return function ( value ) return _integer def decoder ( function , klass = int ) : def _inner ( value ) : return klass ( function ( value ) ) return _inner def PacketLength ( data ) : _str_bad_length = \"\" number = int ( data ) if number > : raise ValueError ( _str_bad_length ) return number def PortValue ( data ) : _str_bad_port = \"\" number = int ( data ) if number < or number > : raise ValueError ( _str_bad_port ) return number def DSCPValue ( data ) : _str_bad_dscp = \"\" number = int ( data ) if number < or number > : raise ValueError ( _str_bad_dscp ) return number def ClassValue ( data ) : _str_bad_class = \"\" number = int ( data ) if number < or number > : raise ValueError ( _str_bad_class ) return number def LabelValue ( data ) : _str_bad_label = \"\" number = int ( data ) if number < or number > : raise ValueError ( _str_bad_label ) return number class FlowDestination ( object ) : ID = NAME = '' class FlowSource ( object ) : ID = NAME = '' class Flow4Destination ( IPrefix4 , FlowDestination ) : NAME = '' class Flow4Source ( IPrefix4 , FlowSource ) : NAME = '' class Flow6Destination ( IPrefix6 , FlowDestination ) : NAME = '' class Flow6Source ( IPrefix6 , FlowSource ) : NAME = '' class FlowIPProtocol ( IOperationByte , NumericString , IPv4 ) : ID = NAME = '' converter = staticmethod ( converter ( Protocol . named , Protocol ) ) decoder = staticmethod ( decoder ( ord , Protocol ) ) class FlowNextHeader ( IOperationByte , NumericString , IPv6 ) : ID = NAME = '' converter = staticmethod ( converter ( Protocol . named , Protocol ) ) decoder = staticmethod ( decoder ( ord , Protocol ) ) class FlowAnyPort ( IOperationByteShort , NumericString , IPv4 , IPv6 ) : ID = NAME = '' converter = staticmethod ( converter ( PortValue ) ) decoder = staticmethod ( _number ) class FlowDestinationPort ( IOperationByteShort , NumericString , IPv4 , IPv6 ) : ID = NAME = '' converter = staticmethod ( converter ( PortValue ) ) decoder = staticmethod ( _number ) class FlowSourcePort ( IOperationByteShort , NumericString , IPv4 , IPv6 ) : ID = NAME = '' converter = staticmethod ( converter ( PortValue ) ) decoder = staticmethod ( _number ) class FlowICMPType ( IOperationByte , BinaryString , IPv4 , IPv6 ) : ID = NAME = '' converter = staticmethod ( converter ( ICMPType . named ) ) decoder = staticmethod ( decoder ( _number , ICMPType ) ) class FlowICMPCode ( IOperationByte , BinaryString , IPv4 , IPv6 ) : ID = NAME = '' converter = staticmethod ( converter ( ICMPCode . named ) ) decoder = staticmethod ( decoder ( _number , ICMPCode ) ) class FlowTCPFlag ( IOperationByte , BinaryString , IPv4 , IPv6 ) : ID = NAME = '' FLAG = True converter = staticmethod ( converter ( TCPFlag . named ) ) decoder = staticmethod ( decoder ( ord , TCPFlag ) ) class FlowPacketLength ( IOperationByteShort , NumericString , IPv4 , IPv6 ) : ID = NAME = '' converter = staticmethod ( converter ( PacketLength ) ) decoder = staticmethod ( _number ) class FlowDSCP ( IOperationByteShort , NumericString , IPv4 ) : ID = NAME = '' converter = staticmethod ( converter ( DSCPValue ) ) decoder = staticmethod ( _number ) class FlowTrafficClass ( IOperationByte , NumericString , IPv6 ) : ID = NAME = '' converter = staticmethod ( converter ( ClassValue ) ) decoder = staticmethod ( _number ) class FlowFragment ( IOperationByteShort , BinaryString , IPv4 ) : ID = NAME = '' FLAG = True converter = staticmethod ( converter ( Fragment . named ) ) decoder = staticmethod ( decoder ( ord , Fragment ) ) class FlowFlowLabel ( IOperationByteShort , NumericString , IPv6 ) : ID = NAME = '' converter = staticmethod ( converter ( LabelValue ) ) decoder = staticmethod ( _number ) decode = { AFI . ipv4 : { } , AFI . ipv6 : { } } factory = { AFI . ipv4 : { } , AFI . ipv6 : { } } for content in dir ( ) : kls = globals ( ) . get ( content , None ) if not isinstance ( kls , type ( IComponent ) ) : continue if not issubclass ( kls , IComponent ) : continue if issubclass ( kls , IPv4 ) : _afi = AFI . ipv4 elif issubclass ( kls , IPv6 ) : _afi = AFI . ipv6 else : continue _ID = getattr ( kls , '' , None ) if not _ID : continue factory [ _afi ] [ _ID ] = kls name = getattr ( kls , '' ) if issubclass ( kls , IOperation ) : if issubclass ( kls , BinaryString ) : ", "answer": "decode [ _afi ] [ _ID ] = ''"}, {"prompt": " from os import path from gluon import * from s3 import S3CustomController THEME = \"\" class index ( S3CustomController ) : \"\"\"\"\"\" def __call__ ( self ) : output = { } if current . deployment_settings . has_module ( \"\" ) : system_roles = current . auth . get_system_roles ( ) ADMIN = system_roles . ADMIN in current . session . s3 . roles s3db = current . s3db table = s3db . cms_post ltable = s3db . cms_post_module module = \"\" resource = \"\" query = ( ltable . module == module ) & ( ( ltable . resource == None ) | ( ltable . resource == resource ) ) & ( ltable . post_id == table . id ) & ( table . deleted != True ) item = current . db ( query ) . select ( table . body , ", "answer": "table . id ,"}, {"prompt": " from __future__ import unicode_literals from django . db import models , migrations import django . utils . timezone import django . core . validators class Migration ( migrations . Migration ) : dependencies = [ ( '' , '' ) , ] operations = [ migrations . CreateModel ( name = '' , fields = [ ( '' , models . AutoField ( verbose_name = '' , serialize = False , auto_created = True , primary_key = True ) ) , ( '' , models . CharField ( max_length = , verbose_name = '' ) ) , ( '' , models . DateTimeField ( default = django . utils . timezone . now , verbose_name = '' , null = True , blank = True ) ) , ", "answer": "( '' , models . BooleanField ( default = False , help_text = '' , verbose_name = '' ) ) ,"}, {"prompt": " from django . contrib import admin ", "answer": "from testproj . testapp import models"}, {"prompt": " \"\"\"\"\"\" from itertools import islice import inspect import warnings import re import os from . _compat import _basestring from . logger import pformat ", "answer": "from . _memory_helpers import open_py_source"}, {"prompt": " import time from json import dumps , loads import warnings from webtest import TestApp from six import b as b_ from six import u as u_ import webob import mock from pecan import Pecan , expose , abort , Request , Response from pecan . rest import RestController from pecan . hooks import PecanHook , HookController from pecan . tests import PecanTestCase class TestThreadingLocalUsage ( PecanTestCase ) : @ property def root ( self ) : class RootController ( object ) : @ expose ( ) def index ( self , req , resp ) : assert isinstance ( req , webob . BaseRequest ) assert isinstance ( resp , webob . Response ) return '' @ expose ( ) def warning ( self ) : return ( \"\" \"\" ) @ expose ( generic = True ) def generic ( self ) : return ( \"\" \"\" ) @ generic . when ( method = '' ) def generic_put ( self , _id ) : return ( \"\" \"\" ) return RootController def test_locals_are_not_used ( self ) : with mock . patch ( '' , side_effect = AssertionError ( ) ) : app = TestApp ( Pecan ( self . root ( ) , use_context_locals = False ) ) r = app . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) self . assertRaises ( AssertionError , Pecan , self . root ) def test_threadlocal_argument_warning ( self ) : with mock . patch ( '' , side_effect = AssertionError ( ) ) : app = TestApp ( Pecan ( self . root ( ) , use_context_locals = False ) ) self . assertRaises ( TypeError , app . get , '' ) def test_threadlocal_argument_warning_on_generic ( self ) : with mock . patch ( '' , side_effect = AssertionError ( ) ) : app = TestApp ( Pecan ( self . root ( ) , use_context_locals = False ) ) self . assertRaises ( TypeError , app . get , '' ) def test_threadlocal_argument_warning_on_generic_delegate ( self ) : with mock . patch ( '' , side_effect = AssertionError ( ) ) : app = TestApp ( Pecan ( self . root ( ) , use_context_locals = False ) ) self . assertRaises ( TypeError , app . put , '' ) class TestIndexRouting ( PecanTestCase ) : @ property def app_ ( self ) : class RootController ( object ) : @ expose ( ) def index ( self , req , resp ) : assert isinstance ( req , webob . BaseRequest ) assert isinstance ( resp , webob . Response ) return '' return TestApp ( Pecan ( RootController ( ) , use_context_locals = False ) ) def test_empty_root ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_index ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_index_html ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) class TestManualResponse ( PecanTestCase ) : def test_manual_response ( self ) : class RootController ( object ) : @ expose ( ) def index ( self , req , resp ) : resp = webob . Response ( resp . environ ) resp . body = b_ ( '' ) return resp app = TestApp ( Pecan ( RootController ( ) , use_context_locals = False ) ) r = app . get ( '' ) assert r . body == b_ ( '' ) , r . body class TestDispatch ( PecanTestCase ) : @ property def app_ ( self ) : class SubSubController ( object ) : @ expose ( ) def index ( self , req , resp ) : assert isinstance ( req , webob . BaseRequest ) assert isinstance ( resp , webob . Response ) return '' @ expose ( ) def deeper ( self , req , resp ) : assert isinstance ( req , webob . BaseRequest ) assert isinstance ( resp , webob . Response ) return '' class SubController ( object ) : @ expose ( ) def index ( self , req , resp ) : assert isinstance ( req , webob . BaseRequest ) assert isinstance ( resp , webob . Response ) return '' @ expose ( ) def deeper ( self , req , resp ) : assert isinstance ( req , webob . BaseRequest ) assert isinstance ( resp , webob . Response ) return '' sub = SubSubController ( ) class RootController ( object ) : @ expose ( ) def index ( self , req , resp ) : assert isinstance ( req , webob . BaseRequest ) assert isinstance ( resp , webob . Response ) return '' @ expose ( ) def deeper ( self , req , resp ) : assert isinstance ( req , webob . BaseRequest ) assert isinstance ( resp , webob . Response ) return '' sub = SubController ( ) return TestApp ( Pecan ( RootController ( ) , use_context_locals = False ) ) def test_index ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_one_level ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_one_level_with_trailing ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_two_levels ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_two_levels_with_trailing ( self ) : r = self . app_ . get ( '' ) assert r . status_int == def test_three_levels ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) class TestLookups ( PecanTestCase ) : @ property def app_ ( self ) : class LookupController ( object ) : def __init__ ( self , someID ) : self . someID = someID @ expose ( ) def index ( self , req , resp ) : return '' % self . someID @ expose ( ) def name ( self , req , resp ) : return '' % self . someID class RootController ( object ) : @ expose ( ) def index ( self , req , resp ) : return '' @ expose ( ) def _lookup ( self , someID , * remainder ) : return LookupController ( someID ) , remainder return TestApp ( Pecan ( RootController ( ) , use_context_locals = False ) ) def test_index ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_lookup ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_lookup_with_method ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_lookup_with_wrong_argspec ( self ) : class RootController ( object ) : @ expose ( ) def _lookup ( self , someID ) : return '' with warnings . catch_warnings ( ) : warnings . simplefilter ( \"\" ) app = TestApp ( Pecan ( RootController ( ) , use_context_locals = False ) ) r = app . get ( '' , expect_errors = True ) assert r . status_int == class TestCanonicalLookups ( PecanTestCase ) : @ property def app_ ( self ) : class LookupController ( object ) : def __init__ ( self , someID ) : self . someID = someID @ expose ( ) def index ( self , req , resp ) : return self . someID class UserController ( object ) : @ expose ( ) def _lookup ( self , someID , * remainder ) : return LookupController ( someID ) , remainder class RootController ( object ) : users = UserController ( ) return TestApp ( Pecan ( RootController ( ) , use_context_locals = False ) ) def test_canonical_lookup ( self ) : assert self . app_ . get ( '' , expect_errors = ) . status_int == assert self . app_ . get ( '' , expect_errors = ) . status_int == assert self . app_ . get ( '' ) . status_int == assert self . app_ . get ( '' ) . body == b_ ( '' ) class TestControllerArguments ( PecanTestCase ) : @ property def app_ ( self ) : class RootController ( object ) : @ expose ( ) def index ( self , req , resp , id ) : return '' % id @ expose ( ) def multiple ( self , req , resp , one , two ) : return '' % ( one , two ) @ expose ( ) def optional ( self , req , resp , id = None ) : return '' % str ( id ) @ expose ( ) def multiple_optional ( self , req , resp , one = None , two = None , three = None ) : return '' % ( one , two , three ) @ expose ( ) def variable_args ( self , req , resp , * args ) : return '' % '' . join ( args ) @ expose ( ) def variable_kwargs ( self , req , resp , ** kwargs ) : data = [ '' % ( key , kwargs [ key ] ) for key in sorted ( kwargs . keys ( ) ) ] return '' % '' . join ( data ) @ expose ( ) def variable_all ( self , req , resp , * args , ** kwargs ) : data = [ '' % ( key , kwargs [ key ] ) for key in sorted ( kwargs . keys ( ) ) ] return '' % '' . join ( list ( args ) + data ) @ expose ( ) def eater ( self , req , resp , id , dummy = None , * args , ** kwargs ) : data = [ '' % ( key , kwargs [ key ] ) for key in sorted ( kwargs . keys ( ) ) ] return '' % ( id , dummy , '' . join ( list ( args ) + data ) ) @ expose ( ) def _route ( self , args , request ) : if hasattr ( self , args [ ] ) : return getattr ( self , args [ ] ) , args [ : ] else : return self . index , args return TestApp ( Pecan ( RootController ( ) , use_context_locals = False ) ) def test_required_argument ( self ) : try : r = self . app_ . get ( '' ) assert r . status_int != except Exception as ex : assert type ( ex ) == TypeError assert ex . args [ ] in ( \"\" , \"\" ) def test_single_argument ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_single_argument_with_encoded_url ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_two_arguments ( self ) : r = self . app_ . get ( '' , status = ) assert r . status_int == def test_keyword_argument ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_keyword_argument_with_encoded_url ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_argument_and_keyword_argument ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_encoded_argument_and_keyword_argument ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_explicit_kwargs ( self ) : r = self . app_ . post ( '' , { '' : '' } ) assert r . status_int == assert r . body == b_ ( '' ) def test_path_with_explicit_kwargs ( self ) : r = self . app_ . post ( '' , { '' : '' } ) assert r . status_int == assert r . body == b_ ( '' ) def test_multiple_kwargs ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_kwargs_from_root ( self ) : r = self . app_ . post ( '' , { '' : '' , '' : '' } ) assert r . status_int == assert r . body == b_ ( '' ) def test_multiple_positional_arguments ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_multiple_positional_arguments_with_url_encode ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_multiple_positional_arguments_with_kwargs ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_multiple_positional_arguments_with_url_encoded_kwargs ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_positional_args_with_dictionary_kwargs ( self ) : r = self . app_ . post ( '' , { '' : '' , '' : '' } ) assert r . status_int == assert r . body == b_ ( '' ) def test_positional_args_with_url_encoded_dictionary_kwargs ( self ) : r = self . app_ . post ( '' , { '' : '' , '' : '' } ) assert r . status_int == assert r . body == b_ ( '' ) def test_optional_arg ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_multiple_optional ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_multiple_optional_url_encoded ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_multiple_optional_missing ( self ) : r = self . app_ . get ( '' , status = ) assert r . status_int == def test_multiple_with_kwargs ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_multiple_with_url_encoded_kwargs ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_multiple_args_with_url_encoded_kwargs ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_url_encoded_positional_args ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_optional_arg_with_kwargs ( self ) : r = self . app_ . post ( '' , { '' : '' } ) assert r . status_int == assert r . body == b_ ( '' ) def test_optional_arg_with_url_encoded_kwargs ( self ) : r = self . app_ . post ( '' , { '' : '' } ) assert r . status_int == assert r . body == b_ ( '' ) def test_multiple_positional_arguments_with_dictionary_kwargs ( self ) : r = self . app_ . post ( '' , { '' : '' } ) assert r . status_int == assert r . body == b_ ( '' ) def test_multiple_positional_url_encoded_arguments_with_kwargs ( self ) : r = self . app_ . post ( '' , { '' : '' } ) assert r . status_int == assert r . body == b_ ( '' ) def test_optional_arg_with_multiple_kwargs ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_optional_arg_with_multiple_url_encoded_kwargs ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_optional_arg_with_multiple_dictionary_kwargs ( self ) : r = self . app_ . post ( '' , { '' : '' , '' : '' } ) assert r . status_int == assert r . body == b_ ( '' ) def test_optional_arg_with_multiple_url_encoded_dictionary_kwargs ( self ) : r = self . app_ . post ( '' , { '' : '' , '' : '' } ) assert r . status_int == assert r . body == b_ ( '' ) def test_multiple_optional_positional_args ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_multiple_optional_positional_args_one_arg ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_multiple_optional_positional_args_one_url_encoded_arg ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_multiple_optional_positional_args_all_args ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_multiple_optional_positional_args_all_url_encoded_args ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_multiple_optional_positional_args_too_many_args ( self ) : r = self . app_ . get ( '' , status = ) assert r . status_int == def test_multiple_optional_positional_args_with_kwargs ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_multiple_optional_positional_args_with_url_encoded_kwargs ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_multiple_optional_positional_args_with_string_kwargs ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_multiple_optional_positional_args_with_encoded_str_kwargs ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_multiple_optional_positional_args_with_dict_kwargs ( self ) : r = self . app_ . post ( '' , { '' : '' } ) assert r . status_int == assert r . body == b_ ( '' ) def test_multiple_optional_positional_args_with_encoded_dict_kwargs ( self ) : r = self . app_ . post ( '' , { '' : '' } ) assert r . status_int == assert r . body == b_ ( '' ) def test_multiple_optional_positional_args_and_dict_kwargs ( self ) : r = self . app_ . post ( '' , { '' : '' } ) assert r . status_int == assert r . body == b_ ( '' ) def test_multiple_optional_encoded_positional_args_and_dict_kwargs ( self ) : r = self . app_ . post ( '' , { '' : '' } ) assert r . status_int == assert r . body == b_ ( '' ) def test_multiple_optional_args_with_multiple_kwargs ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_multiple_optional_args_with_multiple_encoded_kwargs ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_multiple_optional_args_with_multiple_dict_kwargs ( self ) : r = self . app_ . post ( '' , { '' : '' , '' : '' , '' : '' , '' : '' } ) assert r . status_int == assert r . body == b_ ( '' ) def test_multiple_optional_args_with_multiple_encoded_dict_kwargs ( self ) : r = self . app_ . post ( '' , { '' : '' , '' : '' , '' : '' , '' : '' } ) assert r . status_int == assert r . body == b_ ( '' ) def test_multiple_optional_args_with_last_kwarg ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_multiple_optional_args_with_last_encoded_kwarg ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_multiple_optional_args_with_middle_arg ( self ) : r = self . app_ . get ( '' , { '' : '' } ) assert r . status_int == assert r . body == b_ ( '' ) def test_variable_args ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_multiple_variable_args ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_multiple_encoded_variable_args ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_variable_args_with_kwargs ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_variable_args_with_dict_kwargs ( self ) : r = self . app_ . post ( '' , { '' : '' , '' : '' } ) assert r . status_int == assert r . body == b_ ( '' ) def test_variable_kwargs ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_multiple_variable_kwargs ( self ) : r = self . app_ . get ( '' , status = ) assert r . status_int == def test_multiple_variable_kwargs_with_explicit_kwargs ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_multiple_variable_kwargs_with_explicit_encoded_kwargs ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_multiple_variable_kwargs_with_dict_kwargs ( self ) : r = self . app_ . post ( '' , { '' : '' , '' : '' } ) assert r . status_int == assert r . body == b_ ( '' ) def test_multiple_variable_kwargs_with_encoded_dict_kwargs ( self ) : r = self . app_ . post ( '' , { '' : '' , '' : '' } ) assert r . status_int == result = '' assert r . body == b_ ( result ) def test_variable_all ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_variable_all_with_one_extra ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_variable_all_with_two_extras ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_variable_mixed ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_variable_mixed_explicit ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_variable_post ( self ) : r = self . app_ . post ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_variable_post_with_kwargs ( self ) : r = self . app_ . post ( '' , { '' : '' , '' : '' } ) assert r . status_int == assert r . body == b_ ( '' ) def test_variable_post_mixed ( self ) : r = self . app_ . post ( '' , { '' : '' , '' : '' , '' : '' } ) assert r . status_int == assert r . body == b_ ( '' ) def test_no_remainder ( self ) : try : r = self . app_ . get ( '' ) assert r . status_int != except Exception as ex : assert type ( ex ) == TypeError assert ex . args [ ] in ( \"\" , \"\" ) def test_one_remainder ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_two_remainders ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_many_remainders ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_remainder_with_kwargs ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_remainder_with_many_kwargs ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_post_remainder ( self ) : r = self . app_ . post ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_post_three_remainders ( self ) : r = self . app_ . post ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_post_many_remainders ( self ) : r = self . app_ . post ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_post_remainder_with_kwargs ( self ) : r = self . app_ . post ( '' , { '' : '' , '' : '' } ) assert r . status_int == assert r . body == b_ ( '' ) def test_post_many_remainders_with_many_kwargs ( self ) : r = self . app_ . post ( '' , { '' : '' , '' : '' , '' : '' , '' : '' } ) assert r . status_int == assert r . body == b_ ( '' ) class TestRestController ( PecanTestCase ) : @ property def app_ ( self ) : class OthersController ( object ) : @ expose ( ) def index ( self , req , resp ) : return '' @ expose ( ) def echo ( self , req , resp , value ) : return str ( value ) class ThingsController ( RestController ) : data = [ '' , '' , '' , '' ] _custom_actions = { '' : [ '' ] , '' : [ '' , '' ] } others = OthersController ( ) @ expose ( ) def get_one ( self , req , resp , id ) : return self . data [ int ( id ) ] @ expose ( '' ) def get_all ( self , req , resp ) : return dict ( items = self . data ) @ expose ( ) def length ( self , req , resp , id , value = None ) : length = len ( self . data [ int ( id ) ] ) if value : length += len ( value ) return str ( length ) @ expose ( ) def post ( self , req , resp , value ) : self . data . append ( value ) resp . status = return '' @ expose ( ) def edit ( self , req , resp , id ) : return '' % self . data [ int ( id ) ] @ expose ( ) def put ( self , req , resp , id , value ) : self . data [ int ( id ) ] = value return '' @ expose ( ) def get_delete ( self , req , resp , id ) : return '' % self . data [ int ( id ) ] @ expose ( ) def delete ( self , req , resp , id ) : del self . data [ int ( id ) ] return '' @ expose ( ) def reset ( self , req , resp ) : return '' @ expose ( ) def post_options ( self , req , resp ) : return '' @ expose ( ) def options ( self , req , resp ) : abort ( ) @ expose ( ) def other ( self , req , resp ) : abort ( ) class RootController ( object ) : things = ThingsController ( ) return TestApp ( Pecan ( RootController ( ) , use_context_locals = False ) ) def test_get_all ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( dumps ( dict ( items = [ '' , '' , '' , '' ] ) ) ) def test_get_one ( self ) : for i , value in enumerate ( [ '' , '' , '' , '' ] ) : r = self . app_ . get ( '' % i ) assert r . status_int == assert r . body == b_ ( value ) def test_post ( self ) : r = self . app_ . post ( '' , { '' : '' } ) assert r . status_int == assert r . body == b_ ( '' ) def test_custom_action ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_put ( self ) : r = self . app_ . put ( '' , { '' : '' } ) assert r . status_int == assert r . body == b_ ( '' ) def test_put_with_method_parameter_and_get ( self ) : r = self . app_ . get ( '' , { '' : '' } , status = ) assert r . status_int == def test_put_with_method_parameter_and_post ( self ) : r = self . app_ . post ( '' , { '' : '' } ) assert r . status_int == assert r . body == b_ ( '' ) def test_get_delete ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_delete_method ( self ) : r = self . app_ . delete ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_delete_with_method_parameter ( self ) : r = self . app_ . get ( '' , status = ) assert r . status_int == def test_delete_with_method_parameter_and_post ( self ) : r = self . app_ . post ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_custom_method_type ( self ) : r = self . app_ . request ( '' , method = '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_custom_method_type_with_method_parameter ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_options ( self ) : r = self . app_ . request ( '' , method = '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_options_with_method_parameter ( self ) : r = self . app_ . post ( '' , { '' : '' } ) assert r . status_int == assert r . body == b_ ( '' ) def test_other_custom_action ( self ) : with warnings . catch_warnings ( ) : warnings . simplefilter ( \"\" ) r = self . app_ . request ( '' , method = '' , status = ) assert r . status_int == def test_other_custom_action_with_method_parameter ( self ) : r = self . app_ . post ( '' , { '' : '' } , status = ) assert r . status_int == def test_nested_controller_with_trailing_slash ( self ) : with warnings . catch_warnings ( ) : warnings . simplefilter ( \"\" ) r = self . app_ . request ( '' , method = '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_nested_controller_without_trailing_slash ( self ) : with warnings . catch_warnings ( ) : warnings . simplefilter ( \"\" ) r = self . app_ . request ( '' , method = '' , status = ) assert r . status_int == def test_invalid_custom_action ( self ) : r = self . app_ . get ( '' , status = ) assert r . status_int == def test_named_action ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( str ( len ( '' ) ) ) def test_named_nested_action ( self ) : r = self . app_ . get ( '' ) assert r . status_int == assert r . body == b_ ( '' ) def test_nested_post ( self ) : r = self . app_ . post ( '' , { '' : '' } ) assert r . status_int == assert r . body == b_ ( '' ) class TestHooks ( PecanTestCase ) : def test_basic_single_hook ( self ) : run_hook = [ ] class RootController ( object ) : @ expose ( ) def index ( self , req , resp ) : run_hook . append ( '' ) return '' class SimpleHook ( PecanHook ) : def on_route ( self , state ) : run_hook . append ( '' ) def before ( self , state ) : run_hook . append ( '' ) def after ( self , state ) : run_hook . append ( '' ) def on_error ( self , state , e ) : run_hook . append ( '' ) app = TestApp ( Pecan ( RootController ( ) , hooks = [ SimpleHook ( ) ] , use_context_locals = False ) ) response = app . get ( '' ) assert response . status_int == assert response . body == b_ ( '' ) assert len ( run_hook ) == assert run_hook [ ] == '' assert run_hook [ ] == '' assert run_hook [ ] == '' assert run_hook [ ] == '' def test_basic_multi_hook ( self ) : run_hook = [ ] class RootController ( object ) : @ expose ( ) def index ( self , req , resp ) : run_hook . append ( '' ) return '' class SimpleHook ( PecanHook ) : def __init__ ( self , id ) : self . id = str ( id ) def on_route ( self , state ) : run_hook . append ( '' + self . id ) def before ( self , state ) : run_hook . append ( '' + self . id ) def after ( self , state ) : run_hook . append ( '' + self . id ) def on_error ( self , state , e ) : run_hook . append ( '' + self . id ) app = TestApp ( Pecan ( RootController ( ) , hooks = [ SimpleHook ( ) , SimpleHook ( ) , SimpleHook ( ) ] , use_context_locals = False ) ) response = app . get ( '' ) assert response . status_int == assert response . body == b_ ( '' ) assert len ( run_hook ) == assert run_hook [ ] == '' assert run_hook [ ] == '' assert run_hook [ ] == '' assert run_hook [ ] == '' assert run_hook [ ] == '' assert run_hook [ ] == '' assert run_hook [ ] == '' assert run_hook [ ] == '' assert run_hook [ ] == '' assert run_hook [ ] == '' def test_partial_hooks ( self ) : run_hook = [ ] class RootController ( object ) : @ expose ( ) def index ( self , req , resp ) : run_hook . append ( '' ) return '' @ expose ( ) def causeerror ( self , req , resp ) : return [ ] [ ] class ErrorHook ( PecanHook ) : def on_error ( self , state , e ) : run_hook . append ( '' ) class OnRouteHook ( PecanHook ) : def on_route ( self , state ) : run_hook . append ( '' ) app = TestApp ( Pecan ( RootController ( ) , hooks = [ ErrorHook ( ) , OnRouteHook ( ) ] , use_context_locals = False ) ) response = app . get ( '' ) assert response . status_int == assert response . body == b_ ( '' ) assert len ( run_hook ) == assert run_hook [ ] == '' assert run_hook [ ] == '' run_hook = [ ] try : response = app . get ( '' ) except Exception as e : assert isinstance ( e , IndexError ) assert len ( run_hook ) == assert run_hook [ ] == '' assert run_hook [ ] == '' def test_on_error_response_hook ( self ) : run_hook = [ ] class RootController ( object ) : @ expose ( ) def causeerror ( self , req , resp ) : return [ ] [ ] class ErrorHook ( PecanHook ) : def on_error ( self , state , e ) : run_hook . append ( '' ) r = webob . Response ( ) r . text = u_ ( '' ) return r app = TestApp ( Pecan ( RootController ( ) , hooks = [ ErrorHook ( ) ] , use_context_locals = False ) ) response = app . get ( '' ) assert len ( run_hook ) == assert run_hook [ ] == '' assert response . text == '' def test_prioritized_hooks ( self ) : run_hook = [ ] class RootController ( object ) : @ expose ( ) def index ( self , req , resp ) : run_hook . append ( '' ) return '' class SimpleHook ( PecanHook ) : def __init__ ( self , id , priority = None ) : self . id = str ( id ) if priority : self . priority = priority def on_route ( self , state ) : run_hook . append ( '' + self . id ) def before ( self , state ) : run_hook . append ( '' + self . id ) def after ( self , state ) : run_hook . append ( '' + self . id ) def on_error ( self , state , e ) : run_hook . append ( '' + self . id ) papp = Pecan ( RootController ( ) , hooks = [ SimpleHook ( , ) , SimpleHook ( , ) , SimpleHook ( , ) ] , use_context_locals = False ) app = TestApp ( papp ) response = app . get ( '' ) assert response . status_int == assert response . body == b_ ( '' ) assert len ( run_hook ) == assert run_hook [ ] == '' assert run_hook [ ] == '' assert run_hook [ ] == '' assert run_hook [ ] == '' assert run_hook [ ] == '' assert run_hook [ ] == '' assert run_hook [ ] == '' assert run_hook [ ] == '' assert run_hook [ ] == '' assert run_hook [ ] == '' def test_basic_isolated_hook ( self ) : run_hook = [ ] class SimpleHook ( PecanHook ) : def on_route ( self , state ) : run_hook . append ( '' ) def before ( self , state ) : run_hook . append ( '' ) def after ( self , state ) : run_hook . append ( '' ) def on_error ( self , state , e ) : run_hook . append ( '' ) class SubSubController ( object ) : @ expose ( ) def index ( self , req , resp ) : run_hook . append ( '' ) return '' class SubController ( HookController ) : __hooks__ = [ SimpleHook ( ) ] @ expose ( ) def index ( self , req , resp ) : run_hook . append ( '' ) return '' sub = SubSubController ( ) class RootController ( object ) : @ expose ( ) def index ( self , req , resp ) : run_hook . append ( '' ) return '' sub = SubController ( ) app = TestApp ( Pecan ( RootController ( ) , use_context_locals = False ) ) response = app . get ( '' ) assert response . status_int == assert response . body == b_ ( '' ) assert len ( run_hook ) == assert run_hook [ ] == '' run_hook = [ ] response = app . get ( '' ) assert response . status_int == assert response . body == b_ ( '' ) assert len ( run_hook ) == assert run_hook [ ] == '' assert run_hook [ ] == '' assert run_hook [ ] == '' run_hook = [ ] response = app . get ( '' ) assert response . status_int == assert response . body == b_ ( '' ) assert len ( run_hook ) == assert run_hook [ ] == '' assert run_hook [ ] == '' assert run_hook [ ] == '' def test_isolated_hook_with_global_hook ( self ) : run_hook = [ ] class SimpleHook ( PecanHook ) : def __init__ ( self , id ) : self . id = str ( id ) def on_route ( self , state ) : run_hook . append ( '' + self . id ) def before ( self , state ) : run_hook . append ( '' + self . id ) def after ( self , state ) : run_hook . append ( '' + self . id ) def on_error ( self , state , e ) : run_hook . append ( '' + self . id ) class SubController ( HookController ) : __hooks__ = [ SimpleHook ( ) ] @ expose ( ) def index ( self , req , resp ) : run_hook . append ( '' ) return '' class RootController ( object ) : @ expose ( ) def index ( self , req , resp ) : run_hook . append ( '' ) return '' sub = SubController ( ) app = TestApp ( Pecan ( RootController ( ) , hooks = [ SimpleHook ( ) ] , use_context_locals = False ) ) response = app . get ( '' ) assert response . status_int == assert response . body == b_ ( '' ) assert len ( run_hook ) == assert run_hook [ ] == '' assert run_hook [ ] == '' assert run_hook [ ] == '' assert run_hook [ ] == '' run_hook = [ ] response = app . get ( '' ) assert response . status_int == assert response . body == b_ ( '' ) assert len ( run_hook ) == assert run_hook [ ] == '' assert run_hook [ ] == '' assert run_hook [ ] == '' assert run_hook [ ] == '' assert run_hook [ ] == '' assert run_hook [ ] == '' class TestGeneric ( PecanTestCase ) : @ property def root ( self ) : class RootController ( object ) : def __init__ ( self , unique ) : self . unique = unique @ expose ( generic = True , template = '' ) def index ( self , req , resp ) : assert self . __class__ . __name__ == '' assert isinstance ( req , Request ) assert isinstance ( resp , Response ) assert self . unique == req . headers . get ( '' ) return { '' : '' } @ index . when ( method = '' , template = '' ) def index_post ( self , req , resp ) : assert self . __class__ . __name__ == '' assert isinstance ( req , Request ) assert isinstance ( resp , Response ) assert self . unique == req . headers . get ( '' ) return req . json @ expose ( template = '' ) def echo ( self , req , resp ) : assert self . __class__ . __name__ == '' assert isinstance ( req , Request ) assert isinstance ( resp , Response ) assert self . unique == req . headers . get ( '' ) return req . json @ expose ( template = '' ) def extra ( self , req , resp , first , second ) : assert self . __class__ . __name__ == '' assert isinstance ( req , Request ) assert isinstance ( resp , Response ) assert self . unique == req . headers . get ( '' ) return { '' : first , '' : second } return RootController def test_generics_with_im_self_default ( self ) : uniq = str ( time . time ( ) ) with mock . patch ( '' , side_effect = AssertionError ( ) ) : app = TestApp ( Pecan ( self . root ( uniq ) , use_context_locals = False ) ) r = app . get ( '' , headers = { '' : uniq } ) assert r . status_int == json_resp = loads ( r . body . decode ( ) ) assert json_resp [ '' ] == '' def test_generics_with_im_self_with_method ( self ) : uniq = str ( time . time ( ) ) with mock . patch ( '' , side_effect = AssertionError ( ) ) : app = TestApp ( Pecan ( self . root ( uniq ) , use_context_locals = False ) ) r = app . post_json ( '' , { '' : '' } , headers = { '' : uniq } ) assert r . status_int == json_resp = loads ( r . body . decode ( ) ) assert json_resp [ '' ] == '' def test_generics_with_im_self_with_path ( self ) : uniq = str ( time . time ( ) ) with mock . patch ( '' , side_effect = AssertionError ( ) ) : app = TestApp ( Pecan ( self . root ( uniq ) , use_context_locals = False ) ) r = app . post_json ( '' , { '' : '' } , headers = { '' : uniq } ) ", "answer": "assert r . status_int == "}, {"prompt": " pluginName = \"\" ", "answer": "enable = False"}, {"prompt": " \"\"\"\"\"\" import sys from twisted . internet import threads from twisted . python import reflect , log class ConnectionLost ( Exception ) : \"\"\"\"\"\" class Connection ( object ) : \"\"\"\"\"\" def __init__ ( self , pool ) : self . _pool = pool self . _connection = None self . reconnect ( ) def close ( self ) : pass def rollback ( self ) : if not self . _pool . reconnect : self . _connection . rollback ( ) return try : self . _connection . rollback ( ) curs = self . _connection . cursor ( ) curs . execute ( self . _pool . good_sql ) curs . close ( ) self . _connection . commit ( ) return except : log . err ( None , \"\" ) self . _pool . disconnect ( self . _connection ) if self . _pool . noisy : log . msg ( \"\" ) raise ConnectionLost ( ) def reconnect ( self ) : if self . _connection is not None : self . _pool . disconnect ( self . _connection ) self . _connection = self . _pool . connect ( ) def __getattr__ ( self , name ) : return getattr ( self . _connection , name ) class Transaction : \"\"\"\"\"\" _cursor = None def __init__ ( self , pool , connection ) : self . _pool = pool self . _connection = connection self . reopen ( ) def close ( self ) : _cursor = self . _cursor self . _cursor = None _cursor . close ( ) def reopen ( self ) : if self . _cursor is not None : self . close ( ) try : self . _cursor = self . _connection . cursor ( ) return except : if not self . _pool . reconnect : raise else : log . err ( None , \"\" ) if self . _pool . noisy : log . msg ( '' ) self . reconnect ( ) self . _cursor = self . _connection . cursor ( ) def reconnect ( self ) : self . _connection . reconnect ( ) self . _cursor = None def __getattr__ ( self , name ) : return getattr ( self . _cursor , name ) ", "answer": "class ConnectionPool :"}, {"prompt": " from google . protobuf import descriptor as _descriptor from google . protobuf import message as _message from google . protobuf import reflection as _reflection from google . protobuf import descriptor_pb2 import groundstation . objects . base_object_pb2 DESCRIPTOR = _descriptor . FileDescriptor ( name = '' , package = '' , serialized_pb = '' ) _UPDATEOBJECT = _descriptor . Descriptor ( name = '' , full_name = '' , filename = None , file = DESCRIPTOR , containing_type = None , fields = [ _descriptor . FieldDescriptor ( name = '' , full_name = '' , index = , number = , type = , cpp_type = , label = , has_default_value = False , default_value = [ ] , message_type = None , enum_type = None , containing_type = None , is_extension = False , extension_scope = None , options = None ) , _descriptor . FieldDescriptor ( name = '' , full_name = '' , index = , number = , type = , cpp_type = , label = , has_default_value = False , default_value = \"\" , message_type = None , enum_type = None , containing_type = None , is_extension = False , extension_scope = None , ", "answer": "options = None ) ,"}, {"prompt": " from __future__ import unicode_literals , division \"\"\"\"\"\" __author__ = \"\" __version__ = \"\" __maintainer__ = \"\" __email__ = \"\" __status__ = \"\" __date__ = \"\" import subprocess import os import shutil import math import logging from pymatgen . io . vasp import VaspInput , Incar , Poscar , Outcar , Kpoints from pymatgen . io . smart import read_structure from pymatgen . io . vasp . sets import MITVaspInputSet from monty . json import MontyDecoder from monty . os . path import which from custodian . custodian import Job from custodian . vasp . interpreter import VaspModder VASP_INPUT_FILES = { \"\" , \"\" , \"\" , \"\" } VASP_OUTPUT_FILES = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ] class VaspJob ( Job ) : \"\"\"\"\"\" def __init__ ( self , vasp_cmd , output_file = \"\" , suffix = \"\" , final = True , backup = True , default_vasp_input_set = MITVaspInputSet ( ) , auto_npar = True , auto_gamma = True , settings_override = None , gamma_vasp_cmd = None , copy_magmom = False ) : \"\"\"\"\"\" self . vasp_cmd = vasp_cmd self . output_file = output_file self . final = final self . backup = backup self . default_vis = default_vasp_input_set self . suffix = suffix self . settings_override = settings_override self . auto_npar = auto_npar self . auto_gamma = auto_gamma self . gamma_vasp_cmd = gamma_vasp_cmd self . copy_magmom = copy_magmom def setup ( self ) : \"\"\"\"\"\" files = os . listdir ( \"\" ) num_structures = if not set ( files ) . issuperset ( VASP_INPUT_FILES ) : for f in files : try : struct = read_structure ( f ) num_structures += except : pass if num_structures != : raise RuntimeError ( \"\" . format ( num_structures ) ) else : self . default_vis . write_input ( struct , \"\" ) if self . backup : for f in VASP_INPUT_FILES : shutil . copy ( f , \"\" . format ( f ) ) if self . auto_npar : try : incar = Incar . from_file ( \"\" ) if not ( incar . get ( \"\" ) or incar . get ( \"\" ) or incar . get ( \"\" ) ) : if incar . get ( \"\" ) in [ , , , ] : del incar [ \"\" ] else : import multiprocessing ncores = os . environ . get ( '' ) or multiprocessing . cpu_count ( ) ncores = int ( ncores ) for npar in range ( int ( math . sqrt ( ncores ) ) , ncores ) : if ncores % npar == : incar [ \"\" ] = npar break incar . write_file ( \"\" ) except : pass if self . settings_override is not None : VaspModder ( ) . apply_actions ( self . settings_override ) def run ( self ) : \"\"\"\"\"\" cmd = list ( self . vasp_cmd ) if self . auto_gamma : vi = VaspInput . from_directory ( \"\" ) kpts = vi [ \"\" ] if kpts . style == Kpoints . supported_modes . Gamma and tuple ( kpts . kpts [ ] ) == ( , , ) : if self . gamma_vasp_cmd is not None and which ( self . gamma_vasp_cmd [ - ] ) : cmd = self . gamma_vasp_cmd elif which ( cmd [ - ] + \"\" ) : cmd [ - ] += \"\" logging . info ( \"\" . format ( \"\" . join ( cmd ) ) ) with open ( self . output_file , '' ) as f : p = subprocess . Popen ( cmd , stdout = f ) return p def postprocess ( self ) : \"\"\"\"\"\" for f in VASP_OUTPUT_FILES + [ self . output_file ] : if os . path . exists ( f ) : if self . final and self . suffix != \"\" : shutil . move ( f , \"\" . format ( f , self . suffix ) ) elif self . suffix != \"\" : shutil . copy ( f , \"\" . format ( f , self . suffix ) ) if self . copy_magmom and not self . final : try : outcar = Outcar ( \"\" ) magmom = [ m [ '' ] for m in outcar . magnetization ] incar = Incar . from_file ( \"\" ) incar [ '' ] = magmom incar . write_file ( \"\" ) except : logging . error ( '' ) @ classmethod def double_relaxation_run ( cls , vasp_cmd , auto_npar = True ) : \"\"\"\"\"\" return [ VaspJob ( vasp_cmd , final = False , suffix = \"\" , auto_npar = auto_npar ) , VaspJob ( vasp_cmd , final = True , backup = False , suffix = \"\" , auto_npar = auto_npar , settings_override = [ { \"\" : \"\" , \"\" : { \"\" : { \"\" : } } } , { \"\" : \"\" , \"\" : { \"\" : { \"\" : \"\" } } } ] ) ] @ classmethod def full_opt_run ( cls , vasp_cmd , auto_npar = True , vol_change_tol = , max_steps = ) : \"\"\"\"\"\" for i in xrange ( max_steps ) : if i == : settings = None backup = True else : backup = False initial = Poscar . from_file ( \"\" ) . structure final = Poscar . from_file ( \"\" ) . structure vol_change = ( final . volume - initial . volume ) / initial . volume logging . info ( \"\" % ( vol_change * ) ) if abs ( vol_change ) < vol_change_tol : logging . info ( \"\" ) break else : settings = [ { \"\" : \"\" , \"\" : { \"\" : { \"\" : } } } , { \"\" : \"\" , \"\" : { \"\" : { \"\" : \"\" } } } ] logging . info ( \"\" % ( i + ) ) yield VaspJob ( vasp_cmd , final = False , backup = backup , suffix = \"\" % ( i + ) , auto_npar = auto_npar , settings_override = settings ) def as_dict ( self ) : d = dict ( vasp_cmd = self . vasp_cmd , output_file = self . output_file , suffix = self . suffix , final = self . final , backup = self . backup , default_vasp_input_set = self . default_vis . as_dict ( ) , auto_npar = self . auto_npar , auto_gamma = self . auto_gamma , settings_override = self . settings_override , gamma_vasp_cmd = self . gamma_vasp_cmd ) d [ \"\" ] = self . __class__ . __module__ d [ \"\" ] = self . __class__ . __name__ return d @ classmethod def from_dict ( cls , d ) : vis = MontyDecoder ( ) . process_decoded ( d [ \"\" ] ) return VaspJob ( vasp_cmd = d [ \"\" ] , output_file = d [ \"\" ] , ", "answer": "suffix = d [ \"\" ] , final = d [ \"\" ] ,"}, {"prompt": " import mock import libvirt import difflib import unittest from see . context . resources import qemu def compare ( text1 , text2 ) : \"\"\"\"\"\" diff = difflib . ndiff ( str ( text1 ) . splitlines ( True ) , str ( text2 ) . splitlines ( True ) ) return '' + '' . join ( diff ) class DomainXMLTest ( unittest . TestCase ) : def test_domain_xml ( self ) : \"\"\"\"\"\" config = \"\"\"\"\"\" expected = \"\"\"\"\"\" + \"\"\"\"\"\" results = qemu . domain_xml ( '' , config , '' ) self . assertEqual ( results , expected , compare ( results , expected ) ) def test_domain_xml_modifies ( self ) : \"\"\"\"\"\" config = \"\"\"\"\"\" + \"\"\"\"\"\" expected = \"\"\"\"\"\" + \"\"\"\"\"\" results = qemu . domain_xml ( '' , config , '' ) self . assertEqual ( results , expected , compare ( results , expected ) ) def test_domain_xml_network ( self ) : \"\"\"\"\"\" config = \"\"\"\"\"\" expected = \"\"\"\"\"\" + \"\"\"\"\"\" + \"\"\"\"\"\" results = qemu . domain_xml ( '' , config , '' , network_name = '' ) self . assertEqual ( results , expected , compare ( results , expected ) ) def test_domain_xml_network_modifies ( self ) : \"\"\"\"\"\" config = \"\"\"\"\"\" + \"\"\"\"\"\" expected = \"\"\"\"\"\" + \"\"\"\"\"\" + \"\"\"\"\"\" results = qemu . domain_xml ( '' , config , '' , network_name = '' ) self . assertEqual ( results , expected , compare ( results , expected ) ) class DiskXMLTest ( unittest . TestCase ) : def test_disk_xml ( self ) : \"\"\"\"\"\" pool_config = \"\"\"\"\"\" disk_config = \"\"\"\"\"\" expected = \"\"\"\"\"\" results = qemu . disk_xml ( '' , pool_config , disk_config , False ) self . assertEqual ( results , expected , compare ( results , expected ) ) def test_disk_xml_modifies ( self ) : \"\"\"\"\"\" pool_config = \"\"\"\"\"\" disk_config = \"\"\"\"\"\" + \"\"\"\"\"\" expected = \"\"\"\"\"\" results = qemu . disk_xml ( '' , pool_config , disk_config , False ) self . assertEqual ( results , expected , compare ( results , expected ) ) def test_disk_cow ( self ) : \"\"\"\"\"\" pool_config = \"\"\"\"\"\" disk_config = \"\"\"\"\"\" expected = \"\"\"\"\"\" + \"\"\"\"\"\" + \"\"\"\"\"\" + \"\"\"\"\"\" + \"\"\"\"\"\" results = qemu . disk_xml ( '' , pool_config , disk_config , True ) results = results . replace ( '' , '' ) . replace ( '' , '' ) . replace ( '' , '' ) self . assertEqual ( results , expected , compare ( results , expected ) ) class DomainCreateTest ( unittest . TestCase ) : def test_create ( self ) : \"\"\"\"\"\" xml = \"\"\"\"\"\" expected = \"\"\"\"\"\" + \"\"\"\"\"\" hypervisor = mock . Mock ( ) hypervisor . listNetworks . return_value = [ ] with mock . patch ( '' , mock . mock_open ( read_data = xml ) , create = True ) : qemu . domain_create ( hypervisor , '' , { '' : '' } , '' ) results = hypervisor . defineXML . call_args_list [ ] [ ] [ ] self . assertEqual ( results , expected , compare ( results , expected ) ) def test_create_network ( self ) : \"\"\"\"\"\" xml = \"\"\"\"\"\" expected = \"\"\"\"\"\" + \"\"\"\"\"\" + \"\"\"\"\"\" hypervisor = mock . Mock ( ) hypervisor . listNetworks . return_value = [ ] with mock . patch ( '' , mock . mock_open ( read_data = xml ) , create = True ) : qemu . domain_create ( hypervisor , '' , { '' : '' } , '' , network_name = '' ) results = hypervisor . defineXML . call_args_list [ ] [ ] [ ] self . assertEqual ( results , expected , compare ( results , expected ) ) class DomainDeleteTest ( unittest . TestCase ) : def test_delete_destroy ( self ) : \"\"\"\"\"\" domain = mock . Mock ( ) logger = mock . Mock ( ) domain . isActive . return_value = True qemu . domain_delete ( domain , logger ) self . assertTrue ( domain . destroy . called ) def test_delete_destroy_error ( self ) : \"\"\"\"\"\" domain = mock . Mock ( ) logger = mock . Mock ( ) domain . isActive . return_value = True domain . destroy . side_effect = libvirt . libvirtError ( \"\" ) qemu . domain_delete ( domain , logger ) self . assertTrue ( domain . undefineFlags . called ) def test_delete_undefine ( self ) : \"\"\"\"\"\" domain = mock . Mock ( ) logger = mock . Mock ( ) domain . isActive . return_value = False qemu . domain_delete ( domain , logger ) self . assertTrue ( domain . undefineFlags . called ) def test_delete_undefine_snapshots ( self ) : \"\"\"\"\"\" domain = mock . Mock ( ) logger = mock . Mock ( ) domain . isActive . return_value = False qemu . domain_delete ( domain , logger ) domain . undefineFlags . assert_called_with ( libvirt . VIR_DOMAIN_UNDEFINE_SNAPSHOTS_METADATA ) class PoolCreateTest ( unittest . TestCase ) : @ mock . patch ( '' ) @ mock . patch ( '' ) def test_create ( self , exists_mock , makedirs ) : \"\"\"\"\"\" expected = \"\"\"\"\"\" + \"\"\"\"\"\" hypervisor = mock . Mock ( ) exists_mock . return_value = False qemu . pool_create ( hypervisor , '' , '' ) results = hypervisor . storagePoolCreateXML . call_args_list [ ] [ ] [ ] results = results . replace ( '' , '' ) . replace ( '' , '' ) . replace ( '' , '' ) makedirs . assert_called_with ( '' ) self . assertEqual ( results , expected , compare ( results , expected ) ) ", "answer": "class PoolDeleteTest ( unittest . TestCase ) :"}, {"prompt": " import os from ConfigParser import SafeConfigParser , NoOptionError def abs_path ( path ) : path = os . path . expanduser ( path ) path = os . path . abspath ( path ) return path def config_option ( fn , section , option ) : try : return fn ( section , option ) ", "answer": "except NoOptionError :"}, {"prompt": " from django . contrib . comments . models import Comment , FreeComment from django . contrib . comments . models import PHOTOS_REQUIRED , PHOTOS_OPTIONAL , RATINGS_REQUIRED , RATINGS_OPTIONAL , IS_PUBLIC from django . contrib . comments . models import MIN_PHOTO_DIMENSION , MAX_PHOTO_DIMENSION from django import template from django . template import loader from django . core . exceptions import ObjectDoesNotExist from django . contrib . contenttypes . models import ContentType import re register = template . Library ( ) COMMENT_FORM = '' FREE_COMMENT_FORM = '' class CommentFormNode ( template . Node ) : def __init__ ( self , content_type , obj_id_lookup_var , obj_id , free , photos_optional = False , photos_required = False , photo_options = '' , ratings_optional = False , ratings_required = False , rating_options = '' , is_public = True ) : self . content_type = content_type self . obj_id_lookup_var , self . obj_id , self . free = obj_id_lookup_var , obj_id , free self . photos_optional , self . photos_required = photos_optional , photos_required self . ratings_optional , self . ratings_required = ratings_optional , ratings_required self . photo_options , self . rating_options = photo_options , rating_options self . is_public = is_public def render ( self , context ) : from django . utils . text import normalize_newlines import base64 context . push ( ) if self . obj_id_lookup_var is not None : try : self . obj_id = template . resolve_variable ( self . obj_id_lookup_var , context ) except template . VariableDoesNotExist : return '' try : self . content_type . get_object_for_this_type ( pk = self . obj_id ) except ObjectDoesNotExist : context [ '' ] = False else : context [ '' ] = True else : context [ '' ] = True context [ '' ] = '' % ( self . content_type . id , self . obj_id ) options = [ ] for var , abbr in ( ( '' , PHOTOS_REQUIRED ) , ( '' , PHOTOS_OPTIONAL ) , ( '' , RATINGS_REQUIRED ) , ( '' , RATINGS_OPTIONAL ) , ( '' , IS_PUBLIC ) ) : context [ var ] = getattr ( self , var ) if getattr ( self , var ) : options . append ( abbr ) context [ '' ] = '' . join ( options ) if self . free : context [ '' ] = Comment . objects . get_security_hash ( context [ '' ] , '' , '' , context [ '' ] ) default_form = loader . get_template ( FREE_COMMENT_FORM ) else : context [ '' ] = self . photo_options context [ '' ] = normalize_newlines ( base64 . encodestring ( self . rating_options ) . strip ( ) ) if self . rating_options : context [ '' ] , context [ '' ] = Comment . objects . get_rating_options ( self . rating_options ) context [ '' ] = Comment . objects . get_security_hash ( context [ '' ] , context [ '' ] , context [ '' ] , context [ '' ] ) default_form = loader . get_template ( COMMENT_FORM ) output = default_form . render ( context ) context . pop ( ) return output class CommentCountNode ( template . Node ) : def __init__ ( self , package , module , context_var_name , obj_id , var_name , free ) : self . package , self . module = package , module self . context_var_name , self . obj_id = context_var_name , obj_id self . var_name , self . free = var_name , free def render ( self , context ) : from django . conf import settings manager = self . free and FreeComment . objects or Comment . objects if self . context_var_name is not None : self . obj_id = template . resolve_variable ( self . context_var_name , context ) comment_count = manager . filter ( object_id__exact = self . obj_id , content_type__app_label__exact = self . package , content_type__model__exact = self . module , site__id__exact = settings . SITE_ID ) . count ( ) context [ self . var_name ] = comment_count return '' class CommentListNode ( template . Node ) : def __init__ ( self , package , module , context_var_name , obj_id , var_name , free , ordering , extra_kwargs = None ) : self . package , self . module = package , module self . context_var_name , self . obj_id = context_var_name , obj_id self . var_name , self . free = var_name , free self . ordering = ordering self . extra_kwargs = extra_kwargs or { } def render ( self , context ) : from django . conf import settings get_list_function = self . free and FreeComment . objects . filter or Comment . objects . get_list_with_karma if self . context_var_name is not None : try : self . obj_id = template . resolve_variable ( self . context_var_name , context ) except template . VariableDoesNotExist : return '' kwargs = { '' : self . obj_id , '' : self . package , '' : self . module , '' : settings . SITE_ID , } kwargs . update ( self . extra_kwargs ) if not self . free and settings . COMMENTS_BANNED_USERS_GROUP : kwargs [ '' ] = { '' : '' % settings . COMMENTS_BANNED_USERS_GROUP } comment_list = get_list_function ( ** kwargs ) . order_by ( self . ordering + '' ) . select_related ( ) if not self . free : if context . has_key ( '' ) and context [ '' ] . is_authenticated ( ) : user_id = context [ '' ] . id context [ '' ] = Comment . objects . user_is_moderator ( context [ '' ] ) else : user_id = None context [ '' ] = False if settings . COMMENTS_BANNED_USERS_GROUP : comment_list = [ c for c in comment_list if not c . is_hidden or ( user_id == c . user_id ) ] context [ self . var_name ] = comment_list return '' class DoCommentForm : \"\"\"\"\"\" def __init__ ( self , free ) : self . free = free def __call__ ( self , parser , token ) : tokens = token . contents . split ( ) ", "answer": "if len ( tokens ) < :"}, {"prompt": " \"\"\"\"\"\" try : import boto BOTO_INSTALLED = True except ImportError : BOTO_INSTALLED = False try : import gevent . monkey gevent . monkey . patch_all ( ) GEVENT_INSTALLED = True except ImportError : GEVENT_INSTALLED = False import io import mimetypes import os from flask import copy_current_request_context , current_app from flask_store . exceptions import NotConfiguredError from flask_store . providers import Provider from flask_store . providers . temp import TemporaryStore from werkzeug . datastructures import FileStorage class S3Provider ( Provider ) : \"\"\"\"\"\" REQUIRED_CONFIGURATION = [ '' , '' , '' , '' ] @ staticmethod def app_defaults ( app ) : \"\"\"\"\"\" app . config . setdefault ( '' , '' ) app . config . setdefault ( '' , app . config [ '' ] ) app . config . setdefault ( '' , '' ) if not BOTO_INSTALLED : raise ImportError ( '' '' ) def connect ( self ) : \"\"\"\"\"\" if not hasattr ( self , '' ) : s3connection = boto . s3 . connect_to_region ( current_app . config [ '' ] , aws_access_key_id = current_app . config [ '' ] , aws_secret_access_key = current_app . config [ '' ] ) setattr ( self , '' , s3connection ) return getattr ( self , '' ) def bucket ( self , s3connection ) : \"\"\"\"\"\" return s3connection . get_bucket ( current_app . config . get ( '' ) ) def join ( self , * parts ) : \"\"\"\"\"\" return self . url_join ( * parts ) def exists ( self , filename ) : \"\"\"\"\"\" s3connection = self . connect ( ) bucket = self . bucket ( s3connection ) path = self . join ( self . store_path , filename ) key = boto . s3 . key . Key ( name = path , bucket = bucket ) return key . exists ( ) def save ( self ) : \"\"\"\"\"\" fp = self . fp s3connection = self . connect ( ) bucket = self . bucket ( s3connection ) filename = self . safe_filename ( self . filename ) path = self . join ( self . store_path , filename ) mimetype , encoding = mimetypes . guess_type ( filename ) fp . seek ( ) key = bucket . new_key ( path ) key . set_metadata ( '' , mimetype ) key . set_contents_from_file ( fp ) key . set_acl ( current_app . config . get ( '' ) ) self . filename = filename def open ( self ) : \"\"\"\"\"\" s3connection = self . connect ( ) bucket = self . bucket ( s3connection ) key = bucket . get_key ( self . relative_path ) if not key : raise IOError ( '' . format ( self . relative_path ) ) return io . BytesIO ( key . read ( ) ) class S3GeventProvider ( S3Provider ) : \"\"\"\"\"\" def __init__ ( self , * args , ** kwargs ) : \"\"\"\"\"\" if not GEVENT_INSTALLED : raise NotConfiguredError ( '' ) super ( S3GeventProvider , self ) . __init__ ( * args , ** kwargs ) def save ( self ) : \"\"\"\"\"\" fp = self . fp temp = TemporaryStore ( fp ) path = temp . save ( ) filename = self . safe_filename ( fp . filename ) @ copy_current_request_context def _save ( ) : self . fp = FileStorage ( stream = open ( path , '' ) , filename = filename , name = fp . name , content_type = fp . content_type , content_length = fp . content_length , headers = fp . headers ) ", "answer": "super ( S3GeventProvider , self ) . save ( )"}, {"prompt": " from SipFrom import SipFrom class SipRecordRoute ( SipFrom ) : ", "answer": "hf_names = ( '' , )"}, {"prompt": " from . models import Message def soapbox_messages ( request ) : \"\"\"\"\"\" return { '' : Message . objects . match ( request . path ) ", "answer": "} "}, {"prompt": " import urlparse import urllib import cgi import hashlib from six import moves from w3lib . util import unicode_to_str _ALWAYS_SAFE_BYTES = ( b'' b'' b'' b'' ) _reserved = b'' _unreserved_marks = b\"\" _safe_chars = _ALWAYS_SAFE_BYTES + b'' + _reserved + _unreserved_marks def parse_url ( url , encoding = None ) : \"\"\"\"\"\" return url if isinstance ( url , urlparse . ParseResult ) else urlparse . urlparse ( unicode_to_str ( url , encoding ) ) def parse_domain_from_url ( url ) : \"\"\"\"\"\" import tldextract extracted = tldextract . extract ( url ) scheme , _ , _ , _ , _ , _ = parse_url ( url ) sld = extracted . domain tld = extracted . suffix subdomain = extracted . subdomain name = '' . join ( [ sld , tld ] ) if tld else sld netloc = '' . join ( [ subdomain , name ] ) if subdomain else name return netloc , name , scheme , sld , tld , subdomain def parse_domain_from_url_fast ( url ) : \"\"\"\"\"\" result = parse_url ( url ) return result . netloc , result . hostname , result . scheme , \"\" , \"\" , \"\" def safe_url_string ( url , encoding = '' ) : \"\"\"\"\"\" s = unicode_to_str ( url , encoding ) return moves . urllib . parse . quote ( s , _safe_chars ) def _unquotepath ( path ) : for reserved in ( '' , '' , '' , '' ) : path = path . replace ( '' + reserved , '' + reserved . upper ( ) ) return urllib . unquote ( path ) def canonicalize_url ( url , keep_blank_values = True , keep_fragments = False ) : \"\"\"\"\"\" scheme , netloc , path , params , query , fragment = parse_url ( url ) keyvals = cgi . parse_qsl ( query , keep_blank_values ) keyvals . sort ( ) ", "answer": "query = urllib . urlencode ( keyvals )"}, {"prompt": " from atom . api import Int , Typed from enaml . widgets . object_combo import ProxyObjectCombo from . QtCore import QTimer from . QtGui import QComboBox from . q_resource_helpers import get_cached_qicon from . qt_control import QtControl SELECTED_GUARD = class ComboRefreshTimer ( QTimer ) : \"\"\"\"\"\" def __init__ ( self , owner ) : \"\"\"\"\"\" super ( ComboRefreshTimer , self ) . __init__ ( ) self . setSingleShot ( True ) self . owner = owner def timerEvent ( self , event ) : \"\"\"\"\"\" super ( ComboRefreshTimer , self ) . timerEvent ( event ) ", "answer": "owner = self . owner"}, {"prompt": " from thrift . Thrift import * from thrift . transport import TTransport from thrift . protocol import TBinaryProtocol try : from thrift . protocol import fastbinary except : fastbinary = None class TCell : \"\"\"\"\"\" thrift_spec = ( None , ( , TType . STRING , '' , None , None , ) , ( , TType . I64 , '' , None , None , ) , ) def __init__ ( self , value = None , timestamp = None , ) : self . value = value self . timestamp = timestamp def read ( self , iprot ) : if iprot . __class__ == TBinaryProtocol . TBinaryProtocolAccelerated and isinstance ( iprot . trans , TTransport . CReadableTransport ) and self . thrift_spec is not None and fastbinary is not None : fastbinary . decode_binary ( self , iprot . trans , ( self . __class__ , self . thrift_spec ) ) return iprot . readStructBegin ( ) while True : ( fname , ftype , fid ) = iprot . readFieldBegin ( ) if ftype == TType . STOP : break if fid == : if ftype == TType . STRING : self . value = iprot . readString ( ) ; else : iprot . skip ( ftype ) elif fid == : if ftype == TType . I64 : self . timestamp = iprot . readI64 ( ) ; else : iprot . skip ( ftype ) else : iprot . skip ( ftype ) iprot . readFieldEnd ( ) iprot . readStructEnd ( ) def write ( self , oprot ) : if oprot . __class__ == TBinaryProtocol . TBinaryProtocolAccelerated and self . thrift_spec is not None and fastbinary is not None : oprot . trans . write ( fastbinary . encode_binary ( self , ( self . __class__ , self . thrift_spec ) ) ) return oprot . writeStructBegin ( '' ) if self . value != None : oprot . writeFieldBegin ( '' , TType . STRING , ) oprot . writeString ( self . value ) oprot . writeFieldEnd ( ) if self . timestamp != None : oprot . writeFieldBegin ( '' , TType . I64 , ) oprot . writeI64 ( self . timestamp ) oprot . writeFieldEnd ( ) oprot . writeFieldStop ( ) oprot . writeStructEnd ( ) def __repr__ ( self ) : L = [ '' % ( key , value ) for key , value in self . __dict__ . iteritems ( ) ] return '' % ( self . __class__ . __name__ , '' . join ( L ) ) def __eq__ ( self , other ) : return isinstance ( other , self . __class__ ) and self . __dict__ == other . __dict__ def __ne__ ( self , other ) : return not ( self == other ) class ColumnDescriptor : \"\"\"\"\"\" thrift_spec = ( None , ( , TType . STRING , '' , None , None , ) , ( , TType . I32 , '' , None , , ) , ( , TType . STRING , '' , None , \"\" , ) , ( , TType . BOOL , '' , None , False , ) , ( , TType . I32 , '' , None , , ) , ( , TType . STRING , '' , None , \"\" , ) , ( , TType . I32 , '' , None , , ) , ( , TType . I32 , '' , None , , ) , ( , TType . BOOL , '' , None , False , ) , ( , TType . I32 , '' , None , - , ) , ) def __init__ ( self , name = None , maxVersions = thrift_spec [ ] [ ] , compression = thrift_spec [ ] [ ] , inMemory = thrift_spec [ ] [ ] , maxValueLength = thrift_spec [ ] [ ] , bloomFilterType = thrift_spec [ ] [ ] , bloomFilterVectorSize = thrift_spec [ ] [ ] , bloomFilterNbHashes = thrift_spec [ ] [ ] , blockCacheEnabled = thrift_spec [ ] [ ] , timeToLive = thrift_spec [ ] [ ] , ) : self . name = name self . maxVersions = maxVersions self . compression = compression self . inMemory = inMemory self . maxValueLength = maxValueLength self . bloomFilterType = bloomFilterType self . bloomFilterVectorSize = bloomFilterVectorSize self . bloomFilterNbHashes = bloomFilterNbHashes self . blockCacheEnabled = blockCacheEnabled self . timeToLive = timeToLive def read ( self , iprot ) : if iprot . __class__ == TBinaryProtocol . TBinaryProtocolAccelerated and isinstance ( iprot . trans , TTransport . CReadableTransport ) and self . thrift_spec is not None and fastbinary is not None : fastbinary . decode_binary ( self , iprot . trans , ( self . __class__ , self . thrift_spec ) ) return iprot . readStructBegin ( ) while True : ( fname , ftype , fid ) = iprot . readFieldBegin ( ) if ftype == TType . STOP : break if fid == : if ftype == TType . STRING : self . name = iprot . readString ( ) ; else : iprot . skip ( ftype ) elif fid == : if ftype == TType . I32 : self . maxVersions = iprot . readI32 ( ) ; else : iprot . skip ( ftype ) elif fid == : if ftype == TType . STRING : self . compression = iprot . readString ( ) ; else : iprot . skip ( ftype ) elif fid == : if ftype == TType . BOOL : self . inMemory = iprot . readBool ( ) ; else : iprot . skip ( ftype ) elif fid == : if ftype == TType . I32 : self . maxValueLength = iprot . readI32 ( ) ; else : iprot . skip ( ftype ) elif fid == : if ftype == TType . STRING : self . bloomFilterType = iprot . readString ( ) ; else : iprot . skip ( ftype ) elif fid == : if ftype == TType . I32 : self . bloomFilterVectorSize = iprot . readI32 ( ) ; else : iprot . skip ( ftype ) elif fid == : if ftype == TType . I32 : self . bloomFilterNbHashes = iprot . readI32 ( ) ; else : iprot . skip ( ftype ) elif fid == : if ftype == TType . BOOL : self . blockCacheEnabled = iprot . readBool ( ) ; else : iprot . skip ( ftype ) elif fid == : if ftype == TType . I32 : self . timeToLive = iprot . readI32 ( ) ; else : iprot . skip ( ftype ) else : iprot . skip ( ftype ) iprot . readFieldEnd ( ) iprot . readStructEnd ( ) def write ( self , oprot ) : if oprot . __class__ == TBinaryProtocol . TBinaryProtocolAccelerated and self . thrift_spec is not None and fastbinary is not None : oprot . trans . write ( fastbinary . encode_binary ( self , ( self . __class__ , self . thrift_spec ) ) ) return oprot . writeStructBegin ( '' ) if self . name != None : oprot . writeFieldBegin ( '' , TType . STRING , ) oprot . writeString ( self . name ) oprot . writeFieldEnd ( ) if self . maxVersions != None : oprot . writeFieldBegin ( '' , TType . I32 , ) oprot . writeI32 ( self . maxVersions ) oprot . writeFieldEnd ( ) if self . compression != None : oprot . writeFieldBegin ( '' , TType . STRING , ) oprot . writeString ( self . compression ) oprot . writeFieldEnd ( ) if self . inMemory != None : oprot . writeFieldBegin ( '' , TType . BOOL , ) oprot . writeBool ( self . inMemory ) oprot . writeFieldEnd ( ) if self . maxValueLength != None : oprot . writeFieldBegin ( '' , TType . I32 , ) oprot . writeI32 ( self . maxValueLength ) oprot . writeFieldEnd ( ) if self . bloomFilterType != None : oprot . writeFieldBegin ( '' , TType . STRING , ) oprot . writeString ( self . bloomFilterType ) oprot . writeFieldEnd ( ) if self . bloomFilterVectorSize != None : oprot . writeFieldBegin ( '' , TType . I32 , ) oprot . writeI32 ( self . bloomFilterVectorSize ) oprot . writeFieldEnd ( ) if self . bloomFilterNbHashes != None : oprot . writeFieldBegin ( '' , TType . I32 , ) oprot . writeI32 ( self . bloomFilterNbHashes ) oprot . writeFieldEnd ( ) if self . blockCacheEnabled != None : oprot . writeFieldBegin ( '' , TType . BOOL , ) oprot . writeBool ( self . blockCacheEnabled ) oprot . writeFieldEnd ( ) if self . timeToLive != None : oprot . writeFieldBegin ( '' , TType . I32 , ) oprot . writeI32 ( self . timeToLive ) oprot . writeFieldEnd ( ) oprot . writeFieldStop ( ) oprot . writeStructEnd ( ) def __repr__ ( self ) : L = [ '' % ( key , value ) for key , value in self . __dict__ . iteritems ( ) ] return '' % ( self . __class__ . __name__ , '' . join ( L ) ) def __eq__ ( self , other ) : return isinstance ( other , self . __class__ ) and self . __dict__ == other . __dict__ def __ne__ ( self , other ) : return not ( self == other ) class TRegionInfo : \"\"\"\"\"\" thrift_spec = ( None , ( , TType . STRING , '' , None , None , ) , ( , TType . STRING , '' , None , None , ) , ( , TType . I64 , '' , None , None , ) , ( , TType . STRING , '' , None , None , ) , ( , TType . BYTE , '' , None , None , ) , ) def __init__ ( self , startKey = None , endKey = None , id = None , name = None , version = None , ) : self . startKey = startKey self . endKey = endKey self . id = id self . name = name self . version = version def read ( self , iprot ) : if iprot . __class__ == TBinaryProtocol . TBinaryProtocolAccelerated and isinstance ( iprot . trans , TTransport . CReadableTransport ) and self . thrift_spec is not None and fastbinary is not None : fastbinary . decode_binary ( self , iprot . trans , ( self . __class__ , self . thrift_spec ) ) return iprot . readStructBegin ( ) while True : ( fname , ftype , fid ) = iprot . readFieldBegin ( ) if ftype == TType . STOP : break if fid == : if ftype == TType . STRING : self . startKey = iprot . readString ( ) ; else : iprot . skip ( ftype ) elif fid == : if ftype == TType . STRING : self . endKey = iprot . readString ( ) ; else : iprot . skip ( ftype ) elif fid == : if ftype == TType . I64 : self . id = iprot . readI64 ( ) ; else : iprot . skip ( ftype ) elif fid == : if ftype == TType . STRING : self . name = iprot . readString ( ) ; else : iprot . skip ( ftype ) elif fid == : if ftype == TType . BYTE : self . version = iprot . readByte ( ) ; else : iprot . skip ( ftype ) else : iprot . skip ( ftype ) iprot . readFieldEnd ( ) iprot . readStructEnd ( ) def write ( self , oprot ) : if oprot . __class__ == TBinaryProtocol . TBinaryProtocolAccelerated and self . thrift_spec is not None and fastbinary is not None : oprot . trans . write ( fastbinary . encode_binary ( self , ( self . __class__ , self . thrift_spec ) ) ) return oprot . writeStructBegin ( '' ) if self . startKey != None : oprot . writeFieldBegin ( '' , TType . STRING , ) oprot . writeString ( self . startKey ) oprot . writeFieldEnd ( ) if self . endKey != None : oprot . writeFieldBegin ( '' , TType . STRING , ) oprot . writeString ( self . endKey ) oprot . writeFieldEnd ( ) if self . id != None : oprot . writeFieldBegin ( '' , TType . I64 , ) oprot . writeI64 ( self . id ) oprot . writeFieldEnd ( ) if self . name != None : oprot . writeFieldBegin ( '' , TType . STRING , ) oprot . writeString ( self . name ) oprot . writeFieldEnd ( ) if self . version != None : oprot . writeFieldBegin ( '' , TType . BYTE , ) oprot . writeByte ( self . version ) oprot . writeFieldEnd ( ) oprot . writeFieldStop ( ) oprot . writeStructEnd ( ) def __repr__ ( self ) : L = [ '' % ( key , value ) for key , value in self . __dict__ . iteritems ( ) ] return '' % ( self . __class__ . __name__ , '' . join ( L ) ) def __eq__ ( self , other ) : return isinstance ( other , self . __class__ ) and self . __dict__ == other . __dict__ def __ne__ ( self , other ) : return not ( self == other ) class Mutation : \"\"\"\"\"\" thrift_spec = ( None , ( , TType . BOOL , '' , None , False , ) , ( , TType . STRING , '' , None , None , ) , ( , TType . STRING , '' , None , None , ) , ) def __init__ ( self , isDelete = thrift_spec [ ] [ ] , column = None , value = None , ) : self . isDelete = isDelete self . column = column self . value = value def read ( self , iprot ) : if iprot . __class__ == TBinaryProtocol . TBinaryProtocolAccelerated and isinstance ( iprot . trans , TTransport . CReadableTransport ) and self . thrift_spec is not None and fastbinary is not None : fastbinary . decode_binary ( self , iprot . trans , ( self . __class__ , self . thrift_spec ) ) return iprot . readStructBegin ( ) while True : ( fname , ftype , fid ) = iprot . readFieldBegin ( ) if ftype == TType . STOP : break if fid == : if ftype == TType . BOOL : self . isDelete = iprot . readBool ( ) ; else : iprot . skip ( ftype ) elif fid == : if ftype == TType . STRING : self . column = iprot . readString ( ) ; else : iprot . skip ( ftype ) elif fid == : if ftype == TType . STRING : self . value = iprot . readString ( ) ; else : iprot . skip ( ftype ) else : iprot . skip ( ftype ) iprot . readFieldEnd ( ) iprot . readStructEnd ( ) def write ( self , oprot ) : if oprot . __class__ == TBinaryProtocol . TBinaryProtocolAccelerated and self . thrift_spec is not None and fastbinary is not None : oprot . trans . write ( fastbinary . encode_binary ( self , ( self . __class__ , self . thrift_spec ) ) ) return oprot . writeStructBegin ( '' ) if self . isDelete != None : oprot . writeFieldBegin ( '' , TType . BOOL , ) oprot . writeBool ( self . isDelete ) oprot . writeFieldEnd ( ) if self . column != None : oprot . writeFieldBegin ( '' , TType . STRING , ) oprot . writeString ( self . column ) oprot . writeFieldEnd ( ) if self . value != None : oprot . writeFieldBegin ( '' , TType . STRING , ) oprot . writeString ( self . value ) oprot . writeFieldEnd ( ) oprot . writeFieldStop ( ) oprot . writeStructEnd ( ) def __repr__ ( self ) : L = [ '' % ( key , value ) for key , value in self . __dict__ . iteritems ( ) ] ", "answer": "return '' % ( self . __class__ . __name__ , '' . join ( L ) )"}, {"prompt": " from zope . interface import implements from twisted . names import dns , common from twisted . python import failure , log from twisted . internet import interfaces , defer class CacheResolver ( common . ResolverBase ) : \"\"\"\"\"\" implements ( interfaces . IResolver ) cache = None def __init__ ( self , cache = None , verbose = , reactor = None ) : common . ResolverBase . __init__ ( self ) self . cache = { } self . verbose = verbose self . cancel = { } if reactor is None : from twisted . internet import reactor self . _reactor = reactor if cache : for query , ( seconds , payload ) in cache . items ( ) : self . cacheResult ( query , payload , seconds ) def __setstate__ ( self , state ) : self . __dict__ = state now = self . _reactor . seconds ( ) for ( k , ( when , ( ans , add , ns ) ) ) in self . cache . items ( ) : diff = now - when for rec in ans + add + ns : if rec . ttl < diff : del self . cache [ k ] break def __getstate__ ( self ) : for c in self . cancel . values ( ) : c . cancel ( ) self . cancel . clear ( ) return self . __dict__ def _lookup ( self , name , cls , type , timeout ) : now = self . _reactor . seconds ( ) q = dns . Query ( name , type , cls ) try : when , ( ans , auth , add ) = self . cache [ q ] except KeyError : if self . verbose > : log . msg ( '' + repr ( name ) ) return defer . fail ( failure . Failure ( dns . DomainError ( name ) ) ) else : if self . verbose : log . msg ( '' + repr ( name ) ) diff = now - when try : result = ( [ dns . RRHeader ( str ( r . name ) , r . type , r . cls , r . ttl - diff , ", "answer": "r . payload ) for r in ans ] ,"}, {"prompt": " from __future__ import unicode_literals from flask import request , Flask , Blueprint from flask . _compat import reraise , string_types , text_type from flask_api . exceptions import APIException from flask_api . request import APIRequest from flask_api . response import APIResponse from flask_api . settings import APISettings from itertools import chain from werkzeug . exceptions import HTTPException import re import sys api_resources = Blueprint ( '' , __name__ , url_prefix = '' , template_folder = '' , static_folder = '' ) def urlize_quoted_links ( content ) : return re . sub ( r'' , r'' , content ) class FlaskAPI ( Flask ) : request_class = APIRequest response_class = APIResponse def __init__ ( self , * args , ** kwargs ) : super ( FlaskAPI , self ) . __init__ ( * args , ** kwargs ) self . api_settings = APISettings ( self . config ) self . register_blueprint ( api_resources ) self . jinja_env . filters [ '' ] = urlize_quoted_links def preprocess_request ( self ) : request . parser_classes = self . api_settings . DEFAULT_PARSERS request . renderer_classes = self . api_settings . DEFAULT_RENDERERS return super ( FlaskAPI , self ) . preprocess_request ( ) ", "answer": "def make_response ( self , rv ) :"}, {"prompt": " \"\"\"\"\"\" import os , sys , time , logging from subprocess import * import resource import utils from config import settings log = logging . getLogger ( ) blank = '' _threshold = def setrlimit ( ) : \"\"\"\"\"\" resource . setrlimit ( resource . RLIMIT_RSS , ( _threshold , _threshold ) ) class Browser : def __init__ ( self , home = blank ) : \"\"\"\"\"\" self . home = home self . launch ( self . home ) self . do ( '' % home ) def launch ( self , home = blank ) : \"\"\"\"\"\" _threshold = settings . uzbl . ram . hard_limit self . uzbl = Popen ( [ '' , '' % ( settings . screen . width , settings . screen . height ) , '' % home ] , stdin = PIPE , stdout = PIPE , stderr = PIPE , preexec_fn = setrlimit ) self . fifo = '' % self . uzbl . pid while not os . path . exists ( self . fifo ) : time . sleep ( ) self . do ( '' % home ) def terminate ( self ) : \"\"\"\"\"\" self . uzbl . terminate ( ) def kill ( self ) : \"\"\"\"\"\" self . uzbl . kill ( ) ", "answer": "def restart ( self ) :"}, {"prompt": " import warnings ", "answer": "warnings . warn ( \"\" , DeprecationWarning ) "}, {"prompt": " from atom . api import Typed , ForwardTyped , Unicode , Bool , Event , observe ", "answer": "from enaml . core . declarative import d_"}, {"prompt": " \"\"\"\"\"\" from django . db import models , DEFAULT_DB_ALIAS class Article ( models . Model ) : headline = models . CharField ( max_length = , default = '' ) pub_date = models . DateTimeField ( ) class Meta : ", "answer": "ordering = ( '' , '' )"}, {"prompt": " import types def format_exception_only ( etype , value ) : \"\"\"\"\"\" if ( isinstance ( etype , BaseException ) or isinstance ( etype , types . InstanceType ) or etype is None or type ( etype ) is str ) : return [ _format_final_exc_line ( etype , value ) ] stype = etype . __name__ if not issubclass ( etype , SyntaxError ) : return [ _format_final_exc_line ( stype , value ) ] lines = [ ] try : msg , ( filename , lineno , offset , badline ) = value . args except Exception : pass else : filename = filename or \"\" ", "answer": "lines . append ( '' % ( filename , lineno ) )"}, {"prompt": " '''''' import time from socket import AF_INET , SOCK_STREAM , socket from thread import start_new import struct HOST = '' PORT = BUFSIZE = ADDR = ( HOST , PORT ) ", "answer": "client = socket ( AF_INET , SOCK_STREAM )"}, {"prompt": " import ALFlib , os , sys , tempfile , time , urllib2 from datetime import datetime from datetime import timedelta class MetarReader ( object ) : \"\"\"\"\"\" version = \"\" obsType = { '' : '' , '' : '' , '' : '' } equipment = { '' : '' , '' : '' , '' : '' , '' : '' } direction = ALFlib . Constants . TrueNorth tendency = { '' : '' , '' : '' , '' : '' } pressureTendency = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' } qualifier = { '' : '' , '' : '>' } intensity = { '' : '' , '' : '' , '' : '' } proximity = { '' : '' , '' : '' } descriptor = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' } conjunction = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' } precipitation = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' } obscuration = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' } other = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' } coverage = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' } totalCloudCover = { '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : } visibilityCode = { '' : { '' : '' , '' : '' } , '' : { '' : '' , '' : '' } , '' : { '' : '' , '' : '' } , '' : { '' : '' , '' : '' } , '' : { '' : '' , '' : '' } , '' : { '' : '' , '' : '' } , '' : { '' : '' , '' : '' } , } remarks = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' } obs = { } orderedObs = [ ] skipped = [ ] weatherStations = None timeStamp = None data = [ ] undecoded = { } verbose = False ", "answer": "totalObs = "}, {"prompt": " \"\"\"\"\"\" from __future__ import unicode_literals import re from django . db import models from django . utils . encoding import force_text from django . utils . functional import Promise from rest_framework . compat import unicode_repr def manager_repr ( value ) : model = value . model opts = model . _meta for _ , name , manager in opts . concrete_managers + opts . abstract_managers : if manager == value : return '' % ( model . _meta . object_name , name ) ", "answer": "return repr ( value )"}, {"prompt": " from nailgun . db . sqlalchemy . models import Cluster from nailgun . orchestrator . provisioning_serializers import ProvisioningSerializer from nailgun . test import base ", "answer": "class TestFaultTolerance ( base . BaseTestCase ) :"}, {"prompt": " from tweepy1 . error import TweepError from tweepy1 . utils import parse_datetime , parse_html_value , parse_a_href , parse_search_datetime , unescape_html class ResultSet ( list ) : \"\"\"\"\"\" def __init__ ( self , max_id = None , since_id = None ) : super ( ResultSet , self ) . __init__ ( ) self . _max_id = max_id self . _since_id = since_id @ property def max_id ( self ) : if self . _max_id : return self . _max_id ids = self . ids ( ) return max ( ids ) if ids else None @ property def since_id ( self ) : if self . _since_id : return self . _since_id ids = self . ids ( ) return min ( ids ) if ids else None def ids ( self ) : return [ item . id for item in self if hasattr ( item , '' ) ] class Model ( object ) : def __init__ ( self , api = None ) : self . _api = api def __getstate__ ( self ) : pickle = dict ( self . __dict__ ) try : del pickle [ '' ] except KeyError : pass return pickle @ classmethod def parse ( cls , api , json ) : \"\"\"\"\"\" raise NotImplementedError @ classmethod def parse_list ( cls , api , json_list ) : \"\"\"\"\"\" results = ResultSet ( ) for obj in json_list : if obj : results . append ( cls . parse ( api , obj ) ) return results class Status ( Model ) : @ classmethod def parse ( cls , api , json ) : status = cls ( api ) for k , v in json . items ( ) : if k == '' : user_model = getattr ( api . parser . model_factory , '' ) user = user_model . parse ( api , v ) setattr ( status , '' , user ) setattr ( status , '' , user ) elif k == '' : setattr ( status , k , parse_datetime ( v ) ) elif k == '' : if '' in v : setattr ( status , k , parse_html_value ( v ) ) setattr ( status , '' , parse_a_href ( v ) ) else : setattr ( status , k , v ) setattr ( status , '' , None ) elif k == '' : setattr ( status , k , Status . parse ( api , v ) ) elif k == '' : if v is not None : setattr ( status , k , Place . parse ( api , v ) ) else : setattr ( status , k , None ) else : setattr ( status , k , v ) setattr ( status , '' , json ) return status def destroy ( self ) : return self . _api . destroy_status ( self . id ) def retweet ( self ) : return self . _api . retweet ( self . id ) def retweets ( self ) : return self . _api . retweets ( self . id ) def favorite ( self ) : return self . _api . create_favorite ( self . id ) class User ( Model ) : @ classmethod def parse ( cls , api , json ) : user = cls ( api ) for k , v in json . items ( ) : if k == '' : setattr ( user , k , parse_datetime ( v ) ) elif k == '' : setattr ( user , k , Status . parse ( api , v ) ) elif k == '' : if v is True : setattr ( user , k , True ) else : setattr ( user , k , False ) else : setattr ( user , k , v ) return user @ classmethod def parse_list ( cls , api , json_list ) : if isinstance ( json_list , list ) : item_list = json_list else : item_list = json_list [ '' ] results = ResultSet ( ) for obj in item_list : results . append ( cls . parse ( api , obj ) ) return results def timeline ( self , ** kargs ) : return self . _api . user_timeline ( user_id = self . id , ** kargs ) def friends ( self , ** kargs ) : return self . _api . friends ( user_id = self . id , ** kargs ) def followers ( self , ** kargs ) : return self . _api . followers ( user_id = self . id , ** kargs ) def follow ( self ) : self . _api . create_friendship ( user_id = self . id ) self . following = True def unfollow ( self ) : self . _api . destroy_friendship ( user_id = self . id ) self . following = False def lists_memberships ( self , * args , ** kargs ) : return self . _api . lists_memberships ( user = self . screen_name , * args , ** kargs ) def lists_subscriptions ( self , * args , ** kargs ) : return self . _api . lists_subscriptions ( user = self . screen_name , * args , ** kargs ) def lists ( self , * args , ** kargs ) : return self . _api . lists ( user = self . screen_name , * args , ** kargs ) def followers_ids ( self , * args , ** kargs ) : return self . _api . followers_ids ( user_id = self . id , * args , ** kargs ) class DirectMessage ( Model ) : @ classmethod def parse ( cls , api , json ) : dm = cls ( api ) for k , v in json . items ( ) : if k == '' or k == '' : setattr ( dm , k , User . parse ( api , v ) ) elif k == '' : setattr ( dm , k , parse_datetime ( v ) ) else : setattr ( dm , k , v ) return dm def destroy ( self ) : return self . _api . destroy_direct_message ( self . id ) class Friendship ( Model ) : @ classmethod def parse ( cls , api , json ) : relationship = json [ '' ] source = cls ( api ) for k , v in relationship [ '' ] . items ( ) : setattr ( source , k , v ) target = cls ( api ) for k , v in relationship [ '' ] . items ( ) : setattr ( target , k , v ) return source , target class Category ( Model ) : @ classmethod def parse ( cls , api , json ) : category = cls ( api ) for k , v in json . items ( ) : setattr ( category , k , v ) return category class SavedSearch ( Model ) : @ classmethod def parse ( cls , api , json ) : ss = cls ( api ) for k , v in json . items ( ) : if k == '' : setattr ( ss , k , parse_datetime ( v ) ) else : setattr ( ss , k , v ) return ss def destroy ( self ) : return self . _api . destroy_saved_search ( self . id ) class SearchResults ( ResultSet ) : @ classmethod def parse ( cls , api , json ) : metadata = json [ '' ] results = SearchResults ( metadata . get ( '' ) , metadata . get ( '' ) ) results . refresh_url = metadata . get ( '' ) results . completed_in = metadata . get ( '' ) results . query = metadata . get ( '' ) for status in json [ '' ] : results . append ( Status . parse ( api , status ) ) return results class List ( Model ) : @ classmethod def parse ( cls , api , json ) : lst = List ( api ) for k , v in json . items ( ) : if k == '' : setattr ( lst , k , User . parse ( api , v ) ) elif k == '' : setattr ( lst , k , parse_datetime ( v ) ) else : setattr ( lst , k , v ) return lst @ classmethod def parse_list ( cls , api , json_list , result_set = None ) : results = ResultSet ( ) if isinstance ( json_list , dict ) : json_list = json_list [ '' ] for obj in json_list : results . append ( cls . parse ( api , obj ) ) return results def update ( self , ** kargs ) : return self . _api . update_list ( self . slug , ** kargs ) def destroy ( self ) : return self . _api . destroy_list ( self . slug ) def timeline ( self , ** kargs ) : return self . _api . list_timeline ( self . user . screen_name , self . slug , ** kargs ) def add_member ( self , id ) : return self . _api . add_list_member ( self . slug , id ) def remove_member ( self , id ) : return self . _api . remove_list_member ( self . slug , id ) def members ( self , ** kargs ) : return self . _api . list_members ( self . user . screen_name , self . slug , ** kargs ) def is_member ( self , id ) : return self . _api . is_list_member ( self . user . screen_name , self . slug , id ) def subscribe ( self ) : return self . _api . subscribe_list ( self . user . screen_name , self . slug ) def unsubscribe ( self ) : return self . _api . unsubscribe_list ( self . user . screen_name , self . slug ) def subscribers ( self , ** kargs ) : return self . _api . list_subscribers ( self . user . screen_name , self . slug , ** kargs ) def is_subscribed ( self , id ) : return self . _api . is_subscribed_list ( self . user . screen_name , self . slug , id ) class Relation ( Model ) : @ classmethod def parse ( cls , api , json ) : result = cls ( api ) for k , v in json . items ( ) : if k == '' and json [ '' ] in [ '' , '' ] : setattr ( result , k , Status . parse ( api , v ) ) elif k == '' : setattr ( result , k , Relation . parse_list ( api , v ) ) else : setattr ( result , k , v ) return result class Relationship ( Model ) : @ classmethod def parse ( cls , api , json ) : result = cls ( api ) for k , v in json . items ( ) : if k == '' : setattr ( result , '' , '' in v ) setattr ( result , '' , '' in v ) else : setattr ( result , k , v ) ", "answer": "return result"}, {"prompt": " \"\"\"\"\"\" __all__ = [ \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , ] from . _levels import InvalidLogLevelError , LogLevel from . _flatten import extractField from . _format import ( formatEvent , formatEventAsClassicLogText , formatTime , timeFormatRFC3339 , ) ", "answer": "from . _logger import Logger , _loggerFor"}, {"prompt": " from oslo_config import cfg import nova . scheduler . utils import nova . servicegroup from nova import test from nova . tests import fixtures as nova_fixtures from nova . tests . functional . api import client import nova . tests . unit . image . fake from nova . tests . unit import policy_fixture CONF = cfg . CONF ", "answer": "class TestServerValidation ( test . TestCase ) :"}, {"prompt": " from distutils . core import setup ", "answer": "setup ("}, {"prompt": " from __future__ import unicode_literals from django . contrib . auth . models import User from django . core . exceptions import ObjectDoesNotExist from django . http import HttpResponseRedirect from django . utils import six from djblets . webapi . decorators import ( webapi_login_required , webapi_response_errors , webapi_request_fields ) from djblets . webapi . errors import ( DOES_NOT_EXIST , NOT_LOGGED_IN , PERMISSION_DENIED ) from reviewboard . accounts . models import Profile from reviewboard . webapi . base import WebAPIResource from reviewboard . webapi . decorators import ( webapi_check_local_site , webapi_check_login_required ) from reviewboard . webapi . resources import resources class BaseWatchedObjectResource ( WebAPIResource ) : \"\"\"\"\"\" ", "answer": "watched_resource = None"}, {"prompt": " from django . conf . urls . defaults import * from piston . resource import Resource from piston . authentication import HttpBasicAuthentication , HttpBasicSimple from test_project . apps . testapp . handlers import EntryHandler , ExpressiveHandler , AbstractHandler , EchoHandler , PlainOldObjectHandler , Issue58Handler , ListFieldsHandler , FileUploadHandler , CircularAHandler auth = HttpBasicAuthentication ( realm = '' ) entries = Resource ( handler = EntryHandler , authentication = auth ) expressive = Resource ( handler = ExpressiveHandler , authentication = auth ) ", "answer": "abstract = Resource ( handler = AbstractHandler , authentication = auth )"}, {"prompt": " from toscaparser import shell as parser_shell \"\"\"\"\"\" if __name__ == '' : ", "answer": "parser_shell . main ( ) "}, {"prompt": " \"\"\"\"\"\" from tempest . lib import exceptions as tlib_exceptions from neutron . tests import base from neutron . tests . retargetable import client_fixtures from tempest import test as t_test class RestClientFixture ( client_fixtures . AbstractClientFixture ) : \"\"\"\"\"\" ", "answer": "@ property"}, {"prompt": " import copy import numpy as np from chainer import cuda , FunctionSet , Variable , optimizers import chainer . functions as F class QNet : gamma = initial_exploration = ** replay_size = target_model_update_freq = ** data_size = ** hist_size = def __init__ ( self , use_gpu , enable_controller , dim ) : self . use_gpu = use_gpu self . num_of_actions = len ( enable_controller ) self . enable_controller = enable_controller self . dim = dim print ( \"\" ) hidden_dim = self . model = FunctionSet ( l4 = F . Linear ( self . dim * self . hist_size , hidden_dim , wscale = np . sqrt ( ) ) , q_value = F . Linear ( hidden_dim , self . num_of_actions , initialW = np . zeros ( ( self . num_of_actions , hidden_dim ) , dtype = np . float32 ) ) ) if self . use_gpu >= : self . model . to_gpu ( ) self . model_target = copy . deepcopy ( self . model ) self . optimizer = optimizers . RMSpropGraves ( lr = , alpha = , momentum = , eps = ) self . optimizer . setup ( self . model . collect_parameters ( ) ) self . d = [ np . zeros ( ( self . data_size , self . hist_size , self . dim ) , dtype = np . uint8 ) , np . zeros ( self . data_size , dtype = np . uint8 ) , np . zeros ( ( self . data_size , ) , dtype = np . int8 ) , np . zeros ( ( self . data_size , self . hist_size , self . dim ) , dtype = np . uint8 ) , np . zeros ( ( self . data_size , ) , dtype = np . bool ) ] def forward ( self , state , action , reward , state_dash , episode_end ) : num_of_batch = state . shape [ ] s = Variable ( state ) s_dash = Variable ( state_dash ) q = self . q_func ( s ) tmp = self . q_func_target ( s_dash ) if self . use_gpu >= : tmp = list ( map ( np . max , tmp . data . get ( ) ) ) else : tmp = list ( map ( np . max , tmp . data ) ) max_q_dash = np . asanyarray ( tmp , dtype = np . float32 ) if self . use_gpu >= : target = np . asanyarray ( q . data . get ( ) , dtype = np . float32 ) else : target = np . array ( q . data , dtype = np . float32 ) for i in xrange ( num_of_batch ) : if not episode_end [ i ] [ ] : tmp_ = reward [ i ] + self . gamma * max_q_dash [ i ] else : tmp_ = reward [ i ] action_index = self . action_to_index ( action [ i ] ) target [ i , action_index ] = tmp_ if self . use_gpu >= : target = cuda . to_gpu ( target ) td = Variable ( target ) - q td_tmp = td . data + * ( abs ( td . data ) <= ) td_clip = td * ( abs ( td . data ) <= ) + td / abs ( td_tmp ) * ( abs ( td . data ) > ) zero_val = np . zeros ( ( self . replay_size , self . num_of_actions ) , dtype = np . float32 ) if self . use_gpu >= : zero_val = cuda . to_gpu ( zero_val ) zero_val = Variable ( zero_val ) loss = F . mean_squared_error ( td_clip , zero_val ) return loss , q def stock_experience ( self , time , ", "answer": "state , action , reward , state_dash ,"}, {"prompt": " import json from should_dsl import matcher from werkzeug . http import HTTP_STATUS_CODES @ matcher class GenericStatusChecker ( object ) : '''''' name = '' def __call__ ( self , expected ) : self . _expected = expected return self def match ( self , response ) : self . _actual = response . status_code return self . _actual == self . _expected def message_for_failed_should ( self ) : return '' . format ( self . _expected , self . _actual ) def message_for_failed_should_not ( self ) : return '' . format ( self . _expected ) def make_status_checker ( nameprefix , status ) : '''''' class Checker ( object ) : name = '' . format ( nameprefix , status ) def __call__ ( self ) : return self def match ( self , response ) : self . _actual = response . status_code self . _response_data = response . data return self . _actual == status def message_for_failed_should ( self ) : message = '' . format ( status , self . _actual ) if self . _response_data : response = '' . format ( self . _response_data ) message = '' . join ( [ message , response ] ) return message def message_for_failed_should_not ( self ) : return '' . format ( status ) return Checker _status_codes = HTTP_STATUS_CODES . keys ( ) for code in _status_codes : matcher ( make_status_checker ( '' , code ) ) matcher ( make_status_checker ( '' , code ) ) matcher ( make_status_checker ( '' , code ) ) @ matcher class RedirectMatcher ( object ) : '''''' name = '' def __call__ ( self , location ) : self . _expected = '' + location self . _status_ok = True return self def match ( self , response ) : self . _actual_status = response . status_code self . _actual_location = response . location if self . _actual_status not in ( , ) : self . _status_ok = False return False return self . _actual_location == self . _expected def message_for_failed_should ( self ) : if self . _status_ok : return '' . format ( self . _expected , self . _actual_location ) else : return '' . format ( self . _actual_status ) def message_for_failed_should_not ( self ) : return '' . format ( self . _expected ) @ matcher class JsonMatcher ( object ) : '''''' name = '' def __call__ ( self , * pargs , ** kwargs ) : if len ( pargs ) > : raise Exception ( '' ) if len ( kwargs ) > : if len ( pargs ) != : raise Exception ( \"\" \"\" ) self . _expected = dict ( ** kwargs ) else : self . _expected = pargs [ ] return self def match ( self , response ) : try : self . _actual = response . json except AttributeError : self . _actual = json . loads ( response . data ) return self . _actual == self . _expected def message_for_failed_should ( self ) : return \"\" . format ( self . _expected , self . _actual ) def message_for_failed_should_not ( self ) : return \"\" . format ( self . _expected ) @ matcher class ContentTypeMatcher ( object ) : '''''' name = '' def __call__ ( self , content_type ) : self . _mimetype = content_type . find ( '' ) == - self . _match_either = content_type . find ( '' ) == - self . _wildcard = any ( True for sec in content_type . split ( '' ) if sec == '' ) self . _expected = content_type return self def match ( self , response ) : if self . _expected == '' : return True if self . _mimetype : self . _actual = response . mimetype sections = self . _actual . split ( '' ) if self . _match_either : return any ( True for sec in sections if sec == self . _expected ) if self . _wildcard : expectedsections = self . _expected . split ( '' ) for actual , expected in zip ( sections , expectedsections ) : if actual != expected and expected != '' : return False return True else : self . _actual = response . content_type return self . _actual == self . _expected def message_for_failed_should ( self ) : return \"\" . format ( self . _expected , self . _actual ) def message_for_failed_should_not ( self ) : return \"\" . format ( self . _expected ) @ matcher class HeaderMatcher ( object ) : '''''' name = '' def __call__ ( self , * pargs ) : if len ( pargs ) == : expected = pargs [ ] . split ( '' ) elif len ( pargs ) == : expected = pargs else : raise Exception ( '' ) self . _expected_name = expected [ ] try : self . _expected_value = expected [ ] . strip ( ) self . _check_value = True except IndexError : self . _check_value = False return self def match ( self , response ) : self . _value_found = None ", "answer": "for name , value in response . header_list :"}, {"prompt": " import re from ztag . annotation import Annotation from ztag . annotation import OperatingSystem from ztag . annotation import Type from ztag . annotation import Manufacturer from ztag import protocols import ztag . test class FtpTenor ( Annotation ) : protocol = protocols . FTP subprotocol = protocols . FTP . BANNER port = None manufact_re = re . compile ( \"\" , re . IGNORECASE ) ", "answer": "version_re = re . compile ("}, {"prompt": " from django import template register = template . Library ( ) @ register . filter def is_owner_of ( user , repository ) : ", "answer": "return repository . check_user_role ( user , [ '' ] ) "}, {"prompt": " from sqlalchemy import * from migrate import * import migrate . changeset from shakespeare . migration . util import wrap_in_transaction metadata = MetaData ( migrate_engine ) material = Table ( '' , metadata , autoload = True ) src_pkg = Column ( '' , UnicodeText ) src_locator = Column ( '' , UnicodeText ) resource_table = Table ( '' , metadata , ", "answer": "Column ( '' , Integer , primary_key = True ) ,"}, {"prompt": " import __main__ import argparse import code import os import sys def add_config_parameter ( parser ) : parser . add_argument ( '' , '' , dest = '' , action = '' , type = str , help = '' , default = None ) def load_run_parsers ( subparsers ) : run_parser = subparsers . add_parser ( '' , help = '' ) run_parser . add_argument ( '' , '' , dest = '' , action = '' , type = str , help = '' , default = '' ) run_parser . add_argument ( '' , '' , dest = '' , action = '' , type = str , help = '' , default = '' ) run_parser . add_argument ( '' , action = '' , help = '' ) run_parser . add_argument ( '' , action = '' , help = '' ) run_parser . add_argument ( '' , action = '' , help = '' ) add_config_parameter ( run_parser ) run_parser . add_argument ( '' , action = '' , type = int , help = '' ) run_parser . add_argument ( '' , action = '' , type = int , help = '' ) run_parser . add_argument ( '' , action = '' , type = str , help = '' , choices = [ '' , '' , '' ] , ) def load_db_parsers ( subparsers ) : subparsers . add_parser ( '' , help = '' ) subparsers . add_parser ( '' , help = '' ) loaddata_parser = subparsers . add_parser ( '' , help = '' ) loaddata_parser . add_argument ( '' , action = '' , help = '' ) dumpdata_parser = subparsers . add_parser ( '' , help = '' ) dumpdata_parser . add_argument ( '' , action = '' , help = '' '' ) generate_parser = subparsers . add_parser ( '' , help = '' ) generate_parser . add_argument ( '' , '' , dest = '' , action = '' , type = int , help = '' , required = True ) generate_parser . add_argument ( '' , '' , dest = '' , action = '' , type = int , help = '' ) generate_parser . add_argument ( '' , '' , dest = '' , action = '' , type = int , help = '' ) generate_parser . add_argument ( '' , '' , dest = '' , action = '' , type = int , default = , help = '' ) subparsers . add_parser ( '' , help = '' '' ) def load_alembic_parsers ( migrate_parser ) : alembic_parser = migrate_parser . add_subparsers ( dest = \"\" , help = '' ) for name in [ '' , '' , '' ] : parser = alembic_parser . add_parser ( name ) for name in [ '' , '' ] : parser = alembic_parser . add_parser ( name ) parser . add_argument ( '' , type = int ) parser . add_argument ( '' , action = '' ) parser . add_argument ( '' , nargs = '' ) parser = alembic_parser . add_parser ( '' ) parser . add_argument ( '' , action = '' ) parser . add_argument ( '' ) parser = alembic_parser . add_parser ( '' ) parser . add_argument ( '' , '' ) parser . add_argument ( '' , action = '' ) parser . add_argument ( '' , action = '' ) def load_db_migrate_parsers ( subparsers ) : migrate_parser = subparsers . add_parser ( '' , help = '' ) load_alembic_parsers ( migrate_parser ) def load_dbshell_parsers ( subparsers ) : dbshell_parser = subparsers . add_parser ( '' , help = '' ) add_config_parameter ( dbshell_parser ) def load_test_parsers ( subparsers ) : subparsers . add_parser ( '' , help = '' ) def load_shell_parsers ( subparsers ) : shell_parser = subparsers . add_parser ( '' , help = '' ) add_config_parameter ( shell_parser ) def load_settings_parsers ( subparsers ) : subparsers . add_parser ( '' , help = '' ) def load_extensions_parsers ( subparsers ) : extensions_parser = subparsers . add_parser ( '' , help = '' ) load_alembic_parsers ( extensions_parser ) def action_dumpdata ( params ) : import logging logging . disable ( logging . WARNING ) from nailgun . db . sqlalchemy import fixman fixman . dump_fixture ( params . model ) sys . exit ( ) def action_generate_nodes_fixture ( params ) : from oslo_serialization import jsonutils from nailgun . logger import logger from nailgun . utils import fake_generator logger . info ( '' ) total_nodes_count = params . total_nodes fixtures_dir = os . path . join ( os . path . dirname ( os . path . abspath ( __file__ ) ) , '' ) file_path = os . path . join ( fixtures_dir , '' . format ( total_nodes_count ) ) generator = fake_generator . FakeNodesGenerator ( ) res = generator . generate_fake_nodes ( total_nodes_count , error_nodes_count = params . error_nodes , offline_nodes_count = params . offline_nodes , min_ifaces_num = params . min_ifaces_num ) with open ( file_path , '' ) as file_to_write : jsonutils . dump ( res , file_to_write , indent = ) logger . info ( '' . format ( file_path ) ) def action_loaddata ( params ) : from nailgun . db . sqlalchemy import fixman from nailgun . logger import logger logger . info ( \"\" ) with open ( params . fixture , \"\" ) as fileobj : fixman . upload_fixture ( fileobj ) logger . info ( \"\" ) def action_loadfakedeploymenttasks ( params ) : from nailgun . db . sqlalchemy import fixman from nailgun . logger import logger logger . info ( \"\" ) fixman . load_fake_deployment_tasks ( ) logger . info ( \"\" ) def action_loaddefault ( params ) : from nailgun . db . sqlalchemy import fixman from nailgun . logger import logger logger . info ( \"\" ) fixman . upload_fixtures ( ) logger . info ( \"\" ) fixman . load_fake_deployment_tasks ( ) logger . info ( \"\" ) def action_syncdb ( params ) : from nailgun . db import syncdb from nailgun . logger import logger logger . info ( \"\" ) syncdb ( ) logger . info ( \"\" ) def action_dropdb ( params ) : from nailgun . db import dropdb from nailgun . logger import logger logger . info ( \"\" ) dropdb ( ) logger . info ( \"\" ) def action_migrate ( params ) : from nailgun . db . migration import action_migrate_alembic_core action_migrate_alembic_core ( params ) def action_extensions ( params ) : from nailgun . logger import logger from nailgun . db . migration import action_migrate_alembic_extension from nailgun . extensions import get_all_extensions for extension in get_all_extensions ( ) : if extension . alembic_migrations_path ( ) : logger . info ( '' . format ( extension . full_name ( ) ) ) action_migrate_alembic_extension ( params , extension = extension ) else : logger . info ( '' '' . format ( extension . full_name ( ) ) ) def action_test ( params ) : from nailgun . logger import logger from nailgun . unit_test import TestRunner logger . info ( \"\" ) TestRunner . run ( ) logger . info ( \"\" ) def action_dbshell ( params ) : from nailgun . settings import settings if params . config_file : settings . update_from_file ( params . config_file ) args = [ '' ] env = { } if settings . DATABASE [ '' ] : env [ '' ] = settings . DATABASE [ '' ] if settings . DATABASE [ '' ] : args += [ \"\" , settings . DATABASE [ '' ] ] if settings . DATABASE [ '' ] : args . extend ( [ \"\" , settings . DATABASE [ '' ] ] ) if settings . DATABASE [ '' ] : args . extend ( [ \"\" , str ( settings . DATABASE [ '' ] ) ] ) args += [ settings . DATABASE [ '' ] ] if os . name == '' : sys . exit ( os . system ( \"\" . join ( args ) ) ) else : os . execvpe ( '' , args , env ) def action_dump_settings ( params ) : ", "answer": "from nailgun . settings import settings"}, {"prompt": " \"\"\"\"\"\" import unittest import warnings from bs4 import BeautifulSoup from bs4 . builder import ( builder_registry as registry , HTMLParserTreeBuilder , TreeBuilderRegistry , ) try : from bs4 . builder import HTML5TreeBuilder HTML5LIB_PRESENT = True except ImportError : HTML5LIB_PRESENT = False try : from bs4 . builder import ( LXMLTreeBuilderForXML , LXMLTreeBuilder , ) LXML_PRESENT = True except ImportError : LXML_PRESENT = False class BuiltInRegistryTest ( unittest . TestCase ) : \"\"\"\"\"\" def test_combination ( self ) : if LXML_PRESENT : self . assertEqual ( registry . lookup ( '' , '' ) , LXMLTreeBuilder ) if LXML_PRESENT : self . assertEqual ( registry . lookup ( '' , '' ) , LXMLTreeBuilderForXML ) self . assertEqual ( registry . lookup ( '' , '' ) , HTMLParserTreeBuilder ) if HTML5LIB_PRESENT : self . assertEqual ( registry . lookup ( '' , '' ) , HTML5TreeBuilder ) def test_lookup_by_markup_type ( self ) : if LXML_PRESENT : self . assertEqual ( registry . lookup ( '' ) , LXMLTreeBuilder ) self . assertEqual ( registry . lookup ( '' ) , LXMLTreeBuilderForXML ) else : self . assertEqual ( registry . lookup ( '' ) , None ) if HTML5LIB_PRESENT : self . assertEqual ( registry . lookup ( '' ) , HTML5TreeBuilder ) else : self . assertEqual ( registry . lookup ( '' ) , HTMLParserTreeBuilder ) def test_named_library ( self ) : if LXML_PRESENT : self . assertEqual ( registry . lookup ( '' , '' ) , LXMLTreeBuilderForXML ) self . assertEqual ( registry . lookup ( '' , '' ) , LXMLTreeBuilder ) if HTML5LIB_PRESENT : self . assertEqual ( registry . lookup ( '' ) , HTML5TreeBuilder ) self . assertEqual ( registry . lookup ( '' ) , HTMLParserTreeBuilder ) def test_beautifulsoup_constructor_does_lookup ( self ) : with warnings . catch_warnings ( record = True ) as w : BeautifulSoup ( \"\" , features = \"\" ) BeautifulSoup ( \"\" , features = [ \"\" , \"\" ] ) ", "answer": "self . assertRaises ( ValueError , BeautifulSoup ,"}, {"prompt": " import vim import sys import os . path import nrepl from urlparse import urlparse nrepl_connections = { } def detect_project_repl_port ( ) : port_files = [ '' , '' , '' ] for pf in port_files : if os . path . exists ( pf ) : with open ( pf , '' ) as f : return int ( f . read ( ) . strip ( ) ) def split_session_url ( url ) : components = urlparse ( url ) host_port = components . netloc . split ( '' ) if len ( host_port ) < : raise Exception ( '' % ( url ) ) return components . scheme , host_port [ ] , int ( host_port [ ] ) , components . path [ : ] def join_session_url ( components ) : return \"\" % components def get_sessions ( connections ) : for ( scheme , host , port ) , ( conn , sess_list ) in connections . iteritems ( ) : for session in sess_list : yield join_session_url ( ( scheme , host , port , session ) ) def get_buffer_map ( ) : result = { } for buf in vim . buffers : session_url = buf . vars . get ( '' ) if session_url : result . setdefault ( session_url , [ ] ) . append ( buf . name ) return result def create_session ( scheme , host , port ) : conn , sess_list = nrepl_connections . get ( ( scheme , host , port ) , ( None , None ) ) if not conn : conn = nrepl . connect ( port , host , scheme ) sess_list = set ( ) nrepl_connections [ ( scheme , host , port ) ] = ( conn , sess_list ) session = nrepl . open_session ( conn ) sess_list . add ( session ) return conn , session def project_repl ( ) : port = detect_project_repl_port ( ) if port : conn , session = create_session ( '' , '' , port ) return conn , session , join_session_url ( ( '' , '' , port , session ) ) return None , None , None def find_session ( url ) : scheme , host , port , session = split_session_url ( url ) conn , sess_list = nrepl_connections . get ( ( scheme , host , port ) , ( None , None ) ) if conn and session in sess_list : return conn , session return None , None def session_exists ( scheme , host , port , session ) : conn , sess_list = nrepl_connections . get ( ( scheme , host , port ) , ( None , None ) ) return conn and session in sess_list def close_session ( url ) : scheme , host , port , session = split_session_url ( url ) if session : conn , sess_list = nrepl_connections . get ( ( scheme , host , port ) , ( None , None ) ) if conn : nrepl . close_session ( conn , session ) sess_list . remove ( session ) if not len ( sess_list ) : nrepl . disconnect ( conn ) del nrepl_connections [ ( scheme , host , port ) ] def is_our_buffer ( buf ) : return buf . name . endswith ( '' ) def find_our_bufffer ( ) : for b in vim . buffers : if is_our_buffer ( b ) : return b def find_our_window ( ) : for w in vim . windows : if is_our_buffer ( w . buffer ) : return w . number def remove_trailing_new_line ( subject ) : if subject and subject [ - ] == '' : return subject [ : - ] return subject def output_data ( data , target = sys . stdout ) : b = find_our_bufffer ( ) if b : b . append ( remove_trailing_new_line ( data ) . split ( '' ) ) else : print >> target , data def scroll_to_end ( buf ) : win_num = find_our_window ( ) if win_num : vim . command ( str ( win_num ) + '' ) vim . command ( '' ) vim . command ( '' ) def response_completed ( ) : buf = find_our_bufffer ( ) if buf : buf . append ( '' + * '' ) scroll_to_end ( buf ) def print_response ( response ) : for msg in response : if '' in msg : output_data ( msg [ '' ] ) if '' in msg : output_data ( msg [ '' ] , sys . stderr ) if '' in msg : output_data ( msg [ '' ] ) response_completed ( ) def attach_session_url ( buf , session_url ) : buf . vars [ '' ] = session_url vim . command ( '' % ( buf . number ) ) def set_buffer_session ( url ) : if url : scheme , host , port , session = split_session_url ( url ) if session : if not session_exists ( scheme , host , port , session ) : print >> sys . stderr , '' % ( url ) return else : c , session = create_session ( scheme , host , port ) attach_session_url ( vim . current . buffer , join_session_url ( ( scheme , host , port , session ) ) ) print vim . current . buffer . vars . get ( '' ) ", "answer": "def print_sessions ( ) :"}, {"prompt": " from __future__ import unicode_literals from django . contrib . auth . models import Group , User from rest_framework import generics from rest_api . filters import MayanObjectPermissionsFilter from rest_api . permissions import MayanPermission from . permissions import ( permission_group_create , permission_group_delete , permission_group_edit , permission_group_view , permission_user_create , permission_user_delete , permission_user_edit , permission_user_view ) from . serializers import GroupSerializer , UserSerializer class APIGroupListView ( generics . ListCreateAPIView ) : filter_backends = ( MayanObjectPermissionsFilter , ) mayan_object_permissions = { '' : ( permission_group_view , ) } mayan_view_permissions = { '' : ( permission_group_create , ) } permission_classes = ( MayanPermission , ) queryset = Group . objects . all ( ) serializer_class = GroupSerializer def get ( self , * args , ** kwargs ) : \"\"\"\"\"\" return super ( APIGroupListView , self ) . get ( * args , ** kwargs ) def post ( self , * args , ** kwargs ) : \"\"\"\"\"\" return super ( APIGroupListView , self ) . post ( * args , ** kwargs ) class APIGroupView ( generics . RetrieveUpdateDestroyAPIView ) : mayan_object_permissions = { '' : ( permission_group_view , ) , '' : ( permission_group_edit , ) , '' : ( permission_group_edit , ) , '' : ( permission_group_delete , ) } permission_classes = ( MayanPermission , ) queryset = Group . objects . all ( ) serializer_class = GroupSerializer def delete ( self , * args , ** kwargs ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " from nose . tools import eq_ from pyquery import PyQuery as pq from kitsune . sumo . templatetags . jinja_helpers import urlparams from kitsune . sumo . tests import LocalizingClient from kitsune . sumo . urlresolvers import reverse from kitsune . search . tests import ElasticTestCase class TopContributorsNewTests ( ElasticTestCase ) : \"\"\"\"\"\" client_class = LocalizingClient def test_it_works ( self ) : url = reverse ( '' , args = [ '' ] ) res = self . client . get ( url ) eq_ ( res . status_code , ) def test_no_xss ( self ) : bad_string = '' good_string = '' url = reverse ( '' , args = [ '' ] ) url = urlparams ( url , locale = bad_string ) res = self . client . get ( url ) eq_ ( res . status_code , ) doc = pq ( res . content ) ", "answer": "target = doc ( '' )"}, {"prompt": " __author__ = '' import scrapy , json from dateutil import parser from scrapy import log from scrapy . selector import Selector import utils from stockspider . items import * class HqSpider ( scrapy . Spider ) : name = \"\" allowed_domains = [ \"\" ] access_token = None def start_requests ( self ) : request_hq_access_token = scrapy . Request ( \"\" , callback = self . parse_hq ) return [ request_hq_access_token ] def parse_hq ( self , response ) : access_token_list = response . xpath ( '' ) . re ( '' ) assert len ( access_token_list ) == self . access_token = access_token_list [ ] request = scrapy . Request ( \"\" , cookies = self . get_cookies ( ) , headers = self . get_ajax_header ( ) , callback = self . parse_hq_count ) return request def parse_hq_count ( self , response ) : json_response = json . loads ( response . body_as_unicode ( ) ) count = int ( json_response [ '' ] [ '' ] ) page_size = for page in xrange ( , count / page_size + ) : request = scrapy . Request ( \"\" % ( page + , page_size ) , cookies = self . get_cookies ( ) , headers = self . get_ajax_header ( ) , callback = self . parse_hq_stock_name_list ) yield request def parse_hq_stock_name_list ( self , response ) : json_response = json . loads ( response . body_as_unicode ( ) ) if '' not in json_response or json_response [ '' ] != '' : log . msg ( '' ) return for stock in json_response [ '' ] : item = StockItem ( ) item [ '' ] = stock [ '' ] ", "answer": "item [ '' ] = stock [ '' ]"}, {"prompt": " \"\"\"\"\"\" print ( __doc__ ) import numpy as np import matplotlib . pyplot as plt from sklearn . pipeline import Pipeline from sklearn . preprocessing import PolynomialFeatures from sklearn . linear_model import LinearRegression from sklearn . model_selection import cross_val_score np . random . seed ( ) n_samples = degrees = [ , , ] true_fun = lambda X : np . cos ( * np . pi * X ) X = np . sort ( np . random . rand ( n_samples ) ) y = true_fun ( X ) + np . random . randn ( n_samples ) * plt . figure ( figsize = ( , ) ) for i in range ( len ( degrees ) ) : ax = plt . subplot ( , len ( degrees ) , i + ) ", "answer": "plt . setp ( ax , xticks = ( ) , yticks = ( ) )"}, {"prompt": " \"\"\"\"\"\" import os . path ", "answer": "for path in [ '' , '' , '' , '' , '' ] :"}, {"prompt": " from . base import BaseModel , Scraper from . schemas . jurisdiction import schema from . popolo import Organization class Jurisdiction ( BaseModel ) : \"\"\"\"\"\" _type = '' _schema = schema classification = None name = None url = None legislative_sessions = [ ] feature_flags = [ ] extras = { } scrapers = { } default_scrapers = { } parties = [ ] ignored_scraped_sessions = [ ] check_sessions = False ", "answer": "def __init__ ( self ) :"}, {"prompt": " from numpy . testing import assert_ , run_module_suite , assert_raises from scipy . _lib . _version import NumpyVersion def test_main_versions ( ) : assert_ ( NumpyVersion ( '' ) == '' ) for ver in [ '' , '' , '' ] : assert_ ( NumpyVersion ( '' ) < ver ) for ver in [ '' , '' , '' ] : assert_ ( NumpyVersion ( '' ) > ver ) def test_version_1_point_10 ( ) : assert_ ( NumpyVersion ( '' ) < '' ) assert_ ( NumpyVersion ( '' ) < '' ) assert_ ( NumpyVersion ( '' ) == '' ) assert_ ( NumpyVersion ( '' ) < '' ) def test_alpha_beta_rc ( ) : assert_ ( NumpyVersion ( '' ) == '' ) for ver in [ '' , '' ] : assert_ ( NumpyVersion ( '' ) < ver ) for ver in [ '' , '' , '' ] : assert_ ( NumpyVersion ( '' ) > ver ) assert_ ( NumpyVersion ( '' ) > '' ) def test_dev_version ( ) : assert_ ( NumpyVersion ( '' ) < '' ) for ver in [ '' , '' , '' , '' ] : assert_ ( NumpyVersion ( '' ) < ver ) assert_ ( NumpyVersion ( '' ) == '' ) def test_dev_a_b_rc_mixed ( ) : assert_ ( NumpyVersion ( '' ) == '' ) assert_ ( NumpyVersion ( '' ) < '' ) def test_dev0_version ( ) : assert_ ( NumpyVersion ( '' ) < '' ) for ver in [ '' , '' , '' , '' ] : assert_ ( NumpyVersion ( '' ) < ver ) ", "answer": "assert_ ( NumpyVersion ( '' ) == '' )"}, {"prompt": " from __future__ import unicode_literals from django . db import models , migrations class Migration ( migrations . Migration ) : dependencies = [ ( '' , '' ) , ] operations = [ migrations . AlterField ( model_name = '' , name = '' , field = models . CharField ( unique = True , max_length = , verbose_name = '' ) , preserve_default = True , ", "answer": ") ,"}, {"prompt": " from tkinter import * class SearchDialogBase : title = \"\" icon = \"\" needwrapbutton = def __init__ ( self , root , engine ) : self . root = root self . engine = engine self . top = None def open ( self , text , searchphrase = None ) : self . text = text if not self . top : self . create_widgets ( ) else : self . top . deiconify ( ) self . top . tkraise ( ) if searchphrase : self . ent . delete ( , \"\" ) self . ent . insert ( \"\" , searchphrase ) self . ent . focus_set ( ) self . ent . selection_range ( , \"\" ) self . ent . icursor ( ) ", "answer": "self . top . grab_set ( )"}, {"prompt": " from operator import attrgetter from django . db import connection , connections , router from django . db . backends import util from django . db . models import signals , get_model from django . db . models . fields import ( AutoField , Field , IntegerField , PositiveIntegerField , PositiveSmallIntegerField , FieldDoesNotExist ) from django . db . models . related import RelatedObject from django . db . models . query import QuerySet from django . db . models . query_utils import QueryWrapper from django . db . models . deletion import CASCADE from django . utils . encoding import smart_text from django . utils import six from django . utils . translation import ugettext_lazy as _ , string_concat from django . utils . functional import curry , cached_property from django . core import exceptions from django import forms RECURSIVE_RELATIONSHIP_CONSTANT = '' pending_lookups = { } def add_lazy_relation ( cls , field , relation , operation ) : \"\"\"\"\"\" if relation == RECURSIVE_RELATIONSHIP_CONSTANT : app_label = cls . _meta . app_label model_name = cls . __name__ else : if isinstance ( relation , six . string_types ) : try : app_label , model_name = relation . split ( \"\" ) except ValueError : app_label = cls . _meta . app_label model_name = relation else : app_label = relation . _meta . app_label model_name = relation . _meta . object_name model = get_model ( app_label , model_name , seed_cache = False , only_installed = False ) if model : operation ( field , model , cls ) else : key = ( app_label , model_name ) value = ( cls , field , operation ) pending_lookups . setdefault ( key , [ ] ) . append ( value ) def do_pending_lookups ( sender , ** kwargs ) : \"\"\"\"\"\" key = ( sender . _meta . app_label , sender . __name__ ) for cls , field , operation in pending_lookups . pop ( key , [ ] ) : operation ( field , sender , cls ) signals . class_prepared . connect ( do_pending_lookups ) class RelatedField ( object ) : def contribute_to_class ( self , cls , name ) : sup = super ( RelatedField , self ) self . opts = cls . _meta if hasattr ( sup , '' ) : sup . contribute_to_class ( cls , name ) if not cls . _meta . abstract and self . rel . related_name : self . rel . related_name = self . rel . related_name % { '' : cls . __name__ . lower ( ) , '' : cls . _meta . app_label . lower ( ) , } other = self . rel . to if isinstance ( other , six . string_types ) or other . _meta . pk is None : def resolve_related_class ( field , model , cls ) : field . rel . to = model field . do_related_class ( model , cls ) add_lazy_relation ( cls , self , other , resolve_related_class ) else : self . do_related_class ( other , cls ) def set_attributes_from_rel ( self ) : self . name = self . name or ( self . rel . to . _meta . object_name . lower ( ) + '' + self . rel . to . _meta . pk . name ) if self . verbose_name is None : self . verbose_name = self . rel . to . _meta . verbose_name self . rel . field_name = self . rel . field_name or self . rel . to . _meta . pk . name def do_related_class ( self , other , cls ) : self . set_attributes_from_rel ( ) self . related = RelatedObject ( other , cls , self ) if not cls . _meta . abstract : self . contribute_to_related_class ( other , self . related ) def get_prep_lookup ( self , lookup_type , value ) : if hasattr ( value , '' ) : return value . prepare ( ) if hasattr ( value , '' ) : return value . _prepare ( ) if lookup_type in [ '' , '' , '' , '' , '' ] : return self . _pk_trace ( value , '' , lookup_type ) if lookup_type in ( '' , '' ) : return [ self . _pk_trace ( v , '' , lookup_type ) for v in value ] elif lookup_type == '' : return [ ] raise TypeError ( \"\" % lookup_type ) def get_db_prep_lookup ( self , lookup_type , value , connection , prepared = False ) : if not prepared : value = self . get_prep_lookup ( lookup_type , value ) if hasattr ( value , '' ) : value = value . get_compiler ( connection = connection ) if hasattr ( value , '' ) or hasattr ( value , '' ) : if hasattr ( value , '' ) : return value if hasattr ( value , '' ) : sql , params = value . as_sql ( ) else : sql , params = value . _as_sql ( connection = connection ) return QueryWrapper ( ( '' % sql ) , params ) if lookup_type in [ '' , '' , '' , '' , '' ] : return [ self . _pk_trace ( value , '' , lookup_type , connection = connection , prepared = prepared ) ] if lookup_type in ( '' , '' ) : return [ self . _pk_trace ( v , '' , lookup_type , connection = connection , prepared = prepared ) for v in value ] elif lookup_type == '' : return [ ] raise TypeError ( \"\" % lookup_type ) def _pk_trace ( self , value , prep_func , lookup_type , ** kwargs ) : v = value if isinstance ( v , self . rel . to ) : field_name = getattr ( self . rel , \"\" , None ) else : field_name = None try : while True : if field_name is None : field_name = v . _meta . pk . name v = getattr ( v , field_name ) field_name = None except AttributeError : pass except exceptions . ObjectDoesNotExist : v = None field = self while field . rel : if hasattr ( field . rel , '' ) : field = field . rel . to . _meta . get_field ( field . rel . field_name ) else : field = field . rel . to . _meta . pk if lookup_type in ( '' , '' ) : v = [ v ] v = getattr ( field , prep_func ) ( lookup_type , v , ** kwargs ) if isinstance ( v , list ) : v = v [ ] return v def related_query_name ( self ) : return self . rel . related_name or self . opts . object_name . lower ( ) class SingleRelatedObjectDescriptor ( object ) : def __init__ ( self , related ) : self . related = related self . cache_name = related . get_cache_name ( ) def is_cached ( self , instance ) : return hasattr ( instance , self . cache_name ) def get_query_set ( self , ** db_hints ) : db = router . db_for_read ( self . related . model , ** db_hints ) return self . related . model . _base_manager . using ( db ) def get_prefetch_query_set ( self , instances ) : rel_obj_attr = attrgetter ( self . related . field . attname ) instance_attr = lambda obj : obj . _get_pk_val ( ) instances_dict = dict ( ( instance_attr ( inst ) , inst ) for inst in instances ) params = { '' % self . related . field . name : list ( instances_dict ) } qs = self . get_query_set ( instance = instances [ ] ) . filter ( ** params ) rel_obj_cache_name = self . related . field . get_cache_name ( ) for rel_obj in qs : instance = instances_dict [ rel_obj_attr ( rel_obj ) ] setattr ( rel_obj , rel_obj_cache_name , instance ) return qs , rel_obj_attr , instance_attr , True , self . cache_name def __get__ ( self , instance , instance_type = None ) : if instance is None : return self try : rel_obj = getattr ( instance , self . cache_name ) except AttributeError : related_pk = instance . _get_pk_val ( ) if related_pk is None : rel_obj = None else : params = { '' % self . related . field . name : related_pk } try : rel_obj = self . get_query_set ( instance = instance ) . get ( ** params ) except self . related . model . DoesNotExist : rel_obj = None else : setattr ( rel_obj , self . related . field . get_cache_name ( ) , instance ) setattr ( instance , self . cache_name , rel_obj ) if rel_obj is None : raise self . related . model . DoesNotExist else : return rel_obj def __set__ ( self , instance , value ) : if instance is None : raise AttributeError ( \"\" % self . related . opts . object_name ) if value is None and self . related . field . null == False : raise ValueError ( '' % ( instance . _meta . object_name , self . related . get_accessor_name ( ) ) ) elif value is not None and not isinstance ( value , self . related . model ) : raise ValueError ( '' % ( value , instance . _meta . object_name , self . related . get_accessor_name ( ) , self . related . opts . object_name ) ) elif value is not None : if instance . _state . db is None : instance . _state . db = router . db_for_write ( instance . __class__ , instance = value ) elif value . _state . db is None : value . _state . db = router . db_for_write ( value . __class__ , instance = instance ) elif value . _state . db is not None and instance . _state . db is not None : if not router . allow_relation ( value , instance ) : raise ValueError ( '' % ( value , instance . _state . db , value . _state . db ) ) related_pk = getattr ( instance , self . related . field . rel . get_related_field ( ) . attname ) if related_pk is None : raise ValueError ( '' % ( value , instance . _meta . object_name ) ) setattr ( value , self . related . field . attname , related_pk ) setattr ( instance , self . cache_name , value ) setattr ( value , self . related . field . get_cache_name ( ) , instance ) class ReverseSingleRelatedObjectDescriptor ( object ) : def __init__ ( self , field_with_rel ) : self . field = field_with_rel self . cache_name = self . field . get_cache_name ( ) def is_cached ( self , instance ) : return hasattr ( instance , self . cache_name ) def get_query_set ( self , ** db_hints ) : db = router . db_for_read ( self . field . rel . to , ** db_hints ) rel_mgr = self . field . rel . to . _default_manager if getattr ( rel_mgr , '' , False ) : return rel_mgr . using ( db ) else : return QuerySet ( self . field . rel . to ) . using ( db ) def get_prefetch_query_set ( self , instances ) : other_field = self . field . rel . get_related_field ( ) rel_obj_attr = attrgetter ( other_field . attname ) instance_attr = attrgetter ( self . field . attname ) instances_dict = dict ( ( instance_attr ( inst ) , inst ) for inst in instances ) if other_field . rel : params = { '' % self . field . rel . field_name : list ( instances_dict ) } else : params = { '' % self . field . rel . field_name : list ( instances_dict ) } qs = self . get_query_set ( instance = instances [ ] ) . filter ( ** params ) if not self . field . rel . multiple : rel_obj_cache_name = self . field . related . get_cache_name ( ) for rel_obj in qs : instance = instances_dict [ rel_obj_attr ( rel_obj ) ] setattr ( rel_obj , rel_obj_cache_name , instance ) return qs , rel_obj_attr , instance_attr , True , self . cache_name def __get__ ( self , instance , instance_type = None ) : if instance is None : return self try : rel_obj = getattr ( instance , self . cache_name ) except AttributeError : val = getattr ( instance , self . field . attname ) if val is None : rel_obj = None else : other_field = self . field . rel . get_related_field ( ) if other_field . rel : params = { '' % ( self . field . rel . field_name , other_field . rel . field_name ) : val } else : params = { '' % self . field . rel . field_name : val } qs = self . get_query_set ( instance = instance ) rel_obj = qs . get ( ** params ) if not self . field . rel . multiple : setattr ( rel_obj , self . field . related . get_cache_name ( ) , instance ) setattr ( instance , self . cache_name , rel_obj ) if rel_obj is None and not self . field . null : raise self . field . rel . to . DoesNotExist else : return rel_obj def __set__ ( self , instance , value ) : if instance is None : raise AttributeError ( \"\" % self . field . name ) if value is None and self . field . null == False : raise ValueError ( '' % ( instance . _meta . object_name , self . field . name ) ) elif value is not None and not isinstance ( value , self . field . rel . to ) : raise ValueError ( '' % ( value , instance . _meta . object_name , self . field . name , self . field . rel . to . _meta . object_name ) ) elif value is not None : if instance . _state . db is None : instance . _state . db = router . db_for_write ( instance . __class__ , instance = value ) elif value . _state . db is None : value . _state . db = router . db_for_write ( value . __class__ , instance = instance ) elif value . _state . db is not None and instance . _state . db is not None : if not router . allow_relation ( value , instance ) : raise ValueError ( '' % ( value , instance . _state . db , value . _state . db ) ) if value is None : related = getattr ( instance , self . cache_name , None ) if related is not None : setattr ( related , self . field . related . get_cache_name ( ) , None ) try : val = getattr ( value , self . field . rel . get_related_field ( ) . attname ) except AttributeError : val = None setattr ( instance , self . field . attname , val ) setattr ( instance , self . cache_name , value ) if value is not None and not self . field . rel . multiple : setattr ( value , self . field . related . get_cache_name ( ) , instance ) class ForeignRelatedObjectsDescriptor ( object ) : def __init__ ( self , related ) : self . related = related def __get__ ( self , instance , instance_type = None ) : if instance is None : return self return self . related_manager_cls ( instance ) def __set__ ( self , instance , value ) : if instance is None : raise AttributeError ( \"\" ) manager = self . __get__ ( instance ) if self . related . field . null : manager . clear ( ) manager . add ( * value ) @ cached_property def related_manager_cls ( self ) : superclass = self . related . model . _default_manager . __class__ rel_field = self . related . field rel_model = self . related . model attname = rel_field . rel . get_related_field ( ) . attname class RelatedManager ( superclass ) : def __init__ ( self , instance ) : super ( RelatedManager , self ) . __init__ ( ) self . instance = instance self . core_filters = { '' % ( rel_field . name , attname ) : getattr ( instance , attname ) } self . model = rel_model def get_query_set ( self ) : try : return self . instance . _prefetched_objects_cache [ rel_field . related_query_name ( ) ] except ( AttributeError , KeyError ) : db = self . _db or router . db_for_read ( self . model , instance = self . instance ) qs = super ( RelatedManager , self ) . get_query_set ( ) . using ( db ) . filter ( ** self . core_filters ) val = getattr ( self . instance , attname ) if val is None or val == '' and connections [ db ] . features . interprets_empty_strings_as_nulls : return qs . filter ( pk__in = [ ] ) qs . _known_related_objects = { rel_field : { self . instance . pk : self . instance } } return qs def get_prefetch_query_set ( self , instances ) : rel_obj_attr = attrgetter ( rel_field . attname ) instance_attr = attrgetter ( attname ) instances_dict = dict ( ( instance_attr ( inst ) , inst ) for inst in instances ) db = self . _db or router . db_for_read ( self . model , instance = instances [ ] ) query = { '' % ( rel_field . name , attname ) : list ( instances_dict ) } qs = super ( RelatedManager , self ) . get_query_set ( ) . using ( db ) . filter ( ** query ) for rel_obj in qs : instance = instances_dict [ rel_obj_attr ( rel_obj ) ] setattr ( rel_obj , rel_field . name , instance ) cache_name = rel_field . related_query_name ( ) return qs , rel_obj_attr , instance_attr , False , cache_name def add ( self , * objs ) : for obj in objs : if not isinstance ( obj , self . model ) : raise TypeError ( \"\" % ( self . model . _meta . object_name , obj ) ) setattr ( obj , rel_field . name , self . instance ) obj . save ( ) add . alters_data = True def create ( self , ** kwargs ) : kwargs [ rel_field . name ] = self . instance db = router . db_for_write ( self . model , instance = self . instance ) return super ( RelatedManager , self . db_manager ( db ) ) . create ( ** kwargs ) create . alters_data = True def get_or_create ( self , ** kwargs ) : kwargs [ rel_field . name ] = self . instance db = router . db_for_write ( self . model , instance = self . instance ) return super ( RelatedManager , self . db_manager ( db ) ) . get_or_create ( ** kwargs ) get_or_create . alters_data = True if rel_field . null : def remove ( self , * objs ) : val = getattr ( self . instance , attname ) for obj in objs : if getattr ( obj , rel_field . attname ) == val : setattr ( obj , rel_field . name , None ) obj . save ( ) else : raise rel_field . rel . to . DoesNotExist ( \"\" % ( obj , self . instance ) ) remove . alters_data = True def clear ( self ) : self . update ( ** { rel_field . name : None } ) clear . alters_data = True return RelatedManager def create_many_related_manager ( superclass , rel ) : \"\"\"\"\"\" class ManyRelatedManager ( superclass ) : def __init__ ( self , model = None , query_field_name = None , instance = None , symmetrical = None , source_field_name = None , target_field_name = None , reverse = False , through = None , prefetch_cache_name = None ) : super ( ManyRelatedManager , self ) . __init__ ( ) self . model = model self . query_field_name = query_field_name self . core_filters = { '' % query_field_name : instance . _get_pk_val ( ) } self . instance = instance self . symmetrical = symmetrical self . source_field_name = source_field_name self . target_field_name = target_field_name self . reverse = reverse self . through = through self . prefetch_cache_name = prefetch_cache_name self . _fk_val = self . _get_fk_val ( instance , source_field_name ) if self . _fk_val is None : raise ValueError ( '' '' % ( instance , source_field_name ) ) if instance . pk is None : raise ValueError ( \"\" \"\" % instance . __class__ . __name__ ) def _get_fk_val ( self , obj , field_name ) : \"\"\"\"\"\" if not self . through : return obj . pk fk = self . through . _meta . get_field ( field_name ) if fk . rel . field_name and fk . rel . field_name != fk . rel . to . _meta . pk . attname : attname = fk . rel . get_related_field ( ) . get_attname ( ) return fk . get_prep_lookup ( '' , getattr ( obj , attname ) ) else : return obj . pk def get_query_set ( self ) : try : return self . instance . _prefetched_objects_cache [ self . prefetch_cache_name ] except ( AttributeError , KeyError ) : db = self . _db or router . db_for_read ( self . instance . __class__ , instance = self . instance ) return super ( ManyRelatedManager , self ) . get_query_set ( ) . using ( db ) . _next_is_sticky ( ) . filter ( ** self . core_filters ) def get_prefetch_query_set ( self , instances ) : instance = instances [ ] from django . db import connections db = self . _db or router . db_for_read ( instance . __class__ , instance = instance ) query = { '' % self . query_field_name : set ( obj . _get_pk_val ( ) for obj in instances ) } qs = super ( ManyRelatedManager , self ) . get_query_set ( ) . using ( db ) . _next_is_sticky ( ) . filter ( ** query ) fk = self . through . _meta . get_field ( self . source_field_name ) source_col = fk . column join_table = self . through . _meta . db_table connection = connections [ db ] qn = connection . ops . quote_name qs = qs . extra ( select = { '' : '' % ( qn ( join_table ) , qn ( source_col ) ) } ) select_attname = fk . rel . get_related_field ( ) . get_attname ( ) return ( qs , attrgetter ( '' ) , attrgetter ( select_attname ) , False , self . prefetch_cache_name ) if rel . through . _meta . auto_created : def add ( self , * objs ) : self . _add_items ( self . source_field_name , self . target_field_name , * objs ) if self . symmetrical : self . _add_items ( self . target_field_name , self . source_field_name , * objs ) add . alters_data = True def remove ( self , * objs ) : self . _remove_items ( self . source_field_name , self . target_field_name , * objs ) if self . symmetrical : self . _remove_items ( self . target_field_name , self . source_field_name , * objs ) remove . alters_data = True def clear ( self ) : self . _clear_items ( self . source_field_name ) if self . symmetrical : self . _clear_items ( self . target_field_name ) clear . alters_data = True def create ( self , ** kwargs ) : if not self . through . _meta . auto_created : opts = self . through . _meta raise AttributeError ( \"\" % ( opts . app_label , opts . object_name ) ) db = router . db_for_write ( self . instance . __class__ , instance = self . instance ) new_obj = super ( ManyRelatedManager , self . db_manager ( db ) ) . create ( ** kwargs ) self . add ( new_obj ) return new_obj create . alters_data = True def get_or_create ( self , ** kwargs ) : db = router . db_for_write ( self . instance . __class__ , instance = self . instance ) obj , created = super ( ManyRelatedManager , self . db_manager ( db ) ) . get_or_create ( ** kwargs ) if created : self . add ( obj ) return obj , created get_or_create . alters_data = True def _add_items ( self , source_field_name , target_field_name , * objs ) : from django . db . models import Model if objs : new_ids = set ( ) for obj in objs : if isinstance ( obj , self . model ) : if not router . allow_relation ( obj , self . instance ) : raise ValueError ( '' % ( obj , self . instance . _state . db , obj . _state . db ) ) fk_val = self . _get_fk_val ( obj , target_field_name ) if fk_val is None : raise ValueError ( '' % ( obj , target_field_name ) ) new_ids . add ( self . _get_fk_val ( obj , target_field_name ) ) elif isinstance ( obj , Model ) : raise TypeError ( \"\" % ( self . model . _meta . object_name , obj ) ) else : new_ids . add ( obj ) db = router . db_for_write ( self . through , instance = self . instance ) vals = self . through . _default_manager . using ( db ) . values_list ( target_field_name , flat = True ) vals = vals . filter ( ** { source_field_name : self . _fk_val , '' % target_field_name : new_ids , } ) new_ids = new_ids - set ( vals ) if self . reverse or source_field_name == self . source_field_name : signals . m2m_changed . send ( sender = self . through , action = '' , instance = self . instance , reverse = self . reverse , model = self . model , pk_set = new_ids , using = db ) self . through . _default_manager . using ( db ) . bulk_create ( [ self . through ( ** { '' % source_field_name : self . _fk_val , '' % target_field_name : obj_id , } ) for obj_id in new_ids ] ) if self . reverse or source_field_name == self . source_field_name : signals . m2m_changed . send ( sender = self . through , action = '' , instance = self . instance , reverse = self . reverse , model = self . model , pk_set = new_ids , using = db ) def _remove_items ( self , source_field_name , target_field_name , * objs ) : if objs : old_ids = set ( ) for obj in objs : ", "answer": "if isinstance ( obj , self . model ) :"}, {"prompt": " import importlib import os def load_module ( filepath ) : module_name = path_to_module_string ( filepath ) ", "answer": "return importlib . import_module ( module_name )"}, {"prompt": " from django . conf . urls import url , include , patterns from django . conf import settings from django . views . generic . base import RedirectView from django . contrib . staticfiles . urls import staticfiles_urlpatterns from django . contrib import admin ", "answer": "admin . autodiscover ( )"}, {"prompt": " \"\"\"\"\"\" import re def _atoi ( text ) : return int ( text ) if text . isdigit ( ) else text def _natural_keys ( text ) : return [ _atoi ( c ) for c in re . split ( '' , text ) ] def nsorted ( to_sort , key = None ) : \"\"\"\"\"\" if key is None : key_callback = _natural_keys else : def key_callback ( item ) : return _natural_keys ( key ( item ) ) ", "answer": "return sorted ( to_sort , key = key_callback ) "}, {"prompt": " from robotpageobjects import Page class StackTracePage ( Page ) : uri = \"\" def raise_division_by_zero ( self ) : / ", "answer": "return self "}, {"prompt": " __author__ = '' import argparse import sys import os from urllib import FancyURLopener from apiclient import discovery description = \"\"\"\"\"\" parser = argparse . ArgumentParser ( description = description ) parser . add_argument ( '' , help = '' , type = int , default = ) parser . add_argument ( '' , help = '' , action = '' ) parser . add_argument ( '' , help = '' , type = str , choices = ( '' , '' , '' , '' , '' ) ) class MyOpener ( FancyURLopener ) : version = '' myopener = MyOpener ( ) def main ( ) : args = parser . parse_args ( ) searchTerm = '' if args . kittens else '' cat_count = args . count if args . count < else if args . breed : searchTerm += '' . format ( args . breed ) service = discovery . build ( '' , '' , developerKey = os . environ . get ( '' ) ) ", "answer": "cse = service . cse ( )"}, {"prompt": " \"\"\"\"\"\" import sys import atexit __all__ = [ \"\" , \"\" ] _exithandlers = [ ] def _run_exitfuncs ( ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " from __future__ import print_function , unicode_literals from weblab . translator . translators import StoresEverythingTranslator import test . unit . configuration as configuration_module import unittest import voodoo . configuration as ConfigurationManager class StoresEverythingTranslatorTestCase ( unittest . TestCase ) : def setUp ( self ) : self . _cfg_manager = ConfigurationManager . ConfigurationManager ( ) self . _cfg_manager . append_module ( configuration_module ) self . translator = StoresEverythingTranslator ( None , None , self . _cfg_manager ) def test ( self ) : self . assertEquals ( None , self . translator . do_on_start ( '' ) ) self . assertEquals ( ", "answer": "'' ,"}, {"prompt": " try : ", "answer": "from setuptools import setup"}, {"prompt": " \"\"\"\"\"\" import warnings import numpy as np import scipy . sparse as sparse from scipy . linalg import eigh , svd , qr , solve from scipy . sparse import eye , csr_matrix from . . embedding . base import BaseEmbedding from . . utils . validation import check_array , check_random_state from . . utils . eigendecomp import null_space , check_eigen_solver def barycenter_graph ( distance_matrix , X , reg = ) : \"\"\"\"\"\" ( N , d_in ) = X . shape ( rows , cols ) = distance_matrix . nonzero ( ) W = sparse . lil_matrix ( ( N , N ) ) for i in range ( N ) : nbrs_i = cols [ rows == i ] n_neighbors_i = len ( nbrs_i ) v = np . ones ( n_neighbors_i , dtype = X . dtype ) C = X [ nbrs_i ] - X [ i ] G = np . dot ( C , C . T ) trace = np . trace ( G ) if trace > : R = reg * trace else : R = reg G . flat [ : : n_neighbors_i + ] += R w = solve ( G , v , sym_pos = True ) W [ i , nbrs_i ] = w / np . sum ( w ) return W def locally_linear_embedding ( geom , n_components , reg = , max_iter = , eigen_solver = '' , tol = , random_state = None ) : \"\"\"\"\"\" if geom . X is None : raise ValueError ( \"\" ) if geom . adjacency_matrix is None : geom . compute_adjacency_matrix ( ) W = barycenter_graph ( geom . adjacency_matrix , geom . X , reg = reg ) eigen_solver = check_eigen_solver ( eigen_solver , size = W . shape [ ] , nvec = n_components + ) if eigen_solver != '' : M = eye ( * W . shape , format = W . format ) - W M = ( M . T * M ) . tocsr ( ) else : M = ( W . T * W - W . T - W ) . toarray ( ) M . flat [ : : M . shape [ ] + ] += return null_space ( M , n_components , k_skip = , eigen_solver = eigen_solver , tol = tol , max_iter = max_iter , random_state = random_state ) class LocallyLinearEmbedding ( BaseEmbedding ) : \"\"\"\"\"\" def __init__ ( self , n_components = , radius = None , geom = None , eigen_solver = '' , random_state = None , tol = , max_iter = , reg = ) : self . n_components = n_components self . radius = radius self . geom = geom self . eigen_solver = eigen_solver self . random_state = random_state self . tol = tol self . max_iter = max_iter self . reg = reg def fit ( self , X , y = None , input_type = '' ) : \"\"\"\"\"\" X = self . _validate_input ( X , input_type ) self . fit_geometry ( X , input_type ) random_state = check_random_state ( self . random_state ) self . embedding_ , self . error_ = locally_linear_embedding ( self . geom_ , n_components = self . n_components , ", "answer": "eigen_solver = self . eigen_solver ,"}, {"prompt": " import inspect import logging import logging . config import logging . handlers import os ", "answer": "try :"}, {"prompt": " from thrift . Thrift import * from ttypes import * from thrift . Thrift import TProcessor from thrift . transport import TTransport from thrift . protocol import TBinaryProtocol , TProtocol try : from thrift . protocol import fastbinary except : fastbinary = None class Iface : \"\"\"\"\"\" def getName ( self , ) : \"\"\"\"\"\" pass def getVersion ( self , ) : \"\"\"\"\"\" pass def getStatus ( self , ) : \"\"\"\"\"\" pass def getStatusDetails ( self , ) : \"\"\"\"\"\" pass def getCounters ( self , ) : \"\"\"\"\"\" pass def getCounter ( self , key ) : \"\"\"\"\"\" pass def setOption ( self , key , value ) : \"\"\"\"\"\" pass def getOption ( self , key ) : \"\"\"\"\"\" pass def getOptions ( self , ) : \"\"\"\"\"\" pass def getCpuProfile ( self , profileDurationInSec ) : \"\"\"\"\"\" pass def aliveSince ( self , ) : \"\"\"\"\"\" pass def reinitialize ( self , ) : \"\"\"\"\"\" pass def shutdown ( self , ) : \"\"\"\"\"\" pass class Client ( Iface ) : \"\"\"\"\"\" def __init__ ( self , iprot , oprot = None ) : self . _iprot = self . _oprot = iprot if oprot != None : self . _oprot = oprot self . _seqid = def getName ( self , ) : \"\"\"\"\"\" self . send_getName ( ) return self . recv_getName ( ) def send_getName ( self , ) : self . _oprot . writeMessageBegin ( '' , TMessageType . CALL , self . _seqid ) args = getName_args ( ) args . write ( self . _oprot ) self . _oprot . writeMessageEnd ( ) self . _oprot . trans . flush ( ) def recv_getName ( self , ) : ( fname , mtype , rseqid ) = self . _iprot . readMessageBegin ( ) if mtype == TMessageType . EXCEPTION : x = TApplicationException ( ) x . read ( self . _iprot ) self . _iprot . readMessageEnd ( ) raise x result = getName_result ( ) result . read ( self . _iprot ) self . _iprot . readMessageEnd ( ) if result . success != None : return result . success raise TApplicationException ( TApplicationException . MISSING_RESULT , \"\" ) ; def getVersion ( self , ) : \"\"\"\"\"\" self . send_getVersion ( ) return self . recv_getVersion ( ) def send_getVersion ( self , ) : self . _oprot . writeMessageBegin ( '' , TMessageType . CALL , self . _seqid ) args = getVersion_args ( ) args . write ( self . _oprot ) self . _oprot . writeMessageEnd ( ) self . _oprot . trans . flush ( ) def recv_getVersion ( self , ) : ( fname , mtype , rseqid ) = self . _iprot . readMessageBegin ( ) if mtype == TMessageType . EXCEPTION : x = TApplicationException ( ) x . read ( self . _iprot ) self . _iprot . readMessageEnd ( ) raise x result = getVersion_result ( ) result . read ( self . _iprot ) self . _iprot . readMessageEnd ( ) if result . success != None : return result . success raise TApplicationException ( TApplicationException . MISSING_RESULT , \"\" ) ; def getStatus ( self , ) : \"\"\"\"\"\" self . send_getStatus ( ) return self . recv_getStatus ( ) def send_getStatus ( self , ) : self . _oprot . writeMessageBegin ( '' , TMessageType . CALL , self . _seqid ) args = getStatus_args ( ) args . write ( self . _oprot ) self . _oprot . writeMessageEnd ( ) self . _oprot . trans . flush ( ) def recv_getStatus ( self , ) : ( fname , mtype , rseqid ) = self . _iprot . readMessageBegin ( ) if mtype == TMessageType . EXCEPTION : x = TApplicationException ( ) x . read ( self . _iprot ) self . _iprot . readMessageEnd ( ) raise x result = getStatus_result ( ) result . read ( self . _iprot ) self . _iprot . readMessageEnd ( ) if result . success != None : return result . success raise TApplicationException ( TApplicationException . MISSING_RESULT , \"\" ) ; def getStatusDetails ( self , ) : \"\"\"\"\"\" self . send_getStatusDetails ( ) return self . recv_getStatusDetails ( ) def send_getStatusDetails ( self , ) : self . _oprot . writeMessageBegin ( '' , TMessageType . CALL , self . _seqid ) args = getStatusDetails_args ( ) args . write ( self . _oprot ) self . _oprot . writeMessageEnd ( ) self . _oprot . trans . flush ( ) def recv_getStatusDetails ( self , ) : ( fname , mtype , rseqid ) = self . _iprot . readMessageBegin ( ) if mtype == TMessageType . EXCEPTION : x = TApplicationException ( ) x . read ( self . _iprot ) self . _iprot . readMessageEnd ( ) raise x result = getStatusDetails_result ( ) result . read ( self . _iprot ) self . _iprot . readMessageEnd ( ) if result . success != None : return result . success raise TApplicationException ( TApplicationException . MISSING_RESULT , \"\" ) ; def getCounters ( self , ) : \"\"\"\"\"\" self . send_getCounters ( ) return self . recv_getCounters ( ) def send_getCounters ( self , ) : self . _oprot . writeMessageBegin ( '' , TMessageType . CALL , self . _seqid ) args = getCounters_args ( ) args . write ( self . _oprot ) self . _oprot . writeMessageEnd ( ) self . _oprot . trans . flush ( ) def recv_getCounters ( self , ) : ( fname , mtype , rseqid ) = self . _iprot . readMessageBegin ( ) if mtype == TMessageType . EXCEPTION : x = TApplicationException ( ) x . read ( self . _iprot ) self . _iprot . readMessageEnd ( ) raise x result = getCounters_result ( ) result . read ( self . _iprot ) self . _iprot . readMessageEnd ( ) if result . success != None : return result . success raise TApplicationException ( TApplicationException . MISSING_RESULT , \"\" ) ; def getCounter ( self , key ) : \"\"\"\"\"\" self . send_getCounter ( key ) return self . recv_getCounter ( ) def send_getCounter ( self , key ) : self . _oprot . writeMessageBegin ( '' , TMessageType . CALL , self . _seqid ) args = getCounter_args ( ) args . key = key args . write ( self . _oprot ) self . _oprot . writeMessageEnd ( ) self . _oprot . trans . flush ( ) def recv_getCounter ( self , ) : ( fname , mtype , rseqid ) = self . _iprot . readMessageBegin ( ) if mtype == TMessageType . EXCEPTION : x = TApplicationException ( ) x . read ( self . _iprot ) self . _iprot . readMessageEnd ( ) raise x result = getCounter_result ( ) result . read ( self . _iprot ) self . _iprot . readMessageEnd ( ) if result . success != None : return result . success raise TApplicationException ( TApplicationException . MISSING_RESULT , \"\" ) ; def setOption ( self , key , value ) : \"\"\"\"\"\" self . send_setOption ( key , value ) self . recv_setOption ( ) def send_setOption ( self , key , value ) : self . _oprot . writeMessageBegin ( '' , TMessageType . CALL , self . _seqid ) args = setOption_args ( ) args . key = key args . value = value args . write ( self . _oprot ) self . _oprot . writeMessageEnd ( ) self . _oprot . trans . flush ( ) def recv_setOption ( self , ) : ( fname , mtype , rseqid ) = self . _iprot . readMessageBegin ( ) if mtype == TMessageType . EXCEPTION : x = TApplicationException ( ) x . read ( self . _iprot ) self . _iprot . readMessageEnd ( ) raise x result = setOption_result ( ) result . read ( self . _iprot ) self . _iprot . readMessageEnd ( ) return def getOption ( self , key ) : \"\"\"\"\"\" self . send_getOption ( key ) return self . recv_getOption ( ) def send_getOption ( self , key ) : self . _oprot . writeMessageBegin ( '' , TMessageType . CALL , self . _seqid ) args = getOption_args ( ) args . key = key args . write ( self . _oprot ) self . _oprot . writeMessageEnd ( ) self . _oprot . trans . flush ( ) def recv_getOption ( self , ) : ( fname , mtype , rseqid ) = self . _iprot . readMessageBegin ( ) if mtype == TMessageType . EXCEPTION : x = TApplicationException ( ) x . read ( self . _iprot ) self . _iprot . readMessageEnd ( ) raise x result = getOption_result ( ) result . read ( self . _iprot ) self . _iprot . readMessageEnd ( ) if result . success != None : return result . success raise TApplicationException ( TApplicationException . MISSING_RESULT , \"\" ) ; def getOptions ( self , ) : \"\"\"\"\"\" self . send_getOptions ( ) return self . recv_getOptions ( ) def send_getOptions ( self , ) : self . _oprot . writeMessageBegin ( '' , TMessageType . CALL , self . _seqid ) args = getOptions_args ( ) args . write ( self . _oprot ) self . _oprot . writeMessageEnd ( ) self . _oprot . trans . flush ( ) def recv_getOptions ( self , ) : ( fname , mtype , rseqid ) = self . _iprot . readMessageBegin ( ) if mtype == TMessageType . EXCEPTION : x = TApplicationException ( ) x . read ( self . _iprot ) self . _iprot . readMessageEnd ( ) raise x result = getOptions_result ( ) result . read ( self . _iprot ) self . _iprot . readMessageEnd ( ) if result . success != None : return result . success raise TApplicationException ( TApplicationException . MISSING_RESULT , \"\" ) ; def getCpuProfile ( self , profileDurationInSec ) : \"\"\"\"\"\" self . send_getCpuProfile ( profileDurationInSec ) return self . recv_getCpuProfile ( ) def send_getCpuProfile ( self , profileDurationInSec ) : self . _oprot . writeMessageBegin ( '' , TMessageType . CALL , self . _seqid ) args = getCpuProfile_args ( ) args . profileDurationInSec = profileDurationInSec args . write ( self . _oprot ) self . _oprot . writeMessageEnd ( ) self . _oprot . trans . flush ( ) def recv_getCpuProfile ( self , ) : ( fname , mtype , rseqid ) = self . _iprot . readMessageBegin ( ) if mtype == TMessageType . EXCEPTION : x = TApplicationException ( ) x . read ( self . _iprot ) self . _iprot . readMessageEnd ( ) raise x result = getCpuProfile_result ( ) result . read ( self . _iprot ) self . _iprot . readMessageEnd ( ) if result . success != None : return result . success raise TApplicationException ( TApplicationException . MISSING_RESULT , \"\" ) ; def aliveSince ( self , ) : \"\"\"\"\"\" self . send_aliveSince ( ) return self . recv_aliveSince ( ) def send_aliveSince ( self , ) : self . _oprot . writeMessageBegin ( '' , TMessageType . CALL , self . _seqid ) args = aliveSince_args ( ) args . write ( self . _oprot ) self . _oprot . writeMessageEnd ( ) self . _oprot . trans . flush ( ) def recv_aliveSince ( self , ) : ( fname , mtype , rseqid ) = self . _iprot . readMessageBegin ( ) if mtype == TMessageType . EXCEPTION : x = TApplicationException ( ) x . read ( self . _iprot ) self . _iprot . readMessageEnd ( ) raise x result = aliveSince_result ( ) result . read ( self . _iprot ) self . _iprot . readMessageEnd ( ) if result . success != None : return result . success raise TApplicationException ( TApplicationException . MISSING_RESULT , \"\" ) ; def reinitialize ( self , ) : \"\"\"\"\"\" self . send_reinitialize ( ) def send_reinitialize ( self , ) : self . _oprot . writeMessageBegin ( '' , TMessageType . CALL , self . _seqid ) args = reinitialize_args ( ) args . write ( self . _oprot ) self . _oprot . writeMessageEnd ( ) self . _oprot . trans . flush ( ) def shutdown ( self , ) : \"\"\"\"\"\" self . send_shutdown ( ) def send_shutdown ( self , ) : self . _oprot . writeMessageBegin ( '' , TMessageType . CALL , self . _seqid ) args = shutdown_args ( ) args . write ( self . _oprot ) self . _oprot . writeMessageEnd ( ) self . _oprot . trans . flush ( ) class Processor ( Iface , TProcessor ) : def __init__ ( self , handler ) : self . _handler = handler self . _processMap = { } self . _processMap [ \"\" ] = Processor . process_getName self . _processMap [ \"\" ] = Processor . process_getVersion self . _processMap [ \"\" ] = Processor . process_getStatus self . _processMap [ \"\" ] = Processor . process_getStatusDetails self . _processMap [ \"\" ] = Processor . process_getCounters self . _processMap [ \"\" ] = Processor . process_getCounter self . _processMap [ \"\" ] = Processor . process_setOption self . _processMap [ \"\" ] = Processor . process_getOption self . _processMap [ \"\" ] = Processor . process_getOptions self . _processMap [ \"\" ] = Processor . process_getCpuProfile self . _processMap [ \"\" ] = Processor . process_aliveSince self . _processMap [ \"\" ] = Processor . process_reinitialize self . _processMap [ \"\" ] = Processor . process_shutdown def process ( self , iprot , oprot ) : ( name , type , seqid ) = iprot . readMessageBegin ( ) if name not in self . _processMap : iprot . skip ( TType . STRUCT ) iprot . readMessageEnd ( ) x = TApplicationException ( TApplicationException . UNKNOWN_METHOD , '' % ( name ) ) oprot . writeMessageBegin ( name , TMessageType . EXCEPTION , seqid ) x . write ( oprot ) oprot . writeMessageEnd ( ) oprot . trans . flush ( ) return else : self . _processMap [ name ] ( self , seqid , iprot , oprot ) return True def process_getName ( self , seqid , iprot , oprot ) : args = getName_args ( ) args . read ( iprot ) iprot . readMessageEnd ( ) result = getName_result ( ) result . success = self . _handler . getName ( ) oprot . writeMessageBegin ( \"\" , TMessageType . REPLY , seqid ) result . write ( oprot ) oprot . writeMessageEnd ( ) oprot . trans . flush ( ) def process_getVersion ( self , seqid , iprot , oprot ) : args = getVersion_args ( ) args . read ( iprot ) iprot . readMessageEnd ( ) result = getVersion_result ( ) result . success = self . _handler . getVersion ( ) oprot . writeMessageBegin ( \"\" , TMessageType . REPLY , seqid ) result . write ( oprot ) oprot . writeMessageEnd ( ) oprot . trans . flush ( ) def process_getStatus ( self , seqid , iprot , oprot ) : args = getStatus_args ( ) args . read ( iprot ) iprot . readMessageEnd ( ) result = getStatus_result ( ) result . success = self . _handler . getStatus ( ) oprot . writeMessageBegin ( \"\" , TMessageType . REPLY , seqid ) result . write ( oprot ) oprot . writeMessageEnd ( ) oprot . trans . flush ( ) def process_getStatusDetails ( self , seqid , iprot , oprot ) : args = getStatusDetails_args ( ) args . read ( iprot ) iprot . readMessageEnd ( ) result = getStatusDetails_result ( ) result . success = self . _handler . getStatusDetails ( ) oprot . writeMessageBegin ( \"\" , TMessageType . REPLY , seqid ) result . write ( oprot ) oprot . writeMessageEnd ( ) oprot . trans . flush ( ) def process_getCounters ( self , seqid , iprot , oprot ) : args = getCounters_args ( ) args . read ( iprot ) iprot . readMessageEnd ( ) result = getCounters_result ( ) result . success = self . _handler . getCounters ( ) oprot . writeMessageBegin ( \"\" , TMessageType . REPLY , seqid ) result . write ( oprot ) oprot . writeMessageEnd ( ) oprot . trans . flush ( ) def process_getCounter ( self , seqid , iprot , oprot ) : args = getCounter_args ( ) args . read ( iprot ) iprot . readMessageEnd ( ) result = getCounter_result ( ) result . success = self . _handler . getCounter ( args . key ) oprot . writeMessageBegin ( \"\" , TMessageType . REPLY , seqid ) result . write ( oprot ) oprot . writeMessageEnd ( ) oprot . trans . flush ( ) def process_setOption ( self , seqid , iprot , oprot ) : args = setOption_args ( ) args . read ( iprot ) iprot . readMessageEnd ( ) result = setOption_result ( ) self . _handler . setOption ( args . key , args . value ) oprot . writeMessageBegin ( \"\" , TMessageType . REPLY , seqid ) result . write ( oprot ) oprot . writeMessageEnd ( ) oprot . trans . flush ( ) def process_getOption ( self , seqid , iprot , oprot ) : args = getOption_args ( ) args . read ( iprot ) iprot . readMessageEnd ( ) result = getOption_result ( ) result . success = self . _handler . getOption ( args . key ) oprot . writeMessageBegin ( \"\" , TMessageType . REPLY , seqid ) result . write ( oprot ) oprot . writeMessageEnd ( ) oprot . trans . flush ( ) def process_getOptions ( self , seqid , iprot , oprot ) : args = getOptions_args ( ) args . read ( iprot ) iprot . readMessageEnd ( ) result = getOptions_result ( ) result . success = self . _handler . getOptions ( ) oprot . writeMessageBegin ( \"\" , TMessageType . REPLY , seqid ) result . write ( oprot ) oprot . writeMessageEnd ( ) oprot . trans . flush ( ) def process_getCpuProfile ( self , seqid , iprot , oprot ) : args = getCpuProfile_args ( ) args . read ( iprot ) iprot . readMessageEnd ( ) result = getCpuProfile_result ( ) result . success = self . _handler . getCpuProfile ( args . profileDurationInSec ) oprot . writeMessageBegin ( \"\" , TMessageType . REPLY , seqid ) result . write ( oprot ) oprot . writeMessageEnd ( ) oprot . trans . flush ( ) def process_aliveSince ( self , seqid , iprot , oprot ) : args = aliveSince_args ( ) args . read ( iprot ) iprot . readMessageEnd ( ) result = aliveSince_result ( ) result . success = self . _handler . aliveSince ( ) oprot . writeMessageBegin ( \"\" , TMessageType . REPLY , seqid ) result . write ( oprot ) oprot . writeMessageEnd ( ) oprot . trans . flush ( ) def process_reinitialize ( self , seqid , iprot , oprot ) : args = reinitialize_args ( ) args . read ( iprot ) iprot . readMessageEnd ( ) self . _handler . reinitialize ( ) return def process_shutdown ( self , seqid , iprot , oprot ) : args = shutdown_args ( ) args . read ( iprot ) iprot . readMessageEnd ( ) self . _handler . shutdown ( ) return class getName_args : thrift_spec = ( ) def read ( self , iprot ) : if iprot . __class__ == TBinaryProtocol . TBinaryProtocolAccelerated and isinstance ( iprot . trans , TTransport . CReadableTransport ) and self . thrift_spec is not None and fastbinary is not None : fastbinary . decode_binary ( self , iprot . trans , ( self . __class__ , self . thrift_spec ) ) return iprot . readStructBegin ( ) while True : ( fname , ftype , fid ) = iprot . readFieldBegin ( ) if ftype == TType . STOP : break else : iprot . skip ( ftype ) iprot . readFieldEnd ( ) iprot . readStructEnd ( ) def write ( self , oprot ) : if oprot . __class__ == TBinaryProtocol . TBinaryProtocolAccelerated and self . thrift_spec is not None and fastbinary is not None : oprot . trans . write ( fastbinary . encode_binary ( self , ( self . __class__ , self . thrift_spec ) ) ) return oprot . writeStructBegin ( '' ) oprot . writeFieldStop ( ) oprot . writeStructEnd ( ) def validate ( self ) : return def __repr__ ( self ) : L = [ '' % ( key , value ) for key , value in self . __dict__ . iteritems ( ) ] return '' % ( self . __class__ . __name__ , '' . join ( L ) ) def __eq__ ( self , other ) : return isinstance ( other , self . __class__ ) and self . __dict__ == other . __dict__ def __ne__ ( self , other ) : return not ( self == other ) class getName_result : \"\"\"\"\"\" thrift_spec = ( ( , TType . STRING , '' , None , None , ) , ) def __init__ ( self , success = None , ) : self . success = success def read ( self , iprot ) : if iprot . __class__ == TBinaryProtocol . TBinaryProtocolAccelerated and isinstance ( iprot . trans , TTransport . CReadableTransport ) and self . thrift_spec is not None and fastbinary is not None : fastbinary . decode_binary ( self , iprot . trans , ( self . __class__ , self . thrift_spec ) ) return iprot . readStructBegin ( ) while True : ( fname , ftype , fid ) = iprot . readFieldBegin ( ) if ftype == TType . STOP : break if fid == : if ftype == TType . STRING : self . success = iprot . readString ( ) ; else : iprot . skip ( ftype ) else : iprot . skip ( ftype ) iprot . readFieldEnd ( ) iprot . readStructEnd ( ) def write ( self , oprot ) : if oprot . __class__ == TBinaryProtocol . TBinaryProtocolAccelerated and self . thrift_spec is not None and fastbinary is not None : oprot . trans . write ( fastbinary . encode_binary ( self , ( self . __class__ , self . thrift_spec ) ) ) return oprot . writeStructBegin ( '' ) if self . success != None : oprot . writeFieldBegin ( '' , TType . STRING , ) oprot . writeString ( self . success ) oprot . writeFieldEnd ( ) oprot . writeFieldStop ( ) oprot . writeStructEnd ( ) def validate ( self ) : return def __repr__ ( self ) : L = [ '' % ( key , value ) for key , value in self . __dict__ . iteritems ( ) ] return '' % ( self . __class__ . __name__ , '' . join ( L ) ) def __eq__ ( self , other ) : return isinstance ( other , self . __class__ ) and self . __dict__ == other . __dict__ def __ne__ ( self , other ) : return not ( self == other ) class getVersion_args : thrift_spec = ( ) def read ( self , iprot ) : if iprot . __class__ == TBinaryProtocol . TBinaryProtocolAccelerated and isinstance ( iprot . trans , TTransport . CReadableTransport ) and self . thrift_spec is not None and fastbinary is not None : fastbinary . decode_binary ( self , iprot . trans , ( self . __class__ , self . thrift_spec ) ) return iprot . readStructBegin ( ) while True : ( fname , ftype , fid ) = iprot . readFieldBegin ( ) if ftype == TType . STOP : break else : iprot . skip ( ftype ) iprot . readFieldEnd ( ) iprot . readStructEnd ( ) def write ( self , oprot ) : if oprot . __class__ == TBinaryProtocol . TBinaryProtocolAccelerated and self . thrift_spec is not None and fastbinary is not None : oprot . trans . write ( fastbinary . encode_binary ( self , ( self . __class__ , self . thrift_spec ) ) ) return oprot . writeStructBegin ( '' ) oprot . writeFieldStop ( ) oprot . writeStructEnd ( ) def validate ( self ) : return def __repr__ ( self ) : L = [ '' % ( key , value ) for key , value in self . __dict__ . iteritems ( ) ] return '' % ( self . __class__ . __name__ , '' . join ( L ) ) def __eq__ ( self , other ) : return isinstance ( other , self . __class__ ) and self . __dict__ == other . __dict__ def __ne__ ( self , other ) : return not ( self == other ) class getVersion_result : \"\"\"\"\"\" thrift_spec = ( ( , TType . STRING , '' , None , None , ) , ) def __init__ ( self , success = None , ) : self . success = success def read ( self , iprot ) : if iprot . __class__ == TBinaryProtocol . TBinaryProtocolAccelerated and isinstance ( iprot . trans , TTransport . CReadableTransport ) and self . thrift_spec is not None and fastbinary is not None : fastbinary . decode_binary ( self , iprot . trans , ( self . __class__ , self . thrift_spec ) ) return iprot . readStructBegin ( ) while True : ( fname , ftype , fid ) = iprot . readFieldBegin ( ) if ftype == TType . STOP : break if fid == : if ftype == TType . STRING : self . success = iprot . readString ( ) ; else : iprot . skip ( ftype ) else : iprot . skip ( ftype ) iprot . readFieldEnd ( ) iprot . readStructEnd ( ) def write ( self , oprot ) : if oprot . __class__ == TBinaryProtocol . TBinaryProtocolAccelerated and self . thrift_spec is not None and fastbinary is not None : oprot . trans . write ( fastbinary . encode_binary ( self , ( self . __class__ , self . thrift_spec ) ) ) return oprot . writeStructBegin ( '' ) if self . success != None : oprot . writeFieldBegin ( '' , TType . STRING , ) oprot . writeString ( self . success ) oprot . writeFieldEnd ( ) oprot . writeFieldStop ( ) oprot . writeStructEnd ( ) def validate ( self ) : return def __repr__ ( self ) : L = [ '' % ( key , value ) for key , value in self . __dict__ . iteritems ( ) ] return '' % ( self . __class__ . __name__ , '' . join ( L ) ) def __eq__ ( self , other ) : return isinstance ( other , self . __class__ ) and self . __dict__ == other . __dict__ def __ne__ ( self , other ) : return not ( self == other ) class getStatus_args : thrift_spec = ( ) def read ( self , iprot ) : if iprot . __class__ == TBinaryProtocol . TBinaryProtocolAccelerated and isinstance ( iprot . trans , TTransport . CReadableTransport ) and self . thrift_spec is not None and fastbinary is not None : fastbinary . decode_binary ( self , iprot . trans , ( self . __class__ , self . thrift_spec ) ) return iprot . readStructBegin ( ) while True : ( fname , ftype , fid ) = iprot . readFieldBegin ( ) if ftype == TType . STOP : break else : iprot . skip ( ftype ) iprot . readFieldEnd ( ) iprot . readStructEnd ( ) def write ( self , oprot ) : if oprot . __class__ == TBinaryProtocol . TBinaryProtocolAccelerated and self . thrift_spec is not None and fastbinary is not None : oprot . trans . write ( fastbinary . encode_binary ( self , ( self . __class__ , self . thrift_spec ) ) ) return oprot . writeStructBegin ( '' ) oprot . writeFieldStop ( ) oprot . writeStructEnd ( ) def validate ( self ) : return def __repr__ ( self ) : L = [ '' % ( key , value ) for key , value in self . __dict__ . iteritems ( ) ] return '' % ( self . __class__ . __name__ , '' . join ( L ) ) def __eq__ ( self , other ) : return isinstance ( other , self . __class__ ) and self . __dict__ == other . __dict__ def __ne__ ( self , other ) : return not ( self == other ) class getStatus_result : \"\"\"\"\"\" thrift_spec = ( ( , TType . I32 , '' , None , None , ) , ) def __init__ ( self , success = None , ) : self . success = success def read ( self , iprot ) : if iprot . __class__ == TBinaryProtocol . TBinaryProtocolAccelerated and isinstance ( iprot . trans , TTransport . CReadableTransport ) and self . thrift_spec is not None and fastbinary is not None : fastbinary . decode_binary ( self , iprot . trans , ( self . __class__ , self . thrift_spec ) ) return iprot . readStructBegin ( ) while True : ( fname , ftype , fid ) = iprot . readFieldBegin ( ) if ftype == TType . STOP : break if fid == : if ftype == TType . I32 : self . success = iprot . readI32 ( ) ; else : iprot . skip ( ftype ) else : iprot . skip ( ftype ) iprot . readFieldEnd ( ) iprot . readStructEnd ( ) def write ( self , oprot ) : if oprot . __class__ == TBinaryProtocol . TBinaryProtocolAccelerated and self . thrift_spec is not None and fastbinary is not None : oprot . trans . write ( fastbinary . encode_binary ( self , ( self . __class__ , self . thrift_spec ) ) ) return oprot . writeStructBegin ( '' ) if self . success != None : oprot . writeFieldBegin ( '' , TType . I32 , ) oprot . writeI32 ( self . success ) oprot . writeFieldEnd ( ) oprot . writeFieldStop ( ) oprot . writeStructEnd ( ) def validate ( self ) : return def __repr__ ( self ) : L = [ '' % ( key , value ) for key , value in self . __dict__ . iteritems ( ) ] return '' % ( self . __class__ . __name__ , '' . join ( L ) ) def __eq__ ( self , other ) : return isinstance ( other , self . __class__ ) and self . __dict__ == other . __dict__ def __ne__ ( self , other ) : return not ( self == other ) class getStatusDetails_args : thrift_spec = ( ) def read ( self , iprot ) : if iprot . __class__ == TBinaryProtocol . TBinaryProtocolAccelerated and isinstance ( iprot . trans , TTransport . CReadableTransport ) and self . thrift_spec is not None and fastbinary is not None : fastbinary . decode_binary ( self , iprot . trans , ( self . __class__ , self . thrift_spec ) ) return iprot . readStructBegin ( ) while True : ( fname , ftype , fid ) = iprot . readFieldBegin ( ) if ftype == TType . STOP : break else : iprot . skip ( ftype ) iprot . readFieldEnd ( ) iprot . readStructEnd ( ) def write ( self , oprot ) : if oprot . __class__ == TBinaryProtocol . TBinaryProtocolAccelerated and self . thrift_spec is not None and fastbinary is not None : oprot . trans . write ( fastbinary . encode_binary ( self , ( self . __class__ , self . thrift_spec ) ) ) return oprot . writeStructBegin ( '' ) oprot . writeFieldStop ( ) oprot . writeStructEnd ( ) def validate ( self ) : return def __repr__ ( self ) : L = [ '' % ( key , value ) for key , value in self . __dict__ . iteritems ( ) ] return '' % ( self . __class__ . __name__ , '' . join ( L ) ) def __eq__ ( self , other ) : return isinstance ( other , self . __class__ ) and self . __dict__ == other . __dict__ def __ne__ ( self , other ) : return not ( self == other ) class getStatusDetails_result : \"\"\"\"\"\" thrift_spec = ( ( , TType . STRING , '' , None , None , ) , ) def __init__ ( self , success = None , ) : self . success = success def read ( self , iprot ) : if iprot . __class__ == TBinaryProtocol . TBinaryProtocolAccelerated and isinstance ( iprot . trans , TTransport . CReadableTransport ) and self . thrift_spec is not None and fastbinary is not None : fastbinary . decode_binary ( self , iprot . trans , ( self . __class__ , self . thrift_spec ) ) return iprot . readStructBegin ( ) while True : ( fname , ftype , fid ) = iprot . readFieldBegin ( ) if ftype == TType . STOP : break if fid == : if ftype == TType . STRING : self . success = iprot . readString ( ) ; else : iprot . skip ( ftype ) else : iprot . skip ( ftype ) iprot . readFieldEnd ( ) iprot . readStructEnd ( ) def write ( self , oprot ) : if oprot . __class__ == TBinaryProtocol . TBinaryProtocolAccelerated and self . thrift_spec is not None and fastbinary is not None : oprot . trans . write ( fastbinary . encode_binary ( self , ( self . __class__ , self . thrift_spec ) ) ) return oprot . writeStructBegin ( '' ) if self . success != None : oprot . writeFieldBegin ( '' , TType . STRING , ) oprot . writeString ( self . success ) oprot . writeFieldEnd ( ) oprot . writeFieldStop ( ) oprot . writeStructEnd ( ) def validate ( self ) : return def __repr__ ( self ) : L = [ '' % ( key , value ) for key , value in self . __dict__ . iteritems ( ) ] return '' % ( self . __class__ . __name__ , '' . join ( L ) ) def __eq__ ( self , other ) : return isinstance ( other , self . __class__ ) and self . __dict__ == other . __dict__ def __ne__ ( self , other ) : return not ( self == other ) class getCounters_args : thrift_spec = ( ) def read ( self , iprot ) : if iprot . __class__ == TBinaryProtocol . TBinaryProtocolAccelerated and isinstance ( iprot . trans , TTransport . CReadableTransport ) and self . thrift_spec is not None and fastbinary is not None : fastbinary . decode_binary ( self , iprot . trans , ( self . __class__ , self . thrift_spec ) ) return iprot . readStructBegin ( ) while True : ( fname , ftype , fid ) = iprot . readFieldBegin ( ) if ftype == TType . STOP : break else : iprot . skip ( ftype ) iprot . readFieldEnd ( ) iprot . readStructEnd ( ) def write ( self , oprot ) : if oprot . __class__ == TBinaryProtocol . TBinaryProtocolAccelerated and self . thrift_spec is not None and fastbinary is not None : oprot . trans . write ( fastbinary . encode_binary ( self , ( self . __class__ , self . thrift_spec ) ) ) return oprot . writeStructBegin ( '' ) oprot . writeFieldStop ( ) oprot . writeStructEnd ( ) def validate ( self ) : return def __repr__ ( self ) : L = [ '' % ( key , value ) for key , value in self . __dict__ . iteritems ( ) ] return '' % ( self . __class__ . __name__ , '' . join ( L ) ) def __eq__ ( self , other ) : return isinstance ( other , self . __class__ ) and self . __dict__ == other . __dict__ def __ne__ ( self , other ) : return not ( self == other ) class getCounters_result : \"\"\"\"\"\" thrift_spec = ( ( , TType . MAP , '' , ( TType . STRING , None , TType . I64 , None ) , None , ) , ) def __init__ ( self , success = None , ) : self . success = success def read ( self , iprot ) : if iprot . __class__ == TBinaryProtocol . TBinaryProtocolAccelerated and isinstance ( iprot . trans , TTransport . CReadableTransport ) and self . thrift_spec is not None and fastbinary is not None : fastbinary . decode_binary ( self , iprot . trans , ( self . __class__ , self . thrift_spec ) ) return iprot . readStructBegin ( ) while True : ( fname , ftype , fid ) = iprot . readFieldBegin ( ) if ftype == TType . STOP : break if fid == : if ftype == TType . MAP : self . success = { } ( _ktype1 , _vtype2 , _size0 ) = iprot . readMapBegin ( ) for _i4 in xrange ( _size0 ) : _key5 = iprot . readString ( ) ; _val6 = iprot . readI64 ( ) ; self . success [ _key5 ] = _val6 iprot . readMapEnd ( ) else : iprot . skip ( ftype ) else : iprot . skip ( ftype ) iprot . readFieldEnd ( ) iprot . readStructEnd ( ) def write ( self , oprot ) : if oprot . __class__ == TBinaryProtocol . TBinaryProtocolAccelerated and self . thrift_spec is not None and fastbinary is not None : oprot . trans . write ( fastbinary . encode_binary ( self , ( self . __class__ , self . thrift_spec ) ) ) return oprot . writeStructBegin ( '' ) if self . success != None : oprot . writeFieldBegin ( '' , TType . MAP , ) oprot . writeMapBegin ( TType . STRING , TType . I64 , len ( self . success ) ) for kiter7 , viter8 in self . success . items ( ) : oprot . writeString ( kiter7 ) oprot . writeI64 ( viter8 ) oprot . writeMapEnd ( ) oprot . writeFieldEnd ( ) oprot . writeFieldStop ( ) oprot . writeStructEnd ( ) def validate ( self ) : return def __repr__ ( self ) : L = [ '' % ( key , value ) for key , value in self . __dict__ . iteritems ( ) ] return '' % ( self . __class__ . __name__ , '' . join ( L ) ) def __eq__ ( self , other ) : return isinstance ( other , self . __class__ ) and self . __dict__ == other . __dict__ def __ne__ ( self , other ) : return not ( self == other ) class getCounter_args : \"\"\"\"\"\" thrift_spec = ( None , ( , TType . STRING , '' , None , None , ) , ) def __init__ ( self , key = None , ) : self . key = key def read ( self , iprot ) : if iprot . __class__ == TBinaryProtocol . TBinaryProtocolAccelerated and isinstance ( iprot . trans , TTransport . CReadableTransport ) and self . thrift_spec is not None and fastbinary is not None : fastbinary . decode_binary ( self , iprot . trans , ( self . __class__ , self . thrift_spec ) ) return iprot . readStructBegin ( ) while True : ( fname , ftype , fid ) = iprot . readFieldBegin ( ) if ftype == TType . STOP : break if fid == : if ftype == TType . STRING : self . key = iprot . readString ( ) ; else : iprot . skip ( ftype ) else : iprot . skip ( ftype ) iprot . readFieldEnd ( ) iprot . readStructEnd ( ) def write ( self , oprot ) : if oprot . __class__ == TBinaryProtocol . TBinaryProtocolAccelerated and self . thrift_spec is not None and fastbinary is not None : oprot . trans . write ( fastbinary . encode_binary ( self , ( self . __class__ , self . thrift_spec ) ) ) return oprot . writeStructBegin ( '' ) if self . key != None : oprot . writeFieldBegin ( '' , TType . STRING , ) oprot . writeString ( self . key ) oprot . writeFieldEnd ( ) oprot . writeFieldStop ( ) oprot . writeStructEnd ( ) def validate ( self ) : return def __repr__ ( self ) : L = [ '' % ( key , value ) for key , value in self . __dict__ . iteritems ( ) ] return '' % ( self . __class__ . __name__ , '' . join ( L ) ) def __eq__ ( self , other ) : return isinstance ( other , self . __class__ ) and self . __dict__ == other . __dict__ def __ne__ ( self , other ) : return not ( self == other ) class getCounter_result : \"\"\"\"\"\" thrift_spec = ( ( , TType . I64 , '' , None , None , ) , ) def __init__ ( self , success = None , ) : self . success = success def read ( self , iprot ) : if iprot . __class__ == TBinaryProtocol . TBinaryProtocolAccelerated and isinstance ( iprot . trans , TTransport . CReadableTransport ) and self . thrift_spec is not None and fastbinary is not None : fastbinary . decode_binary ( self , iprot . trans , ( self . __class__ , self . thrift_spec ) ) return iprot . readStructBegin ( ) while True : ( fname , ftype , fid ) = iprot . readFieldBegin ( ) if ftype == TType . STOP : break if fid == : if ftype == TType . I64 : self . success = iprot . readI64 ( ) ; else : iprot . skip ( ftype ) else : iprot . skip ( ftype ) iprot . readFieldEnd ( ) iprot . readStructEnd ( ) def write ( self , oprot ) : if oprot . __class__ == TBinaryProtocol . TBinaryProtocolAccelerated and self . thrift_spec is not None and fastbinary is not None : oprot . trans . write ( fastbinary . encode_binary ( self , ( self . __class__ , self . thrift_spec ) ) ) return oprot . writeStructBegin ( '' ) if self . success != None : oprot . writeFieldBegin ( '' , TType . I64 , ) oprot . writeI64 ( self . success ) oprot . writeFieldEnd ( ) oprot . writeFieldStop ( ) oprot . writeStructEnd ( ) def validate ( self ) : return def __repr__ ( self ) : L = [ '' % ( key , value ) for key , value in self . __dict__ . iteritems ( ) ] return '' % ( self . __class__ . __name__ , '' . join ( L ) ) def __eq__ ( self , other ) : return isinstance ( other , self . __class__ ) and self . __dict__ == other . __dict__ def __ne__ ( self , other ) : return not ( self == other ) class setOption_args : \"\"\"\"\"\" thrift_spec = ( None , ( , TType . STRING , '' , None , None , ) , ( , TType . STRING , '' , None , None , ) , ) def __init__ ( self , key = None , value = None , ) : self . key = key self . value = value def read ( self , iprot ) : if iprot . __class__ == TBinaryProtocol . TBinaryProtocolAccelerated and isinstance ( iprot . trans , TTransport . CReadableTransport ) and self . thrift_spec is not None and fastbinary is not None : fastbinary . decode_binary ( self , iprot . trans , ( self . __class__ , self . thrift_spec ) ) return iprot . readStructBegin ( ) while True : ( fname , ftype , fid ) = iprot . readFieldBegin ( ) if ftype == TType . STOP : break if fid == : if ftype == TType . STRING : self . key = iprot . readString ( ) ; else : iprot . skip ( ftype ) elif fid == : if ftype == TType . STRING : self . value = iprot . readString ( ) ; else : iprot . skip ( ftype ) else : iprot . skip ( ftype ) iprot . readFieldEnd ( ) iprot . readStructEnd ( ) def write ( self , oprot ) : if oprot . __class__ == TBinaryProtocol . TBinaryProtocolAccelerated and self . thrift_spec is not None and fastbinary is not None : oprot . trans . write ( fastbinary . encode_binary ( self , ( self . __class__ , self . thrift_spec ) ) ) return oprot . writeStructBegin ( '' ) if self . key != None : oprot . writeFieldBegin ( '' , TType . STRING , ) oprot . writeString ( self . key ) oprot . writeFieldEnd ( ) if self . value != None : oprot . writeFieldBegin ( '' , TType . STRING , ) oprot . writeString ( self . value ) oprot . writeFieldEnd ( ) oprot . writeFieldStop ( ) oprot . writeStructEnd ( ) def validate ( self ) : return def __repr__ ( self ) : L = [ '' % ( key , value ) for key , value in self . __dict__ . iteritems ( ) ] return '' % ( self . __class__ . __name__ , '' . join ( L ) ) def __eq__ ( self , other ) : return isinstance ( other , self . __class__ ) and self . __dict__ == other . __dict__ def __ne__ ( self , other ) : return not ( self == other ) class setOption_result : thrift_spec = ( ) def read ( self , iprot ) : if iprot . __class__ == TBinaryProtocol . TBinaryProtocolAccelerated and isinstance ( iprot . trans , TTransport . CReadableTransport ) and self . thrift_spec is not None and fastbinary is not None : fastbinary . decode_binary ( self , iprot . trans , ( self . __class__ , self . thrift_spec ) ) return iprot . readStructBegin ( ) while True : ( fname , ftype , fid ) = iprot . readFieldBegin ( ) if ftype == TType . STOP : break else : iprot . skip ( ftype ) iprot . readFieldEnd ( ) iprot . readStructEnd ( ) def write ( self , oprot ) : if oprot . __class__ == TBinaryProtocol . TBinaryProtocolAccelerated and self . thrift_spec is not None and fastbinary is not None : oprot . trans . write ( fastbinary . encode_binary ( self , ( self . __class__ , self . thrift_spec ) ) ) return oprot . writeStructBegin ( '' ) oprot . writeFieldStop ( ) oprot . writeStructEnd ( ) def validate ( self ) : return def __repr__ ( self ) : L = [ '' % ( key , value ) for key , value in self . __dict__ . iteritems ( ) ] return '' % ( self . __class__ . __name__ , '' . join ( L ) ) def __eq__ ( self , other ) : return isinstance ( other , self . __class__ ) and self . __dict__ == other . __dict__ def __ne__ ( self , other ) : return not ( self == other ) class getOption_args : \"\"\"\"\"\" thrift_spec = ( None , ( , TType . STRING , '' , None , None , ) , ) def __init__ ( self , key = None , ) : self . key = key def read ( self , iprot ) : if iprot . __class__ == TBinaryProtocol . TBinaryProtocolAccelerated and isinstance ( iprot . trans , TTransport . CReadableTransport ) and self . thrift_spec is not None and fastbinary is not None : fastbinary . decode_binary ( self , iprot . trans , ( self . __class__ , self . thrift_spec ) ) return iprot . readStructBegin ( ) while True : ( fname , ftype , fid ) = iprot . readFieldBegin ( ) if ftype == TType . STOP : break if fid == : if ftype == TType . STRING : self . key = iprot . readString ( ) ; else : iprot . skip ( ftype ) else : iprot . skip ( ftype ) iprot . readFieldEnd ( ) iprot . readStructEnd ( ) def write ( self , oprot ) : if oprot . __class__ == TBinaryProtocol . TBinaryProtocolAccelerated and self . thrift_spec is not None and fastbinary is not None : oprot . trans . write ( fastbinary . encode_binary ( self , ( self . __class__ , self . thrift_spec ) ) ) return oprot . writeStructBegin ( '' ) if self . key != None : oprot . writeFieldBegin ( '' , TType . STRING , ) oprot . writeString ( self . key ) oprot . writeFieldEnd ( ) oprot . writeFieldStop ( ) oprot . writeStructEnd ( ) def validate ( self ) : return def __repr__ ( self ) : L = [ '' % ( key , value ) for key , value in self . __dict__ . iteritems ( ) ] return '' % ( self . __class__ . __name__ , '' . join ( L ) ) def __eq__ ( self , other ) : return isinstance ( other , self . __class__ ) and self . __dict__ == other . __dict__ def __ne__ ( self , other ) : return not ( self == other ) class getOption_result : \"\"\"\"\"\" thrift_spec = ( ( , TType . STRING , '' , None , None , ) , ) def __init__ ( self , success = None , ) : self . success = success def read ( self , iprot ) : if iprot . __class__ == TBinaryProtocol . TBinaryProtocolAccelerated and isinstance ( iprot . trans , TTransport . CReadableTransport ) and self . thrift_spec is not None and fastbinary is not None : fastbinary . decode_binary ( self , iprot . trans , ( self . __class__ , self . thrift_spec ) ) return iprot . readStructBegin ( ) while True : ( fname , ftype , fid ) = iprot . readFieldBegin ( ) if ftype == TType . STOP : break if fid == : if ftype == TType . STRING : self . success = iprot . readString ( ) ; else : iprot . skip ( ftype ) else : iprot . skip ( ftype ) iprot . readFieldEnd ( ) iprot . readStructEnd ( ) def write ( self , oprot ) : if oprot . __class__ == TBinaryProtocol . TBinaryProtocolAccelerated and self . thrift_spec is not None and fastbinary is not None : oprot . trans . write ( fastbinary . encode_binary ( self , ( self . __class__ , self . thrift_spec ) ) ) return oprot . writeStructBegin ( '' ) if self . success != None : oprot . writeFieldBegin ( '' , TType . STRING , ) oprot . writeString ( self . success ) oprot . writeFieldEnd ( ) oprot . writeFieldStop ( ) oprot . writeStructEnd ( ) def validate ( self ) : return def __repr__ ( self ) : L = [ '' % ( key , value ) for key , value in self . __dict__ . iteritems ( ) ] return '' % ( self . __class__ . __name__ , '' . join ( L ) ) def __eq__ ( self , other ) : return isinstance ( other , self . __class__ ) and self . __dict__ == other . __dict__ def __ne__ ( self , other ) : return not ( self == other ) class getOptions_args : thrift_spec = ( ) def read ( self , iprot ) : if iprot . __class__ == TBinaryProtocol . TBinaryProtocolAccelerated and isinstance ( iprot . trans , TTransport . CReadableTransport ) and self . thrift_spec is not None and fastbinary is not None : fastbinary . decode_binary ( self , iprot . trans , ( self . __class__ , self . thrift_spec ) ) return iprot . readStructBegin ( ) while True : ( fname , ftype , fid ) = iprot . readFieldBegin ( ) if ftype == TType . STOP : break else : iprot . skip ( ftype ) iprot . readFieldEnd ( ) iprot . readStructEnd ( ) def write ( self , oprot ) : if oprot . __class__ == TBinaryProtocol . TBinaryProtocolAccelerated and self . thrift_spec is not None and fastbinary is not None : oprot . trans . write ( fastbinary . encode_binary ( self , ( self . __class__ , self . thrift_spec ) ) ) return oprot . writeStructBegin ( '' ) oprot . writeFieldStop ( ) oprot . writeStructEnd ( ) def validate ( self ) : return def __repr__ ( self ) : L = [ '' % ( key , value ) for key , value in self . __dict__ . iteritems ( ) ] return '' % ( self . __class__ . __name__ , '' . join ( L ) ) def __eq__ ( self , other ) : return isinstance ( other , self . __class__ ) and self . __dict__ == other . __dict__ def __ne__ ( self , other ) : return not ( self == other ) class getOptions_result : \"\"\"\"\"\" thrift_spec = ( ( , TType . MAP , '' , ( TType . STRING , None , TType . STRING , None ) , None , ) , ) def __init__ ( self , success = None , ) : self . success = success def read ( self , iprot ) : if iprot . __class__ == TBinaryProtocol . TBinaryProtocolAccelerated and isinstance ( iprot . trans , TTransport . CReadableTransport ) and self . thrift_spec is not None and fastbinary is not None : fastbinary . decode_binary ( self , iprot . trans , ( self . __class__ , self . thrift_spec ) ) return iprot . readStructBegin ( ) while True : ( fname , ftype , fid ) = iprot . readFieldBegin ( ) if ftype == TType . STOP : break if fid == : if ftype == TType . MAP : self . success = { } ( _ktype10 , _vtype11 , _size9 ) = iprot . readMapBegin ( ) ", "answer": "for _i13 in xrange ( _size9 ) :"}, {"prompt": " from keystonemiddleware import auth_token from neutron_lib import exceptions as n_exc from oslo_config import cfg from oslo_middleware import cors from oslo_middleware import request_id import pecan from neutron . api import versions from neutron . pecan_wsgi import hooks from neutron . pecan_wsgi import startup CONF = cfg . CONF CONF . import_opt ( '' , '' ) CONF . import_opt ( '' , '' ) def setup_app ( * args , ** kwargs ) : config = { '' : { '' : CONF . bind_port , '' : CONF . bind_host } , '' : { '' : '' , '' : [ '' ] , } } pecan_config = pecan . configuration . conf_from_dict ( config ) app_hooks = [ hooks . ExceptionTranslationHook ( ) , hooks . ContextHook ( ) , hooks . BodyValidationHook ( ) , ", "answer": "hooks . OwnershipValidationHook ( ) ,"}, {"prompt": " \"\"\"\"\"\" import numpy as np from scipy . optimize import fmin_slsqp import statsmodels . base . l1_solvers_common as l1_solvers_common def fit_l1_slsqp ( f , score , start_params , args , kwargs , disp = False , maxiter = , callback = None , retall = False , full_output = False , hess = None ) : \"\"\"\"\"\" start_params = np . array ( start_params ) . ravel ( '' ) k_params = len ( start_params ) x0 = np . append ( start_params , np . fabs ( start_params ) ) alpha = np . array ( kwargs [ '' ] ) . ravel ( '' ) alpha = alpha * np . ones ( k_params ) assert alpha . min ( ) >= disp_slsqp = _get_disp_slsqp ( disp , retall ) acc = kwargs . setdefault ( '' , ) func = lambda x_full : _objective_func ( f , x_full , k_params , alpha , * args ) f_ieqcons_wrap = lambda x_full : _f_ieqcons ( x_full , k_params ) fprime_wrap = lambda x_full : _fprime ( score , x_full , k_params , alpha ) fprime_ieqcons_wrap = lambda x_full : _fprime_ieqcons ( x_full , k_params ) results = fmin_slsqp ( func , x0 , f_ieqcons = f_ieqcons_wrap , fprime = fprime_wrap , acc = acc , iter = maxiter , disp = disp_slsqp , full_output = full_output , fprime_ieqcons = fprime_ieqcons_wrap ) params = np . asarray ( results [ ] [ : k_params ] ) qc_tol = kwargs [ '' ] qc_verbose = kwargs [ '' ] passed = l1_solvers_common . qc_results ( params , alpha , score , qc_tol , qc_verbose ) trim_mode = kwargs [ '' ] size_trim_tol = kwargs [ '' ] auto_trim_tol = kwargs [ '' ] params , trimmed = l1_solvers_common . do_trim_params ( params , k_params , alpha , score , passed , trim_mode , size_trim_tol , auto_trim_tol ) if full_output : x_full , fx , its , imode , smode = results fopt = func ( np . asarray ( x_full ) ) converged = '' if imode == else smode iterations = its gopt = float ( '' ) hopt = float ( '' ) retvals = { '' : fopt , '' : converged , '' : iterations , '' : gopt , '' : hopt , '' : trimmed } if full_output : return params , retvals else : return params def _get_disp_slsqp ( disp , retall ) : if disp or retall : if disp : disp_slsqp = if retall : disp_slsqp = else : ", "answer": "disp_slsqp = "}, {"prompt": " import nose . tools as nt import numpy . testing as npt import matplotlib . pyplot as plt from . import PlotTestCase from . . import miscplot as misc from seaborn import color_palette class TestPalPlot ( PlotTestCase ) : \"\"\"\"\"\" def test_palplot_size ( self ) : ", "answer": "pal4 = color_palette ( \"\" , )"}, {"prompt": " import functools import os import pytest from click . testing import CliRunner from shpkpr . cli . entrypoint import cli @ pytest . fixture ( scope = \"\" ) def env ( ) : env = { \"\" : os . environ . get ( \"\" , None ) , \"\" : os . environ . get ( \"\" , None ) , \"\" : os . environ . get ( \"\" , None ) , \"\" : os . environ . get ( \"\" , None ) , \"\" : os . environ . get ( \"\" , None ) , \"\" : os . environ . get ( \"\" , None ) , \"\" : os . environ . get ( \"\" , None ) , } assert None not in env . values ( ) return env @ pytest . fixture def runner ( ) : runner = CliRunner ( ) ", "answer": "return functools . partial ( runner . invoke , cli ) "}, {"prompt": " '''''' import time ", "answer": "import grovepi"}, {"prompt": " from __future__ import division import numpy as np def mymean ( x ) : ", "answer": "return np . ma . mean ( x ) "}, {"prompt": " from datetime import datetime try : from urlparse import urlparse except ImportError : from urllib . parse import urlparse try : from collections import OrderedDict except ImportError : from ordereddict import OrderedDict from sqlalchemy import Integer , UnicodeText , Float , DateTime , Boolean from six import string_types row_type = OrderedDict def guess_type ( sample ) : if isinstance ( sample , bool ) : return Boolean elif isinstance ( sample , int ) : return Integer elif isinstance ( sample , float ) : return Float elif isinstance ( sample , datetime ) : return DateTime return UnicodeText def convert_row ( row_type , row ) : if row is None : return None return row_type ( row . items ( ) ) def normalize_column_name ( name ) : if not isinstance ( name , string_types ) : raise ValueError ( '' % name ) name = name . lower ( ) . strip ( ) if not len ( name ) or '' in name or '' in name : raise ValueError ( '' % name ) return name class ResultIter ( object ) : \"\"\"\"\"\" def __init__ ( self , result_proxy , row_type = row_type , step = None ) : self . result_proxy = result_proxy self . row_type = row_type self . step = step self . keys = list ( result_proxy . keys ( ) ) self . _iter = None def _next_chunk ( self ) : if self . result_proxy . closed : return False ", "answer": "if not self . step :"}, {"prompt": " from django . conf . urls import url from openstack_dashboard . dashboards . project . network_topology import views urlpatterns = [ url ( r'' , views . NetworkTopologyView . as_view ( ) , name = '' ) , url ( r'' , views . RouterView . as_view ( ) , name = '' ) , url ( r'' , views . NetworkView . as_view ( ) , name = '' ) , url ( r'' , views . InstanceView . as_view ( ) , name = '' ) , url ( r'' , views . RouterDetailView . as_view ( ) , name = '' ) , url ( r'' , views . NTAddInterfaceView . as_view ( ) , name = '' ) , url ( r'' , views . NetworkDetailView . as_view ( ) , name = '' ) , url ( r'' , views . NTCreateSubnetView . as_view ( ) , name = '' ) , ", "answer": "url ( r'' , views . JSONView . as_view ( ) , name = '' ) ,"}, {"prompt": " '''''' import numpy as np class Linear ( object ) : '''''' def __init__ ( self ) : pass def __repr__ ( self ) : return '' def calc ( self , v1 , v2 ) : if v2 == None : v2 = v1 return np . dot ( v1 . T , v2 ) class Polynomial ( object ) : '''''' __degree = def __init__ ( self , deg = ) : self . __degree = deg def __repr__ ( self ) : return '' . format ( degree = self . __degree ) def calc ( self , v1 , v2 = None ) : ", "answer": "if v2 == None : v2 = v1"}, {"prompt": " import mesonbuild import sys , os , subprocess , time , datetime , pickle , multiprocessing , json import concurrent . futures as conc import argparse import platform import signal def is_windows ( ) : platname = platform . system ( ) . lower ( ) return platname == '' or '' in platname collected_logs = [ ] error_count = options = None parser = argparse . ArgumentParser ( ) parser . add_argument ( '' , default = None , dest = '' , help = '' ) parser . add_argument ( '' , default = None , dest = '' , help = '' ) parser . add_argument ( '' , default = None , dest = '' , help = '' ) parser . add_argument ( '' , default = True , dest = '' , action = '' , help = '' ) parser . add_argument ( '' , default = False , action = '' , help = \"\" ) parser . add_argument ( '' , nargs = '' ) class TestRun ( ) : def __init__ ( self , res , returncode , should_fail , duration , stdo , stde , cmd ) : self . res = res self . returncode = returncode self . duration = duration self . stdo = stdo self . stde = stde self . cmd = cmd self . should_fail = should_fail def get_log ( self ) : res = '' if self . cmd is None : res += '' else : res += '' . join ( self . cmd ) + '' if self . stdo : res += '' res += self . stdo if self . stde : if res [ - : ] != '' : res += '' res += '' res += self . stde if res [ - : ] != '' : res += '' res += '' return res def decode ( stream ) : try : return stream . decode ( '' ) except UnicodeDecodeError : return stream . decode ( '' , errors = '' ) def write_json_log ( jsonlogfile , test_name , result ) : jresult = { '' : test_name , '' : result . stdo , '' : result . res , '' : result . duration , '' : result . returncode , '' : result . cmd } if result . stde : jresult [ '' ] = result . stde jsonlogfile . write ( json . dumps ( jresult ) + '' ) def run_with_mono ( fname ) : if fname . endswith ( '' ) and not is_windows ( ) : return True return False def run_single_test ( wrap , test ) : global options if test . fname [ ] . endswith ( '' ) : cmd = [ '' , '' ] + test . fname elif not test . is_cross and run_with_mono ( test . fname [ ] ) : cmd = [ '' ] + test . fname else : if test . is_cross : if test . exe_runner is None : cmd = None else : cmd = [ test . exe_runner ] + test . fname else : cmd = test . fname if len ( wrap ) > and '' in wrap [ ] : wrap += test . valgrind_args if cmd is None : res = '' duration = stdo = '' stde = None returncode = - else : cmd = wrap + cmd + test . cmd_args starttime = time . time ( ) child_env = os . environ . copy ( ) child_env . update ( test . env ) if len ( test . extra_paths ) > : ", "answer": "child_env [ '' ] = child_env [ '' ] + '' . join ( [ '' ] + test . extra_paths )"}, {"prompt": " import six from novaclient . tests . unit . fixture_data import availability_zones as data from novaclient . tests . unit . fixture_data import client from novaclient . tests . unit import utils from novaclient . tests . unit . v2 import fakes from novaclient . v2 import availability_zones class AvailabilityZoneTest ( utils . FixturedTestCase ) : from novaclient . v2 import shell data_fixture_class = data . V1 scenarios = [ ( '' , { '' : client . V1 } ) , ( '' , { '' : client . SessionV1 } ) ] def setUp ( self ) : super ( AvailabilityZoneTest , self ) . setUp ( ) self . availability_zone_type = self . _get_availability_zone_type ( ) def _get_availability_zone_type ( self ) : return availability_zones . AvailabilityZone def _assertZone ( self , zone , name , status ) : self . assertEqual ( zone . zoneName , name ) self . assertEqual ( zone . zoneState , status ) def test_list_availability_zone ( self ) : zones = self . cs . availability_zones . list ( detailed = False ) self . assert_request_id ( zones , fakes . FAKE_REQUEST_ID_LIST ) self . assert_called ( '' , '' ) for zone in zones : self . assertIsInstance ( zone , self . availability_zone_type ) self . assertEqual ( , len ( zones ) ) l0 = [ six . u ( '' ) , six . u ( '' ) ] l1 = [ six . u ( '' ) , six . u ( '' ) ] z0 = self . shell . _treeizeAvailabilityZone ( zones [ ] ) z1 = self . shell . _treeizeAvailabilityZone ( zones [ ] ) self . assertEqual ( ( , ) , ( len ( z0 ) , len ( z1 ) ) ) self . _assertZone ( z0 [ ] , l0 [ ] , l0 [ ] ) self . _assertZone ( z1 [ ] , l1 [ ] , l1 [ ] ) def test_detail_availability_zone ( self ) : zones = self . cs . availability_zones . list ( detailed = True ) self . assert_request_id ( zones , fakes . FAKE_REQUEST_ID_LIST ) self . assert_called ( '' , '' ) for zone in zones : self . assertIsInstance ( zone , self . availability_zone_type ) self . assertEqual ( , len ( zones ) ) l0 = [ six . u ( '' ) , six . u ( '' ) ] l1 = [ six . u ( '' ) , six . u ( '' ) ] l2 = [ six . u ( '' ) , six . u ( '' ) ] l3 = [ six . u ( '' ) , six . u ( '' ) ] l4 = [ six . u ( '' ) , six . u ( '' ) ] l5 = [ six . u ( '' ) , six . u ( '' ) ] l6 = [ six . u ( '' ) , six . u ( '' ) ] l7 = [ six . u ( '' ) , six . u ( '' ) ] l8 = [ six . u ( '' ) , six . u ( '' ) ] z0 = self . shell . _treeizeAvailabilityZone ( zones [ ] ) z1 = self . shell . _treeizeAvailabilityZone ( zones [ ] ) z2 = self . shell . _treeizeAvailabilityZone ( zones [ ] ) self . assertEqual ( ( , , ) , ( len ( z0 ) , len ( z1 ) , len ( z2 ) ) ) self . _assertZone ( z0 [ ] , l0 [ ] , l0 [ ] ) self . _assertZone ( z0 [ ] , l1 [ ] , l1 [ ] ) self . _assertZone ( z0 [ ] , l2 [ ] , l2 [ ] ) ", "answer": "self . _assertZone ( z1 [ ] , l3 [ ] , l3 [ ] )"}, {"prompt": " \"\"\"\"\"\" try : import unittest2 as unittest except ImportError : import unittest from google . protobuf import unittest_pb2 from google . protobuf import symbol_database class SymbolDatabaseTest ( unittest . TestCase ) : def _Database ( self ) : db = symbol_database . SymbolDatabase ( ) db . RegisterFileDescriptor ( unittest_pb2 . DESCRIPTOR ) db . RegisterMessage ( unittest_pb2 . TestAllTypes ) db . RegisterMessage ( unittest_pb2 . TestAllTypes . NestedMessage ) db . RegisterMessage ( unittest_pb2 . TestAllTypes . OptionalGroup ) db . RegisterMessage ( unittest_pb2 . TestAllTypes . RepeatedGroup ) db . RegisterEnumDescriptor ( unittest_pb2 . ForeignEnum . DESCRIPTOR ) db . RegisterEnumDescriptor ( unittest_pb2 . TestAllTypes . NestedEnum . DESCRIPTOR ) return db def testGetPrototype ( self ) : instance = self . _Database ( ) . GetPrototype ( unittest_pb2 . TestAllTypes . DESCRIPTOR ) self . assertTrue ( instance is unittest_pb2 . TestAllTypes ) def testGetMessages ( self ) : messages = self . _Database ( ) . GetMessages ( [ '' ] ) self . assertTrue ( unittest_pb2 . TestAllTypes is messages [ '' ] ) def testGetSymbol ( self ) : self . assertEqual ( unittest_pb2 . TestAllTypes , self . _Database ( ) . GetSymbol ( '' ) ) self . assertEqual ( unittest_pb2 . TestAllTypes . NestedMessage , self . _Database ( ) . GetSymbol ( '' ) ) self . assertEqual ( unittest_pb2 . TestAllTypes . OptionalGroup , self . _Database ( ) . GetSymbol ( '' ) ) self . assertEqual ( unittest_pb2 . TestAllTypes . RepeatedGroup , self . _Database ( ) . GetSymbol ( '' ) ) def testEnums ( self ) : self . assertEqual ( '' , ", "answer": "self . _Database ( ) . pool . FindEnumTypeByName ("}, {"prompt": " '''''' from datetime import datetime import json import logging import oauth2 as oauth ", "answer": "from time import sleep"}, {"prompt": " import calendar from datetime import timedelta from table . columns . base import Column from table . columns . sequencecolumn import SequenceColumn class DaysColumn ( SequenceColumn ) : def __init__ ( self , field = None , start_date = None , end_date = None , ** kwargs ) : total_days = ( end_date - start_date ) . days + headers = [ ( start_date + timedelta ( day ) ) . strftime ( \"\" ) ", "answer": "for day in range ( total_days ) ]"}, {"prompt": " \"\"\"\"\"\" from twisted . trial import unittest import os from ldaptor import config def writeFile ( path , content ) : f = file ( path , '' ) f . write ( content ) f . close ( ) class TestConfig ( unittest . TestCase ) : def testSomething ( self ) : self . dir = self . mktemp ( ) os . mkdir ( self . dir ) self . f1 = os . path . join ( self . dir , '' ) writeFile ( self . f1 , \"\"\"\"\"\" ) self . f2 = os . path . join ( self . dir , '' ) writeFile ( self . f2 , \"\"\"\"\"\" ) self . cfg = config . loadConfig ( configFiles = [ self . f1 , self . f2 ] , reload = True ) val = self . cfg . get ( '' , '' ) self . assertEquals ( val , '' ) val = self . cfg . get ( '' , '' ) self . assertEquals ( val , '' ) class IdentitySearch ( unittest . TestCase ) : def setUp ( self ) : self . dir = self . mktemp ( ) os . mkdir ( self . dir ) self . f1 = os . path . join ( self . dir , '' ) writeFile ( self . f1 , \"\"\"\"\"\" ) self . cfg = config . loadConfig ( configFiles = [ self . f1 ] , reload = True ) self . config = config . LDAPConfig ( ) def testConfig ( self ) : self . assertEquals ( self . config . getIdentitySearch ( '' ) , '' ) def testCopy ( self ) : conf = self . config . copy ( identitySearch = '' ) self . assertEquals ( conf . getIdentitySearch ( '' ) , '' ) def testInitArg ( self ) : conf = config . LDAPConfig ( identitySearch = '' ) ", "answer": "self . assertEquals ( conf . getIdentitySearch ( '' ) ,"}, {"prompt": " \"\"\"\"\"\" module = request . controller resourcename = request . function if not settings . has_module ( \"\" ) : raise HTTP ( , body = \"\" % module ) def index ( ) : \"\"\"\"\"\" ", "answer": "module_name = settings . modules [ module ] . name_nice"}, {"prompt": " class Display ( object ) : \"\"\"\"\"\" @ classmethod ", "answer": "def display ( klass , unit , val ) :"}, {"prompt": " import os import getopt import sys import sct_utils as sct import scipy . ndimage try : import nibabel except ImportError : print '' sys . exit ( ) try : import numpy as np except ImportError : print '' sys . exit ( ) def main ( ) : strategy = \"\" fname_centerline = \"\" fname_input_image = \"\" fname_output_image = \"\" fname_mask = \"\" path_script = os . path . dirname ( __file__ ) + '' try : opts , args = getopt . getopt ( sys . argv [ : ] , '' ) except getopt . GetoptError as err : print str ( err ) usage ( ) for opt , arg in opts : if opt == '' : usage ( ) elif opt in ( '' ) : fname_input_image = arg elif opt in ( '' ) : fname_output_image = arg elif opt in ( '' ) : fname_mask = arg elif opt in ( '' ) : filter_type = str ( arg ) elif opt in ( '' ) : strategy = str ( arg ) elif opt in ( '' ) : fname_centerline = arg if fname_input_image == '' or fname_mask == '' or ( strategy == \"\" and fname_centerline == \"\" ) : print ( \"\" ) usage ( ) sct . check_file_exist ( fname_input_image ) sct . check_file_exist ( fname_mask ) if strategy == \"\" : sct . check_file_exist ( fname_centerline ) path_input_image , file_input_image , ext_input_image = sct . extract_fname ( fname_input_image ) path_output_image , file_output_image , ext_output_image = sct . extract_fname ( fname_output_image ) img = nibabel . load ( fname_input_image ) data = img . get_data ( ) hdr = img . get_header ( ) mask = nibabel . load ( fname_mask ) mask_data = mask . get_data ( ) mask_hdr = mask . get_header ( ) if strategy == \"\" : print ( \"\" \"\" ) data = smooth_mean_per_slice ( data , mask_data ) ", "answer": "elif strategy == \"\" :"}, {"prompt": " import configobj import os def str_to_bool ( value ) : \"\"\"\"\"\" if isinstance ( value , basestring ) : value = value . strip ( ) . lower ( ) if value in [ '' , '' , '' , '' ] : return True elif value in [ '' , '' , '' , '' , '' ] : return False else : raise NotImplementedError ( \"\" % value ) return value def load_config ( configfile ) : \"\"\"\"\"\" configfile = os . path . abspath ( configfile ) config = configobj . ConfigObj ( configfile ) config_extension = '' if '' in config : config_extension = config [ '' ] . get ( '' , config_extension ) if '' in config [ '' ] : for cfgfile in os . listdir ( config [ '' ] [ '' ] ) : ", "answer": "cfgfile = os . path . join ( config [ '' ] [ '' ] ,"}, {"prompt": " '''''' import numpy as np from numpy . testing import assert_array_almost_equal import statsmodels . api as sm ", "answer": "from statsmodels . sandbox . tools import pca"}, {"prompt": " from django . utils . translation import ugettext_lazy as _ from horizon import exceptions from horizon import forms from horizon . utils import fields from horizon . utils import validators from horizon import workflows from openstack_dashboard import api AVAILABLE_PROTOCOLS = ( '' , '' , '' ) AVAILABLE_METHODS = ( '' , '' , '' ) class AddPoolAction ( workflows . Action ) : name = forms . CharField ( max_length = , label = _ ( \"\" ) ) description = forms . CharField ( initial = \"\" , required = False , max_length = , label = _ ( \"\" ) ) provider = forms . ChoiceField ( label = _ ( \"\" ) , required = False ) subnet_id = forms . ChoiceField ( label = _ ( \"\" ) ) protocol = forms . ChoiceField ( label = _ ( \"\" ) ) lb_method = forms . ChoiceField ( label = _ ( \"\" ) ) admin_state_up = forms . BooleanField ( label = _ ( \"\" ) , initial = True , required = False ) def __init__ ( self , request , * args , ** kwargs ) : super ( AddPoolAction , self ) . __init__ ( request , * args , ** kwargs ) tenant_id = request . user . tenant_id subnet_id_choices = [ ( '' , _ ( \"\" ) ) ] try : networks = api . neutron . network_list_for_tenant ( request , tenant_id ) except Exception : exceptions . handle ( request , _ ( '' ) ) networks = [ ] for n in networks : for s in n [ '' ] : subnet_id_choices . append ( ( s . id , s . cidr ) ) self . fields [ '' ] . choices = subnet_id_choices protocol_choices = [ ( '' , _ ( \"\" ) ) ] [ protocol_choices . append ( ( p , p ) ) for p in AVAILABLE_PROTOCOLS ] self . fields [ '' ] . choices = protocol_choices lb_method_choices = [ ( '' , _ ( \"\" ) ) ] [ lb_method_choices . append ( ( m , m ) ) for m in AVAILABLE_METHODS ] self . fields [ '' ] . choices = lb_method_choices try : if api . neutron . is_extension_supported ( request , '' ) : provider_list = api . neutron . provider_list ( request ) providers = [ p for p in provider_list if p [ '' ] == '' ] else : providers = None except Exception : exceptions . handle ( request , _ ( '' ) ) providers = [ ] if providers : default_providers = [ p for p in providers if p . get ( '' ) ] if default_providers : default_provider = default_providers [ ] [ '' ] else : default_provider = None provider_choices = [ ( p [ '' ] , p [ '' ] ) for p in providers if p [ '' ] != default_provider ] if default_provider : provider_choices . insert ( , ( default_provider , _ ( \"\" ) % default_provider ) ) else : if providers is None : msg = _ ( \"\" ) else : msg = _ ( \"\" ) provider_choices = [ ( '' , msg ) ] self . fields [ '' ] . widget . attrs [ '' ] = True self . fields [ '' ] . choices = provider_choices class Meta : name = _ ( \"\" ) permissions = ( '' , ) help_text = _ ( \"\" \"\" \"\" \"\" \"\" \"\" \"\" ) class AddPoolStep ( workflows . Step ) : action_class = AddPoolAction contributes = ( \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ) def contribute ( self , data , context ) : context = super ( AddPoolStep , self ) . contribute ( data , context ) if data : return context class AddPool ( workflows . Workflow ) : slug = \"\" name = _ ( \"\" ) finalize_button_name = _ ( \"\" ) success_message = _ ( '' ) failure_message = _ ( '' ) success_url = \"\" default_steps = ( AddPoolStep , ) def format_status_message ( self , message ) : name = self . context . get ( '' ) return message % name def handle ( self , request , context ) : try : api . lbaas . pool_create ( request , ** context ) return True except Exception : return False class AddVipAction ( workflows . Action ) : name = forms . CharField ( max_length = , label = _ ( \"\" ) ) description = forms . CharField ( initial = \"\" , required = False , max_length = , label = _ ( \"\" ) ) floatip_address = forms . ChoiceField ( label = _ ( \"\" ) , widget = forms . Select ( attrs = { '' : '' } ) , required = False ) other_address = fields . IPField ( required = False , initial = \"\" , version = fields . IPv4 , mask = False ) protocol_port = forms . IntegerField ( label = _ ( \"\" ) , min_value = , help_text = _ ( \"\" \"\" ) , validators = [ validators . validate_port_range ] ) protocol = forms . ChoiceField ( label = _ ( \"\" ) ) session_persistence = forms . ChoiceField ( required = False , initial = { } , label = _ ( \"\" ) ) cookie_name = forms . CharField ( initial = \"\" , required = False , max_length = , label = _ ( \"\" ) , help_text = _ ( \"\" \"\" ) ) connection_limit = forms . IntegerField ( required = False , min_value = - , label = _ ( \"\" ) , help_text = _ ( \"\" \"\" ) ) admin_state_up = forms . BooleanField ( label = _ ( \"\" ) , initial = True , required = False ) def __init__ ( self , request , * args , ** kwargs ) : super ( AddVipAction , self ) . __init__ ( request , * args , ** kwargs ) self . fields [ '' ] . label = _ ( \"\" \"\" % args [ ] [ '' ] ) protocol_choices = [ ( '' , _ ( \"\" ) ) ] [ protocol_choices . append ( ( p , p ) ) for p in AVAILABLE_PROTOCOLS ] self . fields [ '' ] . choices = protocol_choices session_persistence_choices = [ ( '' , _ ( \"\" ) ) ] for mode in ( '' , '' , '' ) : session_persistence_choices . append ( ( mode , mode ) ) self . fields [ '' ] . choices = session_persistence_choices floatip_address_choices = [ ( '' , _ ( \"\" ) ) ] self . fields [ '' ] . choices = floatip_address_choices def clean ( self ) : cleaned_data = super ( AddVipAction , self ) . clean ( ) if ( cleaned_data . get ( '' ) == '' and not cleaned_data . get ( '' ) ) : msg = _ ( '' ) self . _errors [ '' ] = self . error_class ( [ msg ] ) return cleaned_data class Meta : name = _ ( \"\" ) permissions = ( '' , ) help_text = _ ( \"\" \"\" \"\" \"\" \"\" \"\" \"\" ) class AddVipStep ( workflows . Step ) : action_class = AddVipAction depends_on = ( \"\" , \"\" ) contributes = ( \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ) def contribute ( self , data , context ) : context = super ( AddVipStep , self ) . contribute ( data , context ) return context class AddVip ( workflows . Workflow ) : slug = \"\" name = _ ( \"\" ) finalize_button_name = _ ( \"\" ) success_message = _ ( '' ) failure_message = _ ( '' ) success_url = \"\" default_steps = ( AddVipStep , ) def format_status_message ( self , message ) : name = self . context . get ( '' ) return message % name def handle ( self , request , context ) : if context [ '' ] == '' : context [ '' ] = context [ '' ] else : if not context [ '' ] == '' : self . failure_message = _ ( '' '' ) return False else : context [ '' ] = context [ '' ] try : pool = api . lbaas . pool_get ( request , context [ '' ] ) context [ '' ] = pool [ '' ] except Exception : context [ '' ] = None self . failure_message = _ ( '' '' ) return False if context [ '' ] : stype = context [ '' ] if stype == '' : cookie = context [ '' ] context [ '' ] = { '' : stype , '' : cookie } else : context [ '' ] = { '' : stype } else : context [ '' ] = { } try : api . lbaas . vip_create ( request , ** context ) return True except Exception : return False class AddMemberAction ( workflows . Action ) : pool_id = forms . ChoiceField ( label = _ ( \"\" ) ) members = forms . MultipleChoiceField ( label = _ ( \"\" ) , required = True , initial = [ \"\" ] , widget = forms . CheckboxSelectMultiple ( ) , error_messages = { '' : _ ( '' ) } , help_text = _ ( \"\" ) ) weight = forms . IntegerField ( max_value = , min_value = , label = _ ( \"\" ) , required = False , help_text = _ ( \"\" \"\" ) ) protocol_port = forms . IntegerField ( label = _ ( \"\" ) , min_value = , help_text = _ ( \"\" \"\" ) , validators = [ validators . validate_port_range ] ) admin_state_up = forms . BooleanField ( label = _ ( \"\" ) , initial = True , required = False ) def __init__ ( self , request , * args , ** kwargs ) : super ( AddMemberAction , self ) . __init__ ( request , * args , ** kwargs ) pool_id_choices = [ ( '' , _ ( \"\" ) ) ] try : pools = api . lbaas . pools_get ( request ) except Exception : pools = [ ] exceptions . handle ( request , _ ( '' ) ) pools = sorted ( pools , key = lambda pool : pool . name ) for p in pools : pool_id_choices . append ( ( p . id , p . name ) ) self . fields [ '' ] . choices = pool_id_choices members_choices = [ ] try : servers , has_more = api . nova . server_list ( request ) except Exception : servers = [ ] exceptions . handle ( request , _ ( '' ) ) if len ( servers ) == : self . fields [ '' ] . label = _ ( \"\" \"\" ) self . fields [ '' ] . required = False self . fields [ '' ] . help_text = _ ( \"\" \"\" ) self . fields [ '' ] . required = False self . fields [ '' ] . required = False return for m in servers : members_choices . append ( ( m . id , m . name ) ) self . fields [ '' ] . choices = sorted ( members_choices , key = lambda member : member [ ] ) class Meta : name = _ ( \"\" ) permissions = ( '' , ) help_text = _ ( \"\" \"\" \"\" \"\" \"\" \"\" ) class AddMemberStep ( workflows . Step ) : action_class = AddMemberAction contributes = ( \"\" , \"\" , \"\" , \"\" , \"\" ) def contribute ( self , data , context ) : context = super ( AddMemberStep , self ) . contribute ( data , context ) return context class AddMember ( workflows . Workflow ) : slug = \"\" name = _ ( \"\" ) finalize_button_name = _ ( \"\" ) success_message = _ ( '' ) failure_message = _ ( '' ) success_url = \"\" default_steps = ( AddMemberStep , ) def handle ( self , request , context ) : for m in context [ '' ] : params = { '' : m } try : plist = api . neutron . port_list ( request , ** params ) except Exception : return False if plist : context [ '' ] = plist [ ] . fixed_ips [ ] [ '' ] try : context [ '' ] = api . lbaas . member_create ( ", "answer": "request , ** context ) . id"}, {"prompt": " import sys import argparse import requests from . import validate_app , validate_packaged_app def main ( ) : \"\" parser = argparse . ArgumentParser ( description = \"\" ) parser . add_argument ( \"\" , help = \"\" ) parser . add_argument ( \"\" , \"\" , default = \"\" , choices = ( \"\" , \"\" ) , help = \"\" , required = False ) parser . add_argument ( \"\" , \"\" , action = \"\" , const = True , help = \"\"\"\"\"\" ) parser . add_argument ( \"\" , action = \"\" , const = True , help = \"\"\"\"\"\" ) parser . add_argument ( \"\" , action = \"\" , const = True , help = \"\" \"\" ) parser . add_argument ( \"\" , help = \"\" ", "answer": "\"\" ,"}, {"prompt": " \"\"\"\"\"\" from os . path import basename , join from SCons . Script import ( COMMAND_LINE_TARGETS , AlwaysBuild , Default , DefaultEnvironment , SConscript ) from platformio . util import get_serialports def BeforeUpload ( target , source , env ) : env . AutodetectUploadPort ( ) board_type = env . subst ( \"\" ) if \"\" not in board_type : env . Append ( UPLOADERFLAGS = [ \"\" , \"\" if ( \"\" in board_type . lower ( ) or board_type == \"\" ) else \"\" ] ) upload_options = env . get ( \"\" , { } ) . get ( \"\" , { } ) if not upload_options . get ( \"\" , False ) : env . FlushSerialBuffer ( \"\" ) before_ports = [ i [ '' ] for i in get_serialports ( ) ] if upload_options . get ( \"\" , False ) : env . TouchSerialPort ( \"\" , ) if upload_options . get ( \"\" , False ) : env . Replace ( UPLOAD_PORT = env . WaitForNewSerialPort ( before_ports ) ) if \"\" in env . subst ( \"\" ) : env . Replace ( UPLOAD_PORT = basename ( env . subst ( \"\" ) ) ) env = DefaultEnvironment ( ) SConscript ( env . subst ( join ( \"\" , \"\" , \"\" ) ) ) if env . subst ( \"\" ) == \"\" : env . Replace ( UPLOADER = join ( \"\" , \"\" , \"\" , \"\" ) , UPLOADERFLAGS = [ \"\" , \"\" , join ( \"\" , \"\" , \"\" , \"\" , \"\" ) , \"\" , join ( \"\" , \"\" , \"\" , \"\" , \"\" ) , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ] , UPLOADCMD = '' ) else : env . Replace ( UPLOADER = join ( \"\" , \"\" , \"\" ) , UPLOADERFLAGS = [ \"\" , \"\" , '' , \"\" , \"\" , \"\" , \"\" , \"\" ] , UPLOADCMD = '' ) env . Append ( CCFLAGS = [ \"\" , \"\" , \"\" ] , CFLAGS = [ \"\" ] , CXXFLAGS = [ \"\" , \"\" ] , CPPDEFINES = [ \"\" , '' ] , LINKFLAGS = [ \"\" , \"\" , \"\" , \"\" ] ) if \"\" in env . get ( \"\" , { } ) . get ( \"\" , { } ) . get ( \"\" , None ) : env . Append ( CPPDEFINES = [ \"\" ] , LINKFLAGS = [ \"\" , \"\" ] , UPLOADERFLAGS = [ \"\" , ] ) elif \"\" in env . subst ( \"\" ) : env . Append ( LINKFLAGS = [ \"\" , \"\" ] ) target_elf = env . BuildProgram ( ) if \"\" in COMMAND_LINE_TARGETS : target_firm = join ( \"\" , \"\" ) else : target_firm = env . ElfToBin ( join ( \"\" , \"\" ) , target_elf ) target_size = env . Alias ( \"\" , target_elf , \"\" ) ", "answer": "AlwaysBuild ( target_size )"}, {"prompt": " from __future__ import unicode_literals from django . db import models , migrations ", "answer": "class Migration ( migrations . Migration ) :"}, {"prompt": " \"\"\"\"\"\" import mock import unittest import time from perfkitbenchmarker . linux_benchmarks import object_storage_service_benchmark from tests import mock_flags ", "answer": "class TestBuildCommands ( unittest . TestCase ) :"}, {"prompt": " from lstm_old import * from lut import * from reshape import * from inner_prod import * from dropout import * from sequential import * from const_weights import * from const_value import * from cos_sim import * from lstm import * from sum_prod import * from selector import * from sum2 import * from conv1d import * from maxpool1d import * from meanpool1d import * from normalize import * from ordinal import * from scipy import sparse import h5py import pickle def routeFn ( name ) : if name == '' : return crossEntOne elif name == '' : return crossEntIdx elif name == '' : return crossEntOneIdx elif name == '' : return crossEntOneAccIdx elif name == '' : return rankingLoss elif name == '' : return hardLimit elif name == '' : return argmax elif name == '' : return argmaxDiff elif name == '' : return SigmoidActiveFn elif name == '' : return SoftmaxActiveFn elif name == '' : return TanhActiveFn elif name == '' : return IdentityActiveFn elif name == '' : return ReluActiveFn elif name == '' : return meanSqErr elif name == '' : return meanSqErrEye elif name == '' : return roundInt else : raise Exception ( '' + name + '' ) pass stageLib = { } def routeStage ( name ) : return stageLib [ name ] def addStage ( stageDict ) : stage = None initSeed = stageDict [ '' ] if stageDict . has_key ( '' ) else initRange = stageDict [ '' ] if stageDict . has_key ( '' ) else if stageDict . has_key ( '' ) : print '' , stageDict [ '' ] print '' , stageDict [ '' ] if stageDict . has_key ( '' ) : if stageDict [ '' ] == '' : initWeights = np . loadtxt ( stageDict [ '' ] ) elif stageDict [ '' ] == '' : initWeightsFile = h5py . File ( stageDict [ '' ] ) if stageDict . has_key ( '' ) and stageDict [ '' ] : key = stageDict [ '' ] iwShape = initWeightsFile [ key + '' ] [ : ] iwData = initWeightsFile [ key + '' ] [ : ] iwInd = initWeightsFile [ key + '' ] [ : ] iwPtr = initWeightsFile [ key + '' ] [ : ] initWeights = sparse . csr_matrix ( ( iwData , iwInd , iwPtr ) , shape = iwShape ) else : initWeights = initWeightsFile [ stageDict [ '' ] ] [ : ] print initWeights . shape elif stageDict [ '' ] == '' : initWeights = np . load ( stageDict [ '' ] ) else : raise Exception ( '' % stageDict [ '' ] ) else : initWeights = np . load ( stageDict [ '' ] ) else : initWeights = needInit = False if stageDict . has_key ( '' ) else True biasInitConst = stageDict [ '' ] if stageDict . has_key ( '' ) else - learningRate = stageDict [ '' ] if stageDict . has_key ( '' ) else learningRateAnnealConst = stageDict [ '' ] if stageDict . has_key ( '' ) else momentum = stageDict [ '' ] if stageDict . has_key ( '' ) else deltaMomentum = stageDict [ '' ] if stageDict . has_key ( '' ) else gradientClip = stageDict [ '' ] if stageDict . has_key ( '' ) else weightClip = stageDict [ '' ] if stageDict . has_key ( '' ) else weightRegConst = stageDict [ '' ] if stageDict . has_key ( '' ) else outputdEdX = stageDict [ '' ] if stageDict . has_key ( '' ) else True defaultValue = ( np . zeros ( stageDict [ '' ] ) + stageDict [ '' ] ) if stageDict . has_key ( '' ) else if stageDict . has_key ( '' ) : inputList = stageDict [ '' ] . split ( '' ) for i in range ( len ( inputList ) ) : inputList [ i ] = inputList [ i ] . strip ( ) else : inputList = None if stageDict [ '' ] == '' : stage = LSTM_Old ( name = stageDict [ '' ] , inputDim = stageDict [ '' ] , outputDim = stageDict [ '' ] , inputNames = inputList , initSeed = initSeed , initRange = initRange , initWeights = initWeights , needInit = needInit , cutOffZeroEnd = stageDict [ '' ] , multiErr = stageDict [ '' ] , learningRate = learningRate , learningRateAnnealConst = learningRateAnnealConst , momentum = momentum , deltaMomentum = deltaMomentum , gradientClip = gradientClip , weightClip = weightClip , weightRegConst = weightRegConst , outputdEdX = outputdEdX ) elif stageDict [ '' ] == '' : stage = LSTM ( name = stageDict [ '' ] , inputDim = stageDict [ '' ] , outputDim = stageDict [ '' ] , inputNames = inputList , timespan = stageDict [ '' ] , defaultValue = defaultValue , initSeed = initSeed , initRange = initRange , initWeights = initWeights , needInit = needInit , multiInput = stageDict [ '' ] if stageDict . has_key ( '' ) else True , multiOutput = stageDict [ '' ] if stageDict . has_key ( '' ) else stageDict [ '' ] , cutOffZeroEnd = stageDict [ '' ] if stageDict . has_key ( '' ) else True , learningRate = learningRate , learningRateAnnealConst = learningRateAnnealConst , momentum = momentum , deltaMomentum = deltaMomentum , gradientClip = gradientClip , weightClip = weightClip , weightRegConst = weightRegConst , outputdEdX = outputdEdX ) elif stageDict [ '' ] == '' : stage = LUT ( name = stageDict [ '' ] , inputDim = stageDict [ '' ] , outputDim = stageDict [ '' ] , inputNames = inputList , lazyInit = stageDict [ '' ] if stageDict . has_key ( '' ) else True , initSeed = initSeed , initRange = initRange , initWeights = initWeights , intConversion = stageDict [ '' ] if stageDict . has_key ( '' ) else False , sparse = stageDict [ '' ] == True if stageDict . has_key ( '' ) else False , needInit = needInit , learningRate = learningRate , learningRateAnnealConst = learningRateAnnealConst , momentum = momentum , deltaMomentum = deltaMomentum , gradientClip = gradientClip , weightClip = weightClip , weightRegConst = weightRegConst , outputdEdX = stageDict [ '' ] if stageDict . has_key ( '' ) else False ) elif stageDict [ '' ] == '' : stage = Map ( name = stageDict [ '' ] , outputDim = stageDict [ '' ] , inputNames = inputList , activeFn = routeFn ( stageDict [ '' ] ) , initSeed = initSeed , initRange = initRange , initWeights = initWeights , initType = stageDict [ '' ] if stageDict . has_key ( '' ) else '' , bias = stageDict [ '' ] if stageDict . has_key ( '' ) else True , biasInitConst = biasInitConst , needInit = needInit , learningRate = learningRate , learningRateAnnealConst = learningRateAnnealConst , momentum = momentum , deltaMomentum = deltaMomentum , gradientClip = gradientClip , ", "answer": "weightClip = weightClip ,"}, {"prompt": " import requests from allauth . socialaccount . providers . oauth2 . views import ( OAuth2Adapter , OAuth2LoginView , OAuth2CallbackView ) from . provider import FoursquareProvider class FoursquareOAuth2Adapter ( OAuth2Adapter ) : provider_id = FoursquareProvider . id access_token_url = '' authorize_url = '' profile_url = '' def complete_login ( self , request , app , token , ** kwargs ) : resp = requests . get ( self . profile_url , params = { '' : token . token , '' : '' } ) extra_data = resp . json ( ) [ '' ] [ '' ] ", "answer": "return self . get_provider ( ) . sociallogin_from_response ( request ,"}, {"prompt": " from __future__ import unicode_literals from django . contrib . auth import get_user_model from django . contrib . auth . tokens import default_token_generator from django . core import mail from django . core . urlresolvers import reverse from django . forms . fields import DateField , DateTimeField from django . utils . http import int_to_base36 from mezzanine . accounts import ProfileNotConfigured from mezzanine . accounts . forms import ProfileForm from mezzanine . conf import settings from mezzanine . utils . tests import TestCase User = get_user_model ( ) class AccountsTests ( TestCase ) : def account_data ( self , test_value ) : \"\"\"\"\"\" data = { \"\" : test_value + \"\" } ", "answer": "for field in ( \"\" , \"\" , \"\" ,"}, {"prompt": " from dragonflow . db . drivers import ramcloud_db_driver import getopt import sys def main ( argv ) : db_ip = '' db_port = '' try : opts , args = getopt . getopt ( sys . argv [ : ] , ", "answer": "'' , [ '' , '' , '' ] )"}, {"prompt": " \"\"\"\"\"\" import time ", "answer": "try :"}, {"prompt": " from normality import slugify class TabularColumn ( object ) : def __init__ ( self , schema , data ) : self . schema = schema self . data = data self . label = data . get ( '' ) self . name = data . get ( '' ) def __repr__ ( self ) : return '' % ( self . label , self . name ) class Tabular ( object ) : def __init__ ( self , schema = None ) : self . schema = schema or { } if '' not in self . schema : self . schema [ '' ] = [ ] def add_column ( self , label ) : label = unicode ( label ) column = slugify ( label or '' , sep = '' ) column = column or '' column = column [ : ] name , i = column , while name in [ c . name for c in self . columns ] : name = '' % ( name , i ) i += column = { '' : label , '' : column } self . schema [ '' ] . append ( column ) return TabularColumn ( self , column ) @ property def sheet ( self ) : return self . schema . get ( '' ) @ property def sheet_name ( self ) : name = self . schema . get ( '' ) if name is not None : ", "answer": "return name"}, {"prompt": " from __future__ import unicode_literals import os import json import hashlib from contextlib import contextmanager from django . template . loader import render_to_string from django . http import HttpResponse def render_form_errors ( form ) : return render_to_string ( '' , { '' : form , } ) def json_response ( data = None , status = ) : data = data or { } return HttpResponse ( json . dumps ( data ) , content_type = '' , status = status ) def mkdir_p ( path ) : try : os . makedirs ( path ) except OSError : if not os . path . isdir ( path ) : raise def get_hash ( file ) : md5 = hashlib . md5 ( ) for c in file . chunks ( ) : md5 . update ( c ) return md5 . hexdigest ( ) @ contextmanager def pushd ( new_dir ) : \"\"\"\"\"\" prev_dir = os . getcwd ( ) os . chdir ( new_dir ) yield os . chdir ( prev_dir ) def get_query_string ( request , ** params ) : \"\"\"\"\"\" query_dict = request . GET . copy ( ) for k , v in sorted ( params . items ( ) ) : ", "answer": "query_dict [ k ] = v"}, {"prompt": " import factory . fuzzy ", "answer": "from . . import models"}, {"prompt": " import codecs from os import path from setuptools import find_packages , setup def read ( * parts ) : filename = path . join ( path . dirname ( __file__ ) , * parts ) with codecs . open ( filename , encoding = \"\" ) as fp : return fp . read ( ) setup ( author = \"\" , author_email = \"\" , description = \"\" , name = \"\" , ", "answer": "long_description = read ( \"\" ) ,"}, {"prompt": " from time import gmtime , strftime from random import getrandbits from os . path import basename from base64 import standard_b64decode from urllib import unquote from urlparse import urlparse from werkzeug import Response from pymongo import DESCENDING from flask import request , abort , jsonify , json , current_app , render_template , redirect from regenwolken . utils import login , private , A1 , slug , thumbnail , clear , urlscheme from regenwolken . specs import Item , Account , Drop def index ( ) : \"\"\"\"\"\" db , fs = current_app . db , current_app . fs config , sessions = current_app . config , current_app . sessions if request . method == '' and not request . accept_mimetypes . accept_html : try : account = sessions . pop ( request . form . get ( '' ) ) [ '' ] except KeyError : abort ( ) acc = db . accounts . find_one ( { '' : account } ) source = request . headers . get ( '' , '' ) . split ( '' , ) [ ] privacy = request . form . get ( '' , acc [ '' ] ) _id = fs . upload_file ( config , account , request . files . get ( '' ) , source , privacy ) items = acc [ '' ] items . append ( _id ) db . accounts . update ( { '' : acc [ '' ] } , { '' : { '' : items } } , upsert = False ) obj = fs . get ( _id ) if obj is None : abort ( ) else : return jsonify ( Item ( obj , config , urlscheme ( request ) ) ) else : users = db . accounts . find ( ) . count ( ) files = fs . gfs . _GridFS__files . count ( ) size = sum ( [ f [ '' ] for f in fs . gfs . _GridFS__files . find ( ) ] ) hits = sum ( [ f [ '' ] for f in fs . mdb . find ( ) ] ) if request . args . get ( '' ) == '' : fields = [ ( '' , users ) , ( '' , files ) , ( '' , size ) , ( '' , hits ) ] return Response ( '' . join ( '' % field for field in fields ) , ) return Response ( render_template ( \"\" , ** locals ( ) ) , , content_type = \"\" ) @ login def account ( ) : \"\"\"\"\"\" conf , db = current_app . config , current_app . db account = db . accounts . find_one ( { '' : request . authorization . username } ) if request . method == '' : return jsonify ( clear ( account ) ) try : _id = account [ '' ] data = json . loads ( request . data ) [ '' ] except ValueError : return ( '' , ) if len ( data . keys ( ) ) == and '' in data : db . accounts . update ( { '' : _id } , { '' : { '' : data [ '' ] } } ) account [ '' ] = data [ '' ] elif len ( data . keys ( ) ) == and '' in data : if not account [ '' ] == A1 ( account [ '' ] , data [ '' ] ) : return abort ( ) if '' in data : if filter ( lambda c : not c in conf [ '' ] , data [ '' ] ) or data [ '' ] . isdigit ( ) : abort ( ) if db . accounts . find_one ( { '' : data [ '' ] } ) and account [ '' ] != data [ '' ] : return ( '' , ) new = { '' : data [ '' ] , '' : A1 ( data [ '' ] , data [ '' ] ) } db . accounts . update ( { '' : _id } , { '' : new } ) account [ '' ] = new [ '' ] account [ '' ] = new [ '' ] elif '' in data : passwd = A1 ( account [ '' ] , data [ '' ] ) db . accounts . update ( { '' : _id } , { '' : { '' : passwd } } ) account [ '' ] = passwd else : abort ( ) db . accounts . update ( { '' : account [ '' ] } , { '' : { '' : strftime ( '' , gmtime ( ) ) } } ) return jsonify ( clear ( account ) ) @ login def account_stats ( ) : \"\"\"\"\"\" email = request . authorization . username items = current_app . db . accounts . find_one ( { '' : email } ) [ '' ] views = for item in items : views += current_app . db . items . find_one ( { '' : item } ) [ '' ] return jsonify ( { '' : len ( items ) , '' : views } ) @ login def items ( ) : \"\"\"\"\"\" db , fs = current_app . db , current_app . fs ParseResult = urlparse ( request . url ) params = { '' : '' , '' : '' , '' : None , '' : False , '' : None } if not ParseResult . query == '' : query = dict ( [ part . split ( '' , ) for part in ParseResult . query . split ( '' ) ] ) params . update ( query ) listing = [ ] try : pp = int ( params [ '' ] ) page = int ( params [ '' ] ) email = request . authorization . username except ( ValueError , KeyError ) : abort ( ) query = { '' : email } if params [ '' ] != None : query [ '' ] = params [ '' ] if params [ '' ] == False : query [ '' ] = None if params [ '' ] != None : query [ '' ] = { '' : '' + unquote ( params [ '' ] ) } items = db . items . find ( query ) for item in items . sort ( '' , DESCENDING ) [ pp * ( page - ) : pp * page ] : listing . append ( Item ( fs . get ( _id = item [ '' ] ) , current_app . config , urlscheme ( request ) ) ) return json . dumps ( listing [ : : - ] ) @ login def items_new ( ) : \"\"\"\"\"\" acc = current_app . db . accounts . find_one ( { '' : request . authorization . username } ) ParseResult = urlparse ( request . url ) privacy = '' if acc [ '' ] else '' if not ParseResult . query == '' : query = dict ( [ part . split ( '' , ) for part in ParseResult . query . split ( '' ) ] ) privacy = '' if query . get ( '' , None ) else '' key = current_app . sessions . new ( request . authorization . username ) res = { \"\" : urlscheme ( request ) + '' + current_app . config [ '' ] , \"\" : current_app . config [ '' ] , \"\" : { \"\" : privacy , \"\" : key } , } return jsonify ( res ) @ private ( lambda req : req . accept_mimetypes . accept_html ) def items_view ( short_id ) : \"\"\"\"\"\" db , fs = current_app . db , current_app . fs obj = fs . get ( short_id = short_id ) if obj is None : abort ( ) if request . accept_mimetypes . accept_html : if getattr ( obj , '' , None ) : abort ( ) if obj . item_type != '' : fs . inc_count ( obj . _id ) if obj . item_type == '' : return redirect ( obj . redirect_url ) drop = Drop ( obj , current_app . config , urlscheme ( request ) ) if drop . item_type == '' : return render_template ( '' , drop = drop ) elif drop . item_type == '' : return render_template ( '' , drop = drop ) else : return render_template ( '' , drop = drop ) return jsonify ( Item ( obj , current_app . config , urlscheme ( request ) ) ) @ login def items_edit ( object_id ) : \"\"\"\"\"\" conf , db , fs = current_app . config , current_app . db , current_app . fs item = db . items . find_one ( { '' : request . authorization . username , '' : object_id } ) if not item : abort ( ) if request . method == '' : item [ '' ] = strftime ( '' , gmtime ( ) ) elif request . method == '' : try : data = json . loads ( request . data ) [ '' ] key , value = data . items ( ) [ ] if not key in [ '' , '' , '' ] : raise ValueError except ValueError : return ( '' , ) if key == '' and item [ '' ] != '' : item [ '' ] = value elif key == '' and item [ '' ] == '' and value and not conf [ '' ] : pass else : item [ key ] = value item [ '' ] = strftime ( '' , gmtime ( ) ) db . items . save ( item ) item = fs . get ( item [ '' ] ) return jsonify ( Item ( item , conf , urlscheme ( request ) ) ) @ private ( lambda req : True ) def blob ( short_id , filename ) : \"\"\"\"\"\" fs = current_app . fs obj = fs . get ( short_id = short_id ) if obj is None or getattr ( obj , '' , None ) : abort ( ) fs . inc_count ( obj . _id ) if obj . item_type == '' : return redirect ( obj . redirect_url ) elif not obj . content_type . split ( '' , ) [ ] in [ '' , '' ] : return Response ( obj , content_type = obj . content_type , headers = { '' : '' % basename ( obj . filename ) } ) return Response ( obj , content_type = obj . content_type ) @ login def trash ( ) : \"\"\"\"\"\" empty = current_app . db . items . find ( { '' : request . authorization . username , '' : { '' : None } } ) for item in empty : current_app . fs . delete ( item ) return '' , def register ( ) : \"\"\"\"\"\" conf , db = current_app . config , current_app . db if len ( request . data ) > : return ( '' , ) try : d = json . loads ( request . data ) email = d [ '' ] [ '' ] if email . isdigit ( ) : raise ValueError passwd = d [ '' ] [ '' ] except ( ValueError , KeyError ) : return ( '' , ) if filter ( lambda c : not c in conf [ '' ] , email ) : return ( '' , ) if db . accounts . find_one ( { '' : email } ) != None : return ( '' , ) if not db . accounts . find_one ( { \"\" : \"\" } ) : db . accounts . insert ( { \"\" : \"\" , \"\" : } ) account = Account ( { '' : email , '' : passwd , '' : db . accounts . find_one ( { '' : '' } ) [ '' ] } , conf ) db . accounts . update ( { '' : '' } , { '' : { '' : } } ) if conf [ '' ] : account [ '' ] = strftime ( '' , gmtime ( ) ) account [ '' ] = account [ '' ] db . accounts . insert ( account ) return ( jsonify ( clear ( account ) ) , ) @ login def bookmark ( ) : \"\"\"\"\"\" conf , db = current_app . config , current_app . db def insert ( name , redirect_url ) : acc = db . accounts . find_one ( { '' : request . authorization . username } ) _id = str ( getrandbits ( ) ) retry_count = short_id_length = conf [ '' ] while True : short_id = slug ( short_id_length ) if not db . items . find_one ( { '' : short_id } ) : break else : retry_count += if retry_count > : ", "answer": "short_id_length += "}, {"prompt": " \"\"\"\"\"\" import collections import logging import re import tempfile import unittest ", "answer": "from google . cloud . dataflow . examples import wordcount"}, {"prompt": " from flexmock import flexmock from framework . db . db import DB import framework . db . db_handler as db_handler from collections import defaultdict from framework . lib import general class DBEnvironmentBuilder ( ) : def build ( self ) : self . _create_core_mock ( ) db = flexmock ( DB ( self . core_mock ) ) flexmock ( db . DBHandler ) db . DBHandler . should_receive ( \"\" ) db . DBHandler . Storage [ '' ] = { \"\" : { '' : [ ] , '' : } } db . DBHandler . GetDBNames_old = db . DBHandler . GetDBNames db . DBHandler . should_receive ( \"\" ) . and_return ( [ \"\" , \"\" , \"\" ] ) general . INCOMING_QUEUE_TO_DIR_MAPPING = defaultdict ( list ) general . OUTGOING_QUEUE_TO_DIR_MAPPING = defaultdict ( list ) self . core_mock . DB = db return db def _create_core_mock ( self ) : self . core_mock = flexmock ( ) self . core_mock . Config = flexmock ( ) self . core_mock . Config . should_receive ( \"\" ) . and_return ( [ \"\" ] ) def fake_get ( key ) : values = { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , ", "answer": "\"\" : True ,"}, {"prompt": " \"\"\"\"\"\" from cvs2svn_lib . common import canonicalize_eol from cvs2svn_lib . common import FatalError from cvs2svn_lib . process import get_command_output from cvs2svn_lib . context import Ctx from cvs2svn_lib . revision_manager import RevisionReader from cvs2svn_lib . keyword_expander import expand_keywords from cvs2svn_lib . keyword_expander import collapse_keywords from cvs2svn_lib . apple_single_filter import get_maybe_apple_single class AbstractRCSRevisionReader ( RevisionReader ) : \"\"\"\"\"\" _text_options = { ( False , '' ) : ( [ '' ] , '' ) , ( False , '' ) : ( [ '' ] , '' ) , ", "answer": "( False , '' ) : ( [ '' ] , None ) ,"}, {"prompt": " from __future__ import absolute_import , print_function import time from scipy import weave force = ", "answer": "N = "}, {"prompt": " \"\"\"\"\"\" from django . db import models class Author ( models . Model ) : first_name = models . CharField ( max_length = ) last_name = models . CharField ( max_length = ) def __str__ ( self ) : return '' % ( self . first_name , self . last_name ) class Article ( models . Model ) : author = models . ForeignKey ( Author ) headline = models . CharField ( max_length = ) def __str__ ( self ) : return self . headline class Entry ( models . Model ) : title = models . CharField ( max_length = ) body = models . TextField ( ) pub_date = models . DateField ( ) enable_comments = models . BooleanField ( ) def __str__ ( self ) : return self . title class Book ( models . Model ) : ", "answer": "dewey_decimal = models . DecimalField ( primary_key = True , decimal_places = , max_digits = ) "}, {"prompt": " import scripts . common . feature_extractors as feature_extractors import scripts . common . file_utils as file_utils import matplotlib . pyplot as plt def test_paddle_positions ( ) : ball_pos = ( ( , ) , ( , ) ) prev_ball_pos = ( ( , ) , ( , ) ) weights = file_utils . load_weights ( ) mbb = feature_extractors . MockBoundingBoxExtractor ( ball_pos , prev_ball_pos ) domain = [ ] range_weights = [ ] actions = [ , ] for x in range ( , ) : state = { } best_score = None features = mbb . get_features_paddle_x ( state , actions , x ) for feature_set in features : score = for f , v in feature_set : score += weights [ f ] * v if best_score == None or score > best_score : best_score = score if best_score != None : domain . append ( x ) ", "answer": "range_weights . append ( best_score )"}, {"prompt": " from msrest . serialization import Model class WorkerPoolCollection ( Model ) : \"\"\"\"\"\" _attribute_map = { '' : { '' : '' , '' : '' } , ", "answer": "'' : { '' : '' , '' : '' } ,"}, {"prompt": " from google . protobuf import descriptor as _descriptor from google . protobuf import message as _message from google . protobuf import reflection as _reflection from google . protobuf import symbol_database as _symbol_database from google . protobuf import descriptor_pb2 _sym_db = _symbol_database . Default ( ) DESCRIPTOR = _descriptor . FileDescriptor ( name = '' , package = '' , syntax = '' , serialized_pb = b'' ) _sym_db . RegisterFileDescriptor ( DESCRIPTOR ) _IMPORTNOARENANESTEDMESSAGE = _descriptor . Descriptor ( name = '' , ", "answer": "full_name = '' ,"}, {"prompt": " from pycket import values , values_struct from pycket . base import SingletonMeta , W_Object from pycket . cont import call_cont , continuation , guarded_loop , label from pycket . impersonators import ( ChaperoneMixin , ImpersonatorMixin , ProxyMixin , W_ImpPropertyDescriptor , chaperone_reference_cont , check_chaperone_results , get_base_object , make_property_map , impersonate_reference_cont ) from pycket . hidden_classes import make_caching_map_type , make_map_type , make_composite_map_type from pycket . small_list import inline_small_list from rpython . rlib import jit , unroll from rpython . rlib . objectmodel import import_from_mixin , specialize , always_inline def is_static_handler ( func ) : return isinstance ( func , values . W_Prim ) or isinstance ( func , values . W_PromotableClosure ) def enter_above_depth ( n ) : @ jit . unroll_safe def above_threshold ( self , field , * args ) : if jit . we_are_jitted ( ) : return True for _ in range ( n ) : if not isinstance ( self , W_InterposeStructBase ) : return False self = self . inner ", "answer": "return True"}, {"prompt": " import sys if sys . version_info [ ] > : basestring = str __all__ = [ \"\" , \"\" ] DATA = \"\"\"\"\"\" class NodeList ( list ) : \"\"\"\"\"\" def find ( self , name ) : for node in self : if node == name : return node return None def find_all ( self , name ) : res = NodeList ( ) for node in self : if node == name : res . append ( node ) return res def to_completion ( self ) : return [ ( n . name + \"\" , n . name ) for n in self ] COMPILED_NODES = NodeList ( ) COMPILED_HEADS = NodeList ( ) class ScopeNode ( object ) : \"\"\"\"\"\" def __init__ ( self , name , parent = None , children = None ) : self . name = name self . parent = parent self . children = children or NodeList ( ) ", "answer": "self . level = parent and parent . level + or "}, {"prompt": " import sys class Listener : ", "answer": "ROBOT_LISTENER_API_VERSION = "}, {"prompt": " from django . conf . urls import url import views urlpatterns = [ url ( r'' , views . admin , name = '' ) , url ( r'' , views . manage_project , ", "answer": "name = '' ) ,"}, {"prompt": " from datetime import date from django . conf import settings from django . contrib . auth . models import User from django . core . urlresolvers import reverse from django . test import TestCase from symposion . conference . models import Section , current_conference , Conference from symposion . schedule . models import Day , Schedule , Session class TestScheduleViews ( TestCase ) : username = \"\" first_name = \"\" last_name = \"\" def setUp ( self ) : self . user = User . objects . create_user ( self . username , password = \"\" , email = self . username ) self . user . first_name = self . first_name self . user . last_name = self . last_name self . user . save ( ) def test_session_list ( self ) : ", "answer": "rsp = self . client . get ( reverse ( \"\" ) )"}, {"prompt": " from django . conf import settings ", "answer": "def get_consumer_credentials ( ) :"}, {"prompt": " \"\"\"\"\"\" import array import struct from babel . messages . catalog import Catalog , Message from babel . _compat import range_type , array_tobytes LE_MAGIC = BE_MAGIC = def read_mo ( fileobj ) : \"\"\"\"\"\" catalog = Catalog ( ) headers = { } filename = getattr ( fileobj , '' , '' ) ", "answer": "buf = fileobj . read ( )"}, {"prompt": " import plistlib class A ( object ) : @ classmethod def _getListClass ( cls ) : return AList @ classmethod def _getDictClass ( cls ) : return ADict def __repr__ ( self ) : \"\"\"\"\"\" return u'' % ( self . __class__ . __name__ , self . _data_ ) def __len__ ( self ) : \"\"\"\"\"\" ", "answer": "return len ( self . _data_ )"}, {"prompt": " import sys import time import os import numpy as np import sct_utils as sct from msct_image import Image , get_dimension from sct_image import set_orientation from msct_parser import Parser import msct_gmseg_utils as sct_gm class Param : def __init__ ( self ) : self . debug = self . thinning = True self . verbose = class Thinning : def __init__ ( self , im , v = ) : sct . printv ( '' , v , '' ) self . image = im self . image . data = bin_data ( self . image . data ) self . dim_im = len ( self . image . data . shape ) if self . dim_im == : self . thinned_image = Image ( param = self . zhang_suen ( self . image . data ) , absolutepath = self . image . path + self . image . file_name + '' + self . image . ext , hdr = self . image . hdr ) elif self . dim_im == : assert self . image . orientation == '' thinned_data = np . asarray ( [ self . zhang_suen ( im_slice ) for im_slice in self . image . data ] ) self . thinned_image = Image ( param = thinned_data , absolutepath = self . image . path + self . image . file_name + '' + self . image . ext , hdr = self . image . hdr ) def get_neighbours ( self , x , y , image ) : \"\"\"\"\"\" x_1 , y_1 , x1 , y1 = x - , y - , x + , y + neighbours = [ image [ x_1 ] [ y ] , image [ x_1 ] [ y1 ] , image [ x ] [ y1 ] , image [ x1 ] [ y1 ] , image [ x1 ] [ y ] , image [ x1 ] [ y_1 ] , image [ x ] [ y_1 ] , image [ x_1 ] [ y_1 ] ] return neighbours def transitions ( self , neighbours ) : \"\"\"\"\"\" n = neighbours + neighbours [ : ] s = np . sum ( ( n1 , n2 ) == ( , ) for n1 , n2 in zip ( n , n [ : ] ) ) return s def zhang_suen ( self , image ) : \"\"\"\"\"\" image_thinned = image . copy ( ) changing1 = changing2 = while changing1 or changing2 : changing1 = [ ] max = len ( image_thinned ) - pass_list = [ , max ] for x , y in non_zero_coord ( image_thinned ) : if x not in pass_list and y not in pass_list : P2 , P3 , P4 , P5 , P6 , P7 , P8 , P9 = n = self . get_neighbours ( x , y , image_thinned ) if ( <= sum ( n ) <= and P2 * P4 * P6 == and P4 * P6 * P8 == and self . transitions ( n ) == ) : changing1 . append ( ( x , y ) ) for x , y in changing1 : image_thinned [ x ] [ y ] = changing2 = [ ] for x , y in non_zero_coord ( image_thinned ) : if x not in pass_list and y not in pass_list : P2 , P3 , P4 , P5 , P6 , P7 , P8 , P9 = n = self . get_neighbours ( x , y , image_thinned ) if ( <= sum ( n ) <= and P2 * P4 * P8 == and P2 * P6 * P8 == and self . transitions ( n ) == ) : changing2 . append ( ( x , y ) ) for x , y in changing2 : image_thinned [ x ] [ y ] = return image_thinned class HausdorffDistance : def __init__ ( self , data1 , data2 , v = ) : \"\"\"\"\"\" sct . printv ( '' , v , '' ) self . data1 = bin_data ( data1 ) self . data2 = bin_data ( data2 ) self . min_distances_1 = self . relative_hausdorff_dist ( self . data1 , self . data2 , v ) self . min_distances_2 = self . relative_hausdorff_dist ( self . data2 , self . data1 , v ) self . h1 = np . max ( self . min_distances_1 ) self . h2 = np . max ( self . min_distances_2 ) self . H = max ( self . h1 , self . h2 ) def relative_hausdorff_dist ( self , dat1 , dat2 , v = ) : h = np . zeros ( dat1 . shape ) nz_coord_1 = non_zero_coord ( dat1 ) nz_coord_2 = non_zero_coord ( dat2 ) if len ( nz_coord_1 ) != and len ( nz_coord_2 ) != : for x1 , y1 in nz_coord_1 : d_p1_dat2 = [ ] p1 = np . asarray ( [ x1 , y1 ] ) for x2 , y2 in nz_coord_2 : p2 = np . asarray ( [ x2 , y2 ] ) d_p1_dat2 . append ( np . linalg . norm ( p1 - p2 ) ) h [ x1 , y1 ] = min ( d_p1_dat2 ) else : sct . printv ( '' , v , '' ) return h class ComputeDistances : def __init__ ( self , im1 , im2 = None , param = None ) : self . im1 = im1 self . im2 = im2 self . dim_im = len ( self . im1 . data . shape ) self . dim_pix = self . distances = None self . res = '' self . param = param self . dist1_distribution = None self . dist2_distribution = None if self . dim_im == : self . orientation1 = self . im1 . orientation if self . orientation1 != '' : self . im1 = set_orientation ( self . im1 , '' ) if self . im2 is not None : self . orientation2 = self . im2 . orientation if self . orientation2 != '' : self . im2 = set_orientation ( self . im2 , '' ) if self . param . thinning : self . thinning1 = Thinning ( self . im1 , self . param . verbose ) self . thinning1 . thinned_image . save ( ) if self . im2 is not None : self . thinning2 = Thinning ( self . im2 , self . param . verbose ) self . thinning2 . thinned_image . save ( ) if self . dim_im == and self . im2 is not None : self . compute_dist_2im_2d ( ) if self . dim_im == : if self . im2 is None : self . compute_dist_1im_3d ( ) else : self . compute_dist_2im_3d ( ) if self . dim_im == and self . distances is not None : self . dist1_distribution = self . distances . min_distances_1 [ np . nonzero ( self . distances . min_distances_1 ) ] self . dist2_distribution = self . distances . min_distances_2 [ np . nonzero ( self . distances . min_distances_2 ) ] if self . dim_im == : self . dist1_distribution = [ ] self . dist2_distribution = [ ] for d in self . distances : self . dist1_distribution . append ( d . min_distances_1 [ np . nonzero ( d . min_distances_1 ) ] ) self . dist2_distribution . append ( d . min_distances_2 [ np . nonzero ( d . min_distances_2 ) ] ) self . res = '' for i , d in enumerate ( self . distances ) : med1 = np . median ( self . dist1_distribution [ i ] ) med2 = np . median ( self . dist2_distribution [ i ] ) if self . im2 is None : self . res += '' + str ( i ) + '' + str ( i + ) + '' + str ( d . H * self . dim_pix ) + '' + str ( med1 * self . dim_pix ) + '' + str ( med2 * self . dim_pix ) + '' else : self . res += '' + str ( i ) + '' + str ( d . H * self . dim_pix ) + '' + str ( med1 * self . dim_pix ) + '' + str ( med2 * self . dim_pix ) + '' sct . printv ( '' + self . res , self . param . verbose , '' ) if self . param . verbose == : self . show_results ( ) def compute_dist_2im_2d ( self ) : ", "answer": "nx1 , ny1 , nz1 , nt1 , px1 , py1 , pz1 , pt1 = get_dimension ( self . im1 )"}, {"prompt": " from django import template from adv_cache_tag . tag import CacheTag , Node register = template . Library ( ) class TestNode ( Node ) : def __init__ ( self , nodename , nodelist , expire_time , multiplicator , fragment_name , vary_on ) : \"\"\"\"\"\" super ( TestNode , self ) . __init__ ( nodename , nodelist , expire_time , fragment_name , vary_on ) self . multiplicator = multiplicator class TestCacheTag ( CacheTag ) : class Meta ( CacheTag . Meta ) : compress_spaces = True Node = TestNode @ classmethod def get_template_node_arguments ( cls , tokens ) : \"\"\"\"\"\" if len ( tokens ) < : raise template . TemplateSyntaxError ( \"\" % tokens [ ] ) return tokens [ ] , tokens [ ] , tokens [ ] , tokens [ : ] ", "answer": "def prepare_params ( self ) :"}, {"prompt": " import ctypes import numpy as np from PIL import ImageDraw from pi3d . constants import * from pi3d . Texture import Texture import sys if sys . version_info [ ] == : unichr = chr class Pngfont ( Texture ) : def __init__ ( self , font , color = ( , , , ) ) : \"\"\"\"\"\" if not font . endswith ( '' ) : font += '' super ( Pngfont , self ) . __init__ ( font ) pixels = self . im . load ( ) self . glyph_table = { } for v in range ( ) : x = ( pixels [ v * , ] [ ] * ) / self . ix y = ( ( pixels [ v * , ] [ ] + ) * ) / self . iy width = float ( pixels [ v * + , ] [ ] ) height = float ( pixels [ v * + , ] [ ] ) width_scale = width / self . ix height_scale = height / self . iy ", "answer": "self . glyph_table [ unichr ( v + ) ] = [ width , height ,"}, {"prompt": " \"\"\"\"\"\" from behave import given , then , when import docx from docx import Document from helpers import test_docx @ given ( '' ) def given_I_have_python_docx_installed ( context ) : pass @ when ( '' ) def when_I_call_docx_Document_with_no_arguments ( context ) : context . document = Document ( ) @ when ( '' ) def when_I_call_docx_Document_with_the_path_of_a_docx_file ( context ) : context . document = Document ( test_docx ( '' ) ) @ then ( '' ) def then_document_is_a_Document_object ( context ) : document = context . document assert isinstance ( document , docx . document . Document ) @ then ( '' ) def then_last_p_contains_specified_text ( context ) : document = context . document text = context . paragraph_text p = document . paragraphs [ - ] assert p . text == text @ then ( '' ) ", "answer": "def then_the_last_paragraph_has_the_style_I_specified ( context ) :"}, {"prompt": " import matplotlib . pyplot as plt from pylab import * from qstkutil import DataAccess as da from qstkutil import timeutil as tu from qstkutil import timeseries as ts symbols = list ( ) symbols = list ( np . loadtxt ( '' , dtype = '' , delimiter = '' , comments = '' , skiprows = ) ) symbols . append ( \"\" ) tsstart = tu . ymd2epoch ( , , ) tsend = tu . ymd2epoch ( , , ) storename = \"\" fieldname = \"\" adjcloses = ts . getTSFromData ( storename , fieldname , symbols , tsstart , tsend ) print \"\" print symbols print adjcloses . values dates = [ ] for ts in adjcloses . timestamps : dates . append ( tu . epoch2date ( ts ) ) normdat = adjcloses . values / adjcloses . values [ , : ] plt . clf ( ) for i in range ( , size ( normdat [ , : ] ) ) : ", "answer": "plt . plot ( dates , normdat [ : , i ] )"}, {"prompt": " from __future__ import print_function , absolute_import , division from numba import unittest_support as unittest import numpy as np from numba import njit from numba . npyufunc import dufunc from . . support import MemoryLeakMixin def pyuadd ( a0 , a1 ) : return a0 + a1 class TestDUFunc ( MemoryLeakMixin , unittest . TestCase ) : def nopython_dufunc ( self , pyfunc ) : return dufunc . DUFunc ( pyfunc , targetoptions = dict ( nopython = True ) ) def test_frozen ( self ) : duadd = self . nopython_dufunc ( pyuadd ) self . assertFalse ( duadd . _frozen ) duadd . _frozen = True self . assertTrue ( duadd . _frozen ) with self . assertRaises ( ValueError ) : duadd . _frozen = False with self . assertRaises ( TypeError ) : duadd ( np . linspace ( , , ) , np . linspace ( , , ) ) def test_scalar ( self ) : duadd = self . nopython_dufunc ( pyuadd ) self . assertEqual ( pyuadd ( , ) , duadd ( , ) ) def test_npm_call ( self ) : ", "answer": "duadd = self . nopython_dufunc ( pyuadd )"}, {"prompt": " \"\"\"\"\"\" import os , errno import serial from serial import PARITY_NONE , PARITY_EVEN , PARITY_ODD from serial import STOPBITS_ONE , STOPBITS_TWO from serial import FIVEBITS , SIXBITS , SEVENBITS , EIGHTBITS from serialport import BaseSerialPort from twisted . internet import abstract , fdesc , main class SerialPort ( BaseSerialPort , abstract . FileDescriptor ) : \"\"\"\"\"\" connected = def __init__ ( self , protocol , deviceNameOrPortNumber , reactor , baudrate = , bytesize = EIGHTBITS , parity = PARITY_NONE , stopbits = STOPBITS_ONE , timeout = , xonxoff = , rtscts = ) : abstract . FileDescriptor . __init__ ( self , reactor ) self . _serial = self . _serialFactory ( deviceNameOrPortNumber , baudrate = baudrate , bytesize = bytesize , parity = parity , stopbits = stopbits , timeout = timeout , xonxoff = xonxoff , rtscts = rtscts ) self . reactor = reactor self . flushInput ( ) self . flushOutput ( ) self . protocol = protocol self . protocol . makeConnection ( self ) self . startReading ( ) def fileno ( self ) : return self . _serial . fd def writeSomeData ( self , data ) : \"\"\"\"\"\" return fdesc . writeToFD ( self . fileno ( ) , data ) def doRead ( self ) : \"\"\"\"\"\" return fdesc . readFromFD ( self . fileno ( ) , self . protocol . dataReceived ) def connectionLost ( self , reason ) : \"\"\"\"\"\" abstract . FileDescriptor . connectionLost ( self , reason ) ", "answer": "self . _serial . close ( )"}, {"prompt": " \"\"\"\"\"\" import string import logging from perfkitbenchmarker import disk from perfkitbenchmarker import vm_util from perfkitbenchmarker import flags from perfkitbenchmarker . providers . cloudstack import util FLAGS = flags . FLAGS class CloudStackDisk ( disk . BaseDisk ) : \"\"\"\"\"\" def __init__ ( self , disk_spec , name , zone_id , project_id = None ) : super ( CloudStackDisk , self ) . __init__ ( disk_spec ) self . cs = util . CsClient ( FLAGS . CS_API_URL , FLAGS . CS_API_KEY , FLAGS . CS_API_SECRET ) self . attached_vm_name = None self . attached_vm_id = None self . name = name self . zone_id = zone_id self . project_id = project_id self . disk_offering_id = self . _GetBestOfferingId ( self . disk_size ) assert self . disk_offering_id , \"\" if disk_spec . disk_type : logging . warn ( \"\" ) @ vm_util . Retry ( max_retries = ) def _Create ( self ) : \"\"\"\"\"\" volume = self . cs . create_volume ( self . name , self . disk_offering_id , self . zone_id , self . project_id ) assert volume , \"\" self . volume_id = volume [ '' ] self . disk_type = volume [ '' ] self . actual_disk_size = int ( volume [ '' ] ) / ( ** ) def _Delete ( self ) : \"\"\"\"\"\" vol = self . cs . get_volume ( self . name , self . project_id ) if vol : self . cs . delete_volume ( self . volume_id ) def _Exists ( self ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " from __future__ import unicode_literals from django . db import models , migrations class Migration ( migrations . Migration ) : dependencies = [ ( '' , '' ) , ] operations = [ migrations . RemoveField ( model_name = '' , name = '' , ) , migrations . RemoveField ( model_name = '' , name = '' , ) , migrations . RemoveField ( model_name = '' , name = '' , ) , migrations . RemoveField ( model_name = '' , name = '' , ) , migrations . RemoveField ( model_name = '' , name = '' , ) , migrations . AlterField ( model_name = '' , name = '' , field = models . ForeignKey ( related_name = '' , to = '' ) , ) , migrations . AlterField ( model_name = '' , name = '' , field = models . ForeignKey ( to = '' ) , ) , migrations . AlterField ( model_name = '' , name = '' , field = models . ForeignKey ( to = '' ) , ) , migrations . AlterField ( model_name = '' , name = '' , field = models . ForeignKey ( to = '' ) , ", "answer": ") ,"}, {"prompt": " '''''' ", "answer": "from . tools_pca import * "}, {"prompt": " import json from magnumclient . common import cliutils as utils from magnumclient . common import utils as magnum_utils from magnumclient import exceptions def _show_container ( container ) : utils . print_dict ( container . _info ) @ utils . arg ( '' , metavar = '' , help = '' ) @ utils . arg ( '' , required = True , metavar = '' , help = '' ) @ utils . arg ( '' , required = True , metavar = '' , help = '' ) @ utils . arg ( '' , metavar = '' , help = '' ) @ utils . arg ( '' , metavar = '' , help = '' '' ) def do_container_create ( cs , args ) : \"\"\"\"\"\" bay = cs . bays . get ( args . bay ) if bay . status not in [ '' , '' , '' ] : raise exceptions . InvalidAttribute ( '' '' '' % ( bay . uuid , bay . status , \"\" ) ) return opts = { } opts [ '' ] = args . name opts [ '' ] = args . image opts [ '' ] = bay . uuid opts [ '' ] = args . command opts [ '' ] = args . memory _show_container ( cs . containers . create ( ** opts ) ) @ utils . arg ( '' , metavar = '' , default = None , help = '' '' ) @ utils . arg ( '' , metavar = '' , type = int , help = '' ) @ utils . arg ( '' , metavar = '' , help = '' ) @ utils . arg ( '' , metavar = '' , choices = [ '' , '' ] , help = '' ) @ utils . arg ( '' , metavar = '' , help = \"\" ) def do_container_list ( cs , args ) : \"\"\"\"\"\" opts = { } opts [ '' ] = args . bay opts [ '' ] = args . marker opts [ '' ] = args . limit opts [ '' ] = args . sort_key opts [ '' ] = args . sort_dir containers = cs . containers . list ( ** opts ) columns = ( '' , '' , '' , '' ) utils . print_list ( containers , columns , { '' : magnum_utils . print_list_field ( '' ) } , sortby_index = None ) @ utils . arg ( '' , metavar = '' , nargs = '' , help = '' ) def do_container_delete ( cs , args ) : \"\"\"\"\"\" for container in args . containers : try : cs . containers . delete ( container ) print ( \"\" % container ) except Exception as e : print ( \"\" % { '' : container , '' : e } ) @ utils . arg ( '' , metavar = '' , help = '' ) @ utils . arg ( '' , action = '' , default = False , help = '' ) def do_container_show ( cs , args ) : \"\"\"\"\"\" container = cs . containers . get ( args . container ) if args . json : print ( json . dumps ( container . _info ) ) else : _show_container ( container ) @ utils . arg ( '' , metavar = '' , nargs = '' , help = '' ) def do_container_reboot ( cs , args ) : \"\"\"\"\"\" for container in args . containers : try : cs . containers . reboot ( container ) except Exception as e : print ( \"\" % { '' : container , '' : e } ) @ utils . arg ( '' , metavar = '' , nargs = '' , help = '' ) def do_container_stop ( cs , args ) : \"\"\"\"\"\" for container in args . containers : try : cs . containers . stop ( container ) except Exception as e : print ( \"\" % { '' : container , '' : e } ) @ utils . arg ( '' , metavar = '' , nargs = '' , help = '' ) def do_container_start ( cs , args ) : \"\"\"\"\"\" for container in args . containers : try : cs . containers . start ( container ) except Exception as e : print ( \"\" % { '' : container , '' : e } ) @ utils . arg ( '' , metavar = '' , nargs = '' , help = '' ) def do_container_pause ( cs , args ) : \"\"\"\"\"\" for container in args . containers : try : cs . containers . pause ( container ) ", "answer": "except Exception as e :"}, {"prompt": " from __future__ import division import numpy as np import multiprocessing as multi import logging import types import sklearn from sklearn . preprocessing import LabelBinarizer , MultiLabelBinarizer from import_utils import import_class from preprocessing_utils import map_feature_extractor logging . basicConfig ( format = '' , level = logging . INFO ) logger = logging . getLogger ( '' ) def init_class ( klass , args ) : return klass ( * args ) def filter_contexts ( token_contexts , min_total = ) : return { token : contexts for token , contexts in token_contexts . items ( ) if len ( contexts ) >= min_total } def filter_contexts_class ( token_contexts , min_total = , min_class_count = , proportion = ) : new_token_contexts = { } classes = set ( [ cc [ '' ] for context in token_contexts . values ( ) for cc in context ] ) for token , contexts in token_contexts . items ( ) : if len ( contexts ) < min_total : continue class_counts = { cl : for cl in classes } for cc in contexts : class_counts [ cc [ '' ] ] += min_class = min ( class_counts . values ( ) ) cur_proportion = max ( class_counts . values ( ) ) / max ( min_class , ) if min_class >= min_class_count and cur_proportion <= proportion : new_token_contexts [ token ] = contexts return new_token_contexts import copy def convert_tagset ( tagmap , tok_contexts ) : tok_contexts_copy = copy . deepcopy ( tok_contexts ) for tok , contexts in tok_contexts_copy . iteritems ( ) : for context in contexts : context [ '' ] = tagmap [ context [ '' ] ] return tok_contexts_copy def flatten ( lofl ) : return [ item for sublist in lofl for item in sublist ] def map_contexts ( tokens , context_creators ) : return { token : flatten ( [ creator . get_contexts ( token ) for creator in context_creators ] ) for token in tokens } def map_context_creators ( ( token , context_creators ) ) : logger . info ( '' + token ) contexts = flatten ( [ creator . get_contexts ( token ) for creator in context_creators ] ) return token , contexts def map_contexts ( tokens , context_creators , workers = ) : if workers == : return { token : flatten ( [ creator . get_contexts ( token ) for creator in context_creators ] ) for token in tokens } else : pool = multi . Pool ( workers ) tokens_with_extractors = [ ( token , context_creators ) for token in tokens ] res = pool . map ( map_context_creators , tokens_with_extractors ) res_dict = { k : v for k , v in res } return res_dict def token_contexts_to_features ( token_contexts , feature_extractors , workers = ) : if workers == : return { token : np . vstack ( [ np . hstack ( [ map_feature_extractor ( ( context , extractor ) ) for extractor in feature_extractors ] ) for context in contexts ] ) for token , contexts in token_contexts . items ( ) } else : res_dict = { } pool = multi . Pool ( workers ) print ( \"\" , feature_extractors ) for token , contexts in token_contexts . items ( ) : logger . info ( '' + token + '' + str ( len ( contexts ) ) + '' ) extractors_output = [ ] for extractor in feature_extractors : context_list = [ ( cont , extractor ) for cont in contexts ] extractors_output . append ( np . vstack ( pool . map ( map_feature_extractor , context_list ) ) ) res_dict [ token ] = np . hstack ( extractors_output ) return res_dict def token_contexts_to_features_categorical ( token_contexts , feature_extractors , workers = ) : if workers == : return { token : [ [ x for a_list in [ map_feature_extractor ( ( context , extractor ) ) for extractor in feature_extractors ] for x in a_list ] for context in contexts ] for token , contexts in token_contexts . items ( ) } else : res_dict = { } pool = multi . Pool ( workers ) print ( \"\" , feature_extractors ) ", "answer": "for token , contexts in token_contexts . items ( ) :"}, {"prompt": " \"\"\"\"\"\" from __future__ import division , absolute_import from twisted . internet import reactor , defer , task from twisted . trial import unittest class FakeDelayedCall ( object ) : \"\"\"\"\"\" def __init__ ( self , func ) : \"\"\"\"\"\" self . func = func self . cancelled = False def cancel ( self ) : \"\"\"\"\"\" self . cancelled = True class FakeScheduler ( object ) : \"\"\"\"\"\" def __init__ ( self ) : \"\"\"\"\"\" self . work = [ ] def __call__ ( self , thunk ) : \"\"\"\"\"\" unit = FakeDelayedCall ( thunk ) self . work . append ( unit ) return unit def pump ( self ) : \"\"\"\"\"\" work , self . work = self . work , [ ] for unit in work : if not unit . cancelled : unit . func ( ) class CooperatorTests ( unittest . TestCase ) : RESULT = '' def ebIter ( self , err ) : err . trap ( task . SchedulerStopped ) return self . RESULT def cbIter ( self , ign ) : self . fail ( ) def testStoppedRejectsNewTasks ( self ) : \"\"\"\"\"\" def testwith ( stuff ) : c = task . Cooperator ( ) c . stop ( ) d = c . coiterate ( iter ( ( ) ) , stuff ) d . addCallback ( self . cbIter ) d . addErrback ( self . ebIter ) return d . addCallback ( lambda result : self . assertEqual ( result , self . RESULT ) ) return testwith ( None ) . addCallback ( lambda ign : testwith ( defer . Deferred ( ) ) ) def testStopRunning ( self ) : \"\"\"\"\"\" c = task . Cooperator ( ) def myiter ( ) : for myiter . value in range ( ) : yield myiter . value myiter . value = - d = c . coiterate ( myiter ( ) ) d . addCallback ( self . cbIter ) d . addErrback ( self . ebIter ) c . stop ( ) def doasserts ( result ) : self . assertEqual ( result , self . RESULT ) self . assertEqual ( myiter . value , - ) d . addCallback ( doasserts ) return d def testStopOutstanding ( self ) : \"\"\"\"\"\" testControlD = defer . Deferred ( ) outstandingD = defer . Deferred ( ) ", "answer": "def myiter ( ) :"}, {"prompt": " AUTHORIZATION_FAILED = PERMISSION_IS_DENIED = CAPTCHA_IS_NEEDED = ACCESS_DENIED = USER_IS_DELETED_OR_BANNED = INVALID_USER_ID = class VkException ( Exception ) : pass class VkAuthError ( VkException ) : pass class VkParseError ( VkAuthError ) : \"\"\"\"\"\" pass class VkPageWarningsError ( VkParseError ) : \"\"\"\"\"\" pass ", "answer": "class VkAPIError ( VkException ) :"}, {"prompt": " \"\"\"\"\"\" import logging from six . moves import cStringIO as StringIO import six from email . utils import COMMASPACE , formatdate from six . moves . email_mime_multipart import MIMEMultipart from six . moves . email_mime_text import MIMEText from six . moves . email_mime_base import MIMEBase if six . PY2 : from email . MIMENonMultipart import MIMENonMultipart from email import Encoders else : from email . mime . nonmultipart import MIMENonMultipart from email import encoders as Encoders from twisted . internet import defer , reactor , ssl logger = logging . getLogger ( __name__ ) class MailSender ( object ) : def __init__ ( self , smtphost = '' , mailfrom = '' , smtpuser = None , smtppass = None , smtpport = , smtptls = False , smtpssl = False , debug = False ) : self . smtphost = smtphost self . smtpport = smtpport self . smtpuser = smtpuser self . smtppass = smtppass self . smtptls = smtptls self . smtpssl = smtpssl self . mailfrom = mailfrom self . debug = debug @ classmethod def from_settings ( cls , settings ) : return cls ( settings [ '' ] , settings [ '' ] , settings [ '' ] , settings [ '' ] , settings . getint ( '' ) , settings . getbool ( '' ) , settings . getbool ( '' ) ) def send ( self , to , subject , body , cc = None , attachs = ( ) , mimetype = '' , charset = None , _callback = None ) : if attachs : msg = MIMEMultipart ( ) else : msg = MIMENonMultipart ( * mimetype . split ( '' , ) ) msg [ '' ] = self . mailfrom msg [ '' ] = COMMASPACE . join ( to ) msg [ '' ] = formatdate ( localtime = True ) msg [ '' ] = subject rcpts = to [ : ] if cc : rcpts . extend ( cc ) ", "answer": "msg [ '' ] = COMMASPACE . join ( cc )"}, {"prompt": " import re from django import forms from django . contrib . contenttypes . models import ContentType from django . utils . translation import ugettext_lazy as _ from annotatetext . models import Annotation , ANNOTATION_FLAGS class NewAnnotationForm ( forms . Form ) : selection_start = forms . IntegerField ( required = True ) selection_end = forms . IntegerField ( required = True ) flags = forms . ChoiceField ( choices = enumerate ( ANNOTATION_FLAGS ) , widget = forms . Select ( attrs = { \"\" : \"\" } ) , required = True ) content_type = forms . IntegerField ( widget = forms . HiddenInput , required = True ) object_id = forms . IntegerField ( widget = forms . HiddenInput , required = True ) comment = forms . CharField ( widget = forms . Textarea ( attrs = { '' : , '' : } ) , required = False ) color = forms . CharField ( initial = \"\" , widget = forms . TextInput ( attrs = { \"\" : } ) , required = False ) lengthcheck = forms . IntegerField ( widget = forms . HiddenInput , required = True ) def clean_color ( self ) : data = self . cleaned_data [ \"\" ] data = data . lower ( ) if re . match ( \"\" , data ) is None : raise forms . ValidationError ( _ ( \"\" ) ) return data def clean_flags ( self ) : flags = self . cleaned_data [ \"\" ] flags = int ( flags ) if not flags in range ( len ( ANNOTATION_FLAGS ) ) : raise forms . ValidationError ( _ ( \"\" ) ) return flags def clean ( self ) : cleaned_data = self . cleaned_data content_type_id = cleaned_data . get ( \"\" , None ) object_id = cleaned_data . get ( \"\" , None ) if content_type_id is None or object_id is None : raise forms . ValidationError ( _ ( \"\" ) ) try : ct = ContentType . objects . get ( id = content_type_id ) except ContentType . DoesNotExist : raise forms . ValidationError ( _ ( \"\" ) ) try : obj = ct . get_object_for_this_type ( id = object_id ) except ct . model_class ( ) . DoesNotExist : raise forms . ValidationError ( _ ( \"\" ) ) cleaned_data [ \"\" ] = ct if not getattr ( obj , \"\" , False ) : raise forms . ValidationError ( _ ( \"\" ) ) if not hasattr ( obj , Annotation . field_name ) : raise forms . ValidationError ( _ ( \"\" ) ) text = getattr ( obj , Annotation . field_name ) if len ( text ) != cleaned_data [ \"\" ] : raise forms . ValidationError ( _ ( \"\" ) ) if not \"\" in cleaned_data or not \"\" in cleaned_data : raise forms . ValidationError ( _ ( \"\" ) ) if not Annotation . validate_selection ( text , start = cleaned_data [ \"\" ] , end = cleaned_data [ \"\" ] ) : raise forms . ValidationError ( _ ( \"\" ) ) if \"\" not in cleaned_data or \"\" not in cleaned_data : raise forms . ValidationError ( _ ( \"\" ) ) ", "answer": "return cleaned_data "}, {"prompt": " import base64 import bz2 import errno import gzip import os import re import select import signal import struct import sys import threading import time from xml . sax import saxutils from conary . errors import ConaryError try : import fcntl import termios import tty except ImportError : fcntl = termios = tty = None BUFFER = * MARKER , FREETEXT , NEWLINE , CARRIAGE_RETURN , COMMAND , CLOSE = range ( ) LINEBREAKS = ( '' , '' ) def callable ( func ) : func . _callable = True return func def makeRecord ( d ) : res = \"\" for key , val in sorted ( d . iteritems ( ) ) : res += \"\" % ( key , val , key ) res += \"\" return res def getTime ( ) : \"\"\"\"\"\" curTime = time . time ( ) msecs = * ( curTime - long ( curTime ) ) fmtStr = \"\" return time . strftime ( fmtStr , time . gmtime ( curTime ) ) % msecs def openPath ( path ) : class BZ2File ( bz2 . BZ2File ) : def flush ( self ) : pass if path . endswith ( '' ) : return BZ2File ( path , '' ) if path . endswith ( '' ) : return gzip . GzipFile ( path , '' ) return open ( path , '' ) class Lexer ( object ) : def __init__ ( self , marker , callbacks = None ) : self . marker = marker self . callbacks = callbacks or [ ] self . stream = '' self . mark = False self . markMatch = '' self . state = FREETEXT def registerCallback ( self , callback ) : self . callbacks . append ( callback ) def freetext ( self , text ) : self . emit ( ( FREETEXT , text ) ) def newline ( self ) : self . emit ( ( NEWLINE , None ) ) def carriageReturn ( self ) : self . emit ( ( CARRIAGE_RETURN , None ) ) def command ( self , text ) : self . emit ( ( COMMAND , text . split ( None , ) ) ) def close ( self ) : if self . state == NEWLINE : self . newline ( ) self . emit ( ( CLOSE , None ) ) def scan ( self , sequence ) : \"\"\"\"\"\" for char in sequence : if self . state == FREETEXT : if char in LINEBREAKS : if self . stream : self . freetext ( self . stream ) self . stream = '' if char == '' : self . state = NEWLINE else : self . carriageReturn ( ) else : self . stream += char elif self . state == NEWLINE : if char in LINEBREAKS : self . newline ( ) self . stream = '' if char == '' : self . carriageReturn ( ) self . state = FREETEXT else : if self . marker . startswith ( char ) : self . stream = char self . state = MARKER else : self . newline ( ) self . stream = char self . state = FREETEXT elif self . state == MARKER : if char in LINEBREAKS : self . newline ( ) if self . stream : self . freetext ( self . stream ) self . stream = '' if char == '' : self . carriageReturn ( ) self . state = FREETEXT else : self . state = NEWLINE else : candidate = self . stream + char self . stream += char if self . stream == self . marker : self . stream = '' self . state = COMMAND else : if not self . marker . startswith ( candidate ) : self . newline ( ) self . state = FREETEXT elif self . state == COMMAND : if char == '' : self . command ( self . stream . lstrip ( ) ) self . stream = '' self . state = FREETEXT else : self . stream += char if self . state == FREETEXT : if self . stream : self . freetext ( self . stream ) self . stream = '' def write ( self , text ) : return self . scan ( text ) def flush ( self ) : self . scan ( '' ) def emit ( self , token ) : for callback in self . callbacks : callback ( token ) class LogWriter ( object ) : def handleToken ( self , token ) : mode , param = token if mode == FREETEXT : self . freetext ( param ) elif mode == NEWLINE : self . newline ( ) elif mode == CARRIAGE_RETURN : self . carriageReturn ( ) elif mode == COMMAND : self . command ( * param ) elif mode == CLOSE : self . close ( ) def freetext ( self , text ) : pass def write ( self , text ) : return self . freetext ( text ) def flush ( self ) : pass def newline ( self ) : pass def carriageReturn ( self ) : pass def start ( self ) : pass @ callable def reportMissingBuildRequires ( self , data ) : self . freetext ( \"\" % \"\" . join ( data . split ( '' ) ) ) self . newline ( ) @ callable def reportExcessBuildRequires ( self , data ) : self . freetext ( \"\" % \"\" . join ( data . split ( '' ) ) ) self . newline ( ) @ callable def reportExcessSuperclassBuildRequires ( self , data ) : self . freetext ( \"\" % \"\" . join ( data . split ( '' ) ) ) self . newline ( ) def command ( self , cmd , * args ) : func = getattr ( self . __class__ , cmd , False ) if func and func . __dict__ . get ( '' , False ) : try : return func ( self , * args ) except TypeError : self . freetext ( '' '' % ( cmd , repr ( args ) ) ) except Exception , e : self . freetext ( '' '' % ( str ( e . __class__ ) , str ( e ) , cmd , repr ( args ) ) ) def close ( self ) : pass class XmlLogWriter ( LogWriter ) : def __init__ ( self , path ) : self . data = threading . local ( ) self . messageId = self . path = path self . logging = False self . text = '' self . stream = None LogWriter . __init__ ( self ) def flush ( self ) : self . stream . flush ( ) def start ( self ) : self . stream = openPath ( self . path ) print >> self . stream , '' print >> self . stream , \"\" self . log ( '' , '' ) self . stream . flush ( ) self . logging = True def _getDescriptorStack ( self ) : if not hasattr ( self . data , '' ) : self . data . descriptorStack = [ ] return self . data . descriptorStack def _getRecordData ( self ) : if not hasattr ( self . data , '' ) : self . data . recordData = { } return self . data . recordData def close ( self ) : if not self . logging : return del self . _getDescriptorStack ( ) [ : ] self . _getRecordData ( ) . clear ( ) self . log ( '' , '' ) print >> self . stream , \"\" self . stream . flush ( ) self . stream . close ( ) def freetext ( self , text ) : self . text += text def newline ( self ) : if self . text : self . log ( self . text ) self . text = '' carriageReturn = newline def _getDescriptor ( self ) : descriptorStack = self . _getDescriptorStack ( ) return '' . join ( descriptorStack ) def log ( self , message , levelname = '' ) : message = saxutils . escape ( message ) message = message . replace ( '' , '' ) macros = { } recordData = self . _getRecordData ( ) macros . update ( recordData ) macros [ '' ] = getTime ( ) macros [ '' ] = message macros [ '' ] = levelname macros [ '' ] = os . getpid ( ) threadName = threading . currentThread ( ) . getName ( ) if threadName != '' : macros [ '' ] = threadName macros [ '' ] = self . messageId self . messageId += descriptor = self . _getDescriptor ( ) if descriptor : macros [ '' ] = descriptor print >> self . stream , makeRecord ( macros ) @ callable def pushDescriptor ( self , descriptor ) : descriptorStack = self . _getDescriptorStack ( ) descriptorStack . append ( descriptor ) @ callable def popDescriptor ( self , descriptor = None ) : descriptorStack = self . _getDescriptorStack ( ) desc = descriptorStack . pop ( ) if descriptor : assert descriptor == desc return desc @ callable def addRecordData ( self , * args ) : if not args : return if len ( args ) < : key , val = args [ ] . split ( None , ) else : key , val = args if key [ ] . isdigit ( ) or not re . match ( '' , key , flags = re . LOCALE | re . UNICODE ) : raise RuntimeError ( \"\" % key ) if isinstance ( val , ( str , unicode ) ) : val = saxutils . escape ( val ) recordData = self . _getRecordData ( ) recordData [ key ] = val @ callable def delRecordData ( self , key ) : recordData = self . _getRecordData ( ) recordData . pop ( key , None ) @ callable def reportMissingBuildRequires ( self , data ) : self . pushDescriptor ( '' ) self . log ( data , levelname = '' ) self . popDescriptor ( '' ) @ callable def reportExcessBuildRequires ( self , data ) : self . pushDescriptor ( '' ) self . log ( data , levelname = '' ) self . popDescriptor ( '' ) @ callable def reportExcessSuperclassBuildRequires ( self , data ) : self . pushDescriptor ( '' ) self . log ( data , levelname = '' ) self . popDescriptor ( '' ) class FileLogWriter ( LogWriter ) : def __init__ ( self , path ) : self . path = path self . stream = None LogWriter . __init__ ( self ) self . logging = False def start ( self ) : self . stream = openPath ( self . path ) self . logging = True def freetext ( self , text ) : if self . logging : self . stream . write ( text ) self . stream . flush ( ) def newline ( self ) : if self . logging : self . stream . write ( '' ) self . stream . flush ( ) carriageReturn = newline def close ( self ) : self . stream . close ( ) self . logging = False class StreamLogWriter ( LogWriter ) : def __init__ ( self , stream = None ) : self . data = threading . local ( ) self . data . hideLog = False self . stream = stream LogWriter . __init__ ( self ) self . index = self . closed = bool ( self . stream ) def start ( self ) : if not self . stream : self . stream = sys . stdout def freetext ( self , text ) : if not self . data . __dict__ . get ( '' ) : self . stream . write ( text ) self . stream . flush ( ) self . index += len ( text ) def newline ( self ) : if not self . data . __dict__ . get ( '' ) : self . stream . write ( '' ) self . stream . flush ( ) self . index = def carriageReturn ( self ) : if not self . data . __dict__ . get ( '' ) : if ( self . index % ) : spaces = - ( self . index % ) self . stream . write ( spaces * '' ) self . stream . write ( '' ) self . stream . flush ( ) self . index = @ callable def pushDescriptor ( self , descriptor ) : if descriptor == '' : self . data . hideLog = True @ callable def popDescriptor ( self , descriptor = None ) : if descriptor is None : return if descriptor == '' : self . data . hideLog = False @ callable def reportExcessSuperclassBuildRequires ( self , data ) : pass class SubscriptionLogWriter ( LogWriter ) : def __init__ ( self , path ) : self . path = path self . stream = None LogWriter . __init__ ( self ) self . logging = False self . current = None self . rePatternList = [ ] ", "answer": "self . r = None"}, {"prompt": " \"\"\"\"\"\" from libcloud . base import ConnectionKey , Response , NodeDriver , Node from libcloud . base import NodeSize , NodeImage from libcloud . types import Provider , NodeState , InvalidCredsException try : import json except : import simplejson as json \"\"\"\"\"\" DH_PS_SIZES = { '' : { '' : '' , '' : '' , '' : , '' : , '' : None , '' : None } , '' : { '' : '' , '' : '' , '' : , '' : , '' : None , '' : None } , '' : { '' : '' , '' : '' , '' : , '' : , '' : None , '' : None } , '' : { '' : '' , '' : '' , '' : , '' : , '' : None , '' : None } , '' : { '' : '' , '' : '' , '' : , '' : , '' : None , '' : None } , } class DreamhostAPIException ( Exception ) : def __str__ ( self ) : return self . args [ ] def __repr__ ( self ) : return \"\" % ( self . args [ ] ) class DreamhostResponse ( Response ) : \"\"\"\"\"\" def parse_body ( self ) : resp = json . loads ( self . body ) if resp [ '' ] != '' : raise Exception ( self . _api_parse_error ( resp ) ) return resp [ '' ] def parse_error ( self ) : raise Exception def _api_parse_error ( self , response ) : if '' in response : if response [ '' ] == '' : raise InvalidCredsException ( \"\" ) else : ", "answer": "raise DreamhostAPIException ( response [ '' ] )"}, {"prompt": " from . extension import Extension from . extension_point import ExtensionPoint from . plugin import Plugin ", "answer": "from . plugin_manifest import PluginManifest"}, {"prompt": " \"\"\"\"\"\" import py class TestMultiChannelAndGateway : def test_multichannel_receive_each ( self ) : class pseudochannel : def receive ( self ) : return pc1 = pseudochannel ( ) pc2 = pseudochannel ( ) multichannel = py . execnet . MultiChannel ( [ pc1 , pc2 ] ) l = multichannel . receive_each ( withchannel = True ) assert len ( l ) == assert l == [ ( pc1 , ) , ( pc2 , ) ] l = multichannel . receive_each ( withchannel = False ) assert l == [ , ] def test_multichannel_send_each ( self ) : l = [ py . execnet . PopenGateway ( ) for x in range ( ) ] gm = py . execnet . MultiGateway ( l ) mc = gm . remote_exec ( \"\"\"\"\"\" ) mc . send_each ( ) l = mc . receive_each ( ) assert l == [ , ] def test_multichannel_receive_queue_for_two_subprocesses ( self ) : ", "answer": "l = [ py . execnet . PopenGateway ( ) for x in range ( ) ]"}, {"prompt": " from __future__ import absolute_import import os import string import random from salttesting import skipIf from salttesting . helpers import ( destructiveTest , ensure_in_syspath , requires_system_grains ) ensure_in_syspath ( '' ) import salt . utils import integration from salt . ext . six . moves import range @ destructiveTest @ skipIf ( os . geteuid ( ) != , '' ) @ skipIf ( not salt . utils . is_linux ( ) , '' ) class UseraddModuleTest ( integration . ModuleCase ) : def setUp ( self ) : super ( UseraddModuleTest , self ) . setUp ( ) os_grain = self . run_function ( '' , [ '' ] ) if os_grain [ '' ] not in ( '' , '' ) : self . skipTest ( '' . format ( ** os_grain ) ) def __random_string ( self , size = ) : return '' + '' . join ( random . choice ( string . ascii_uppercase + string . digits ) for x in range ( size ) ) @ requires_system_grains def test_groups_includes_primary ( self , grains = None ) : uname = self . __random_string ( ) if self . run_function ( '' , [ uname ] ) is not True : self . run_function ( '' , [ uname , True , True ] ) self . skipTest ( '' ) try : uinfo = self . run_function ( '' , [ uname ] ) if grains [ '' ] in ( '' , ) : self . assertIn ( '' , uinfo [ '' ] ) else : self . assertIn ( uname , uinfo [ '' ] ) uid = uinfo [ '' ] self . run_function ( '' , [ uname , True , True ] ) gname = self . __random_string ( ) if self . run_function ( '' , [ gname ] ) is not True : self . run_function ( '' , [ gname , True , True ] ) self . skipTest ( '' ) ginfo = self . run_function ( '' , [ gname ] ) if self . run_function ( '' , [ uname , uid , ginfo [ '' ] ] ) is False : self . run_function ( '' , [ uname , True , True ] ) self . skipTest ( '' ) uinfo = self . run_function ( '' , [ uname ] ) self . assertIn ( gname , uinfo [ '' ] ) except AssertionError : self . run_function ( '' , [ uname , True , True ] ) raise def test_linux_user_primary_group ( self , grains = None ) : '''''' name = '' if self . run_function ( '' , [ name ] ) is not True : self . run_function ( '' , [ name ] ) self . skipTest ( '' ) try : ", "answer": "primary_group = self . run_function ( '' , [ name ] )"}, {"prompt": " __all__ = [ '' ] from . . common import * import re def kuwo_download_by_rid ( rid , output_dir = '' , merge = True , info_only = False ) : html = get_content ( \"\" % rid ) title = match1 ( html , r\"\" ) url = get_content ( \"\" % rid ) songtype , ext , size = url_info ( url ) print_info ( site_info , title , songtype , size ) if not info_only : download_urls ( [ url ] , title , ext , size , output_dir ) def kuwo_playlist_download ( url , output_dir = '' , merge = True , info_only = False , ** kwargs ) : html = get_content ( url ) matched = set ( re . compile ( \"\" ) . findall ( html ) ) for rid in matched : kuwo_download_by_rid ( rid , output_dir , merge , info_only ) def kuwo_download ( url , output_dir = '' , merge = True , info_only = False , ** kwargs ) : if \"\" in url : rid = match1 ( url , '' ) kuwo_download_by_rid ( rid , output_dir , merge , info_only ) else : ", "answer": "kuwo_playlist_download ( url , output_dir , merge , info_only )"}, {"prompt": " import warnings import numpy as np import numpy . ma as ma from scipy import sparse from scipy import stats from . . base import BaseEstimator , TransformerMixin from . . utils import check_array from . . utils import safe_mask from . . utils . fixes import astype from . . utils . sparsefuncs import _get_median from . . utils . validation import check_is_fitted from . . utils . validation import FLOAT_DTYPES from . . externals import six zip = six . moves . zip map = six . moves . map __all__ = [ '' , ] def _get_mask ( X , value_to_mask ) : \"\"\"\"\"\" if value_to_mask == \"\" or np . isnan ( value_to_mask ) : return np . isnan ( X ) else : return X == value_to_mask def _most_frequent ( array , extra_value , n_repeat ) : \"\"\"\"\"\" ", "answer": "if array . size > :"}, {"prompt": " import logging import os import argparse from six . moves import configparser from nose2 import config , events , util log = logging . getLogger ( __name__ ) __unittest = True class Session ( object ) : \"\"\"\"\"\" configClass = config . Config def __init__ ( self ) : self . argparse = argparse . ArgumentParser ( prog = '' , add_help = False ) self . pluginargs = self . argparse . add_argument_group ( '' , '' ) self . config = configparser . ConfigParser ( ) self . hooks = events . PluginInterface ( ) self . plugins = [ ] self . verbosity = self . startDir = None self . topLevelDir = None self . testResult = None self . testLoader = None self . logLevel = logging . WARN def get ( self , section ) : \"\"\"\"\"\" items = [ ] if self . config . has_section ( section ) : items = self . config . items ( section ) return self . configClass ( items ) def loadConfigFiles ( self , * filenames ) : \"\"\"\"\"\" self . config . read ( filenames ) def loadPlugins ( self , modules = None , exclude = None ) : \"\"\"\"\"\" if modules is None : modules = [ ] if exclude is None : exclude = [ ] cfg = self . unittest more_plugins = cfg . as_list ( '' , [ ] ) cfg_exclude = cfg . as_list ( '' , [ ] ) exclude . extend ( cfg_exclude ) exclude = set ( exclude ) all_ = ( set ( modules ) | set ( more_plugins ) ) - exclude log . debug ( \"\" , all_ ) for module in all_ : self . loadPluginsFromModule ( util . module_from_name ( module ) ) self . hooks . pluginsLoaded ( events . PluginsLoadedEvent ( self . plugins ) ) def loadPluginsFromModule ( self , module ) : \"\"\"\"\"\" avail = [ ] for entry in dir ( module ) : ", "answer": "try :"}, {"prompt": " \"\"\"\"\"\" import json import networkx as nx from networkx . utils . decorators import not_implemented_for __all__ = [ '' , '' ] def jit_graph ( data ) : \"\"\"\"\"\" G = nx . Graph ( ) for node in data : G . add_node ( node [ '' ] , ** node [ '' ] ) if node . get ( '' ) is not None : for adj in node [ '' ] : G . add_edge ( node [ '' ] , adj [ '' ] , ** adj [ '' ] ) return G @ not_implemented_for ( '' ) def jit_data ( G , indent = None ) : \"\"\"\"\"\" json_graph = [ ] for node in G . nodes ( ) : json_node = { \"\" : node , \"\" : node } json_node [ \"\" ] = G . node [ node ] if G [ node ] : ", "answer": "json_node [ \"\" ] = [ ]"}, {"prompt": " from flask import request from . . models import db , Class , Registration from . . decorators import json , collection , etag from . import api @ api . route ( '' , methods = [ '' ] ) @ etag @ json @ collection ( Class ) def get_classes ( ) : return Class . query @ api . route ( '' , methods = [ '' ] ) @ etag @ json def get_class ( id ) : return Class . query . get_or_404 ( id ) @ api . route ( '' , methods = [ '' ] ) @ etag @ json @ collection ( Registration ) def get_class_registrations ( id ) : class_ = Class . query . get_or_404 ( id ) return class_ . registrations @ api . route ( '' , methods = [ '' ] ) @ json def new_class ( ) : class_ = Class ( ) . import_data ( request . get_json ( force = True ) ) db . session . add ( class_ ) ", "answer": "db . session . commit ( )"}, {"prompt": " from flask import Flask , current_app from flask_docker import Docker from pytest import fixture , raises import responses docker = Docker ( ) def create_app ( ) : app = Flask ( __name__ ) docker . init_app ( app ) return app ", "answer": "@ fixture"}, {"prompt": " import configobj import os import sys import logging import inspect import traceback from diamond . util import load_class_from_name from diamond . collector import Collector from diamond . handler . Handler import Handler def load_include_path ( paths ) : \"\"\"\"\"\" for path in paths : if not os . path . isdir ( path ) : continue if path not in sys . path : sys . path . insert ( , path ) for f in os . listdir ( path ) : fpath = os . path . join ( path , f ) if os . path . isdir ( fpath ) : load_include_path ( [ fpath ] ) def load_dynamic_class ( fqn , subclass ) : \"\"\"\"\"\" if not isinstance ( fqn , basestring ) : return fqn cls = load_class_from_name ( fqn ) if cls == subclass or not issubclass ( cls , subclass ) : raise TypeError ( \"\" % ( fqn , subclass . __name__ ) ) return cls def load_handlers ( config , handler_names ) : \"\"\"\"\"\" log = logging . getLogger ( '' ) handlers = [ ] if isinstance ( handler_names , basestring ) : handler_names = [ handler_names ] for handler in handler_names : log . debug ( '' , handler ) try : cls = load_dynamic_class ( handler , Handler ) cls_name = cls . __name__ handler_config = configobj . ConfigObj ( ) handler_config . merge ( config [ '' ] [ '' ] ) if cls_name in config [ '' ] : handler_config . merge ( config [ '' ] [ cls_name ] ) if '' in config [ '' ] : configfile = os . path . join ( config [ '' ] [ '' ] , cls_name ) + '' if os . path . exists ( configfile ) : handler_config . merge ( configobj . ConfigObj ( configfile ) ) h = cls ( handler_config ) handlers . append ( h ) except ( ImportError , SyntaxError ) : log . warning ( \"\" , ", "answer": "handler ,"}, {"prompt": " import twisted . internet . protocol from twisted . internet import reactor from twisted . internet . defer import Deferred from twisted . protocols . basic import Int32StringReceiver from twisted . internet . protocol import DatagramProtocol import google . protobuf . service from protobufrpc_pb2 import Rpc , Request , Response , Error from common import Controller __all__ = [ \"\" , \"\" , \"\" , \"\" ] class BaseChannel ( google . protobuf . service . RpcChannel ) : id = def __init__ ( self ) : google . protobuf . service . RpcChannel . __init__ ( self ) self . _pending = { } self . _services = { } def add_service ( self , service ) : self . _services [ service . GetDescriptor ( ) . name ] = service def unserialize_response ( self , serializedResponse , responseClass , rpcController ) : response = responseClass ( ) if serializedResponse . error : rpcController . setFailed ( serializedResponse . error . text ) else : response . ParseFromString ( serializedResponse . serialized_response ) return response , rpcController def serialize_response ( self , response , serializedRequest , controller ) : serializedResponse = Response ( ) serializedResponse . id = serializedRequest . id if controller . Failed ( ) : serializedResponse . error . code = serializedResponse . error . text = controller . ErrorText ( ) else : serializedResponse . serialized_response = response . SerializeToString ( ) return serializedResponse def serialize_rpc ( self , serializedResponse ) : rpc = Rpc ( ) rpcResponse = rpc . response . add ( ) rpcResponse . serialized_response = serializedResponse . serialized_response rpcResponse . id = serializedResponse . id if serializedResponse . error . code != : rpcResponse . error . code = serializedResponse . error . code rpcResponse . error . text = serializedResponse . error . text return rpc def _call_method ( self , methodDescriptor , rpcController , request , responseClass , done ) : self . id += d = Deferred ( ) d . addCallback ( self . unserialize_response , responseClass , rpcController ) d . addCallback ( done ) self . _pending [ self . id ] = d rpc = Rpc ( ) rpcRequest = rpc . request . add ( ) rpcRequest . method = methodDescriptor . containing_service . name + '' + methodDescriptor . name rpcRequest . serialized_request = request . SerializeToString ( ) rpcRequest . id = self . id return rpc def CallMethod ( self , methodDescriptor , rpcController , request , responseClass , done ) : pass class RpcErrors : SUCCESS = UNSERIALIZE_RPC = SERVICE_NOT_FOUND = METHOD_NOT_FOUND = CANNOT_DESERIALIZE_REQUEST = ", "answer": "msgs = [ '' ,"}, {"prompt": " \"\"\"\"\"\" import argparse import copy import fnmatch import os import sys from Bcfg2 . Options import Types from Bcfg2 . Compat import ConfigParser __all__ = [ \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ] unit_test = False def _debug ( msg ) : \"\"\"\"\"\" if unit_test : print ( \"\" % msg ) elif os . environ . get ( '' , '' ) . lower ( ) in [ \"\" , \"\" , \"\" , \"\" ] : sys . stderr . write ( \"\" % msg ) _action_map = dict ( ) def _get_action_class ( action_name ) : \"\"\"\"\"\" if ( isinstance ( action_name , type ) and issubclass ( action_name , argparse . Action ) ) : return action_name if action_name not in _action_map : action = argparse . ArgumentParser ( ) . add_argument ( action_name , action = action_name ) _action_map [ action_name ] = action . __class__ return _action_map [ action_name ] class Option ( object ) : \"\"\"\"\"\" _local_args = [ '' , '' , '' ] def __init__ ( self , * args , ** kwargs ) : \"\"\"\"\"\" self . args = args self . _kwargs = kwargs self . cf = None self . env = None self . man = None self . parsers = [ ] self . actions = dict ( ) self . type = self . _kwargs . get ( \"\" ) self . help = self . _kwargs . get ( \"\" ) self . _default = self . _kwargs . get ( \"\" ) for kwarg in self . _local_args : setattr ( self , kwarg , self . _kwargs . pop ( kwarg , None ) ) if self . args : self . _dest = None else : action_cls = _get_action_class ( self . _kwargs . get ( '' , '' ) ) self . _dest = None if '' in self . _kwargs : self . _dest = self . _kwargs . pop ( '' ) elif self . env is not None : self . _dest = self . env elif self . cf is not None : self . _dest = self . cf [ ] self . _dest = self . _dest . lower ( ) . replace ( \"\" , \"\" ) kwargs = copy . copy ( self . _kwargs ) kwargs . pop ( \"\" , None ) self . actions [ None ] = action_cls ( self . _dest , self . _dest , ** kwargs ) def __repr__ ( self ) : sources = [ ] if self . args : sources . extend ( self . args ) if self . cf : sources . append ( \"\" % self . cf ) if self . env : sources . append ( \"\" + self . env ) spec = [ \"\" % sources , \"\" % self . default , \"\" % len ( self . parsers ) ] return '' % ( self . __class__ . __name__ , self . dest , \"\" . join ( spec ) ) def list_options ( self ) : \"\"\"\"\"\" return [ self ] def finalize ( self , namespace ) : \"\"\"\"\"\" for parser , action in self . actions . items ( ) : if hasattr ( action , \"\" ) : if parser : _debug ( \"\" % ( self , parser ) ) else : _debug ( \"\" % self ) action . finalize ( parser , namespace ) @ property def _type_func ( self ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " import pytest from mock import Mock from calvin . tests import DummyNode from calvin . runtime . north . actormanager import ActorManager from calvin . runtime . south . endpoint import LocalOutEndpoint , LocalInEndpoint from calvin . actor . actor import Actor pytestmark = pytest . mark . unittest def create_actor ( node ) : actor_manager = ActorManager ( node ) actor_id = actor_manager . new ( '' , { } ) actor = actor_manager . actors [ actor_id ] actor . _calvinsys = Mock ( ) return actor @ pytest . fixture def actor ( ) : return create_actor ( DummyNode ( ) ) @ pytest . mark . parametrize ( \"\" , [ ( \"\" , \"\" , \"\" , \"\" , False ) , ( \"\" , \"\" , \"\" , \"\" , False ) , ( \"\" , \"\" , \"\" , \"\" , False ) , ( \"\" , \"\" , \"\" , \"\" , False ) , ( \"\" , \"\" , \"\" , \"\" , False ) , ( \"\" , \"\" , \"\" , \"\" , True ) , ( \"\" , \"\" , \"\" , \"\" , True ) , ", "answer": "] )"}, {"prompt": " import sys from neutronclient . neutron . v2_0 . lb . v2 import healthmonitor from neutronclient . tests . unit import test_cli20 class CLITestV20LbHealthMonitorJSON ( test_cli20 . CLITestV20Base ) : def test_create_healthmonitor_with_mandatory_params ( self ) : resource = '' cmd_resource = '' cmd = healthmonitor . CreateHealthMonitor ( test_cli20 . MyApp ( sys . stdout ) , None ) my_id = '' type = '' max_retries = '' delay = '' timeout = '' pool = '' args = [ '' , type , '' , max_retries , '' , delay , '' , timeout , '' , pool ] position_names = [ '' , '' , '' , '' , '' ] position_values = [ type , max_retries , delay , timeout , pool ] self . _test_create_resource ( resource , cmd , '' , my_id , args , position_names , position_values , cmd_resource = cmd_resource ) def test_create_healthmonitor_with_all_params ( self ) : resource = '' cmd_resource = '' cmd = healthmonitor . CreateHealthMonitor ( test_cli20 . MyApp ( sys . stdout ) , None ) my_id = '' type = '' max_retries = '' delay = '' timeout = '' http_method = '' expected_codes = '' url_path = '' pool = '' name = '' args = [ '' , '' , http_method , '' , expected_codes , '' , url_path , '' , type , '' , max_retries , '' , delay , '' , timeout , '' , pool , '' , name ] position_names = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ] position_values = [ False , http_method , expected_codes , url_path , type , max_retries , delay , timeout , pool , name ] self . _test_create_resource ( resource , cmd , '' , my_id , args , position_names , position_values , cmd_resource = cmd_resource ) def test_list_healthmonitors ( self ) : resources = '' cmd_resources = '' cmd = healthmonitor . ListHealthMonitor ( test_cli20 . MyApp ( sys . stdout ) , None ) self . _test_list_resources ( resources , cmd , True , cmd_resources = cmd_resources ) def test_list_healthmonitors_pagination ( self ) : resources = '' cmd_resources = '' cmd = healthmonitor . ListHealthMonitor ( test_cli20 . MyApp ( sys . stdout ) , None ) self . _test_list_resources_with_pagination ( resources , cmd , cmd_resources = cmd_resources ) def test_list_healthmonitors_sort ( self ) : resources = '' cmd_resources = '' cmd = healthmonitor . ListHealthMonitor ( test_cli20 . MyApp ( sys . stdout ) , None ) self . _test_list_resources ( resources , cmd , True , cmd_resources = cmd_resources ) def test_list_healthmonitors_limit ( self ) : resources = '' cmd_resources = '' cmd = healthmonitor . ListHealthMonitor ( test_cli20 . MyApp ( sys . stdout ) , None ) self . _test_list_resources ( resources , cmd , page_size = , cmd_resources = cmd_resources ) def test_show_healthmonitor_id ( self ) : resource = '' cmd_resource = '' cmd = healthmonitor . ShowHealthMonitor ( test_cli20 . MyApp ( sys . stdout ) , None ) args = [ '' , '' , self . test_id ] self . _test_show_resource ( resource , cmd , self . test_id , args , [ '' ] , cmd_resource = cmd_resource ) def test_show_healthmonitor_id_name ( self ) : resource = '' cmd_resource = '' cmd = healthmonitor . ShowHealthMonitor ( test_cli20 . MyApp ( sys . stdout ) , None ) args = [ '' , '' , '' , '' , self . test_id ] ", "answer": "self . _test_show_resource ( resource , cmd , self . test_id ,"}, {"prompt": " from sqlalchemy . testing import eq_ , is_ from sqlalchemy import * from sqlalchemy . testing import fixtures from sqlalchemy import testing class IdiosyncrasyTest ( fixtures . TestBase ) : __only_on__ = '' __backend__ = True @ testing . emits_warning ( ) def test_is_boolean_symbols_despite_no_native ( self ) : is_ ( testing . db . scalar ( select ( [ cast ( true ( ) . is_ ( true ( ) ) , Boolean ) ] ) ) , True ) is_ ( testing . db . scalar ( select ( [ cast ( true ( ) . isnot ( true ( ) ) , Boolean ) ] ) ) , False ) is_ ( testing . db . scalar ( select ( [ cast ( false ( ) . is_ ( false ( ) ) , Boolean ) ] ) ) , True ) class MatchTest ( fixtures . TestBase ) : __only_on__ = '' __backend__ = True @ classmethod def setup_class ( cls ) : global metadata , cattable , matchtable metadata = MetaData ( testing . db ) cattable = Table ( '' , metadata , Column ( '' , Integer , primary_key = True ) , Column ( '' , String ( ) ) , mysql_engine = '' ) matchtable = Table ( '' , metadata , Column ( '' , Integer , primary_key = True ) , Column ( '' , String ( ) ) , Column ( '' , Integer , ForeignKey ( '' ) ) , mysql_engine = '' ) metadata . create_all ( ) cattable . insert ( ) . execute ( [ { '' : , '' : '' } , { '' : , '' : '' } , ] ) matchtable . insert ( ) . execute ( [ { '' : , '' : '' , '' : } , { '' : , '' : '' , '' : } , { '' : , '' : \"\" , '' : } , { '' : , '' : '' , '' : } , { '' : , '' : '' , '' : } ] ) @ classmethod def teardown_class ( cls ) : metadata . drop_all ( ) def test_simple_match ( self ) : results = ( matchtable . select ( ) . where ( matchtable . c . title . match ( '' ) ) . order_by ( matchtable . c . id ) . execute ( ) . fetchall ( ) ) eq_ ( [ , ] , [ r . id for r in results ] ) def test_not_match ( self ) : results = ( matchtable . select ( ) . where ( ~ matchtable . c . title . match ( '' ) ) . order_by ( matchtable . c . id ) . execute ( ) . fetchall ( ) ) eq_ ( [ , , ] , [ r . id for r in results ] ) def test_simple_match_with_apostrophe ( self ) : results = ( matchtable . select ( ) . where ( matchtable . c . title . match ( \"\" ) ) . execute ( ) . fetchall ( ) ) eq_ ( [ ] , [ r . id for r in results ] ) def test_return_value ( self ) : result = testing . db . execute ( select ( [ matchtable . c . title . match ( '' ) . label ( '' ) , matchtable . c . title . match ( '' ) . label ( '' ) , matchtable . c . title ", "answer": "] ) . order_by ( matchtable . c . id )"}, {"prompt": " from __future__ import ( absolute_import , print_function , unicode_literals , ) from unittest import TestCase from pydocx . exceptions import MalformedDocxException from pydocx . util . xml import ( el_iter , parse_xml_from_string , xml_remove_namespaces , xml_tag_split , XmlNamespaceManager , ) def elements_to_tags ( elements ) : for element in elements : yield element . tag def make_xml ( s ) : xml = b'' + s return parse_xml_from_string ( xml ) def remove_whitespace ( s ) : return '' . join ( s . split ( ) ) class UtilsTestCase ( TestCase ) : def test_el_iter ( self ) : root = make_xml ( b'' ) expected = [ '' , '' , '' , '' ] result = el_iter ( root ) ", "answer": "self . assertEqual ( list ( elements_to_tags ( result ) ) , expected )"}, {"prompt": " version = ( , , ) __version__ = '' . join ( map ( str , version ) ) default_app_config = '' __all__ = [ ", "answer": "'' ,"}, {"prompt": " \"\"\"\"\"\" import base64 from cafe . drivers . unittest . decorators import tags from cloudcafe . common . tools . datagen import rand_name from cloudroast . compute . fixtures import ComputeFixture class CloudInitConfigTest ( ComputeFixture ) : @ classmethod def setUpClass ( cls ) : \"\"\"\"\"\" super ( CloudInitConfigTest , cls ) . setUpClass ( ) init_st = cls . config_drive_behaviors . read_cloud_init_for_config_drive ( cls . cloud_init_config . cloud_config_format_script ) cls . user_data_contents = init_st user_data = base64 . b64encode ( cls . user_data_contents ) ", "answer": "cls . key = cls . keypairs_client . create_keypair ( rand_name ( \"\" ) ) . entity"}, {"prompt": " from pdb import set_trace as br class ASTBuilder : def ast ( self , begin , ast ) : end = self . parser . input . position full = '' . join ( self . parser . input . data ) text = full [ begin : end ] start_line = full [ : begin ] . count ( \"\" ) + self . line_offset start_col = begin - full . rfind ( \"\" , , begin ) - end_line = start_line + text . count ( \"\" ) inside_nl = text . rfind ( \"\" , ) if inside_nl == - : end_col = start_col + len ( text ) else : end_col = len ( text [ inside_nl : ] ) node = ASTNode ( ast , text , start_line , start_col , end_line , end_col ) return node def sint_ast ( self , last_begin , ast ) : end = self . parser . input . position full = '' . join ( self . parser . input . data ) text = full [ last_begin : end ] line = full [ : last_begin ] . count ( \"\" ) + self . line_offset + node = ASTNode ( ast , text , line , , line , ) return node class ASTNode ( ) : def __init__ ( self , lst , text , start_line , start_col , end_line , end_col ) : self . lst = lst self . text = text self . start_line = start_line self . start_col = start_col self . end_line = end_line self . end_col = end_col def __len__ ( self ) : return len ( self . lst ) def __getitem__ ( self , key ) : return self . lst [ key ] def __setitem__ ( self , key , val ) : ", "answer": "self . lst [ key ] = val"}, {"prompt": " \"\"\"\"\"\" from tests . case . api . crud import ApiCrudCases import logging mozlogger = logging . getLogger ( '' ) class CaseStepResourceTest ( ApiCrudCases ) : @ property def factory ( self ) : \"\"\"\"\"\" return self . F . CaseStepFactory ( ) @ property def resource_name ( self ) : return \"\" @ property def permission ( self ) : \"\"\"\"\"\" return \"\" @ property def new_object_data ( self ) : \"\"\"\"\"\" modifiers = ( self . datetime , self . resource_name ) self . caseversion_fixture = self . F . CaseVersionFactory . create ( ) fields = { u\"\" : unicode ( self . get_detail_url ( \"\" , str ( self . caseversion_fixture . id ) ) ) , u\"\" : , u\"\" : u\"\" % self . datetime , u\"\" : u\"\" % self . datetime , } ", "answer": "return fields"}, {"prompt": " import base64 import sys from . _common_models import ( _unicode_type , ) def _encode_base64 ( data ) : if isinstance ( data , _unicode_type ) : data = data . encode ( '' ) encoded = base64 . b64encode ( data ) return encoded . decode ( '' ) def _decode_base64_to_bytes ( data ) : if isinstance ( data , _unicode_type ) : data = data . encode ( '' ) return base64 . b64decode ( data ) def _decode_base64_to_text ( data ) : decoded_bytes = _decode_base64_to_bytes ( data ) return decoded_bytes . decode ( '' ) if sys . version_info < ( , ) : def _str ( value ) : if isinstance ( value , unicode ) : return value . encode ( '' ) return str ( value ) else : _str = str def _str_or_none ( value ) : if value is None : return None return _str ( value ) def _int_or_none ( value ) : if value is None : return None return str ( int ( value ) ) def _bool_or_none ( value ) : if value is None : return None if isinstance ( value , bool ) : if value : return '' ", "answer": "else :"}, {"prompt": " HPSSA_NO_DRIVES = '''''' HPSSA_ONE_DRIVE = '''''' HPSSA_ONE_DRIVE_RAID_50 = '''''' HPSSA_ONE_DRIVE_100GB_RAID_5 = '''''' HPSSA_TWO_DRIVES_100GB_RAID5_50GB_RAID1 = '''''' ", "answer": "HPSSA_BAD_SIZE_PHYSICAL_DRIVE = ''''''"}, {"prompt": " from django . conf import settings import logging logger = logging . getLogger ( __name__ ) FACEBOOK_APP_ID = getattr ( settings , '' , None ) FACEBOOK_APP_SECRET = getattr ( settings , '' , None ) FACEBOOK_DEFAULT_SCOPE = getattr ( settings , '' , [ '' , '' , '' , '' ] ) FACEBOOK_STORE_LIKES = getattr ( settings , '' , False ) FACEBOOK_STORE_FRIENDS = getattr ( settings , '' , False ) FACEBOOK_CELERY_STORE = getattr ( settings , '' , False ) FACEBOOK_CELERY_TOKEN_EXTEND = getattr ( settings , '' , False ) default_registration_backend = '' FACEBOOK_REGISTRATION_BACKEND = getattr ( settings , '' , default_registration_backend ) FACEBOOK_CANVAS_PAGE = getattr ( settings , '' , '' ) FACEBOOK_STORE_LOCAL_IMAGE = getattr ( settings , '' , True ) FACEBOOK_TRACK_RAW_DATA = getattr ( settings , '' , False ) FACEBOOK_DEBUG_REDIRECTS = getattr ( settings , '' , False ) FACEBOOK_READ_ONLY = getattr ( settings , '' , False ) default_registration_template = [ '' , '' ] FACEBOOK_REGISTRATION_TEMPLATE = getattr ( settings , '' , default_registration_template ) FACEBOOK_REGISTRATION_FORM = getattr ( settings , '' , None ) FACEBOOK_LOGIN_DEFAULT_REDIRECT = getattr ( settings , '' , '' ) FACEBOOK_FORCE_PROFILE_UPDATE_ON_LOGIN = getattr ( settings , '' , False ) FACEBOOK_OG_SHARE_RETRIES = getattr ( settings , '' , ) FACEBOOK_OG_SHARE_RETRY_DAYS = getattr ( settings , '' , ) FACEBOOK_OG_SHARE_DB_TABLE = getattr ( settings , '' , None ) FACEBOOK_FORCE_PROFILE_UPDATE_ON_LOGIN = getattr ( settings , '' , False ) FACEBOOK_PROFILE_IMAGE_PATH = getattr ( settings , '' , None ) FACEBOOK_CLASS_MAPPING = getattr ( settings , '' , None ) FACEBOOK_SKIP_VALIDATE = getattr ( ", "answer": "settings , '' , False ) "}, {"prompt": " from sys import exit def gold_room ( ) : print \"\" choice = raw_input ( \"\" ) if \"\" in choice or \"\" in choice : how_much = int ( choice ) else : dead ( \"\" ) if how_much < : print \"\" exit ( ) else : dead ( \"\" ) def bear_room ( ) : print \"\" print \"\" print \"\" print \"\" bear_moved = False while True : choice = raw_input ( \"\" ) if choice == \"\" : dead ( \"\" ) elif choice == \"\" and not bear_moved : print \"\" bear_moved = True elif choice == \"\" and bear_moved : dead ( \"\" ) elif choice == \"\" and bear_moved : gold_room ( ) else : print \"\" def cthulhu_room ( ) : print \"\" ", "answer": "print \"\""}, {"prompt": " class ConfigParser ( object ) : machine_wide_config = False mode_config = False ", "answer": "config_section = ''"}, {"prompt": " import sys import os def run ( ) : base = os . path . dirname ( os . path . dirname ( os . path . abspath ( __file__ ) ) ) ", "answer": "sys . path . insert ( , base )"}, {"prompt": " \"\"\"\"\"\" from pymongo import MongoClient import logging import base import constants as cons from bson . objectid import ObjectId from uid import UID logger = logging . getLogger ( \"\" ) class MongoClientPool ( object ) : def __init__ ( self ) : self . __clients = { } def getDataBase ( self , connectionString , databaseName ) : key = ( connectionString , databaseName ) if key in self . __clients : return self . __clients [ key ] [ databaseName ] else : try : client = MongoClient ( connectionString , connectTimeoutMS = ) self . __clients [ key ] = client return client [ databaseName ] except Exception as e : logger . warning ( e . message ) logger . warning ( '' . format ( databaseName , connectionString ) ) return None def getClient ( self , connectionString ) : if connectionString in self . __clients : return self . __clients [ connectionString ] else : try : client = MongoClient ( connectionString , connectTimeoutMS = ) self . __clients [ connectionString ] = client return client except Exception as e : logger . warning ( e . message ) logger . warning ( '' . format ( connectionString ) ) return None def exists ( self ) : [ client . close ( ) for client in self . __clients . values ( ) ] class Crane ( object ) : mongoClientPool = MongoClientPool ( ) def __init__ ( self , connectionString = None , database = None , collectionName = None ) : if connectionString is None or database is None or collectionName is None : return logger . info ( '' . format ( collectionName ) ) self . _defaultCollectionName = collectionName self . _currentCollectionName = collectionName self . _database = self . mongoClientPool . getDataBase ( connectionString , database ) ", "answer": "self . _coll = self . _database [ collectionName ]"}, {"prompt": " from preggy import expect from tests . base import FilterTestCase class FillFilterTestCase ( FilterTestCase ) : def test_fill_filter_with_fixed_color ( self ) : def config_context ( context ) : context . request . fit_in = True context . request . width = context . request . height = image = self . get_filtered ( '' , '' , '' , config_context = config_context ) expected = self . get_fixture ( '' ) ssim = self . get_ssim ( image , expected ) expect ( ssim ) . to_be_greater_than ( ) def test_fill_filter_with_average ( self ) : def config_context ( context ) : context . request . fit_in = True context . request . width = context . request . height = image = self . get_filtered ( '' , '' , '' , config_context = config_context ) expected = self . get_fixture ( '' ) ", "answer": "ssim = self . get_ssim ( image , expected )"}, {"prompt": " \"\"\"\"\"\" from __future__ import print_function , unicode_literals , division from collections import defaultdict from os . path import join from nltk . data import load _UNIVERSAL_DATA = \"\" _UNIVERSAL_TAGS = ( '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ) _MAPPINGS = defaultdict ( lambda : defaultdict ( lambda : defaultdict ( lambda : '' ) ) ) def _load_universal_map ( fileid ) : contents = load ( join ( _UNIVERSAL_DATA , fileid + '' ) , format = \"\" ) _MAPPINGS [ fileid ] [ '' ] . default_factory = lambda : '' for line in contents . splitlines ( ) : line = line . strip ( ) if line == '' : continue fine , coarse = line . split ( '' ) assert coarse in _UNIVERSAL_TAGS , '' . format ( coarse ) assert fine not in _MAPPINGS [ fileid ] [ '' ] , '' . format ( fine ) _MAPPINGS [ fileid ] [ '' ] [ fine ] = coarse def tagset_mapping ( source , target ) : \"\"\"\"\"\" if source not in _MAPPINGS or target not in _MAPPINGS [ source ] : if target == '' : _load_universal_map ( source ) return _MAPPINGS [ source ] [ target ] def map_tag ( source , target , source_tag ) : \"\"\"\"\"\" if target == '' : if source == '' : source = '' if source == '' : ", "answer": "source = ''"}, {"prompt": " import unittest from flask . ext . testing import TestCase from tango . app import Tango class AppInitTestCase ( TestCase ) : def create_app ( self ) : return Tango . build_app ( '' ) def setUp ( self ) : self . client = self . app . test_client ( ) def tearDown ( self ) : pass def test_static ( self ) : response = self . client . get ( '' ) ", "answer": "self . assertEqual ( response . status_code , )"}, {"prompt": " '''''' import grove_barometer_lib b = grove_barometer_lib . barometer ( ) while True ( ) : print ( \"\" , b . temperature , \"\" , b . pressure , \"\" , b . altitude ) ", "answer": "b . update ( )"}, {"prompt": " from monascaclient . common import utils def Client ( version , * args , ** kwargs ) : ", "answer": "module = utils . import_versioned_module ( version , '' )"}, {"prompt": " import datetime from south . db import db from south . v2 import SchemaMigration from django . db import models class Migration ( SchemaMigration ) : def forwards ( self , orm ) : db . add_column ( '' , '' , self . gf ( '' ) ( default = '' , max_length = , blank = True ) , keep_default = False ) def backwards ( self , orm ) : db . delete_column ( '' , '' ) models = { '' : { '' : { '' : '' } , '' : ( '' , [ ] , { } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } ", "answer": "}"}, {"prompt": " import os import bdb import types from tkinter import * from . WindowList import ListedToplevel from . ScrolledList import ScrolledList from . import macosxSupport class Idb ( bdb . Bdb ) : def __init__ ( self , gui ) : self . gui = gui bdb . Bdb . __init__ ( self ) def user_line ( self , frame ) : if self . in_rpc_code ( frame ) : self . set_step ( ) return message = self . __frame2message ( frame ) self . gui . interaction ( message , frame ) def user_exception ( self , frame , info ) : if self . in_rpc_code ( frame ) : self . set_step ( ) return message = self . __frame2message ( frame ) self . gui . interaction ( message , frame , info ) def in_rpc_code ( self , frame ) : if frame . f_code . co_filename . count ( '' ) : return True else : prev_frame = frame . f_back if prev_frame . f_code . co_filename . count ( '' ) : return False return self . in_rpc_code ( prev_frame ) def __frame2message ( self , frame ) : code = frame . f_code filename = code . co_filename lineno = frame . f_lineno basename = os . path . basename ( filename ) message = \"\" % ( basename , lineno ) if code . co_name != \"\" : message = \"\" % ( message , code . co_name ) return message class Debugger : vstack = vsource = vlocals = vglobals = None def __init__ ( self , pyshell , idb = None ) : if idb is None : idb = Idb ( self ) self . pyshell = pyshell self . idb = idb self . frame = None self . make_gui ( ) self . interacting = def run ( self , * args ) : try : self . interacting = return self . idb . run ( * args ) finally : self . interacting = def close ( self , event = None ) : if self . interacting : self . top . bell ( ) return if self . stackviewer : self . stackviewer . close ( ) ; self . stackviewer = None self . pyshell . close_debugger ( ) self . top . destroy ( ) def make_gui ( self ) : pyshell = self . pyshell self . flist = pyshell . flist self . root = root = pyshell . root self . top = top = ListedToplevel ( root ) self . top . wm_title ( \"\" ) self . top . wm_iconname ( \"\" ) top . wm_protocol ( \"\" , self . close ) self . top . bind ( \"\" , self . close ) self . bframe = bframe = Frame ( top ) self . bframe . pack ( anchor = \"\" ) self . buttons = bl = [ ] self . bcont = b = Button ( bframe , text = \"\" , command = self . cont ) bl . append ( b ) self . bstep = b = Button ( bframe , text = \"\" , command = self . step ) bl . append ( b ) self . bnext = b = Button ( bframe , text = \"\" , command = self . next ) bl . append ( b ) self . bret = b = Button ( bframe , text = \"\" , command = self . ret ) bl . append ( b ) self . bret = b = Button ( bframe , text = \"\" , command = self . quit ) bl . append ( b ) for b in bl : b . configure ( state = \"\" ) b . pack ( side = \"\" ) self . cframe = cframe = Frame ( bframe ) self . cframe . pack ( side = \"\" ) if not self . vstack : self . __class__ . vstack = BooleanVar ( top ) self . vstack . set ( ) self . bstack = Checkbutton ( cframe , text = \"\" , command = self . show_stack , variable = self . vstack ) self . bstack . grid ( row = , column = ) if not self . vsource : self . __class__ . vsource = BooleanVar ( top ) self . bsource = Checkbutton ( cframe , text = \"\" , command = self . show_source , variable = self . vsource ) self . bsource . grid ( row = , column = ) if not self . vlocals : self . __class__ . vlocals = BooleanVar ( top ) self . vlocals . set ( ) self . blocals = Checkbutton ( cframe , text = \"\" , command = self . show_locals , variable = self . vlocals ) self . blocals . grid ( row = , column = ) if not self . vglobals : self . __class__ . vglobals = BooleanVar ( top ) self . bglobals = Checkbutton ( cframe , text = \"\" , command = self . show_globals , variable = self . vglobals ) self . bglobals . grid ( row = , column = ) self . status = Label ( top , anchor = \"\" ) self . status . pack ( anchor = \"\" ) self . error = Label ( top , anchor = \"\" ) self . error . pack ( anchor = \"\" , fill = \"\" ) self . errorbg = self . error . cget ( \"\" ) self . fstack = Frame ( top , height = ) self . fstack . pack ( expand = , fill = \"\" ) self . flocals = Frame ( top ) self . flocals . pack ( expand = , fill = \"\" ) self . fglobals = Frame ( top , height = ) self . fglobals . pack ( expand = , fill = \"\" ) if self . vstack . get ( ) : self . show_stack ( ) if self . vlocals . get ( ) : self . show_locals ( ) if self . vglobals . get ( ) : self . show_globals ( ) def interaction ( self , message , frame , info = None ) : self . frame = frame self . status . configure ( text = message ) if info : type , value , tb = info try : m1 = type . __name__ except AttributeError : m1 = \"\" % str ( type ) if value is not None : try : m1 = \"\" % ( m1 , str ( value ) ) except : pass bg = \"\" else : m1 = \"\" tb = None bg = self . errorbg self . error . configure ( text = m1 , background = bg ) sv = self . stackviewer if sv : stack , i = self . idb . get_stack ( self . frame , tb ) sv . load_stack ( stack , i ) self . show_variables ( ) if self . vsource . get ( ) : self . sync_source_line ( ) for b in self . buttons : b . configure ( state = \"\" ) self . top . wakeup ( ) self . root . mainloop ( ) for b in self . buttons : b . configure ( state = \"\" ) self . status . configure ( text = \"\" ) self . error . configure ( text = \"\" , background = self . errorbg ) self . frame = None def sync_source_line ( self ) : frame = self . frame if not frame : return filename , lineno = self . __frame2fileline ( frame ) if filename [ : ] + filename [ - : ] != \"\" and os . path . exists ( filename ) : self . flist . gotofileline ( filename , lineno ) def __frame2fileline ( self , frame ) : code = frame . f_code filename = code . co_filename lineno = frame . f_lineno return filename , lineno def cont ( self ) : self . idb . set_continue ( ) self . root . quit ( ) def step ( self ) : self . idb . set_step ( ) self . root . quit ( ) def next ( self ) : self . idb . set_next ( self . frame ) self . root . quit ( ) def ret ( self ) : self . idb . set_return ( self . frame ) self . root . quit ( ) def quit ( self ) : self . idb . set_quit ( ) self . root . quit ( ) stackviewer = None def show_stack ( self ) : if not self . stackviewer and self . vstack . get ( ) : self . stackviewer = sv = StackViewer ( self . fstack , self . flist , self ) if self . frame : stack , i = self . idb . get_stack ( self . frame , None ) sv . load_stack ( stack , i ) else : sv = self . stackviewer if sv and not self . vstack . get ( ) : self . stackviewer = None sv . close ( ) self . fstack [ '' ] = def show_source ( self ) : if self . vsource . get ( ) : self . sync_source_line ( ) def show_frame ( self , stackitem ) : frame , lineno = stackitem self . frame = frame self . show_variables ( ) localsviewer = None globalsviewer = None def show_locals ( self ) : lv = self . localsviewer if self . vlocals . get ( ) : if not lv : self . localsviewer = NamespaceViewer ( self . flocals , \"\" ) else : if lv : self . localsviewer = None lv . close ( ) self . flocals [ '' ] = self . show_variables ( ) def show_globals ( self ) : gv = self . globalsviewer if self . vglobals . get ( ) : if not gv : self . globalsviewer = NamespaceViewer ( self . fglobals , \"\" ) else : if gv : self . globalsviewer = None gv . close ( ) self . fglobals [ '' ] = self . show_variables ( ) def show_variables ( self , force = ) : lv = self . localsviewer gv = self . globalsviewer frame = self . frame if not frame : ldict = gdict = None else : ldict = frame . f_locals gdict = frame . f_globals if lv and gv and ldict is gdict : ldict = None if lv : lv . load_dict ( ldict , force , self . pyshell . interp . rpcclt ) if gv : gv . load_dict ( gdict , force , self . pyshell . interp . rpcclt ) def set_breakpoint_here ( self , filename , lineno ) : self . idb . set_break ( filename , lineno ) def clear_breakpoint_here ( self , filename , lineno ) : self . idb . clear_break ( filename , lineno ) def clear_file_breaks ( self , filename ) : self . idb . clear_all_file_breaks ( filename ) def load_breakpoints ( self ) : \"\" for editwin in self . pyshell . flist . inversedict : filename = editwin . io . filename try : for lineno in editwin . breakpoints : self . set_breakpoint_here ( filename , lineno ) except AttributeError : continue class StackViewer ( ScrolledList ) : def __init__ ( self , master , flist , gui ) : if macosxSupport . runningAsOSXApp ( ) : ScrolledList . __init__ ( self , master ) else : ScrolledList . __init__ ( self , master , width = ) self . flist = flist self . gui = gui self . stack = [ ] def load_stack ( self , stack , index = None ) : self . stack = stack self . clear ( ) for i in range ( len ( stack ) ) : frame , lineno = stack [ i ] try : modname = frame . f_globals [ \"\" ] except : modname = \"\" code = frame . f_code filename = code . co_filename funcname = code . co_name import linecache sourceline = linecache . getline ( filename , lineno ) sourceline = sourceline . strip ( ) if funcname in ( \"\" , \"\" , None ) : item = \"\" % ( modname , lineno , sourceline ) else : item = \"\" % ( modname , funcname , lineno , sourceline ) if i == index : item = \"\" + item self . append ( item ) if index is not None : self . select ( index ) def popup_event ( self , event ) : \"\" if self . stack : return ScrolledList . popup_event ( self , event ) def fill_menu ( self ) : \"\" menu = self . menu menu . add_command ( label = \"\" , command = self . goto_source_line ) menu . add_command ( label = \"\" , command = self . show_stack_frame ) def on_select ( self , index ) : \"\" if <= index < len ( self . stack ) : self . gui . show_frame ( self . stack [ index ] ) def on_double ( self , index ) : \"\" self . show_source ( index ) def goto_source_line ( self ) : index = self . listbox . index ( \"\" ) self . show_source ( index ) def show_stack_frame ( self ) : index = self . listbox . index ( \"\" ) if <= index < len ( self . stack ) : self . gui . show_frame ( self . stack [ index ] ) def show_source ( self , index ) : if not ( <= index < len ( self . stack ) ) : return frame , lineno = self . stack [ index ] code = frame . f_code filename = code . co_filename if os . path . isfile ( filename ) : edit = self . flist . open ( filename ) if edit : edit . gotoline ( lineno ) class NamespaceViewer : def __init__ ( self , master , title , dict = None ) : width = height = if dict : height = * len ( dict ) self . master = master self . title = title import reprlib self . repr = reprlib . Repr ( ) self . repr . maxstring = self . repr . maxother = self . frame = frame = Frame ( master ) self . frame . pack ( expand = , fill = \"\" ) self . label = Label ( frame , text = title , borderwidth = , relief = \"\" ) self . label . pack ( fill = \"\" ) self . vbar = vbar = Scrollbar ( frame , name = \"\" ) vbar . pack ( side = \"\" , fill = \"\" ) self . canvas = canvas = Canvas ( frame , height = min ( , max ( , height ) ) , scrollregion = ( , , width , height ) ) canvas . pack ( side = \"\" , fill = \"\" , expand = ) vbar [ \"\" ] = canvas . yview canvas [ \"\" ] = vbar . set self . subframe = subframe = Frame ( canvas ) self . sfid = canvas . create_window ( , , window = subframe , anchor = \"\" ) self . load_dict ( dict ) dict = - def load_dict ( self , dict , force = , rpc_client = None ) : if dict is self . dict and not force : return subframe = self . subframe frame = self . frame for c in list ( subframe . children . values ( ) ) : c . destroy ( ) self . dict = None if not dict : l = Label ( subframe , text = \"\" ) l . grid ( row = , column = ) else : keys_list = dict . keys ( ) names = sorted ( keys_list ) row = for name in names : value = dict [ name ] svalue = self . repr . repr ( value ) if rpc_client : svalue = svalue [ : - ] l = Label ( subframe , text = name ) l . grid ( row = row , column = , sticky = \"\" ) l = Entry ( subframe , width = , borderwidth = ) l . insert ( , svalue ) l . grid ( row = row , column = , sticky = \"\" ) row = row + self . dict = dict subframe . update_idletasks ( ) width = subframe . winfo_reqwidth ( ) height = subframe . winfo_reqheight ( ) ", "answer": "canvas = self . canvas"}, {"prompt": " \"\"\"\"\"\" __revision__ = \"\" __all__ = [ '' , ] import os import os . path import SCons . Errors class _PathVariableClass : def PathAccept ( self , key , val , env ) : \"\"\"\"\"\" pass def PathIsDir ( self , key , val , env ) : \"\"\"\"\"\" if not os . path . isdir ( val ) : ", "answer": "if os . path . isfile ( val ) :"}, {"prompt": " \"\"\"\"\"\" __version__ = \"\" def toListOf ( value , converter , allowOne = False , allowNone = False , name = \"\" ) : \"\"\"\"\"\" if value is None and allowNone : return None ", "answer": "if name :"}, {"prompt": " \"\"\"\"\"\" GL_ETC1_RGB8_OES = GL_PALETTE4_RGB8_OES = GL_PALETTE4_RGBA8_OES = GL_PALETTE4_R5_G6_B5_OES = GL_PALETTE4_RGBA4_OES = GL_PALETTE4_RGB5_A1_OES = GL_PALETTE8_RGB8_OES = GL_PALETTE8_RGBA8_OES = GL_PALETTE8_R5_G6_B5_OES = GL_PALETTE8_RGBA4_OES = GL_PALETTE8_RGB5_A1_OES = GL_DEPTH_COMPONENT24_OES = GL_DEPTH_COMPONENT32_OES = GL_TEXTURE_EXTERNAL_OES = GL_SAMPLER_EXTERNAL_OES = GL_TEXTURE_BINDING_EXTERNAL_OES = GL_REQUIRED_TEXTURE_IMAGE_UNITS_OES = GL_UNSIGNED_INT = GL_PROGRAM_BINARY_LENGTH_OES = GL_NUM_PROGRAM_BINARY_FORMATS_OES = GL_PROGRAM_BINARY_FORMATS_OES = GL_WRITE_ONLY_OES = GL_BUFFER_ACCESS_OES = GL_BUFFER_MAPPED_OES = GL_BUFFER_MAP_POINTER_OES = GL_DEPTH_STENCIL_OES = GL_UNSIGNED_INT_24_8_OES = GL_DEPTH24_STENCIL8_OES = GL_RGB8_OES = GL_RGBA8_OES = GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES = GL_STENCIL_INDEX1_OES = GL_STENCIL_INDEX4_OES = GL_TEXTURE_WRAP_R_OES = GL_TEXTURE_3D_OES = GL_TEXTURE_BINDING_3D_OES = GL_MAX_3D_TEXTURE_SIZE_OES = GL_SAMPLER_3D_OES = GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_3D_ZOFFSET_OES = GL_HALF_FLOAT_OES = GL_VERTEX_ARRAY_BINDING_OES = GL_UNSIGNED_INT_10_10_10_2_OES = GL_INT_10_10_10_2_OES = GL_3DC_X_AMD = GL_3DC_XY_AMD = GL_ATC_RGB_AMD = GL_ATC_RGBA_EXPLICIT_ALPHA_AMD = GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD = GL_COUNTER_TYPE_AMD = GL_COUNTER_RANGE_AMD = GL_UNSIGNED_INT64_AMD = GL_PERCENTAGE_AMD = GL_PERFMON_RESULT_AVAILABLE_AMD = GL_PERFMON_RESULT_SIZE_AMD = GL_PERFMON_RESULT_AMD = GL_Z400_BINARY_AMD = GL_READ_FRAMEBUFFER_ANGLE = GL_DRAW_FRAMEBUFFER_ANGLE = GL_DRAW_FRAMEBUFFER_BINDING_ANGLE = GL_READ_FRAMEBUFFER_BINDING_ANGLE = ", "answer": "GL_RENDERBUFFER_SAMPLES_ANGLE = "}, {"prompt": " import itertools import random import requests import logging registry = { } class Plugin ( type ) : def __new__ ( metacls , name , bases , namespace , ** kwargs ) : cls = type . __new__ ( metacls , name , bases , dict ( namespace ) ) if hasattr ( cls , \"\" ) : registry [ cls . __provider_name__ ] = cls return cls class TeleportationProvider ( object ) : __metaclass__ = Plugin GEOIP_URL = '' def __init__ ( self , name , countries , debug = False , ** kwargs ) : self . name = name self . countries = countries self . debug = debug self . kwargs = kwargs def __repr__ ( self ) : return \"\" . format ( self . __provider_name__ , self . name ) def can_teleport_to ( self , place ) : return place in self . countries def teleport ( self , place ) : \"\"\"\"\"\" raise NotImplemented @ property def is_proxy ( self ) : return False def where_we_teleported ( self ) : return requests . get ( self . GEOIP_URL , proxies = self . get_proxies ( ) ) . text . lower ( ) def go_home ( self ) : pass def get_proxies ( self ) : return { } def get_peer_address ( self ) : raise NotImplementedError def _shuffle ( i ) : i = list ( i ) random . shuffle ( i ) return i def _construct ( args ) : if args [ \"\" ] not in registry : raise RuntimeError ( \"\" . format ( args [ \"\" ] ) ) return registry [ args [ \"\" ] ] ( ** args ) class Teleport ( object ) : def __init__ ( self , config ) : self . config = config def get_sorted_providers ( self ) : by_priority = lambda provider : provider [ \"\" ] sorted_by_priority = sorted ( self . config [ \"\" ] , key = by_priority ) grouped_by_priority = itertools . groupby ( sorted_by_priority , key = by_priority ) res = [ ] for _ , providers in grouped_by_priority : for args in _shuffle ( providers ) : res . append ( _construct ( args ) ) return res def who_can_teleport_to ( self , place ) : return [ provider for provider in self . get_sorted_providers ( ) if provider . can_teleport_to ( place ) ] def goto ( self , place ) : \"\"\"\"\"\" providers = self . who_can_teleport_to ( place ) if not providers : raise RuntimeError ( '' . format ( place ) ) logging . info ( '' , place , providers ) _errors = [ ] ", "answer": "for provider in providers :"}, {"prompt": " from __future__ import print_function , unicode_literals import time import datetime import random import json from voodoo . log import logged import voodoo . log as log from voodoo . typechecker import typecheck from voodoo . gen import CoordAddress import voodoo . sessions . session_id as SessionId from voodoo . override import Override from weblab . core . coordinator . exc import ExpiredSessionError from weblab . core . coordinator . scheduler_transactions_synchronizer import SchedulerTransactionsSynchronizer from weblab . core . coordinator . scheduler import Scheduler import weblab . core . coordinator . status as WSS from weblab . core . coordinator . resource import Resource from weblab . data . experiments import ExperimentInstanceId , ExperimentId from weblab . core . coordinator . redis . constants import ( WEBLAB_RESOURCE_RESERVATION_PQUEUE , WEBLAB_RESOURCE_SLOTS , WEBLAB_RESOURCE_RESERVATIONS , WEBLAB_RESOURCE_PQUEUE_RESERVATIONS , WEBLAB_RESOURCE_PQUEUE_POSITIONS , WEBLAB_RESOURCE_PQUEUE_MAP , WEBLAB_RESOURCE_PQUEUE_SORTED , WEBLAB_RESOURCE_PQUEUE_INSTANCE_RESERVATIONS , LAB_COORD , CLIENT_INITIAL_DATA , REQUEST_INFO , EXPERIMENT_TYPE , EXPERIMENT_INSTANCE , START_TIME , TIME , INITIALIZATION_IN_ACCOUNTING , PRIORITY , TIMESTAMP_BEFORE , TIMESTAMP_AFTER , LAB_SESSION_ID , EXP_INFO , INITIAL_CONFIGURATION , RESOURCE_INSTANCE , ACTIVE_STATUS , STATUS_RESERVED , STATUS_WAITING_CONFIRMATION , ) EXPIRATION_TIME = * DEBUG = False def exc_checker ( func ) : def wrapper ( * args , ** kwargs ) : try : return func ( * args , ** kwargs ) except : if DEBUG : import traceback traceback . print_exc ( ) log . log ( PriorityQueueScheduler , log . level . Error , \"\" % func . __name__ ) log . log_exc ( PriorityQueueScheduler , log . level . Warning ) raise wrapper . __name__ = func . __name__ wrapper . __doc__ = func . __doc__ return wrapper TIME_ANTI_RACE_CONDITIONS = class PriorityQueueScheduler ( Scheduler ) : def __init__ ( self , generic_scheduler_arguments , randomize_instances = True , ** kwargs ) : super ( PriorityQueueScheduler , self ) . __init__ ( generic_scheduler_arguments , ** kwargs ) self . randomize_instances = randomize_instances self . _synchronizer = SchedulerTransactionsSynchronizer ( self ) self . _synchronizer . start ( ) @ Override ( Scheduler ) def stop ( self ) : self . _synchronizer . stop ( ) @ Override ( Scheduler ) def is_remote ( self ) : return False @ exc_checker @ logged ( ) @ Override ( Scheduler ) @ typecheck ( typecheck . ANY , typecheck . ANY , Resource ) def removing_current_resource_slot ( self , client , resource ) : weblab_resource_instance_reservations = WEBLAB_RESOURCE_PQUEUE_INSTANCE_RESERVATIONS % ( resource . resource_type , resource . resource_instance ) current_reservation_ids = client . smembers ( weblab_resource_instance_reservations ) if len ( current_reservation_ids ) > : current_reservation_id = list ( current_reservation_ids ) [ ] if client . srem ( weblab_resource_instance_reservations , current_reservation_id ) : self . reservations_manager . downgrade_confirmation ( current_reservation_id ) self . resources_manager . release_resource ( resource ) weblab_reservation_pqueue = WEBLAB_RESOURCE_RESERVATION_PQUEUE % ( self . resource_type_name , current_reservation_id ) reservation_data_str = client . get ( weblab_reservation_pqueue ) reservation_data = json . loads ( reservation_data_str ) reservation_data . pop ( ACTIVE_STATUS , None ) reservation_data . pop ( TIMESTAMP_BEFORE , None ) reservation_data . pop ( TIMESTAMP_AFTER , None ) reservation_data . pop ( LAB_SESSION_ID , None ) reservation_data . pop ( EXP_INFO , None ) reservation_data_str = json . dumps ( reservation_data ) reservation_data = client . set ( weblab_reservation_pqueue , reservation_data_str ) weblab_resource_pqueue_map = WEBLAB_RESOURCE_PQUEUE_MAP % self . resource_type_name weblab_resource_pqueue_sorted = WEBLAB_RESOURCE_PQUEUE_SORTED % self . resource_type_name filled_reservation_id = client . hget ( weblab_resource_pqueue_map , current_reservation_id ) client . zadd ( weblab_resource_pqueue_sorted , filled_reservation_id , - ) return True return False @ exc_checker @ logged ( ) @ Override ( Scheduler ) def reserve_experiment ( self , reservation_id , experiment_id , time , priority , initialization_in_accounting , client_initial_data , request_info ) : \"\"\"\"\"\" client = self . redis_maker ( ) weblab_reservation_pqueue = WEBLAB_RESOURCE_RESERVATION_PQUEUE % ( self . resource_type_name , reservation_id ) weblab_resource_reservations = WEBLAB_RESOURCE_RESERVATIONS % self . resource_type_name weblab_resource_pqueue_reservations = WEBLAB_RESOURCE_PQUEUE_RESERVATIONS % self . resource_type_name weblab_resource_pqueue_positions = WEBLAB_RESOURCE_PQUEUE_POSITIONS % self . resource_type_name weblab_resource_pqueue_map = WEBLAB_RESOURCE_PQUEUE_MAP % self . resource_type_name weblab_resource_pqueue_sorted = WEBLAB_RESOURCE_PQUEUE_SORTED % self . resource_type_name current_position = client . incr ( weblab_resource_pqueue_positions ) filled_reservation_id = \"\" % ( str ( current_position ) . zfill ( ) , reservation_id ) pipeline = client . pipeline ( ) pipeline . hset ( weblab_resource_pqueue_map , reservation_id , filled_reservation_id ) pipeline . zadd ( weblab_resource_pqueue_sorted , filled_reservation_id , priority ) pipeline . sadd ( weblab_resource_reservations , reservation_id ) pipeline . sadd ( weblab_resource_pqueue_reservations , reservation_id ) generic_data = { TIME : time , INITIALIZATION_IN_ACCOUNTING : initialization_in_accounting , PRIORITY : priority , } pipeline . set ( weblab_reservation_pqueue , json . dumps ( generic_data ) ) pipeline . execute ( ) return self . get_reservation_status ( reservation_id ) @ exc_checker @ logged ( ) @ Override ( Scheduler ) def get_reservation_status ( self , reservation_id ) : self . _remove_expired_reservations ( ) expired = self . reservations_manager . update ( reservation_id ) if expired : self . _delete_reservation ( reservation_id ) raise ExpiredSessionError ( \"\" ) self . _synchronizer . request_and_wait ( ) reservation_id_with_route = '' % ( reservation_id , reservation_id , self . core_server_route ) client = self . redis_maker ( ) weblab_reservation_pqueue = WEBLAB_RESOURCE_RESERVATION_PQUEUE % ( self . resource_type_name , reservation_id ) reservation_data_str = client . get ( weblab_reservation_pqueue ) if reservation_data_str is None : log . log ( PriorityQueueScheduler , log . level . Error , \"\" ) return WSS . WaitingInstancesQueueStatus ( reservation_id_with_route , ) reservation_data = json . loads ( reservation_data_str ) if ACTIVE_STATUS in reservation_data : status = reservation_data [ ACTIVE_STATUS ] if status == STATUS_WAITING_CONFIRMATION : return WSS . WaitingConfirmationQueueStatus ( reservation_id_with_route , self . core_server_url ) str_lab_coord_address = reservation_data [ LAB_COORD ] obtained_time = reservation_data [ TIME ] initialization_in_accounting = reservation_data [ INITIALIZATION_IN_ACCOUNTING ] lab_session_id = reservation_data [ LAB_SESSION_ID ] initial_configuration = reservation_data [ INITIAL_CONFIGURATION ] timestamp_before_tstamp = reservation_data [ TIMESTAMP_BEFORE ] timestamp_after_tstamp = reservation_data [ TIMESTAMP_AFTER ] if EXP_INFO in reservation_data and reservation_data [ EXP_INFO ] : exp_info = json . loads ( reservation_data [ EXP_INFO ] ) else : exp_info = { } timestamp_before = datetime . datetime . fromtimestamp ( timestamp_before_tstamp ) timestamp_after = datetime . datetime . fromtimestamp ( timestamp_after_tstamp ) lab_coord_address = CoordAddress . translate ( str_lab_coord_address ) if initialization_in_accounting : before = timestamp_before_tstamp else : before = timestamp_after_tstamp if before is not None : remaining = ( before + obtained_time ) - self . time_provider . get_time ( ) else : remaining = obtained_time return WSS . LocalReservedStatus ( reservation_id_with_route , lab_coord_address , SessionId . SessionId ( lab_session_id ) , exp_info , obtained_time , initial_configuration , timestamp_before , timestamp_after , initialization_in_accounting , remaining , self . core_server_url ) weblab_resource_pqueue_map = WEBLAB_RESOURCE_PQUEUE_MAP % self . resource_type_name weblab_resource_pqueue_sorted = WEBLAB_RESOURCE_PQUEUE_SORTED % self . resource_type_name filled_reservation_id = client . hget ( weblab_resource_pqueue_map , reservation_id ) if filled_reservation_id is None : log . log ( PriorityQueueScheduler , log . level . Error , \"\" ) return WSS . WaitingInstancesQueueStatus ( reservation_id_with_route , ) position = client . zrank ( weblab_resource_pqueue_sorted , filled_reservation_id ) if position is None : time . sleep ( TIME_ANTI_RACE_CONDITIONS * random . random ( ) ) return self . get_reservation_status ( reservation_id ) if self . resources_manager . are_resource_instances_working ( self . resource_type_name ) : ", "answer": "return WSS . WaitingQueueStatus ( reservation_id_with_route , position )"}, {"prompt": " \"\"\"\"\"\" import numpy as np from scipy import special np_log = np . log ", "answer": "np_pi = np . pi"}, {"prompt": " '''''' import wx import math class ImageTileSizer ( wx . PySizer ) : def __init__ ( self ) : wx . PySizer . __init__ ( self ) def pitch ( self ) : sizes = [ c . GetSize ( ) + wx . Size ( * c . GetBorder ( ) , * c . GetBorder ( ) ) for c in self . GetChildren ( ) ] if sizes == [ ] : ", "answer": "return None"}, {"prompt": " from scipy import ndimage import numpy as np import math from utils import computeCellSize , Projection , isGeographic class Hillshade ( ) : def __init__ ( self ) : self . name = \"\" self . description = \"\" self . prepare ( ) self . proj = Projection ( ) def getParameterInfo ( self ) : return [ { '' : '' , '' : '' , '' : None , '' : True , '' : \"\" , '' : \"\" , } , { '' : '' , '' : '' , '' : , '' : False , '' : \"\" , '' : ( \"\" \"\" ) , } , { '' : '' , '' : '' , '' : , '' : False , '' : \"\" , '' : ( \"\" \"\" ) , } , { '' : '' , '' : '' , '' : , '' : False , '' : \"\" , '' : ( \"\" ", "answer": "\"\""}, {"prompt": " import unittest import azure . mgmt . notificationhubs from testutils . common_recordingtestcase import record from tests . mgmt_testcase import HttpStatusCode , AzureMgmtTestCase class MgmtNotificationHubsTest ( AzureMgmtTestCase ) : def setUp ( self ) : super ( MgmtNotificationHubsTest , self ) . setUp ( ) self . notificationhubs_client = self . create_mgmt_client ( azure . mgmt . notificationhubs . NotificationHubsManagementClientConfiguration , azure . mgmt . notificationhubs . NotificationHubsManagementClient ) @ record def test_notification_hubs ( self ) : self . create_resource_group ( ) account_name = self . get_resource_name ( '' ) ", "answer": "output = self . notificationhubs_client . namespaces . check_availability ("}, {"prompt": " from django . db import models from django . contrib . sites . models import Site from django . utils . translation import ugettext_lazy as _ class FlatPage ( models . Model ) : url = models . CharField ( _ ( '' ) , max_length = , db_index = True ) title = models . CharField ( _ ( '' ) , max_length = ) content = models . TextField ( _ ( '' ) , blank = True ) enable_comments = models . BooleanField ( _ ( '' ) ) template_name = models . CharField ( _ ( '' ) , max_length = , blank = True , help_text = _ ( \"\" ) ) registration_required = models . BooleanField ( _ ( '' ) , help_text = _ ( \"\" ) ) sites = models . ManyToManyField ( Site ) class Meta : db_table = '' verbose_name = _ ( '' ) verbose_name_plural = _ ( '' ) ordering = ( '' , ) def __unicode__ ( self ) : return u\"\" % ( self . url , self . title ) def get_absolute_url ( self ) : ", "answer": "return self . url "}, {"prompt": " \"\"\"\"\"\" import json import logging import multiprocessing import os import sys import yaml import constants import file_io sys . path . append ( os . path . join ( os . path . dirname ( __file__ ) , '' ) ) from google . appengine . api . appcontroller_client import AppControllerClient def read_file_contents ( path ) : \"\"\"\"\"\" with open ( path ) as file_handle : return file_handle . read ( ) def get_appcontroller_client ( ) : \"\"\"\"\"\" head_node_ip_file = '' head_node = read_file_contents ( head_node_ip_file ) . rstrip ( '' ) secret_file = '' secret = read_file_contents ( secret_file ) return AppControllerClient ( head_node , secret ) def get_keyname ( ) : \"\"\"\"\"\" return get_db_info ( ) [ '' ] def get_all_ips ( ) : \"\"\"\"\"\" nodes = file_io . read ( constants . ALL_IPS_LOC ) nodes = nodes . split ( '' ) return filter ( None , nodes ) def get_login_ip ( ) : \"\"\"\"\"\" return file_io . read ( constants . LOGIN_IP_LOC ) . rstrip ( ) def get_private_ip ( ) : \"\"\"\"\"\" return file_io . read ( constants . PRIVATE_IP_LOC ) . rstrip ( ) def get_public_ip ( ) : \"\"\"\"\"\" return file_io . read ( constants . PUBLIC_IP_LOC ) . rstrip ( ) def get_secret ( ) : \"\"\"\"\"\" return file_io . read ( constants . SECRET_LOC ) . rstrip ( ) def get_num_cpus ( ) : \"\"\"\"\"\" return multiprocessing . cpu_count ( ) def get_db_info ( ) : \"\"\"\"\"\" info = file_io . read ( constants . DB_INFO_LOC ) return yaml . load ( info ) def get_taskqueue_nodes ( ) : \"\"\"\"\"\" nodes = file_io . read ( constants . TASKQUEUE_NODE_FILE ) nodes = nodes . split ( '' ) if nodes [ - ] == '' : nodes = nodes [ : - ] return nodes def get_app_path ( app_id ) : \"\"\"\"\"\" return constants . APPS_PATH + app_id + '' def get_zk_locations_string ( ) : \"\"\"\"\"\" try : info = file_io . read ( constants . ZK_LOCATIONS_JSON_FILE ) zk_json = json . loads ( info ) return \"\" . join ( zk_json [ '' ] ) + \"\" except IOError , io_error : logging . exception ( io_error ) return constants . ZK_DEFAULT_CONNECTION_STR except ValueError , value_error : logging . exception ( value_error ) return constants . ZK_DEFAULT_CONNECTION_STR except TypeError , type_error : logging . exception ( type_error ) return constants . ZK_DEFAULT_CONNECTION_STR except KeyError , key_error : ", "answer": "logging . exception ( key_error )"}, {"prompt": " from ... query . expression import QueryExpression from . relation import Relation from . result import Result class BelongsTo ( Relation ) : def __init__ ( self , query , parent , foreign_key , other_key , relation ) : \"\"\"\"\"\" self . _other_key = other_key self . _relation = relation self . _foreign_key = foreign_key super ( BelongsTo , self ) . __init__ ( query , parent ) def get_results ( self ) : \"\"\"\"\"\" return self . _query . first ( ) def add_constraints ( self ) : \"\"\"\"\"\" if self . _constraints : table = self . _related . get_table ( ) self . _query . where ( '' % ( table , self . _other_key ) , '' , getattr ( self . _parent , self . _foreign_key ) ) def get_relation_count_query ( self , query , parent ) : \"\"\"\"\"\" query . select ( QueryExpression ( '' ) ) other_key = self . wrap ( '' % ( query . get_model ( ) . get_table ( ) , self . _other_key ) ) return query . where ( self . get_qualified_foreign_key ( ) , '' , QueryExpression ( other_key ) ) def add_eager_constraints ( self , models ) : \"\"\"\"\"\" key = '' % ( self . _related . get_table ( ) , self . _other_key ) self . _query . where_in ( key , self . _get_eager_model_keys ( models ) ) def _get_eager_model_keys ( self , models ) : \"\"\"\"\"\" keys = [ ] for model in models : value = getattr ( model , self . _foreign_key ) if value is not None and value not in keys : keys . append ( value ) if not len ( keys ) : return [ ] return keys def init_relation ( self , models , relation ) : \"\"\"\"\"\" for model in models : model . set_relation ( relation , Result ( None , self , model ) ) return models def match ( self , models , results , relation ) : \"\"\"\"\"\" foreign = self . _foreign_key other = self . _other_key dictionary = { } for result in results : dictionary [ result . get_attribute ( other ) ] = result for model in models : value = getattr ( model , foreign ) if value in dictionary : results = Result ( dictionary [ value ] , self , model ) else : results = Result ( None , self , model ) model . set_relation ( relation , results ) return models def associate ( self , model ) : \"\"\"\"\"\" ", "answer": "self . _parent . set_attribute ( self . _foreign_key , model . get_attribute ( self . _other_key ) )"}, {"prompt": " from twisted . trial import unittest from twisted . internet import reactor from twisted . internet . defer import Deferred import os import sys ", "answer": "sys . path . append ( os . path . join ( os . path . dirname ( __file__ ) , \"\" ) )"}, {"prompt": " import mock from sahara . tests . unit import base from sahara . utils . openstack import neutron as neutron_client class NeutronClientTest ( base . SaharaTestCase ) : ", "answer": "@ mock . patch ( \"\" )"}, {"prompt": " import hashlib from pkgutil import get_data from functools import wraps import six from yaml import load as load_yaml from . utils import registry ", "answer": "@ registry"}, {"prompt": " \"\"\"\"\"\" import cProfile import os import pstats import sys import time from google . appengine . ext import testbed tb = testbed . Testbed ( ) tb . activate ( ) tb . init_datastore_v3_stub ( ) tb . init_memcache_stub ( ) from google . appengine . ext import db import ndb N = class Person ( db . Model ) : a0 = db . StringProperty ( default = '' ) a1 = db . StringProperty ( default = '' ) a2 = db . StringProperty ( default = '' ) a3 = db . StringProperty ( default = '' ) a4 = db . StringProperty ( default = '' ) a5 = db . StringProperty ( default = '' ) a6 = db . StringProperty ( default = '' ) a7 = db . StringProperty ( default = '' ) a8 = db . StringProperty ( default = '' ) a9 = db . StringProperty ( default = '' ) OldPerson = Person class Person ( ndb . Model ) : a0 = ndb . StringProperty ( default = '' ) a1 = ndb . StringProperty ( default = '' ) ", "answer": "a2 = ndb . StringProperty ( default = '' )"}, {"prompt": " from . sub_resource import SubResource class ExpressRouteCircuitPeering ( SubResource ) : \"\"\"\"\"\" _attribute_map = { '' : { '' : '' , '' : '' } , '' : { '' : '' , '' : '' } , '' : { '' : '' , '' : '' } , '' : { '' : '' , '' : '' } , '' : { '' : '' , '' : '' } , '' : { '' : '' , '' : '' } , '' : { '' : '' , '' : '' } , '' : { '' : '' , '' : '' } , '' : { '' : '' , '' : '' } , '' : { '' : '' , '' : '' } , '' : { '' : '' , '' : '' } , '' : { '' : '' , '' : '' } , '' : { '' : '' , '' : '' } , '' : { '' : '' , '' : '' } , '' : { '' : '' , '' : '' } , ", "answer": "'' : { '' : '' , '' : '' } ,"}, {"prompt": " from social . backends . oauth import BaseOAuth1 class WithingsOAuth ( BaseOAuth1 ) : name = '' AUTHORIZATION_URL = '' REQUEST_TOKEN_URL = '' ACCESS_TOKEN_URL = '' ID_KEY = '' def get_user_details ( self , response ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " from random import randrange , shuffle from BitTornado . clock import clock try : True except : True = False = class PiecePicker : def __init__ ( self , numpieces , rarest_first_cutoff = , rarest_first_priority_cutoff = , priority_step = ) : self . rarest_first_cutoff = rarest_first_cutoff self . rarest_first_priority_cutoff = rarest_first_priority_cutoff + priority_step self . priority_step = priority_step self . cutoff = rarest_first_priority_cutoff self . numpieces = numpieces self . started = [ ] self . totalcount = self . numhaves = [ ] * numpieces self . priority = [ ] * numpieces self . removed_partials = { } self . crosscount = [ numpieces ] self . crosscount2 = [ numpieces ] self . has = [ ] * numpieces self . numgot = self . done = False self . seed_connections = { } self . past_ips = { } self . seed_time = None self . superseed = False self . seeds_connected = self . _init_interests ( ) def _init_interests ( self ) : self . interests = [ [ ] for x in xrange ( self . priority_step ) ] self . level_in_interests = [ self . priority_step ] * self . numpieces interests = range ( self . numpieces ) shuffle ( interests ) self . pos_in_interests = [ ] * self . numpieces for i in xrange ( self . numpieces ) : self . pos_in_interests [ interests [ i ] ] = i self . interests . append ( interests ) def got_have ( self , piece ) : self . totalcount += numint = self . numhaves [ piece ] self . numhaves [ piece ] += self . crosscount [ numint ] -= if numint + == len ( self . crosscount ) : self . crosscount . append ( ) self . crosscount [ numint + ] += if not self . done : numintplus = numint + self . has [ piece ] self . crosscount2 [ numintplus ] -= if numintplus + == len ( self . crosscount2 ) : self . crosscount2 . append ( ) self . crosscount2 [ numintplus + ] += numint = self . level_in_interests [ piece ] self . level_in_interests [ piece ] += if self . superseed : self . seed_got_haves [ piece ] += numint = self . level_in_interests [ piece ] self . level_in_interests [ piece ] += elif self . has [ piece ] or self . priority [ piece ] == - : return if numint == len ( self . interests ) - : self . interests . append ( [ ] ) self . _shift_over ( piece , self . interests [ numint ] , self . interests [ numint + ] ) def lost_have ( self , piece ) : self . totalcount -= numint = self . numhaves [ piece ] self . numhaves [ piece ] -= self . crosscount [ numint ] -= self . crosscount [ numint - ] += if not self . done : numintplus = numint + self . has [ piece ] self . crosscount2 [ numintplus ] -= self . crosscount2 [ numintplus - ] += numint = self . level_in_interests [ piece ] self . level_in_interests [ piece ] -= if self . superseed : numint = self . level_in_interests [ piece ] self . level_in_interests [ piece ] -= elif self . has [ piece ] or self . priority [ piece ] == - : return self . _shift_over ( piece , self . interests [ numint ] , self . interests [ numint - ] ) def _shift_over ( self , piece , l1 , l2 ) : assert self . superseed or ( not self . has [ piece ] and self . priority [ piece ] >= ) parray = self . pos_in_interests p = parray [ piece ] assert l1 [ p ] == piece q = l1 [ - ] l1 [ p ] = q parray [ q ] = p del l1 [ - ] newp = randrange ( len ( l2 ) + ) if newp == len ( l2 ) : parray [ piece ] = len ( l2 ) l2 . append ( piece ) else : old = l2 [ newp ] parray [ old ] = len ( l2 ) l2 . append ( old ) l2 [ newp ] = piece parray [ piece ] = newp def got_seed ( self ) : self . seeds_connected += self . cutoff = max ( self . rarest_first_priority_cutoff - self . seeds_connected , ) def became_seed ( self ) : self . got_seed ( ) self . totalcount -= self . numpieces self . numhaves = [ i - for i in self . numhaves ] if self . superseed or not self . done : self . level_in_interests = [ i - for i in self . level_in_interests ] if self . interests : del self . interests [ ] del self . crosscount [ ] if not self . done : del self . crosscount2 [ ] def lost_seed ( self ) : self . seeds_connected -= self . cutoff = max ( self . rarest_first_priority_cutoff - self . seeds_connected , ) def requested ( self , piece ) : if piece not in self . started : self . started . append ( piece ) def _remove_from_interests ( self , piece , keep_partial = False ) : l = self . interests [ self . level_in_interests [ piece ] ] p = self . pos_in_interests [ piece ] assert l [ p ] == piece q = l [ - ] l [ p ] = q self . pos_in_interests [ q ] = p del l [ - ] try : self . started . remove ( piece ) if keep_partial : self . removed_partials [ piece ] = except ValueError : pass def complete ( self , piece ) : assert not self . has [ piece ] self . has [ piece ] = self . numgot += if self . numgot == self . numpieces : self . done = True self . crosscount2 = self . crosscount else : numhaves = self . numhaves [ piece ] self . crosscount2 [ numhaves ] -= if numhaves + == len ( self . crosscount2 ) : self . crosscount2 . append ( ) self . crosscount2 [ numhaves + ] += self . _remove_from_interests ( piece ) def next ( self , haves , wantfunc , complete_first = False ) : cutoff = self . numgot < self . rarest_first_cutoff complete_first = ( complete_first or cutoff ) and not haves . complete ( ) best = None bestnum = ** for i in self . started : if haves [ i ] and wantfunc ( i ) : if self . level_in_interests [ i ] < bestnum : best = i bestnum = self . level_in_interests [ i ] if best is not None : if complete_first or ( cutoff and len ( self . interests ) > self . cutoff ) : return best if haves . complete ( ) : r = [ ( , min ( bestnum , len ( self . interests ) ) ) ] elif cutoff and len ( self . interests ) > self . cutoff : r = [ ( self . cutoff , min ( bestnum , len ( self . interests ) ) ) , ( , self . cutoff ) ] else : r = [ ( , min ( bestnum , len ( self . interests ) ) ) ] for lo , hi in r : for i in xrange ( lo , hi ) : for j in self . interests [ i ] : if haves [ j ] and wantfunc ( j ) : return j if best is not None : return best return None def am_I_complete ( self ) : return self . done def bump ( self , piece ) : l = self . interests [ self . level_in_interests [ piece ] ] pos = self . pos_in_interests [ piece ] del l [ pos ] l . append ( piece ) for i in range ( pos , len ( l ) ) : self . pos_in_interests [ l [ i ] ] = i try : self . started . remove ( piece ) except : pass def set_priority ( self , piece , p ) : if self . superseed : return False oldp = self . priority [ piece ] if oldp == p : return False self . priority [ piece ] = p if p == - : if not self . has [ piece ] : self . _remove_from_interests ( piece , True ) return True if oldp == - : level = self . numhaves [ piece ] + ( self . priority_step * p ) self . level_in_interests [ piece ] = level if self . has [ piece ] : return True while len ( self . interests ) < level + : self . interests . append ( [ ] ) l2 = self . interests [ level ] parray = self . pos_in_interests newp = randrange ( len ( l2 ) + ) if newp == len ( l2 ) : parray [ piece ] = len ( l2 ) l2 . append ( piece ) else : old = l2 [ newp ] parray [ old ] = len ( l2 ) l2 . append ( old ) l2 [ newp ] = piece parray [ piece ] = newp if self . removed_partials . has_key ( piece ) : del self . removed_partials [ piece ] self . started . append ( piece ) return True numint = self . level_in_interests [ piece ] newint = numint + ( ( p - oldp ) * self . priority_step ) self . level_in_interests [ piece ] = newint if self . has [ piece ] : return False while len ( self . interests ) < newint + : self . interests . append ( [ ] ) self . _shift_over ( piece , self . interests [ numint ] , self . interests [ newint ] ) return False def is_blocked ( self , piece ) : return self . priority [ piece ] < def set_superseed ( self ) : assert self . done self . superseed = True self . seed_got_haves = [ ] * self . numpieces ", "answer": "self . _init_interests ( )"}, {"prompt": " \"\"\"\"\"\" class InstallationError ( Exception ) : \"\"\"\"\"\" class UninstallationError ( Exception ) : \"\"\"\"\"\" class DistributionNotFound ( InstallationError ) : \"\"\"\"\"\" ", "answer": "class BadCommand ( Exception ) :"}, {"prompt": " import numpy import theano from theano . gof import Apply , Constant , Generic , Op , Type , hashtype from theano . gradient import DisconnectedType def as_int_none_variable ( x ) : if x is None : return NoneConst elif NoneConst . equals ( x ) : return x x = theano . tensor . as_tensor_variable ( x , ndim = ) if x . type . dtype [ : ] not in ( '' , '' ) : raise TypeError ( '' ) return x ", "answer": "class MakeSlice ( Op ) :"}, {"prompt": " from __future__ import unicode_literals from django . db import models , migrations class Migration ( migrations . Migration ) : dependencies = [ ( '' , '' ) , ] operations = [ migrations . AddField ( model_name = '' , name = '' , field = models . IntegerField ( default = , choices = [ ( - , '' ) , ( , '' ) ] ) , ) , ", "answer": "migrations . AlterField ("}, {"prompt": " import blinker signals = blinker . Namespace ( ) ", "answer": "user_registered = signals . signal ( '' )"}, {"prompt": " \"\"\"\"\"\" from flask . ext . script import Manager from overholt . api import create_app ", "answer": "from overholt . manage import CreateUserCommand , DeleteUserCommand , ListUsersCommand"}, {"prompt": " from django . contrib . gis . db import models from django . utils . encoding import python_2_unicode_compatible @ python_2_unicode_compatible class City3D ( models . Model ) : name = models . CharField ( max_length = ) point = models . PointField ( dim = ) objects = models . GeoManager ( ) def __str__ ( self ) : return self . name @ python_2_unicode_compatible class Interstate2D ( models . Model ) : name = models . CharField ( max_length = ) line = models . LineStringField ( srid = ) objects = models . GeoManager ( ) def __str__ ( self ) : return self . name @ python_2_unicode_compatible class Interstate3D ( models . Model ) : name = models . CharField ( max_length = ) line = models . LineStringField ( dim = , srid = ) objects = models . GeoManager ( ) def __str__ ( self ) : return self . name @ python_2_unicode_compatible class InterstateProj2D ( models . Model ) : name = models . CharField ( max_length = ) line = models . LineStringField ( srid = ) objects = models . GeoManager ( ) def __str__ ( self ) : return self . name @ python_2_unicode_compatible ", "answer": "class InterstateProj3D ( models . Model ) :"}, {"prompt": " import unittest import logging import ufora . native . FORA as ForaNative import ufora . FORA . python . ExecutionContext as ExecutionContext import ufora . FORA . python . FORA as FORA import ufora . native . CallbackScheduler as CallbackScheduler callbackScheduler = CallbackScheduler . singletonForTesting ( ) callbackSchedulerFactory = callbackScheduler . getFactory ( ) emptyCodeDefinitionPoint = ForaNative . CodeDefinitionPoint . ExternalFromStringList ( [ ] ) class NotInterruptedException ( Exception ) : def __init__ ( self , context ) : self . context = context def __repr__ ( self ) : return repr ( self . context ) class NotAResultException ( Exception ) : def __init__ ( self , x ) : self . val = x def __repr__ ( self ) : return repr ( self . val ) class CouldntFinishException ( Exception ) : def __init__ ( self , x ) : self . val = x def __repr__ ( self ) : return repr ( self . val ) def finishPausedComputation ( pausedComputation ) : vdm = ForaNative . VectorDataManager ( callbackScheduler , * * ) context2 = ExecutionContext . ExecutionContext ( dataManager = vdm , allowInterpreterTracing = False ) context2 . resumePausedComputation ( pausedComputation ) context2 . resume ( ) if ( not context2 . isFinished ( ) ) : raise CouldntFinishException ( pausedComputation ) finishedResult = context2 . getFinishedResult ( ) if ( finishedResult . isResult ( ) ) : return finishedResult . asResult . result elif ( finishedResult . isException ( ) ) : return finishedResult . asException . exception else : raise Exception ( \"\" ) def callAndGetResult ( funImplVal ) : vdm = ForaNative . VectorDataManager ( callbackScheduler , * * ) context = ExecutionContext . ExecutionContext ( dataManager = vdm , allowInterpreterTracing = False ) context . evaluate ( funImplVal , ForaNative . symbol_Call ) finishedResult = context . getFinishedResult ( ) if ( not finishedResult . isResult ( ) ) : raise NotAResultException ( finishedResult ) return finishedResult . asResult . result def callAndExtractPausedCompuationAfterSteps ( funToCall , steps ) : vdm = ForaNative . VectorDataManager ( callbackScheduler , * * ) context = ExecutionContext . ExecutionContext ( dataManager = vdm , allowInterpreterTracing = False ) context . interruptAfterCycleCount ( steps ) context . evaluate ( funToCall , ForaNative . symbol_Call ) if ( not context . isInterrupted ( ) ) : raise NotInterruptedException ( context ) computation = context . extractPausedComputation ( ) context . teardown ( ) return computation class ControlFlowGraphSplitterTest ( unittest . TestCase ) : def parseStringToFunction ( self , expr ) : expression = ForaNative . parseStringToExpression ( expr , emptyCodeDefinitionPoint , \"\" ) return expression . extractRootLevelCreateFunctionPredicate ( ) def test_cfgSplitting_1 ( self ) : cfg1 = self . parseStringToFunction ( \"\" ) . toCFG ( ) steps = ForaNative . extractApplyStepsFromControlFlowGraph ( cfg1 , \"\" ) self . assertEqual ( len ( steps ) , ) splits = ForaNative . splitControlFlowGraph ( cfg1 , \"\" ) self . assertTrue ( splits is not None ) def test_cfgSplitting_2 ( self ) : cfg1 = self . parseStringToFunction ( \"\" ) . toCFG ( ) splits = ForaNative . splitControlFlowGraph ( cfg1 , None ) self . assertTrue ( splits is None ) def test_cfgSplitting_3 ( self ) : cfg1 = self . parseStringToFunction ( \"\" ) . toCFG ( ) splits = ForaNative . splitControlFlowGraph ( cfg1 , None ) self . assertTrue ( splits is None ) def test_cfgSplitting_4 ( self ) : funString = \"\" cfg = self . parseStringToFunction ( funString ) . toCFG ( ) steps = ForaNative . extractApplyStepsFromControlFlowGraph ( cfg , None ) splits = ForaNative . splitControlFlowGraph ( cfg , \"\" ) ", "answer": "self . assertTrue ( splits is not None )"}, {"prompt": " __version__ = '' ", "answer": "from prophet . app import Prophet "}, {"prompt": " '''''' import sys import os from ngsutils . bam import bam_pileup_iter , bam_open import pysam class ExpressedRegion ( object ) : _count = def __init__ ( self , chrom , only_uniq_starts = False ) : ExpressedRegion . _count += self . name = '' % ExpressedRegion . _count self . chrom = chrom self . start = None self . end = None self . fwd_count = self . rev_count = self . reads = set ( ) self . read_count = self . only_uniq_starts = only_uniq_starts self . uniq_starts = set ( ) def add_column ( self , read , pos ) : if not self . start : ", "answer": "self . start = pos"}, {"prompt": " from django . contrib import admin from models import * class PodcastCategoryNameInline ( admin . TabularInline ) : model = PodcastCategoryName fk_name = \"\" class PodcastCategoryAdmin ( admin . ModelAdmin ) : list_display = ( '' , '' ) inlines = [ PodcastCategoryNameInline , ] class PodcastAdmin ( admin . ModelAdmin ) : list_display = ( '' , '' ) ", "answer": "list_filter = ( '' , )"}, {"prompt": " from collections import deque from muntjac . addon . colorpicker . color import Color from muntjac . ui . custom_component import CustomComponent from muntjac . addon . colorpicker . color_picker_grid import ColorPickerGrid from muntjac . addon . colorpicker . color_change_event import ColorChangeEvent from muntjac . addon . colorpicker . color_picker import IColorChangeListener from muntjac . addon . colorpicker . color_selector import IColorSelector _COLOR_CHANGE_METHOD = getattr ( IColorChangeListener , '' ) class ColorPickerHistory ( CustomComponent , IColorSelector , IColorChangeListener ) : \"\"\"\"\"\" _STYLENAME = '' _rows = _columns = _colorHistory = deque ( ) _grid = None def __init__ ( self ) : \"\"\"\"\"\" super ( ColorPickerHistory , self ) . __init__ ( ) self . removeStyleName ( '' ) self . setStyleName ( self . _STYLENAME ) self . _grid = ColorPickerGrid ( self . _rows , self . _columns ) self . _grid . setWidth ( '' ) self . _grid . setPosition ( , ) self . _grid . addListener ( self , IColorChangeListener ) self . setCompositionRoot ( self . _grid ) def setHeight ( self , height , unit = None ) : super ( ColorPickerHistory , self ) . setHeight ( height , unit ) self . _grid . setHeight ( height , unit ) def setColor ( self , color ) : exists = False for c in self . _colorHistory : if color == c : exists = True break if not exists : self . _colorHistory . append ( color ) colorList = list ( self . _colorHistory ) colorList . reverse ( ) colorList . insert ( , colorList . pop ( colorList . index ( color ) ) ) colors = [ ( [ None ] * self . _columns ) for _ in range ( self . _rows ) ] iterator = iter ( colorList ) for row in range ( self . _rows ) : for col in range ( self . _columns ) : try : colors [ row ] [ col ] = iterator . next ( ) except StopIteration : colors [ row ] [ col ] = Color . WHITE self . _grid . setColorGrid ( colors ) self . _grid . requestRepaint ( ) def getColor ( self ) : return self . _colorHistory [ ] def getHistory ( self ) : \"\"\"\"\"\" array = list ( self . _colorHistory ) return array def hasColor ( self , c ) : \"\"\"\"\"\" return c in self . _colorHistory def addListener ( self , listener , iface = None ) : \"\"\"\"\"\" if ( isinstance ( listener , IColorChangeListener ) and ( iface is None or issubclass ( iface , IColorChangeListener ) ) ) : self . registerListener ( ColorChangeEvent , listener , _COLOR_CHANGE_METHOD ) super ( ColorPickerHistory , self ) . addListener ( listener , iface ) def addCallback ( self , callback , eventType = None , * args ) : if eventType is None : eventType = callback . _eventType if issubclass ( eventType , ColorChangeEvent ) : self . registerCallback ( ColorChangeEvent , callback , None , * args ) else : super ( ColorPickerHistory , self ) . addCallback ( callback , eventType , ", "answer": "* args )"}, {"prompt": " from __future__ import print_function , division , absolute_import ", "answer": "import unittest"}, {"prompt": " \"\"\"\"\"\" from pyherc . rules import Dying from pyherc . rules . combat import RangedCombatFactory from pyherc . rules . combat . factories import ( AttackFactory , MeleeCombatFactory , UnarmedCombatFactory ) from pyherc . rules . consume . factories import DrinkFactory from pyherc . rules . digging . factories import DigFactory from pyherc . rules . inventory . equip import EquipFactory from pyherc . rules . inventory . factories import ( DropFactory , InventoryFactory , PickUpFactory ) from pyherc . rules . inventory . unequip import UnEquipFactory from pyherc . rules . magic import GainDomainFactory , SpellCastingFactory from pyherc . rules . mitosis . factory import MitosisFactory from pyherc . rules . metamorphosis . factory import MetamorphosisFactory from pyherc . rules . moving . factories import MoveFactory from pyherc . rules . trapping . factory import TrappingFactory from pyherc . rules . public import ActionFactory from pyherc . rules . waiting . factories import WaitFactory from random import Random class ActionFactoryBuilder ( ) : \"\"\"\"\"\" def __init__ ( self ) : \"\"\"\"\"\" super ( ) . __init__ ( ) self . model = None self . factories = [ ] self . dying_rules = Dying ( ) self . effect_factory = None self . use_real_attack_factory = False self . use_real_drink_factory = False self . use_real_inventory_factory = False self . use_real_move_factory = False self . use_real_spellcasting_factory = False self . use_real_wait_factory = False self . use_real_gain_domain_factory = False self . use_real_dying_rules = False self . use_real_mitosis_factory = False self . use_real_metamorphosis_factory = False self . use_real_dig_factory = False self . use_real_trapping_factory = False def with_move_factory ( self ) : \"\"\"\"\"\" self . use_real_move_factory = True return self def with_attack_factory ( self ) : \"\"\"\"\"\" self . use_real_attack_factory = True return self def with_drink_factory ( self , drink_factory = None ) : \"\"\"\"\"\" if drink_factory is None : self . use_real_drink_factory = True else : if hasattr ( drink_factory , '' ) : self . factories . append ( drink_factory . build ( ) ) else : self . factories . append ( drink_factory ) return self def with_spellcasting_factory ( self , spellcasting_factory = None ) : \"\"\"\"\"\" if not spellcasting_factory : self . use_real_spellcasting_factory = True else : if hasattr ( spellcasting_factory , '' ) : self . factories . append ( spellcasting_factory . build ( ) ) else : self . factories . append ( spellcasting_factory ) return self def with_wait_factory ( self , wait_factory = None ) : \"\"\"\"\"\" if not wait_factory : self . use_real_wait_factory = True else : if hasattr ( wait_factory , '' ) : self . factories . append ( wait_factory . build ( ) ) else : self . factories . append ( wait_factory ) return self def with_inventory_factory ( self ) : \"\"\"\"\"\" self . use_real_inventory_factory = True return self def with_effect_factory ( self , effect_factory ) : \"\"\"\"\"\" self . effect_factory = effect_factory return self def with_dying_rules ( self ) : \"\"\"\"\"\" self . use_real_dying_rules = True return self def with_gain_domain_factory ( self , gain_domain_factory = None ) : \"\"\"\"\"\" if gain_domain_factory : self . factories . append ( gain_domain_factory ) else : self . use_real_gain_domain_factory = True return self def with_mitosis_factory ( self , mitosis_factory = None ) : \"\"\"\"\"\" if mitosis_factory : self . factories . append ( mitosis_factory ) else : self . use_real_mitosis_factory = True return self def with_metamorphosis_factory ( self , metamorphosis_factory = None ) : \"\"\"\"\"\" if metamorphosis_factory : self . factories . append ( metamorphosis_factory ) else : self . use_real_metamorphosis_factory = True return self def with_dig_factory ( self , dig_factory = None ) : if dig_factory : self . factories . append ( dig_factory ) else : self . use_real_dig_factory = True return self def with_trapping_factory ( self , trapping_factory = None ) : if trapping_factory : self . factories . append ( trapping_factory ) else : self . use_real_trapping_factory = True return self def build ( self ) : \"\"\"\"\"\" if self . use_real_dying_rules : self . dying_rules = Dying ( ) if self . use_real_attack_factory : unarmed_combat_factory = UnarmedCombatFactory ( self . effect_factory , self . dying_rules ) melee_combat_factory = MeleeCombatFactory ( self . effect_factory , ", "answer": "self . dying_rules )"}, {"prompt": " from django . conf . urls . defaults import * ", "answer": "urlpatterns = patterns ( '' ,"}, {"prompt": " from unittest import suite class DeferrableTestSuite ( suite . TestSuite ) : r'''''' def run ( self , result , debug = False ) : ", "answer": "topLevel = False"}, {"prompt": " import py from pypy . tool . ansi_print import ansi_log log = py . log . Producer ( \"\" ) py . log . setconsumer ( \"\" , ansi_log ) from pypy . objspace . flow import model as flowmodel from pypy . rpython . ootypesystem import ootype from pypy . translator . oosupport . treebuilder import SubOperation from pypy . translator . oosupport . metavm import InstructionList , StoreResult def render_sub_op ( sub_op , db , generator ) : op = sub_op . op instr_list = db . genoo . opcodes . get ( op . opname , None ) assert instr_list is not None , '' % op assert isinstance ( instr_list , InstructionList ) assert instr_list [ - ] is StoreResult , \"\" db . cts . lltype_to_cts ( op . result . concretetype ) for v in op . args : db . cts . lltype_to_cts ( v . concretetype ) instr_list = InstructionList ( instr_list [ : - ] ) instr_list . render ( generator , op ) class Function ( object ) : auto_propagate_exceptions = False def __init__ ( self , db , graph , name = None , is_method = False , is_entrypoint = False ) : self . db = db self . cts = db . genoo . TypeSystem ( db ) self . graph = graph self . name = self . cts . escape_name ( name or graph . name ) self . is_method = is_method self . is_entrypoint = is_entrypoint self . generator = None self . label_counters = { } def current_label ( self , prefix = '' ) : current = self . label_counters . get ( prefix , ) return '' % ( prefix , current ) def next_label ( self , prefix = '' ) : current = self . label_counters . get ( prefix , ) self . label_counters [ prefix ] = current + return self . current_label ( prefix ) def get_name ( self ) : return self . name def __repr__ ( self ) : return '' % self . name def __hash__ ( self ) : return hash ( self . graph ) def __eq__ ( self , other ) : return self . graph == other . graph def __ne__ ( self , other ) : return not self == other def _is_return_block ( self , block ) : return ( not block . exits ) and len ( block . inputargs ) == def _is_raise_block ( self , block ) : return ( not block . exits ) and len ( block . inputargs ) == def _is_exc_handling_block ( self , block ) : return block . exitswitch == flowmodel . c_last_exception def begin_render ( self ) : raise NotImplementedError def render_return_block ( self , block ) : raise NotImplementedError def render_raise_block ( self , block ) : raise NotImplementedError def begin_try ( self ) : \"\"\"\"\"\" raise NotImplementedError def end_try ( self , target_label ) : \"\"\"\"\"\" raise NotImplementedError def begin_catch ( self , llexitcase ) : \"\"\"\"\"\" raise NotImplementedError def end_catch ( self , target_label ) : \"\"\"\"\"\" raise NotImplementedError def render ( self , ilasm ) : if self . db . graph_name ( self . graph ) is not None and not self . is_method : return self . ilasm = ilasm self . generator = self . _create_generator ( self . ilasm ) graph = self . graph self . begin_render ( ) self . return_block = None self . raise_block = None for block in graph . iterblocks ( ) : if self . _is_return_block ( block ) : self . return_block = block elif self . _is_raise_block ( block ) : self . raise_block = block else : self . set_label ( self . _get_block_name ( block ) ) if self . _is_exc_handling_block ( block ) : self . render_exc_handling_block ( block ) else : self . render_normal_block ( block ) self . before_last_blocks ( ) if self . raise_block : self . set_label ( self . _get_block_name ( self . raise_block ) ) self . render_raise_block ( self . raise_block ) if self . return_block : self . set_label ( self . _get_block_name ( self . return_block ) ) self . render_return_block ( self . return_block ) self . end_render ( ) if not self . is_method : self . db . record_function ( self . graph , self . name ) def before_last_blocks ( self ) : pass def render_exc_handling_block ( self , block ) : for op in block . operations [ : - ] : self . _render_op ( op ) anyHandler = False for link in block . exits : if link . exitcase is None : continue anyHandler = anyHandler or not self . _auto_propagate ( link , block ) if block . operations : self . begin_try ( anyHandler ) ", "answer": "self . _render_op ( block . operations [ - ] )"}, {"prompt": " from __future__ import unicode_literals from . common import InfoExtractor from . . utils import ( HEADRequest , ", "answer": "get_element_by_attribute ,"}, {"prompt": " import sys import os sys . path . insert ( , os . path . abspath ( '' ) ) extensions = [ '' , '' , '' , '' , '' , '' , ] templates_path = [ '' ] source_suffix = '' master_doc = '' project = u'' copyright = u'' version = '' release = version ", "answer": "exclude_patterns = [ ]"}, {"prompt": " from __future__ import absolute_import import collections import itertools import json import logging from django . conf import settings import glanceclient as glance_client from six . moves import _thread as thread from horizon . utils import functions as utils from horizon . utils . memoized import memoized from openstack_dashboard . api import base LOG = logging . getLogger ( __name__ ) VERSIONS = base . APIVersionManager ( \"\" , preferred_version = ) @ memoized def glanceclient ( request , version = '' ) : url = base . url_for ( request , '' ) insecure = getattr ( settings , '' , False ) cacert = getattr ( settings , '' , None ) return glance_client . Client ( version , url , token = request . user . token . id , insecure = insecure , cacert = cacert ) def image_delete ( request , image_id ) : return glanceclient ( request ) . images . delete ( image_id ) def image_get ( request , image_id ) : \"\"\"\"\"\" image = glanceclient ( request ) . images . get ( image_id ) if not hasattr ( image , '' ) : image . name = None return image def image_list_detailed ( request , marker = None , sort_dir = '' , sort_key = '' , filters = None , paginate = False ) : limit = getattr ( settings , '' , ) page_size = utils . get_page_size ( request ) if paginate : request_size = page_size + else : request_size = limit kwargs = { '' : filters or { } } if marker : kwargs [ '' ] = marker kwargs [ '' ] = sort_dir kwargs [ '' ] = sort_key images_iter = glanceclient ( request ) . images . list ( page_size = request_size , limit = limit , ** kwargs ) has_prev_data = False has_more_data = False if paginate : images = list ( itertools . islice ( images_iter , request_size ) ) if len ( images ) > page_size : images . pop ( - ) has_more_data = True if marker is not None : has_prev_data = True elif sort_dir == '' and marker is not None : has_more_data = True elif marker is not None : has_prev_data = True else : images = list ( images_iter ) return ( images , has_more_data , has_prev_data ) def image_update ( request , image_id , ** kwargs ) : return glanceclient ( request ) . images . update ( image_id , ** kwargs ) def image_create ( request , ** kwargs ) : copy_from = kwargs . pop ( '' , None ) data = kwargs . pop ( '' , None ) image = glanceclient ( request ) . images . create ( ** kwargs ) if data : thread . start_new_thread ( image_update , ( request , image . id ) , { '' : data , '' : False } ) elif copy_from : thread . start_new_thread ( image_update , ( request , image . id ) , { '' : copy_from , '' : False } ) return image def image_update_properties ( request , image_id , remove_props = None , ** kwargs ) : \"\"\"\"\"\" return glanceclient ( request , '' ) . images . update ( image_id , remove_props , ** kwargs ) def image_delete_properties ( request , image_id , keys ) : \"\"\"\"\"\" return glanceclient ( request , '' ) . images . update ( image_id , keys ) class BaseGlanceMetadefAPIResourceWrapper ( base . APIResourceWrapper ) : @ property def description ( self ) : return ( getattr ( self . _apiresource , '' , None ) or getattr ( self . _apiresource , '' , None ) ) def as_json ( self , indent = ) : result = collections . OrderedDict ( ) for attr in self . _attrs : if hasattr ( self , attr ) : result [ attr ] = getattr ( self , attr ) return json . dumps ( result , indent = indent ) class Namespace ( BaseGlanceMetadefAPIResourceWrapper ) : _attrs = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ] @ property def resource_type_names ( self ) : result = [ resource_type [ '' ] for resource_type in getattr ( self . _apiresource , '' ) ] return sorted ( result ) @ property def public ( self ) : if getattr ( self . _apiresource , '' ) == '' : return True else : return False def metadefs_namespace_get ( request , namespace , resource_type = None , wrap = False ) : namespace = glanceclient ( request , '' ) . metadefs_namespace . get ( namespace , resource_type = resource_type ) if wrap : return Namespace ( namespace ) else : return namespace def metadefs_namespace_list ( request , filters = { } , ", "answer": "sort_dir = '' ,"}, {"prompt": " from __future__ import unicode_literals import re from django . template import ( Node , Variable , TemplateSyntaxError , TokenParser , Library , TOKEN_TEXT , TOKEN_VAR ) from django . template . base import _render_value_in_context from django . template . defaulttags import token_kwargs from django . utils import six from django . utils import translation register = Library ( ) class GetAvailableLanguagesNode ( Node ) : def __init__ ( self , variable ) : self . variable = variable def render ( self , context ) : from django . conf import settings context [ self . variable ] = [ ( k , translation . ugettext ( v ) ) for k , v in settings . LANGUAGES ] return '' class GetLanguageInfoNode ( Node ) : def __init__ ( self , lang_code , variable ) : self . lang_code = Variable ( lang_code ) self . variable = variable def render ( self , context ) : lang_code = self . lang_code . resolve ( context ) context [ self . variable ] = translation . get_language_info ( lang_code ) return '' class GetLanguageInfoListNode ( Node ) : def __init__ ( self , languages , variable ) : self . languages = Variable ( languages ) self . variable = variable def get_language_info ( self , language ) : if len ( language [ ] ) > : return translation . get_language_info ( language [ ] ) else : return translation . get_language_info ( str ( language ) ) def render ( self , context ) : langs = self . languages . resolve ( context ) context [ self . variable ] = [ self . get_language_info ( lang ) for lang in langs ] return '' class GetCurrentLanguageNode ( Node ) : def __init__ ( self , variable ) : self . variable = variable def render ( self , context ) : context [ self . variable ] = translation . get_language ( ) return '' class GetCurrentLanguageBidiNode ( Node ) : def __init__ ( self , variable ) : self . variable = variable def render ( self , context ) : context [ self . variable ] = translation . get_language_bidi ( ) return '' class TranslateNode ( Node ) : def __init__ ( self , filter_expression , noop , asvar = None , message_context = None ) : self . noop = noop self . asvar = asvar self . message_context = message_context self . filter_expression = filter_expression if isinstance ( self . filter_expression . var , six . string_types ) : self . filter_expression . var = Variable ( \"\" % self . filter_expression . var ) def render ( self , context ) : self . filter_expression . var . translate = not self . noop if self . message_context : self . filter_expression . var . message_context = ( self . message_context . resolve ( context ) ) output = self . filter_expression . resolve ( context ) value = _render_value_in_context ( output , context ) if self . asvar : context [ self . asvar ] = value return '' else : return value class BlockTranslateNode ( Node ) : def __init__ ( self , extra_context , singular , plural = None , countervar = None , counter = None , message_context = None ) : self . extra_context = extra_context self . singular = singular self . plural = plural self . countervar = countervar self . counter = counter self . message_context = message_context def render_token_list ( self , tokens ) : result = [ ] vars = [ ] for token in tokens : if token . token_type == TOKEN_TEXT : result . append ( token . contents . replace ( '' , '' ) ) elif token . token_type == TOKEN_VAR : result . append ( '' % token . contents ) vars . append ( token . contents ) return '' . join ( result ) , vars def render ( self , context , nested = False ) : if self . message_context : message_context = self . message_context . resolve ( context ) else : message_context = None tmp_context = { } for var , val in self . extra_context . items ( ) : tmp_context [ var ] = val . resolve ( context ) context . update ( tmp_context ) singular , vars = self . render_token_list ( self . singular ) if self . plural and self . countervar and self . counter : count = self . counter . resolve ( context ) context [ self . countervar ] = count plural , plural_vars = self . render_token_list ( self . plural ) if message_context : result = translation . npgettext ( message_context , singular , plural , count ) else : result = translation . ungettext ( singular , plural , count ) vars . extend ( plural_vars ) else : if message_context : result = translation . pgettext ( message_context , singular ) else : result = translation . ugettext ( singular ) data = dict ( [ ( v , _render_value_in_context ( context . get ( v , '' ) , context ) ) for v in vars ] ) context . pop ( ) try : result = result % data except ( KeyError , ValueError ) : if nested : raise TemplateSyntaxError ( \"\" \"\" % ( result , data ) ) with translation . override ( None ) : result = self . render ( context , nested = True ) return result class LanguageNode ( Node ) : def __init__ ( self , nodelist , language ) : self . nodelist = nodelist self . language = language def render ( self , context ) : with translation . override ( self . language . resolve ( context ) ) : output = self . nodelist . render ( context ) return output @ register . tag ( \"\" ) def do_get_available_languages ( parser , token ) : \"\"\"\"\"\" args = token . contents . split ( ) if len ( args ) != or args [ ] != '' : raise TemplateSyntaxError ( \"\" % args ) return GetAvailableLanguagesNode ( args [ ] ) @ register . tag ( \"\" ) def do_get_language_info ( parser , token ) : \"\"\"\"\"\" args = token . contents . split ( ) if len ( args ) != or args [ ] != '' or args [ ] != '' : raise TemplateSyntaxError ( \"\" % ( args [ ] , args [ : ] ) ) return GetLanguageInfoNode ( args [ ] , args [ ] ) @ register . tag ( \"\" ) def do_get_language_info_list ( parser , token ) : \"\"\"\"\"\" args = token . contents . split ( ) if len ( args ) != or args [ ] != '' or args [ ] != '' : raise TemplateSyntaxError ( \"\" % ( args [ ] , args [ : ] ) ) return GetLanguageInfoListNode ( args [ ] , args [ ] ) @ register . filter def language_name ( lang_code ) : return translation . get_language_info ( lang_code ) [ '' ] @ register . filter def language_name_local ( lang_code ) : return translation . get_language_info ( lang_code ) [ '' ] @ register . filter def language_bidi ( lang_code ) : return translation . get_language_info ( lang_code ) [ '' ] @ register . tag ( \"\" ) def do_get_current_language ( parser , token ) : \"\"\"\"\"\" args = token . contents . split ( ) if len ( args ) != or args [ ] != '' : raise TemplateSyntaxError ( \"\" % args ) return GetCurrentLanguageNode ( args [ ] ) @ register . tag ( \"\" ) def do_get_current_language_bidi ( parser , token ) : \"\"\"\"\"\" args = token . contents . split ( ) if len ( args ) != or args [ ] != '' : raise TemplateSyntaxError ( \"\" % args ) return GetCurrentLanguageBidiNode ( args [ ] ) @ register . tag ( \"\" ) def do_translate ( parser , token ) : \"\"\"\"\"\" class TranslateParser ( TokenParser ) : def top ( self ) : value = self . value ( ) if value [ ] == \"\" : m = re . match ( \"\" , value ) if m : value = '' % ( m . group ( ) . replace ( '' , '' ) , m . group ( ) ) elif value [ - ] == \"\" : value = '' % value [ : - ] . replace ( '' , '' ) noop = False asvar = None message_context = None while self . more ( ) : tag = self . tag ( ) if tag == '' : noop = True elif tag == '' : message_context = parser . compile_filter ( self . value ( ) ) elif tag == '' : asvar = self . tag ( ) else : raise TemplateSyntaxError ( \"\" \"\" ) return value , noop , asvar , message_context value , noop , asvar , message_context = TranslateParser ( token . contents ) . top ( ) return TranslateNode ( parser . compile_filter ( value ) , noop , asvar , message_context ) @ register . tag ( \"\" ) def do_block_translate ( parser , token ) : \"\"\"\"\"\" bits = token . split_contents ( ) options = { } remaining_bits = bits [ : ] while remaining_bits : option = remaining_bits . pop ( ) if option in options : raise TemplateSyntaxError ( '' '' % option ) ", "answer": "if option == '' :"}, {"prompt": " import py , sys from pypy . conftest import gettestobjspace from pypy . module . thread . test . support import GenericTestThread class AppTestFork ( GenericTestThread ) : def test_fork ( self ) : import thread import os import time if not hasattr ( os , '' ) : skip ( \"\" ) run = True ", "answer": "done = [ ]"}, {"prompt": " import gzip import os import struct import h5py import numpy from fuel . converters . base import fill_hdf5_file , check_exists MNIST_IMAGE_MAGIC = MNIST_LABEL_MAGIC = TRAIN_IMAGES = '' TRAIN_LABELS = '' TEST_IMAGES = '' TEST_LABELS = '' ALL_FILES = [ TRAIN_IMAGES , TRAIN_LABELS , TEST_IMAGES , TEST_LABELS ] @ check_exists ( required_files = ALL_FILES ) def convert_mnist ( directory , output_directory , output_filename = None , dtype = None ) : \"\"\"\"\"\" if not output_filename : if dtype : output_filename = '' . format ( dtype ) else : output_filename = '' output_path = os . path . join ( output_directory , output_filename ) h5file = h5py . File ( output_path , mode = '' ) train_feat_path = os . path . join ( directory , TRAIN_IMAGES ) train_features = read_mnist_images ( train_feat_path , dtype ) train_lab_path = os . path . join ( directory , TRAIN_LABELS ) train_labels = read_mnist_labels ( train_lab_path ) test_feat_path = os . path . join ( directory , TEST_IMAGES ) test_features = read_mnist_images ( test_feat_path , dtype ) test_lab_path = os . path . join ( directory , TEST_LABELS ) test_labels = read_mnist_labels ( test_lab_path ) data = ( ( '' , '' , train_features ) , ( '' , '' , train_labels ) , ( '' , '' , test_features ) , ( '' , '' , test_labels ) ) fill_hdf5_file ( h5file , data ) ", "answer": "h5file [ '' ] . dims [ ] . label = ''"}, {"prompt": " from collections import deque import re import time import logging from twisted . python import log from txstatsd . metrics . metermetric import MeterMetricReporter SPACES = re . compile ( \"\" ) SLASHES = re . compile ( \"\" ) NON_ALNUM = re . compile ( \"\" ) RATE = re . compile ( \"\" ) def normalize_key ( key ) : \"\"\"\"\"\" key = SPACES . sub ( \"\" , key ) key = SLASHES . sub ( \"\" , key ) key = NON_ALNUM . sub ( \"\" , key ) return key class BaseMessageProcessor ( object ) : def process ( self , message ) : \"\"\"\"\"\" if not \"\" in message : return self . fail ( message ) key , data = message . strip ( ) . split ( \"\" , ) if not \"\" in data : return self . fail ( message ) fields = data . split ( \"\" ) if len ( fields ) < or len ( fields ) > : return self . fail ( message ) key = normalize_key ( key ) metric_type = fields [ ] return self . process_message ( message , metric_type , key , fields ) def rebuild_message ( self , metric_type , key , fields ) : return key + \"\" + \"\" . join ( fields ) def fail ( self , message ) : \"\"\"\"\"\" log . msg ( \"\" % message , logLevel = logging . DEBUG ) class MessageProcessor ( BaseMessageProcessor ) : \"\"\"\"\"\" def __init__ ( self , time_function = time . time , plugins = None ) : self . time_function = time_function self . stats_prefix = \"\" self . internal_metrics_prefix = \"\" self . count_prefix = \"\" self . timer_prefix = self . stats_prefix + \"\" self . gauge_prefix = self . stats_prefix + \"\" self . process_timings = { } self . by_type = { } self . last_flush_duration = self . last_process_duration = self . timer_metrics = { } self . counter_metrics = { } self . gauge_metrics = deque ( ) self . meter_metrics = { } self . plugins = { } self . plugin_metrics = { } if plugins is not None : for plugin in plugins : self . plugins [ plugin . metric_type ] = plugin def get_metric_names ( self ) : \"\"\"\"\"\" metrics = set ( ) metrics . update ( self . timer_metrics . keys ( ) ) metrics . update ( self . counter_metrics . keys ( ) ) metrics . update ( v for k , v in self . gauge_metrics ) metrics . update ( self . meter_metrics . keys ( ) ) metrics . update ( self . plugin_metrics . keys ( ) ) return list ( metrics ) def process_message ( self , message , metric_type , key , fields ) : \"\"\"\"\"\" start = self . time_function ( ) if metric_type == \"\" : self . process_counter_metric ( key , fields , message ) elif metric_type == \"\" : self . process_timer_metric ( key , fields [ ] , message ) elif metric_type == \"\" : self . process_gauge_metric ( key , fields [ ] , message ) elif metric_type == \"\" : self . process_meter_metric ( key , fields [ ] , message ) elif metric_type in self . plugins : self . process_plugin_metric ( metric_type , key , fields , message ) else : return self . fail ( message ) self . process_timings . setdefault ( metric_type , ) self . process_timings [ metric_type ] += self . time_function ( ) - start self . by_type . setdefault ( metric_type , ) self . by_type [ metric_type ] += def get_message_prefix ( self , kind ) : return \"\" + kind def process_plugin_metric ( self , metric_type , key , items , message ) : if not key in self . plugin_metrics : factory = self . plugins [ metric_type ] metric = factory . build_metric ( self . get_message_prefix ( factory . name ) , name = key , wall_time_func = self . time_function ) self . plugin_metrics [ key ] = metric self . plugin_metrics [ key ] . process ( items ) def process_timer_metric ( self , key , duration , message ) : try : duration = float ( duration ) except ( TypeError , ValueError ) : return self . fail ( message ) self . compose_timer_metric ( key , duration ) def compose_timer_metric ( self , key , duration ) : if key not in self . timer_metrics : self . timer_metrics [ key ] = [ ] self . timer_metrics [ key ] . append ( duration ) def process_counter_metric ( self , key , composite , message ) : try : value = float ( composite [ ] ) except ( TypeError , ValueError ) : return self . fail ( message ) rate = if len ( composite ) == : match = RATE . match ( composite [ ] ) if match is None : return self . fail ( message ) rate = match . group ( ) self . compose_counter_metric ( key , value , rate ) def compose_counter_metric ( self , key , value , rate ) : if key not in self . counter_metrics : self . counter_metrics [ key ] = self . counter_metrics [ key ] += value * ( / float ( rate ) ) def process_gauge_metric ( self , key , composite , message ) : values = composite . split ( \"\" ) if not len ( values ) == : return self . fail ( message ) try : value = float ( values [ ] ) except ( TypeError , ValueError ) : self . fail ( message ) self . compose_gauge_metric ( key , value ) def compose_gauge_metric ( self , key , value ) : metric = [ value , key ] self . gauge_metrics . append ( metric ) def process_meter_metric ( self , key , composite , message ) : values = composite . split ( \"\" ) if not len ( values ) == : return self . fail ( message ) try : value = float ( values [ ] ) except ( TypeError , ValueError ) : self . fail ( message ) self . compose_meter_metric ( key , value ) def compose_meter_metric ( self , key , value ) : if not key in self . meter_metrics : metric = MeterMetricReporter ( key , self . time_function , prefix = \"\" ) self . meter_metrics [ key ] = metric self . meter_metrics [ key ] . mark ( value ) def flush ( self , interval = , percent = ) : \"\"\"\"\"\" per_metric = { } num_stats = interval = interval / timestamp = int ( self . time_function ( ) ) start = self . time_function ( ) events = for metrics in self . flush_counter_metrics ( interval , timestamp ) : for metric in metrics : yield metric events += duration = self . time_function ( ) - start num_stats += events per_metric [ \"\" ] = ( events , duration ) start = self . time_function ( ) events = for metrics in self . flush_timer_metrics ( percent , timestamp ) : for metric in metrics : yield metric events += duration = self . time_function ( ) - start num_stats += events per_metric [ \"\" ] = ( events , duration ) start = self . time_function ( ) events = for metrics in self . flush_gauge_metrics ( timestamp ) : for metric in metrics : yield metric events += duration = self . time_function ( ) - start num_stats += events per_metric [ \"\" ] = ( events , duration ) start = self . time_function ( ) events = for metrics in self . flush_meter_metrics ( timestamp ) : for metric in metrics : yield metric events += duration = self . time_function ( ) - start num_stats += events per_metric [ \"\" ] = ( events , duration ) start = self . time_function ( ) events = for metrics in self . flush_plugin_metrics ( interval , timestamp ) : for metric in metrics : yield metric events += duration = self . time_function ( ) - start num_stats += events per_metric [ \"\" ] = ( events , duration ) for metrics in self . flush_metrics_summary ( num_stats , per_metric , timestamp ) : for metric in metrics : yield metric def flush_counter_metrics ( self , interval , timestamp ) : for key , count in self . counter_metrics . iteritems ( ) : self . counter_metrics [ key ] = value = count / interval ", "answer": "yield ( ( self . stats_prefix + key , value , timestamp ) ,"}, {"prompt": " import logging from synapse . storage . prepare_database import get_statements import ujson logger = logging . getLogger ( __name__ ) ALTER_TABLE = ( \"\" \"\" ) def run_upgrade ( cur , database_engine , * args , ** kwargs ) : for statement in get_statements ( ALTER_TABLE . splitlines ( ) ) : ", "answer": "cur . execute ( statement )"}, {"prompt": " import environment_vim as environment import eiffel_ide import string def get_class_from_buffer ( a_project ) : \"\"\"\"\"\" if environment . evaluate ( \"\" ) == environment . get_global_variable ( \"\" ) : try : l_class = environment . get_buffer_variable ( \"\" ) except : l_class = \"\" else : l_buffer_text = environment . buffer_to_text ( ) l_class = a_project . class_name_from_text ( l_buffer_text ) return l_class def set_class_and_info ( a_info_name , a_class_name ) : \"\"\"\"\"\" environment . set_buffer_variable ( \"\" , a_info_name ) environment . set_buffer_variable ( \"\" , a_class_name ) def unset_class_and_info ( ) : \"\"\"\"\"\" environment . set_buffer_variable ( \"\" , None ) environment . set_buffer_variable ( \"\" , None ) def class_execute ( a_project , a_name , a_routine , a_class_name = None ) : \"\"\"\"\"\" if a_class_name : l_class = a_class_name if l_class == \"\" : l_class = get_class_from_buffer ( a_project ) else : l_class = environment . word_under_the_cursor ( ) if not l_class : l_class = get_class_from_buffer ( a_project ) if l_class : eiffel_ide . launch_process ( a_project , lambda window : a_routine ( l_class , window ) , \"\" + a_name . lower ( ) + \"\" + l_class , a_name + \"\" + l_class , False , True , lambda : set_class_and_info ( a_name , l_class ) ) environment . execute ( \"\" ) def flat ( a_project , * arguments ) : \"\"\"\"\"\" l_class_name = None if arguments : l_class_name = arguments [ ] class_execute ( a_project , \"\" , lambda a_class , a_buffer : a_project . fetch_class_flat ( a_class , a_buffer ) , l_class_name ) environment . eiffel_fold ( ) def ancestors ( a_project , * arguments ) : \"\"\"\"\"\" l_class_name = None if arguments : l_class_name = arguments [ ] class_execute ( a_project , \"\" , lambda a_class , a_buffer : a_project . fetch_class_ancestors ( a_class , a_buffer ) , l_class_name ) def attributes ( a_project , * arguments ) : \"\"\"\"\"\" l_class_name = None if arguments : l_class_name = arguments [ ] class_execute ( a_project , \"\" , lambda a_class , a_buffer : a_project . fetch_class_attributes ( a_class , a_buffer ) , l_class_name ) def clients ( a_project , * arguments ) : \"\"\"\"\"\" l_class_name = None if arguments : l_class_name = arguments [ ] class_execute ( a_project , \"\" , lambda a_class , a_buffer : a_project . fetch_class_clients ( a_class , a_buffer ) , l_class_name ) def deferred ( a_project , * arguments ) : \"\"\"\"\"\" l_class_name = None if arguments : l_class_name = arguments [ ] class_execute ( a_project , \"\" , lambda a_class , a_buffer : a_project . fetch_class_deferred ( a_class , a_buffer ) , l_class_name ) def descendants ( a_project , * arguments ) : \"\"\"\"\"\" l_class_name = None if arguments : l_class_name = arguments [ ] class_execute ( a_project , \"\" , lambda a_class , a_buffer : a_project . fetch_class_descendants ( a_class , a_buffer ) , l_class_name ) def exported ( a_project , * arguments ) : \"\"\"\"\"\" l_class_name = None if arguments : l_class_name = arguments [ ] class_execute ( a_project , \"\" , lambda a_class , a_buffer : a_project . fetch_class_exported ( a_class , a_buffer ) , l_class_name ) def externals ( a_project , * arguments ) : \"\"\"\"\"\" l_class_name = None if arguments : l_class_name = arguments [ ] class_execute ( a_project , \"\" , lambda a_class , a_buffer : a_project . fetch_class_externals ( a_class , a_buffer ) , l_class_name ) def flatshort ( a_project , * arguments ) : \"\"\"\"\"\" l_class_name = None if arguments : l_class_name = arguments [ ] class_execute ( a_project , \"\" , lambda a_class , a_buffer : a_project . fetch_class_flatshort ( a_class , a_buffer ) , l_class_name ) environment . eiffel_fold ( ) def once ( a_project , * arguments ) : \"\"\"\"\"\" l_class_name = None if arguments : l_class_name = arguments [ ] class_execute ( a_project , \"\" , lambda a_class , a_buffer : a_project . fetch_class_once ( a_class , a_buffer ) , l_class_name ) def invariants ( a_project , * arguments ) : \"\"\"\"\"\" l_class_name = None if arguments : l_class_name = arguments [ ] class_execute ( a_project , \"\" , lambda a_class , a_buffer : a_project . fetch_class_invariants ( a_class , a_buffer ) , l_class_name ) def routines ( a_project , * arguments ) : \"\"\"\"\"\" l_class_name = None if arguments : l_class_name = arguments [ ] class_execute ( a_project , \"\" , lambda a_class , a_buffer : a_project . fetch_class_routines ( a_class , a_buffer ) , l_class_name ) def creators ( a_project , * arguments ) : \"\"\"\"\"\" l_class_name = None if arguments : l_class_name = arguments [ ] class_execute ( a_project , \"\" , lambda a_class , a_buffer : a_project . fetch_class_creators ( a_class , a_buffer ) , l_class_name ) def short ( a_project , * arguments ) : \"\"\"\"\"\" l_class_name = None if arguments : l_class_name = arguments [ ] class_execute ( a_project , \"\" , lambda a_class , a_buffer : a_project . fetch_class_short ( a_class , a_buffer ) , l_class_name ) environment . eiffel_fold ( ) def suppliers ( a_project , * arguments ) : \"\"\"\"\"\" l_class_name = None if arguments : l_class_name = arguments [ ] class_execute ( a_project , \"\" , lambda a_class , a_buffer : a_project . fetch_class_suppliers ( a_class , a_buffer ) , l_class_name ) def text ( a_project , * arguments ) : \"\"\"\"\"\" l_class_name = None if arguments : l_class_name = arguments [ ] class_execute ( a_project , \"\" , lambda a_class , a_buffer : a_project . fetch_class_text ( a_class , a_buffer ) , l_class_name ) environment . eiffel_fold ( ) def _edit_command_and_flag ( is_split , is_vertical , is_tab , force_edit ) : \"\"\"\"\"\" flags = \"\" if is_split : command = \"\" if is_vertical : flags = \"\" elif is_tab : command = \"\" else : command = \"\" if force_edit : command = command + \"\" return ( command , flags ) def edit ( a_project , is_split = False , is_vertical = False , is_tab = False , force_edit = False , * argument ) : \"\"\"\"\"\" has_error = False if argument : class_name = argument [ ] else : class_name = environment . word_under_the_cursor ( ) if class_name : class_path = a_project . file_path_from_class_name ( class_name ) else : class_path = None if class_path : ( command , flags ) = _edit_command_and_flag ( is_split , is_vertical , is_tab , force_edit ) if not is_split and not is_tab and not force_edit : if int ( environment . get_option ( \"\" ) ) : print ( \"\" ) has_error = True if not has_error : environment . execute ( flags + \"\" + command + \"\" + class_path ) ", "answer": "def complete_start ( ) :"}, {"prompt": " from __future__ import unicode_literals from django . db import migrations , models class Migration ( migrations . Migration ) : dependencies = [ ( '' , '' ) , ] operations = [ migrations . AlterField ( model_name = '' , name = '' , field = models . CharField ( max_length = , blank = True ) , ) , ", "answer": "migrations . AlterField ("}, {"prompt": " from east import utils def worst_case_strings_collection ( m , n ) : prefix = utils . random_string ( n - ) ", "answer": "strings_collection = [ prefix + utils . random_string ( ) for _ in xrange ( m ) ]"}, {"prompt": " from larch import Interpreter from larch_plugins . xafs import pre_edge , autobk from larch_plugins . io import read_ascii ", "answer": "_larch = Interpreter ( with_plugins = False )"}, {"prompt": " \"\"\"\"\"\" import os import sys from glob import glob import matplotlib ", "answer": "import matplotlib . pyplot as plt"}, {"prompt": " import sys from neutronclient . neutron . v2_0 import servicetype from neutronclient . tests . unit import test_cli20 class CLITestV20ServiceProvidersJSON ( test_cli20 . CLITestV20Base ) : id_field = \"\" def setUp ( self ) : super ( CLITestV20ServiceProvidersJSON , self ) . setUp ( plurals = { '' : '' } ) def test_list_service_providers ( self ) : resources = \"\" cmd = servicetype . ListServiceProvider ( test_cli20 . MyApp ( sys . stdout ) , None ) ", "answer": "self . _test_list_resources ( resources , cmd , True )"}, {"prompt": " '''''' import unittest class Test ( unittest . TestCase ) : def setUp ( self ) : pass ", "answer": "def tearDown ( self ) :"}, {"prompt": " from django . contrib import admin from django . utils . safestring import mark_safe from models import SourceImage , CropSize , CroppedImage admin . site . register ( SourceImage ) admin . site . register ( CropSize ) class CroppedImageAdmin ( admin . ModelAdmin ) : change_form_template = '' def get_form ( self , request , obj = None , ** kwargs ) : if obj is None : fields = ( '' , '' ) else : fields = ( '' , '' , '' , '' , '' , '' ) kwargs [ '' ] = fields return super ( CroppedImageAdmin , self ) . get_form ( request , obj , ** kwargs ) def preview_thumb ( self , obj ) : if obj . image : return mark_safe ( ", "answer": "u'' % obj . image . url"}, {"prompt": " import logging from math import floor import time from csvkit import CSVKitReader from django . conf import settings from django . utils . translation import ugettext from livesettings import config_value from panda import solr , utils from panda . exceptions import DataImportError from panda . tasks . import_file import ImportFileTask from panda . utils . typecoercion import DataTyper SOLR_ADD_BUFFER_SIZE = class ImportCSVTask ( ImportFileTask ) : \"\"\"\"\"\" name = '' def _count_lines ( self , filename ) : \"\"\"\"\"\" with open ( filename ) as f : for i , l in enumerate ( f ) : pass return i + def run ( self , dataset_slug , upload_id , external_id_field_index = None , * args , ** kwargs ) : \"\"\"\"\"\" from panda . models import Dataset , DataUpload log = logging . getLogger ( self . name ) log . info ( '' % dataset_slug ) try : dataset = Dataset . objects . get ( slug = dataset_slug ) except Dataset . DoesNotExist : log . warning ( '' % dataset_slug ) return upload = DataUpload . objects . get ( id = upload_id ) task_status = dataset . current_task task_status . begin ( ugettext ( '' ) ) line_count = self . _count_lines ( upload . get_path ( ) ) if self . is_aborted ( ) : task_status . abort ( '' ) log . warning ( '' % dataset_slug ) return f = open ( upload . get_path ( ) , '' ) reader = CSVKitReader ( f , encoding = upload . encoding , ** upload . dialect_as_parameters ( ) ) reader . next ( ) add_buffer = [ ] data_typer = DataTyper ( dataset . column_schema ) throttle = config_value ( '' , '' ) i = while True : i += try : row = reader . next ( ) except StopIteration : i -= break except UnicodeDecodeError : raise DataImportError ( ugettext ( '' ) % { '' : upload . encoding , '' : i } ) external_id = None if external_id_field_index is not None : external_id = row [ external_id_field_index ] data = utils . solr . make_data_row ( dataset , row , data_upload = upload , external_id = external_id ) data = data_typer ( data , row ) add_buffer . append ( data ) if i % SOLR_ADD_BUFFER_SIZE == : solr . add ( settings . SOLR_DATA_CORE , add_buffer ) add_buffer = [ ] task_status . update ( ugettext ( '' ) % floor ( float ( i ) / float ( line_count ) * ) ) if self . is_aborted ( ) : task_status . abort ( ugettext ( '' ) % floor ( float ( i ) / float ( line_count ) * ) ) log . warning ( '' % dataset_slug ) return time . sleep ( throttle ) if add_buffer : solr . add ( settings . SOLR_DATA_CORE , add_buffer ) add_buffer = [ ] solr . commit ( settings . SOLR_DATA_CORE ) f . close ( ) task_status . update ( '' ) try : dataset = Dataset . objects . get ( slug = dataset_slug ) except Dataset . DoesNotExist : log . warning ( '' % dataset_slug ) return if not dataset . row_count : dataset . row_count = i else : dataset . row_count += i dataset . column_schema = data_typer . schema dataset . save ( ) upload = DataUpload . objects . get ( id = upload_id ) upload . imported = True upload . save ( ) log . info ( '' % dataset_slug ) ", "answer": "return data_typer "}, {"prompt": " \"\"\"\"\"\" ", "answer": "def traversal ( graph , node , order ) :"}, {"prompt": " import location import gobject import sys import time import math if len ( sys . argv ) < : sys . stderr . write ( '' + sys . argv [ ] + '' ) sys . exit ( ) acc = prepend_text = sys . argv [ ] sleep_time = int ( sys . argv [ ] ) filename = sys . argv [ ] class gps_fix : fix = None def on_error ( self , control , error , data ) : print \"\" % error ", "answer": "data . quit ( )"}, {"prompt": " import sys import numpy from threshold_finder import Threshold_Finder class Average_Threshold_Finder ( object ) : def get_average_noise_threshold ( self , file_with_samples , no_of_samples ) : with open ( file_with_samples ) as f : samples = [ line [ : - ] for line in f ] noise_spectra = [ ] avg_noise_powers = [ ] for i in range ( , int ( no_of_samples ) , ) : chord = samples [ i ] first = samples [ i + ] second = samples [ i + ] third = samples [ i + ] t_finder = Threshold_Finder ( chord , first , second , third ) coefficients , residual , average_noise_power = t_finder . find_least_squares ( ) noise = residual ** noise_spectra . append ( noise ) avg_noise_powers . append ( average_noise_power ) average_noise = numpy . mean ( noise_spectra ) sd_noise = numpy . std ( noise_spectra ) ", "answer": "avg_power = numpy . mean ( avg_noise_powers )"}, {"prompt": " import json from nativeconfig . exceptions import DeserializationError , ValidationError , InitializationError from nativeconfig . options . base_option import BaseOption class ArrayOption ( BaseOption ) : \"\"\"\"\"\" def __init__ ( self , name , value_option = None , ** kwargs ) : \"\"\"\"\"\" super ( ) . __init__ ( name , setter = '' , getter = '' , ** kwargs ) if value_option : from nativeconfig . options . dict_option import DictOption if isinstance ( value_option , BaseOption ) and not isinstance ( value_option , ArrayOption ) and not isinstance ( value_option , DictOption ) : self . _value_option = value_option else : raise InitializationError ( \"\" ) else : self . _value_option = None def serialize ( self , value ) : if self . _value_option : serializable_list = [ ] for i in value : serializable_list . append ( self . _value_option . serialize ( i ) ) return serializable_list else : return value def deserialize ( self , raw_value ) : try : if self . _value_option : deserialized_list = [ ] for i in raw_value : deserialized_list . append ( self . _value_option . deserialize ( i ) ) value = deserialized_list else : value = raw_value except DeserializationError : raise DeserializationError ( \"\" . format ( raw_value , self . name ) , raw_value , self . name ) else : return value def serialize_json ( self , value ) : if value is None : return json . dumps ( None ) elif self . _value_option : return '' + '' . join ( [ self . _value_option . serialize_json ( v ) for v in value ] ) + '' else : return json . dumps ( value ) def deserialize_json ( self , json_value ) : try : value = json . loads ( json_value ) except ValueError : raise DeserializationError ( \"\" . format ( self . name , json_value ) , json_value , self . name ) else : if value is not None : if not isinstance ( value , list ) : raise DeserializationError ( \"\" . format ( json_value ) , json_value , self . name ) ", "answer": "else :"}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import from functools import partial from optparse import OptionGroup , SUPPRESS_HELP , Option import warnings from pip . index import ( FormatControl , fmt_ctl_handle_mutual_exclude , fmt_ctl_no_binary , fmt_ctl_no_use_wheel ) from pip . models import PyPI from pip . locations import USER_CACHE_DIR , src_prefix from pip . utils . hashes import STRONG_HASHES def make_option_group ( group , parser ) : \"\"\"\"\"\" option_group = OptionGroup ( parser , group [ '' ] ) for option in group [ '' ] : option_group . add_option ( option ( ) ) return option_group def resolve_wheel_no_use_binary ( options ) : if not options . use_wheel : control = options . format_control fmt_ctl_no_use_wheel ( control ) def check_install_build_global ( options , check_options = None ) : \"\"\"\"\"\" if check_options is None : check_options = options def getname ( n ) : return getattr ( check_options , n , None ) names = [ \"\" , \"\" , \"\" ] if any ( map ( getname , names ) ) : control = options . format_control fmt_ctl_no_binary ( control ) warnings . warn ( '' '' , stacklevel = ) help_ = partial ( Option , '' , '' , dest = '' , action = '' , help = '' ) isolated_mode = partial ( Option , \"\" , dest = \"\" , action = \"\" , default = False , help = ( \"\" \"\" ) , ) require_virtualenv = partial ( Option , '' , '' , dest = '' , action = '' , default = False , help = SUPPRESS_HELP ) verbose = partial ( Option , '' , '' , dest = '' , action = '' , default = , help = '' ) version = partial ( Option , '' , '' , dest = '' , action = '' , help = '' ) quiet = partial ( Option , '' , '' , dest = '' , action = '' , default = , help = '' ) log = partial ( Option , \"\" , \"\" , \"\" , dest = \"\" , metavar = \"\" , help = \"\" ) no_input = partial ( Option , '' , dest = '' , action = '' , default = False , help = SUPPRESS_HELP ) proxy = partial ( Option , '' , dest = '' , type = '' , default = '' , help = \"\" ) retries = partial ( Option , '' , dest = '' , type = '' , default = , help = \"\" \"\" ) timeout = partial ( Option , '' , '' , metavar = '' , dest = '' , type = '' , default = , help = '' ) default_vcs = partial ( Option , '' , dest = '' , type = '' , default = '' , help = SUPPRESS_HELP ) skip_requirements_regex = partial ( Option , '' , dest = '' , type = '' , default = '' , help = SUPPRESS_HELP ) def exists_action ( ) : return Option ( '' , dest = '' , type = '' , choices = [ '' , '' , '' , '' ] , default = [ ] , action = '' , metavar = '' , help = \"\" \"\" ) cert = partial ( Option , '' , dest = '' , type = '' , metavar = '' , help = \"\" ) client_cert = partial ( Option , '' , dest = '' , type = '' , default = None , metavar = '' , help = \"\" \"\" ) index_url = partial ( Option , '' , '' , '' , dest = '' , metavar = '' , default = PyPI . simple_url , help = '' ) def extra_index_url ( ) : return Option ( '' , dest = '' , metavar = '' , action = '' , default = [ ] , help = '' ) no_index = partial ( Option , '' , dest = '' , action = '' , default = False , help = '' ) def find_links ( ) : return Option ( '' , '' , dest = '' , action = '' , default = [ ] , metavar = '' , help = \"\" \"\" \"\" ) def allow_external ( ) : return Option ( \"\" , dest = \"\" , action = \"\" , default = [ ] , metavar = \"\" , help = SUPPRESS_HELP , ) allow_all_external = partial ( Option , \"\" , dest = \"\" , action = \"\" , default = False , help = SUPPRESS_HELP , ) def trusted_host ( ) : return Option ( \"\" , dest = \"\" , action = \"\" , metavar = \"\" , default = [ ] , help = \"\" \"\" , ) no_allow_external = partial ( Option , ", "answer": "\"\" ,"}, {"prompt": " import json as jsonutils from requests . adapters import HTTPAdapter from requests . cookies import MockRequest , MockResponse from requests . cookies import RequestsCookieJar from requests . cookies import merge_cookies , cookiejar_from_dict from requests . packages . urllib3 . response import HTTPResponse import six from requests_mock import compat from requests_mock import exceptions _BODY_ARGS = frozenset ( [ '' , '' , '' , '' , '' ] ) _HTTP_ARGS = frozenset ( [ '' , '' , '' , '' ] ) _DEFAULT_STATUS = _http_adapter = HTTPAdapter ( ) class CookieJar ( RequestsCookieJar ) : def set ( self , name , value , ** kwargs ) : \"\"\"\"\"\" return super ( CookieJar , self ) . set ( name , value , ** kwargs ) def _check_body_arguments ( ** kwargs ) : provided = [ x for x in _BODY_ARGS if kwargs . pop ( x , None ) is not None ] if len ( provided ) > : raise RuntimeError ( '' '' % '' . join ( provided ) ) extra = [ x for x in kwargs if x not in _HTTP_ARGS ] if extra : raise TypeError ( '' '' % '' . join ( extra ) ) class _FakeConnection ( object ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " \"\"\"\"\"\" import re from django . http import Http404 from django . core . exceptions import ImproperlyConfigured , ViewDoesNotExist from django . utils . datastructures import MultiValueDict from django . utils . encoding import iri_to_uri , force_unicode , smart_str from django . utils . functional import memoize from django . utils . importlib import import_module from django . utils . regex_helper import normalize from django . utils . thread_support import currentThread try : reversed except NameError : from django . utils . itercompat import reversed from sets import Set as set _resolver_cache = { } _callable_cache = { } _prefixes = { } class Resolver404 ( Http404 ) : pass class NoReverseMatch ( Exception ) : silent_variable_failure = True def get_callable ( lookup_view , can_fail = False ) : \"\"\"\"\"\" if not callable ( lookup_view ) : try : lookup_view = lookup_view . encode ( '' ) mod_name , func_name = get_mod_func ( lookup_view ) if func_name != '' : lookup_view = getattr ( import_module ( mod_name ) , func_name ) if not callable ( lookup_view ) : raise AttributeError ( \"\" % ( mod_name , func_name ) ) except ( ImportError , AttributeError ) : if not can_fail : raise except UnicodeEncodeError : pass return lookup_view get_callable = memoize ( get_callable , _callable_cache , ) def get_resolver ( urlconf ) : if urlconf is None : from django . conf import settings urlconf = settings . ROOT_URLCONF return RegexURLResolver ( r'' , urlconf ) get_resolver = memoize ( get_resolver , _resolver_cache , ) def get_mod_func ( callback ) : try : dot = callback . rindex ( '' ) except ValueError : return callback , '' return callback [ : dot ] , callback [ dot + : ] class RegexURLPattern ( object ) : def __init__ ( self , regex , callback , default_args = None , name = None ) : self . regex = re . compile ( regex , re . UNICODE ) if callable ( callback ) : self . _callback = callback else : self . _callback = None self . _callback_str = callback self . default_args = default_args or { } self . name = name def __repr__ ( self ) : return '' % ( self . __class__ . __name__ , self . name , self . regex . pattern ) def add_prefix ( self , prefix ) : \"\"\"\"\"\" if not prefix or not hasattr ( self , '' ) : return self . _callback_str = prefix + '' + self . _callback_str def resolve ( self , path ) : match = self . regex . search ( path ) if match : kwargs = match . groupdict ( ) if kwargs : args = ( ) else : args = match . groups ( ) kwargs . update ( self . default_args ) return self . callback , args , kwargs def _get_callback ( self ) : if self . _callback is not None : return self . _callback try : self . _callback = get_callable ( self . _callback_str ) except ImportError , e : mod_name , _ = get_mod_func ( self . _callback_str ) raise ViewDoesNotExist , \"\" % ( mod_name , str ( e ) ) except AttributeError , e : mod_name , func_name = get_mod_func ( self . _callback_str ) raise ViewDoesNotExist , \"\" % ( func_name , mod_name , str ( e ) ) return self . _callback callback = property ( _get_callback ) class RegexURLResolver ( object ) : def __init__ ( self , regex , urlconf_name , default_kwargs = None , app_name = None , namespace = None ) : self . regex = re . compile ( regex , re . UNICODE ) self . urlconf_name = urlconf_name if not isinstance ( urlconf_name , basestring ) : ", "answer": "self . _urlconf_module = self . urlconf_name"}, {"prompt": " \"\"\"\"\"\" from distutils . version import LooseVersion from twisted . internet import reactor from twisted . internet . defer import gatherResults from hypothesis . strategies import integers from bitmath import GiB from eliot import Message from ... common import loop_until from ... common . runner import run_ssh from ... dockerplugin . test . test_api import volume_expression from ... testtools import AsyncTestCase , random_name , flaky , async_runner from . . testtools import ( require_cluster , post_http_server , assert_http_server , get_docker_client , verify_socket , check_http_server , extract_external_port , create_dataset , require_moving_backend , ACCEPTANCE_TEST_TIMEOUT ) from . . scripts import SCRIPTS from ... node import backends from ... node . agents . ebs import EBSMandatoryProfileAttributes class DockerPluginTests ( AsyncTestCase ) : \"\"\"\"\"\" run_tests_with = async_runner ( timeout = ACCEPTANCE_TEST_TIMEOUT ) def require_docker ( self , required_version , cluster ) : \"\"\"\"\"\" client = get_docker_client ( cluster , cluster . nodes [ ] . public_address ) client_version = LooseVersion ( client . version ( ) [ '' ] ) minimum_version = LooseVersion ( required_version ) if client_version < minimum_version : self . skipTest ( '' '' . format ( minimum_version , client_version ) ) def docker_service ( self , address , action ) : \"\"\"\"\"\" distro = [ ] get_distro = run_ssh ( reactor , b\"\" , address , [ \"\" , \"\" , \"\" ] , handle_stdout = distro . append ) get_distro . addCallback ( lambda _ : distro [ ] . lower ( ) ) def action_docker ( distribution ) : if '' in distribution : command = [ \"\" , \"\" , action ] else : command = [ \"\" , action , \"\" ] d = run_ssh ( reactor , b\"\" , address , command ) def handle_error ( _ , action ) : self . fail ( \"\" . format ( action ) ) d . addErrback ( handle_error , action ) return d acting = get_distro . addCallback ( action_docker ) return acting def run_python_container ( self , cluster , address , docker_arguments , script , script_arguments , cleanup = True , client = None ) : \"\"\"\"\"\" if client is None : client = get_docker_client ( cluster , address ) for container in client . containers ( ) : client . remove_container ( container [ \"\" ] , force = True ) container = client . create_container ( \"\" , [ \"\" , \"\" , script . getContent ( ) ] + list ( script_arguments ) , volume_driver = \"\" , ** docker_arguments ) cid = container [ \"\" ] client . start ( container = cid ) if cleanup : self . addCleanup ( client . remove_container , cid , force = True ) return cid def _create_volume ( self , client , name , driver_opts ) : \"\"\"\"\"\" result = client . create_volume ( name , u'' , driver_opts ) self . addCleanup ( client . remove_volume , name ) return result def _test_sized_vol_container ( self , cluster , node ) : \"\"\"\"\"\" client = get_docker_client ( cluster , node . public_address ) volume_name = random_name ( self ) size = integers ( min_value = , max_value = ) . example ( ) expression = volume_expression . example ( ) size_opt = \"\" . join ( str ( size ) ) + expression size_bytes = int ( GiB ( size ) . to_Byte ( ) . value ) self . _create_volume ( client , volume_name , driver_opts = { '' : size_opt } ) http_port = ", "answer": "container_identifier = self . run_python_container ("}, {"prompt": " from django_nose . tools import assert_equal from pontoon . base . tests import ( assert_attributes_equal , create_tempfile , LocaleFactory , ) from pontoon . base . utils import match_attr class FormatTestsMixin ( object ) : \"\"\"\"\"\" maxDiff = None parse = None supports_keys = False supports_source = False supports_source_string = False def setUp ( self ) : super ( FormatTestsMixin , self ) . setUp ( ) self . locale = LocaleFactory . create ( code = '' , name = '' , plural_rule = '' , cldr_plurals = '' , ) def parse_string ( self , string , source_string = None , locale = None ) : path = create_tempfile ( string ) locale = locale or self . locale if source_string is not None : source_path = create_tempfile ( source_string ) return path , self . parse ( path , source_path = source_path , locale = locale ) else : return path , self . parse ( path , locale = locale ) def key ( self , source_string ) : \"\"\"\"\"\" return source_string if not self . supports_keys else source_string + '' def run_parse_basic ( self , input_string , translation_index ) : \"\"\"\"\"\" path , resource = self . parse_string ( input_string ) assert_attributes_equal ( resource . translations [ translation_index ] , comments = [ '' ] , key = self . key ( '' ) , strings = { None : '' } , fuzzy = False , order = translation_index , ) if self . supports_source : assert_equal ( resource . translations [ translation_index ] . source , [ ( '' , '' ) ] ) if self . supports_source_string : assert_attributes_equal ( resource . translations [ translation_index ] , source_string = '' , source_string_plural = '' ) def run_parse_multiple_comments ( self , input_string , translation_index ) : path , resource = self . parse_string ( input_string ) assert_attributes_equal ( resource . translations [ translation_index ] , comments = [ '' , '' ] , source = [ ] , key = self . key ( '' ) , strings = { None : '' } , fuzzy = False , order = translation_index , ) if self . supports_source_string : assert_attributes_equal ( resource . translations [ translation_index ] , source_string = '' , source_string_plural = '' ) def run_parse_multiple_sources ( self , input_string , translation_index ) : path , resource = self . parse_string ( input_string ) assert_attributes_equal ( resource . translations [ translation_index ] , comments = [ ] , source = [ ( '' , '' ) , ( '' , '' ) ] , key = self . key ( '' ) , strings = { None : '' } , fuzzy = False , order = translation_index , ) if self . supports_source_string : assert_attributes_equal ( resource . translations [ translation_index ] , source_string = '' , source_string_plural = '' ) def run_parse_fuzzy ( self , input_string , translation_index ) : path , resource = self . parse_string ( input_string ) assert_attributes_equal ( resource . translations [ translation_index ] , comments = [ ] , source = [ ] , key = self . key ( '' ) , strings = { None : '' } , fuzzy = True , order = translation_index , ) if self . supports_source_string : assert_attributes_equal ( resource . translations [ translation_index ] , source_string = '' , source_string_plural = '' ) def run_parse_no_comments_no_sources ( self , input_string , translation_index ) : path , resource = self . parse_string ( input_string ) assert_attributes_equal ( resource . translations [ translation_index ] , comments = [ ] , source = [ ] , key = self . key ( '' ) , strings = { None : '' } , fuzzy = False , order = translation_index , ) if self . supports_source_string : assert_attributes_equal ( resource . translations [ translation_index ] , source_string = '' , source_string_plural = '' ) def run_parse_missing_traslation ( self , input_string , translation_index ) : path , resource = self . parse_string ( input_string ) assert_attributes_equal ( resource . translations [ translation_index ] , comments = [ ] , source = [ ] , key = self . key ( '' ) , strings = { } , fuzzy = False , order = translation_index , ) if self . supports_source_string : assert_attributes_equal ( resource . translations [ translation_index ] , source_string = '' , source_string_plural = '' ) def run_parse_plural_translation ( self , input_string , translation_index ) : path , resource = self . parse_string ( input_string ) assert_attributes_equal ( resource . translations [ translation_index ] , comments = [ ] , source = [ ] , key = self . key ( '' ) , strings = { : '' , : '' } , fuzzy = False , order = translation_index , ) if self . supports_source_string : assert_attributes_equal ( resource . translations [ translation_index ] , source_string = '' , source_string_plural = '' , ) def run_parse_plural_translation_missing ( self , input_string , translation_index ) : path , resource = self . parse_string ( input_string ) assert_attributes_equal ( resource . translations [ translation_index ] , comments = [ ] , source = [ ] , key = self . key ( '' ) , strings = { : '' } , fuzzy = False , order = translation_index , ) if self . supports_source_string : assert_attributes_equal ( resource . translations [ translation_index ] , source_string = '' , source_string_plural = '' , ) def run_parse_empty_translation ( self , input_string , translation_index ) : \"\"\"\"\"\" path , resource = self . parse_string ( input_string ) assert_attributes_equal ( resource . translations [ translation_index ] , comments = [ ] , source = [ ] , key = self . key ( '' ) , strings = { None : u'' } , fuzzy = False , order = translation_index , ) if self . supports_source_string : assert_attributes_equal ( resource . translations [ translation_index ] , source_string = '' , ) def assert_file_content ( self , file_path , expected_content , strip = True ) : with open ( file_path ) as f : actual_content = f . read ( ) if strip : actual_content = actual_content . strip ( ) expected_content = expected_content . strip ( ) self . assertMultiLineEqual ( actual_content , expected_content ) def run_save_basic ( self , input_string , expected_string , source_string = None , resource_cb = None ) : \"\"\"\"\"\" path , resource = self . parse_string ( input_string , source_string = source_string ) ", "answer": "def test_default ( res ) :"}, {"prompt": " import os from datetime import timedelta from subprocess import Popen from celery import task from django . contrib . auth . models import User from django . utils import timezone from mod . models import TaskEvent from settings import MEDIA_ROOT , SERVER_EXEC @ task ( ) def run_server ( path , server ) : log_path = os . path . join ( MEDIA_ROOT , '' , server . owner . username , server . mod . title ) if not os . path . exists ( log_path ) : os . makedirs ( log_path ) with open ( os . path . join ( log_path , '' . format ( server . id , timezone . now ( ) . strftime ( \"\" ) , User . objects . make_random_password ( ) ) ) , '' ) as f : p = Popen ( ( os . path . join ( path , SERVER_EXEC ) , '' , os . path . join ( path , '' , server . owner . username , '' . format ( server . id ) , server . random_key , '' ) ) , cwd = path , stdout = f , stderr = f ) server . pid = p . pid server . online = True server . locked = False server . save ( ) @ task ( ) def check_server_state ( ) : from mod . models import Server servers = Server . active . filter ( is_active = True ) for server in servers : old_is_online = server . is_online if not server . is_online and server . set_online_at >= timezone . now ( ) - timedelta ( seconds = ) : server . locked = False server . save ( ) server . check_online ( ) server . get_server_info ( ) if server . automatic_restart and old_is_online and not server . is_online : server . set_online ( ) @ task ( ) def start_server ( event_id ) : event = TaskEvent . objects . filter ( pk = event_id ) if event : event = event [ ] else : return event . server . set_online ( ) if not event . repeat : event . status = event . save ( update_fields = [ '' ] ) else : next_run = event . date + timedelta ( minutes = event . repeat ) if timezone . now ( ) >= next_run : event . status = event . save ( update_fields = [ '' ] ) return task = start_server . apply_async ( ( event_id , ) , eta = next_run ) event . date = next_run event . task_id = task . task_id event . save ( update_fields = [ '' , '' ] ) ", "answer": "@ task ( )"}, {"prompt": " import abc import copy import operator import os . path import re import requests from rally . common . i18n import _ from rally . common import logging from rally . common . plugin import plugin from rally import exceptions from rally import osclients from rally . task import scenario LOG = logging . getLogger ( __name__ ) @ logging . log_deprecated ( \"\" , \"\" , once = True ) def set ( ** kwargs ) : \"\"\"\"\"\" def wrapper ( func ) : func . _meta_setdefault ( \"\" , { } ) func . _meta_get ( \"\" ) . update ( kwargs ) return func return wrapper ", "answer": "def _get_preprocessor_loader ( plugin_name ) :"}, {"prompt": " \"\"\"\"\"\" from canonicaljson import encode_canonical_json from signedjson . key import decode_verify_key_bytes from signedjson . sign import verify_signed_json , SignatureVerifyException from twisted . internet import defer from synapse . api . constants import EventTypes , Membership , JoinRules from synapse . api . errors import AuthError , Codes , SynapseError , EventSizeError from synapse . types import Requester , RoomID , UserID , EventID from synapse . util . logutils import log_function from synapse . util . logcontext import preserve_context_over_fn from unpaddedbase64 import decode_base64 import logging import pymacaroons logger = logging . getLogger ( __name__ ) AuthEventTypes = ( EventTypes . Create , EventTypes . Member , EventTypes . PowerLevels , EventTypes . JoinRules , EventTypes . RoomHistoryVisibility , EventTypes . ThirdPartyInvite , ) class Auth ( object ) : def __init__ ( self , hs ) : self . hs = hs self . store = hs . get_datastore ( ) self . state = hs . get_state_handler ( ) self . TOKEN_NOT_FOUND_HTTP_STATUS = self . _KNOWN_CAVEAT_PREFIXES = set ( [ \"\" , \"\" , \"\" , \"\" , \"\" , ] ) def check ( self , event , auth_events ) : \"\"\"\"\"\" self . check_size_limits ( event ) try : if not hasattr ( event , \"\" ) : raise AuthError ( , \"\" % event ) if auth_events is None : logger . warn ( \"\" , event . event_id ) return True if event . type == EventTypes . Create : return True creation_event = auth_events . get ( ( EventTypes . Create , \"\" ) , None ) if not creation_event : raise SynapseError ( , \"\" % ( event . room_id , ) ) creating_domain = RoomID . from_string ( event . room_id ) . domain originating_domain = UserID . from_string ( event . sender ) . domain if creating_domain != originating_domain : if not self . can_federate ( event , auth_events ) : raise AuthError ( , \"\" ) if event . type == EventTypes . Aliases : return True logger . debug ( \"\" , [ a . event_id for a in auth_events . values ( ) ] ) if event . type == EventTypes . Member : allowed = self . is_membership_change_allowed ( event , auth_events ) if allowed : logger . debug ( \"\" , event ) else : logger . debug ( \"\" , event ) return allowed self . check_event_sender_in_room ( event , auth_events ) self . _can_send_event ( event , auth_events ) if event . type == EventTypes . PowerLevels : self . _check_power_levels ( event , auth_events ) if event . type == EventTypes . Redaction : self . check_redaction ( event , auth_events ) logger . debug ( \"\" , event ) except AuthError as e : logger . info ( \"\" , event , e . msg ) logger . info ( \"\" , event ) raise def check_size_limits ( self , event ) : def too_big ( field ) : raise EventSizeError ( \"\" % ( field , ) ) if len ( event . user_id ) > : too_big ( \"\" ) if len ( event . room_id ) > : too_big ( \"\" ) if event . is_state ( ) and len ( event . state_key ) > : too_big ( \"\" ) if len ( event . type ) > : too_big ( \"\" ) if len ( event . event_id ) > : too_big ( \"\" ) if len ( encode_canonical_json ( event . get_pdu_json ( ) ) ) > : too_big ( \"\" ) @ defer . inlineCallbacks def check_joined_room ( self , room_id , user_id , current_state = None ) : \"\"\"\"\"\" if current_state : member = current_state . get ( ( EventTypes . Member , user_id ) , None ) else : member = yield self . state . get_current_state ( room_id = room_id , event_type = EventTypes . Member , state_key = user_id ) self . _check_joined_room ( member , user_id , room_id ) defer . returnValue ( member ) @ defer . inlineCallbacks def check_user_was_in_room ( self , room_id , user_id ) : \"\"\"\"\"\" member = yield self . state . get_current_state ( room_id = room_id , event_type = EventTypes . Member , state_key = user_id ) membership = member . membership if member else None if membership not in ( Membership . JOIN , Membership . LEAVE ) : raise AuthError ( , \"\" % ( user_id , room_id ) ) if membership == Membership . LEAVE : forgot = yield self . store . did_forget ( user_id , room_id ) if forgot : raise AuthError ( , \"\" % ( user_id , room_id ) ) defer . returnValue ( member ) @ defer . inlineCallbacks def check_host_in_room ( self , room_id , host ) : curr_state = yield self . state . get_current_state ( room_id ) for event in curr_state . values ( ) : if event . type == EventTypes . Member : try : if UserID . from_string ( event . state_key ) . domain != host : continue except : logger . warn ( \"\" , event . state_key ) continue if event . content [ \"\" ] == Membership . JOIN : defer . returnValue ( True ) defer . returnValue ( False ) def check_event_sender_in_room ( self , event , auth_events ) : key = ( EventTypes . Member , event . user_id , ) member_event = auth_events . get ( key ) return self . _check_joined_room ( member_event , event . user_id , event . room_id ) def _check_joined_room ( self , member , user_id , room_id ) : if not member or member . membership != Membership . JOIN : raise AuthError ( , \"\" % ( user_id , room_id , repr ( member ) ) ) def can_federate ( self , event , auth_events ) : creation_event = auth_events . get ( ( EventTypes . Create , \"\" ) ) return creation_event . content . get ( \"\" , True ) is True @ log_function def is_membership_change_allowed ( self , event , auth_events ) : membership = event . content [ \"\" ] if len ( event . prev_events ) == and Membership . JOIN == membership : key = ( EventTypes . Create , \"\" , ) create = auth_events . get ( key ) if create and event . prev_events [ ] [ ] == create . event_id : if create . content [ \"\" ] == event . state_key : return True target_user_id = event . state_key creating_domain = RoomID . from_string ( event . room_id ) . domain target_domain = UserID . from_string ( target_user_id ) . domain if creating_domain != target_domain : if not self . can_federate ( event , auth_events ) : raise AuthError ( , \"\" ) key = ( EventTypes . Member , event . user_id , ) caller = auth_events . get ( key ) caller_in_room = caller and caller . membership == Membership . JOIN caller_invited = caller and caller . membership == Membership . INVITE key = ( EventTypes . Member , target_user_id , ) target = auth_events . get ( key ) target_in_room = target and target . membership == Membership . JOIN target_banned = target and target . membership == Membership . BAN key = ( EventTypes . JoinRules , \"\" , ) join_rule_event = auth_events . get ( key ) if join_rule_event : join_rule = join_rule_event . content . get ( \"\" , JoinRules . INVITE ) else : join_rule = JoinRules . INVITE user_level = self . _get_user_power_level ( event . user_id , auth_events ) target_level = self . _get_user_power_level ( target_user_id , auth_events ) ban_level = self . _get_named_level ( auth_events , \"\" , ) logger . debug ( \"\" , { \"\" : caller_in_room , \"\" : caller_invited , \"\" : target_banned , \"\" : target_in_room , \"\" : membership , \"\" : join_rule , \"\" : target_user_id , \"\" : event . user_id , } ) if Membership . INVITE == membership and \"\" in event . content : if not self . _verify_third_party_invite ( event , auth_events ) : raise AuthError ( , \"\" ) return True if Membership . JOIN != membership : if ( caller_invited and Membership . LEAVE == membership and target_user_id == event . user_id ) : return True if not caller_in_room : raise AuthError ( , \"\" % ( event . user_id , event . room_id , ) ) if Membership . INVITE == membership : if target_banned : raise AuthError ( , \"\" % ( target_user_id , ) ) elif target_in_room : raise AuthError ( , \"\" % target_user_id ) else : invite_level = self . _get_named_level ( auth_events , \"\" , ) if user_level < invite_level : raise AuthError ( , \"\" % target_user_id ) elif Membership . JOIN == membership : if event . user_id != target_user_id : raise AuthError ( , \"\" ) elif target_banned : raise AuthError ( , \"\" ) elif join_rule == JoinRules . PUBLIC : pass elif join_rule == JoinRules . INVITE : if not caller_in_room and not caller_invited : raise AuthError ( , \"\" ) else : raise AuthError ( , \"\" ) elif Membership . LEAVE == membership : if target_banned and user_level < ban_level : raise AuthError ( , \"\" % ( target_user_id , ) ) elif target_user_id != event . user_id : kick_level = self . _get_named_level ( auth_events , \"\" , ) if user_level < kick_level or user_level <= target_level : raise AuthError ( , \"\" % target_user_id ) elif Membership . BAN == membership : if user_level < ban_level or user_level <= target_level : raise AuthError ( , \"\" ) else : raise AuthError ( , \"\" % membership ) return True def _verify_third_party_invite ( self , event , auth_events ) : \"\"\"\"\"\" if \"\" not in event . content : return False if \"\" not in event . content [ \"\" ] : return False signed = event . content [ \"\" ] [ \"\" ] for key in { \"\" , \"\" } : if key not in signed : return False token = signed [ \"\" ] invite_event = auth_events . get ( ( EventTypes . ThirdPartyInvite , token , ) ) if not invite_event : return False if event . user_id != invite_event . user_id : return False if signed [ \"\" ] != event . state_key : return False if signed [ \"\" ] != token : return False for public_key_object in self . get_public_keys ( invite_event ) : public_key = public_key_object [ \"\" ] try : for server , signature_block in signed [ \"\" ] . items ( ) : for key_name , encoded_signature in signature_block . items ( ) : if not key_name . startswith ( \"\" ) : continue verify_key = decode_verify_key_bytes ( key_name , decode_base64 ( public_key ) ) verify_signed_json ( signed , server , verify_key ) return True except ( KeyError , SignatureVerifyException , ) : continue return False def get_public_keys ( self , invite_event ) : public_keys = [ ] if \"\" in invite_event . content : o = { \"\" : invite_event . content [ \"\" ] , } if \"\" in invite_event . content : o [ \"\" ] = invite_event . content [ \"\" ] public_keys . append ( o ) public_keys . extend ( invite_event . content . get ( \"\" , [ ] ) ) return public_keys def _get_power_level_event ( self , auth_events ) : key = ( EventTypes . PowerLevels , \"\" , ) return auth_events . get ( key ) def _get_user_power_level ( self , user_id , auth_events ) : power_level_event = self . _get_power_level_event ( auth_events ) if power_level_event : level = power_level_event . content . get ( \"\" , { } ) . get ( user_id ) if not level : level = power_level_event . content . get ( \"\" , ) if level is None : return else : return int ( level ) else : key = ( EventTypes . Create , \"\" , ) create_event = auth_events . get ( key ) if ( create_event is not None and create_event . content [ \"\" ] == user_id ) : return else : return def _get_named_level ( self , auth_events , name , default ) : power_level_event = self . _get_power_level_event ( auth_events ) if not power_level_event : return default level = power_level_event . content . get ( name , None ) if level is not None : return int ( level ) else : return default @ defer . inlineCallbacks def get_user_by_req ( self , request , allow_guest = False ) : \"\"\"\"\"\" try : user_id = yield self . _get_appservice_user_id ( request . args ) if user_id : request . authenticated_entity = user_id defer . returnValue ( Requester ( UserID . from_string ( user_id ) , \"\" , False ) ) access_token = request . args [ \"\" ] [ ] user_info = yield self . get_user_by_access_token ( access_token ) user = user_info [ \"\" ] token_id = user_info [ \"\" ] is_guest = user_info [ \"\" ] ip_addr = self . hs . get_ip_from_request ( request ) user_agent = request . requestHeaders . getRawHeaders ( \"\" , default = [ \"\" ] ) [ ] if user and access_token and ip_addr : preserve_context_over_fn ( self . store . insert_client_ip , user = user , access_token = access_token , ip = ip_addr , user_agent = user_agent ) if is_guest and not allow_guest : raise AuthError ( , \"\" , errcode = Codes . GUEST_ACCESS_FORBIDDEN ) request . authenticated_entity = user . to_string ( ) defer . returnValue ( Requester ( user , token_id , is_guest ) ) except KeyError : raise AuthError ( self . TOKEN_NOT_FOUND_HTTP_STATUS , \"\" , errcode = Codes . MISSING_TOKEN ) @ defer . inlineCallbacks def _get_appservice_user_id ( self , request_args ) : app_service = yield self . store . get_app_service_by_token ( request_args [ \"\" ] [ ] ) if app_service is None : defer . returnValue ( None ) if \"\" not in request_args : defer . returnValue ( app_service . sender ) user_id = request_args [ \"\" ] [ ] if app_service . sender == user_id : defer . returnValue ( app_service . sender ) if not app_service . is_interested_in_user ( user_id ) : raise AuthError ( , \"\" ) if not ( yield self . store . get_user_by_id ( user_id ) ) : raise AuthError ( , \"\" ) defer . returnValue ( user_id ) @ defer . inlineCallbacks def get_user_by_access_token ( self , token ) : \"\"\"\"\"\" try : ret = yield self . get_user_from_macaroon ( token ) except AuthError : ret = yield self . _look_up_user_by_access_token ( token ) defer . returnValue ( ret ) @ defer . inlineCallbacks def get_user_from_macaroon ( self , macaroon_str ) : try : macaroon = pymacaroons . Macaroon . deserialize ( macaroon_str ) self . validate_macaroon ( macaroon , \"\" , False ) user_prefix = \"\" user = None guest = False for caveat in macaroon . caveats : if caveat . caveat_id . startswith ( user_prefix ) : user = UserID . from_string ( caveat . caveat_id [ len ( user_prefix ) : ] ) elif caveat . caveat_id == \"\" : guest = True if user is None : raise AuthError ( self . TOKEN_NOT_FOUND_HTTP_STATUS , \"\" , errcode = Codes . UNKNOWN_TOKEN ) if guest : ret = { \"\" : user , \"\" : True , \"\" : None , } else : ret = yield self . _look_up_user_by_access_token ( macaroon_str ) if ret [ \"\" ] != user : logger . error ( \"\" , user , ret [ \"\" ] ) raise AuthError ( self . TOKEN_NOT_FOUND_HTTP_STATUS , \"\" , errcode = Codes . UNKNOWN_TOKEN ) defer . returnValue ( ret ) except ( pymacaroons . exceptions . MacaroonException , TypeError , ValueError ) : raise AuthError ( self . TOKEN_NOT_FOUND_HTTP_STATUS , \"\" , errcode = Codes . UNKNOWN_TOKEN ) def validate_macaroon ( self , macaroon , type_string , verify_expiry ) : \"\"\"\"\"\" v = pymacaroons . Verifier ( ) v . satisfy_exact ( \"\" ) v . satisfy_exact ( \"\" + type_string ) v . satisfy_general ( lambda c : c . startswith ( \"\" ) ) v . satisfy_exact ( \"\" ) if verify_expiry : v . satisfy_general ( self . _verify_expiry ) else : v . satisfy_general ( lambda c : c . startswith ( \"\" ) ) v . verify ( macaroon , self . hs . config . macaroon_secret_key ) v = pymacaroons . Verifier ( ) v . satisfy_general ( self . _verify_recognizes_caveats ) v . verify ( macaroon , self . hs . config . macaroon_secret_key ) def _verify_expiry ( self , caveat ) : prefix = \"\" if not caveat . startswith ( prefix ) : return False expiry = int ( caveat [ len ( prefix ) : ] ) now = self . hs . get_clock ( ) . time_msec ( ) return now < expiry def _verify_recognizes_caveats ( self , caveat ) : first_space = caveat . find ( \"\" ) if first_space < : return False second_space = caveat . find ( \"\" , first_space + ) if second_space < : return False return caveat [ : second_space + ] in self . _KNOWN_CAVEAT_PREFIXES @ defer . inlineCallbacks def _look_up_user_by_access_token ( self , token ) : ret = yield self . store . get_user_by_access_token ( token ) if not ret : logger . warn ( \"\" % ( token , ) ) raise AuthError ( self . TOKEN_NOT_FOUND_HTTP_STATUS , \"\" , errcode = Codes . UNKNOWN_TOKEN ) user_info = { \"\" : UserID . from_string ( ret . get ( \"\" ) ) , \"\" : ret . get ( \"\" , None ) , \"\" : False , } defer . returnValue ( user_info ) @ defer . inlineCallbacks def get_appservice_by_req ( self , request ) : try : token = request . args [ \"\" ] [ ] service = yield self . store . get_app_service_by_token ( token ) if not service : logger . warn ( \"\" % ( token , ) ) raise AuthError ( self . TOKEN_NOT_FOUND_HTTP_STATUS , \"\" , errcode = Codes . UNKNOWN_TOKEN ) request . authenticated_entity = service . sender defer . returnValue ( service ) except KeyError : raise AuthError ( self . TOKEN_NOT_FOUND_HTTP_STATUS , \"\" ) def is_server_admin ( self , user ) : return self . store . is_server_admin ( user ) @ defer . inlineCallbacks def add_auth_events ( self , builder , context ) : auth_ids = self . compute_auth_events ( builder , context . current_state ) auth_events_entries = yield self . store . add_event_hashes ( auth_ids ) builder . auth_events = auth_events_entries def compute_auth_events ( self , event , current_state ) : if event . type == EventTypes . Create : return [ ] auth_ids = [ ] key = ( EventTypes . PowerLevels , \"\" , ) power_level_event = current_state . get ( key ) if power_level_event : auth_ids . append ( power_level_event . event_id ) key = ( EventTypes . JoinRules , \"\" , ) join_rule_event = current_state . get ( key ) key = ( EventTypes . Member , event . user_id , ) member_event = current_state . get ( key ) key = ( EventTypes . Create , \"\" , ) create_event = current_state . get ( key ) if create_event : auth_ids . append ( create_event . event_id ) if join_rule_event : join_rule = join_rule_event . content . get ( \"\" ) is_public = join_rule == JoinRules . PUBLIC if join_rule else False else : is_public = False if event . type == EventTypes . Member : e_type = event . content [ \"\" ] if e_type in [ Membership . JOIN , Membership . INVITE ] : if join_rule_event : auth_ids . append ( join_rule_event . event_id ) if e_type == Membership . JOIN : if member_event and not is_public : auth_ids . append ( member_event . event_id ) else : if member_event : auth_ids . append ( member_event . event_id ) if e_type == Membership . INVITE : if \"\" in event . content : key = ( EventTypes . ThirdPartyInvite , event . content [ \"\" ] [ \"\" ] [ \"\" ] ) third_party_invite = current_state . get ( key ) if third_party_invite : auth_ids . append ( third_party_invite . event_id ) elif member_event : if member_event . content [ \"\" ] == Membership . JOIN : auth_ids . append ( member_event . event_id ) return auth_ids def _get_send_level ( self , etype , state_key , auth_events ) : ", "answer": "key = ( EventTypes . PowerLevels , \"\" , )"}, {"prompt": " '''''' from __future__ import absolute_import import logging import re import getopt import copy from os import path as ospath import salt . utils from salt . exceptions import SaltRenderError import salt . ext . six as six from salt . ext . six . moves import StringIO __all__ = [ '' ] log = logging . getLogger ( __name__ ) __opts__ = { '' : r'' , '' : '' , '' : '' , '' : '' } STATE_FUNC = STATE_NAME = '' def __init__ ( opts ) : global STATE_NAME , STATE_FUNC STATE_FUNC = __opts__ [ '' ] STATE_NAME = STATE_FUNC . split ( '' ) [ ] MOD_BASENAME = ospath . basename ( __file__ ) INVALID_USAGE_ERROR = SaltRenderError ( '' '''''' . format ( MOD_BASENAME , MOD_BASENAME ) ) def render ( input , saltenv = '' , sls = '' , argline = '' , ** kws ) : gen_start_state = False no_goal_state = False implicit_require = False def process_sls_data ( data , context = None , extract = False ) : sls_dir = ospath . dirname ( sls . replace ( '' , ospath . sep ) ) if '' in sls else sls ctx = dict ( sls_dir = sls_dir if sls_dir else '' ) if context : ctx . update ( context ) tmplout = render_template ( StringIO ( data ) , saltenv , sls , context = ctx , argline = rt_argline . strip ( ) , ** kws ) high = render_data ( tmplout , saltenv , sls , argline = rd_argline . strip ( ) ) return process_high_data ( high , extract ) def process_high_data ( high , extract ) : data = copy . deepcopy ( high ) try : rewrite_single_shorthand_state_decl ( data ) rewrite_sls_includes_excludes ( data , sls , saltenv ) if not extract and implicit_require : sid = has_names_decls ( data ) if sid : raise SaltRenderError ( '' '' '' '' . format ( sid ) ) add_implicit_requires ( data ) if gen_start_state : add_start_state ( data , sls ) if not extract and not no_goal_state : add_goal_state ( data ) rename_state_ids ( data , sls ) extract_state_confs ( data ) except SaltRenderError : raise except Exception as err : log . exception ( '' '' . format ( sls , err ) ) from salt . state import State state = State ( __opts__ ) errors = state . verify_high ( high ) if errors : raise SaltRenderError ( '' . join ( errors ) ) raise SaltRenderError ( '' ) return data renderers = kws [ '' ] opts , args = getopt . getopt ( argline . split ( ) , '' ) argline = '' . join ( args ) if args else '' if ( '' , '' ) in opts : no_goal_state = True if ( '' , '' ) in opts : implicit_require = True if ( '' , '' ) in opts : gen_start_state = True if ( '' , '' ) in opts : data = process_high_data ( input , extract = False ) else : args = [ arg . strip ( ) . replace ( '' , '' ) for arg in re . split ( r'' , argline , ) ] try : name , rd_argline = ( args [ ] + '' ) . split ( '' , ) render_data = renderers [ name ] if implicit_require : if name == '' : rd_argline = '' + rd_argline else : raise SaltRenderError ( '' '' ) name , rt_argline = ( args [ ] + '' ) . split ( '' , ) render_template = renderers [ name ] except KeyError as err : raise SaltRenderError ( '' . format ( err ) ) except IndexError : raise INVALID_USAGE_ERROR if isinstance ( input , six . string_types ) : with salt . utils . fopen ( input , '' ) as ifile : sls_templ = ifile . read ( ) else : sls_templ = input . read ( ) match = re . search ( __opts__ [ '' ] , sls_templ ) if match : process_sls_data ( sls_templ [ : match . start ( ) ] , extract = True ) if STATE_CONF : tmplctx = STATE_CONF . copy ( ) if tmplctx : prefix = sls + '' for k in six . iterkeys ( tmplctx ) : if k . startswith ( prefix ) : tmplctx [ k [ len ( prefix ) : ] ] = tmplctx [ k ] del tmplctx [ k ] else : tmplctx = { } data = process_sls_data ( sls_templ , tmplctx ) if log . isEnabledFor ( logging . DEBUG ) : import pprint log . debug ( '' . format ( pprint . pformat ( data ) ) ) return data def has_names_decls ( data ) : for sid , _ , _ , args in statelist ( data ) : if sid == '' : continue for _ in nvlist ( args , [ '' ] ) : return sid def rewrite_single_shorthand_state_decl ( data ) : '''''' for sid , states in six . iteritems ( data ) : if isinstance ( states , six . string_types ) : data [ sid ] = { states : [ ] } def rewrite_sls_includes_excludes ( data , sls , saltenv ) : for sid in data : if sid == '' : includes = data [ sid ] for i , each in enumerate ( includes ) : if isinstance ( each , dict ) : slsenv , incl = each . popitem ( ) else : slsenv = saltenv incl = each if incl . startswith ( '' ) : includes [ i ] = { slsenv : _relative_to_abs_sls ( incl , sls ) } elif sid == '' : for sdata in data [ sid ] : if '' in sdata and sdata [ '' ] . startswith ( '' ) : sdata [ '' ] = _relative_to_abs_sls ( sdata [ '' ] , sls ) def _local_to_abs_sid ( sid , sls ) : if '' in sid : return _relative_to_abs_sls ( sid , sls ) else : abs_sls = _relative_to_abs_sls ( sid , sls + '' ) return '' . join ( abs_sls . rsplit ( '' , ) ) def _relative_to_abs_sls ( relative , sls ) : '''''' levels , suffix = re . match ( r'' , relative ) . groups ( ) level_count = len ( levels ) p_comps = sls . split ( '' ) if level_count > len ( p_comps ) : raise SaltRenderError ( '' ) return '' . join ( p_comps [ : - level_count ] + [ suffix ] ) def nvlist ( thelist , names = None ) : '''''' for nvitem in thelist : if isinstance ( nvitem , dict ) : name , value = next ( six . iteritems ( nvitem ) ) if names is None or name in names : yield nvitem , name , value def nvlist2 ( thelist , names = None ) : '''''' for _ , _ , value in nvlist ( thelist , names ) : for each in nvlist ( value ) : yield each def statelist ( states_dict , sid_excludes = frozenset ( [ '' , '' ] ) ) : for sid , states in six . iteritems ( states_dict ) : if sid . startswith ( '' ) : continue if sid in sid_excludes : continue for sname , args in six . iteritems ( states ) : if sname . startswith ( '' ) : continue yield sid , states , sname , args REQUISITES = set ( [ '' , '' , '' , '' , '' , '' ] ) def rename_state_ids ( data , sls , is_extend = False ) : if '' in data and not is_extend : rename_state_ids ( data [ '' ] , sls , True ) for sid , _ , _ , args in statelist ( data ) : for req , sname , sid in nvlist2 ( args , REQUISITES ) : if sid . startswith ( '' ) : ", "answer": "req [ sname ] = _local_to_abs_sid ( sid , sls )"}, {"prompt": " from __future__ import absolute_import , division , with_statement from fudge import patch from revolver import git @ patch ( \"\" ) def test_revparse ( local ) : cmd = \"\" local . expects_call ( ) . with_args ( cmd , capture = True ) . returns ( \"\" ) assert git . revparse ( \"\" ) == \"\" @ patch ( \"\" ) def test_repository_name ( local ) : cmd = \"\" ", "answer": "local . expects_call ( ) . with_args ( cmd , capture = True ) . returns ( \"\" )"}, {"prompt": " \"\"\"\"\"\" import os import unittest import StringIO import dbutil import dbcompare MODULE = '' class TestReporter ( unittest . TestCase ) : \"\"\"\"\"\" TEST_COLUMNS = [ '' , '' , '' ] TEST_ROWS = [ ( , '' , '' ) , ( , '' , '' ) , ( , '' , '' ) , ( , '' , '' ) ] SUITE = '' TEST_TABLE = '' TEST_COLUMN = '' def setUp ( self ) : self . output = [ None ] * for i in range ( ) : self . output [ i ] = StringIO . StringIO ( ) self . report = [ None ] * for i in range ( ) : self . report [ i ] = dbcompare . Reporter ( '' , '' , i , self . output [ i ] ) def check_output ( self , file_name , output_str ) : \"\"\"\"\"\" output_dir_path = dbutil . output_directory ( MODULE , self . SUITE ) output_file_path = os . path . join ( output_dir_path , file_name ) with open ( output_file_path , '' ) as output_file : output_file . write ( output_str ) expected_dir_path = dbutil . expected_directory ( MODULE , self . SUITE ) expected_file_path = os . path . join ( expected_dir_path , file_name ) if os . path . isfile ( expected_file_path ) : with open ( expected_file_path ) as expected_file : expected_str = expected_file . read ( ) self . assertEqual ( output_str , expected_str ) else : self . skipTest ( ( \"\" + \"\" ) % ( file_name , MODULE , self . SUITE ) ) def test_table_only_in_v0 ( self ) : \"\" self . report [ ] . table_only_in ( , self . TEST_TABLE ) self . assertEqual ( self . output [ ] . getvalue ( ) , \"\" ) def test_table_only_in_v1 ( self ) : \"\" self . report [ ] . table_only_in ( , self . TEST_TABLE ) self . check_output ( '' , self . output [ ] . getvalue ( ) ) def test_table_only_in_v2 ( self ) : \"\" self . report [ ] . table_only_in ( , self . TEST_TABLE ) self . check_output ( '' , self . output [ ] . getvalue ( ) ) def test_column_only_in_v0 ( self ) : \"\" self . report [ ] . column_only_in ( , self . TEST_TABLE , self . TEST_COLUMN ) self . assertEqual ( self . output [ ] . getvalue ( ) , \"\" ) def test_column_only_in_v1 ( self ) : \"\" self . report [ ] . column_only_in ( , self . TEST_TABLE , self . TEST_COLUMN ) self . check_output ( '' , self . output [ ] . getvalue ( ) ) def test_column_only_in_v3 ( self ) : \"\" self . report [ ] . column_only_in ( , self . TEST_TABLE , self . TEST_COLUMN ) self . check_output ( '' , self . output [ ] . getvalue ( ) ) def test_primary_keys_differ_v0 ( self ) : \"\" self . report [ ] . primary_keys_differ ( self . TEST_TABLE ) self . assertEqual ( self . output [ ] . getvalue ( ) , \"\" ) def test_primary_keys_differ_v1 ( self ) : \"\" self . report [ ] . primary_keys_differ ( self . TEST_TABLE ) self . check_output ( '' , self . output [ ] . getvalue ( ) ) def test_content_differences_v3 ( self ) : \"\" self . report [ ] . new_table ( self . TEST_TABLE , self . TEST_COLUMNS ) self . report [ ] . add_difference ( , self . TEST_ROWS [ ] ) self . report [ ] . add_difference ( , self . TEST_ROWS [ ] ) self . report [ ] . add_difference ( , self . TEST_ROWS [ ] ) self . report [ ] . add_difference ( , self . TEST_ROWS [ ] ) self . report [ ] . content_differences ( ) self . check_output ( '' , self . output [ ] . getvalue ( ) ) class TestComparisonWrapper ( unittest . TestCase ) : \"\"\"\"\"\" SAVE_DIR = dbutil . input_directory ( '' , '' ) TEST_DB_FILE = \"\" NOT_A_TABLE = \"\" EXPECTED_TABLE_LIST = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ] COLUMN_LIST_TABLE = \"\" EXPECTED_COLUMN_LIST = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ] SIMPLE_PKEY_TABLE = \"\" EXPECTED_SIMPLE_PKEY = [ '' ] COMPOUND_PKEY_TABLE = \"\" EXPECTED_COMPOUND_PKEY = [ '' , '' ] SREF_PKEY_TABLE = \"\" EXPECTED_SREF_PKEY = [ '' ] def setUp ( self ) : self . conn = None self . dbname = dbutil . random_name ( '' ) dbutil . TESTSERVER . create ( self . dbname , self . SAVE_DIR , self . TEST_DB_FILE ) self . conn = dbutil . TESTSERVER . connect ( self . dbname ) self . conn = dbcompare . ComparisonWrapper ( self . conn ) def test_table_exists ( self ) : \"\" self . assertTrue ( self . conn . table_exists ( self . EXPECTED_TABLE_LIST [ ] ) , \"\" % self . EXPECTED_TABLE_LIST [ ] ) self . assertTrue ( self . conn . table_exists ( self . EXPECTED_TABLE_LIST [ - ] ) , \"\" % self . EXPECTED_TABLE_LIST [ - ] ) self . assertTrue ( self . conn . table_exists ( self . EXPECTED_TABLE_LIST [ ] ) , \"\" % self . EXPECTED_TABLE_LIST [ ] ) self . assertFalse ( self . conn . table_exists ( self . NOT_A_TABLE ) , \"\" % self . NOT_A_TABLE ) def test_table_list ( self ) : \"\" tab_list = self . conn . table_list ( ) self . assertEqual ( tab_list , self . EXPECTED_TABLE_LIST ) def test_column_list ( self ) : \"\" col_list = self . conn . column_list ( self . COLUMN_LIST_TABLE ) self . assertEqual ( col_list , self . EXPECTED_COLUMN_LIST ) def test_primary_key_simple ( self ) : \"\" pkey = self . conn . primary_key ( self . SIMPLE_PKEY_TABLE ) self . assertEqual ( pkey , self . EXPECTED_SIMPLE_PKEY ) def test_primary_key_compound ( self ) : \"\" pkey = self . conn . primary_key ( self . COMPOUND_PKEY_TABLE ) self . assertEqual ( pkey , self . EXPECTED_COMPOUND_PKEY ) def test_primary_key_sref ( self ) : \"\" pkey = self . conn . primary_key ( self . SREF_PKEY_TABLE ) self . assertEqual ( pkey , self . EXPECTED_SREF_PKEY ) def tearDown ( self ) : if self . conn : self . conn . close ( ) dbutil . TESTSERVER . drop ( self . dbname ) class TestCompareFunctions ( unittest . TestCase ) : \"\"\"\"\"\" SUITE = '' INPUT_DIR = dbutil . input_directory ( MODULE , SUITE ) OUTPUT_DIR = dbutil . output_directory ( MODULE , SUITE ) EXPECTED_DIR = dbutil . expected_directory ( MODULE , SUITE ) VERSION = dbutil . version_or_user ( ) DB_LIST = [ '' , '' , '' ] def setUp ( self ) : self . db_count = len ( self . DB_LIST ) self . conn = [ None ] * self . db_count self . dbname = [ None ] * self . db_count for i in range ( self . db_count ) : self . dbname [ i ] = self . VERSION + \"\" + str ( i ) if not dbutil . TESTSERVER . exists ( self . dbname [ i ] ) : dbutil . TESTSERVER . create ( self . dbname [ i ] , self . INPUT_DIR , self . DB_LIST [ i ] ) self . conn [ i ] = dbutil . TESTSERVER . connect ( self . dbname [ i ] ) def test_compare_empty ( self ) : \"\" result = dbcompare . compare_databases ( self . conn [ ] , self . conn [ ] , verbosity = ) self . assertTrue ( result , \"\" + \"\" ) def test_compare_equal_tables ( self ) : \"\" result = dbcompare . compare_tables ( self . conn [ ] , self . conn [ ] , '' , verbosity = ) self . assertTrue ( result , \"\" + \"\" ) def test_compare_different ( self ) : \"\" file_name = '' output = StringIO . StringIO ( ) result = dbcompare . compare_databases ( self . conn [ ] , self . conn [ ] , verbosity = , output = output ) output_file_path = os . path . join ( self . OUTPUT_DIR , file_name ) with open ( output_file_path , '' ) as output_file : output_file . write ( output . getvalue ( ) ) self . assertFalse ( result , \"\" + \"\" ) expected_file_path = os . path . join ( self . EXPECTED_DIR , file_name ) if os . path . isfile ( expected_file_path ) : ", "answer": "with open ( expected_file_path ) as expected_file :"}, {"prompt": " import os , sys , traceback from video . management . commands . sub_commands import SubCommand from django . contrib . contenttypes . models import ContentType from committees . models import Committee from video . models import Video from video . utils import get_videos_queryset class DownloadCommitteesVideos ( SubCommand ) : def __init__ ( self , command , mms = None , mb_quota = None ) : if mms is None : import video . utils . mms as mms SubCommand . __init__ ( self , command ) self . _verifyDataDir ( ) videos = self . _getVideosToDownload ( ) self . _debug ( '' + str ( len ( videos ) ) + '' ) total_bytes = for video in videos : if mb_quota is not None and ( total_bytes / ) > mb_quota : self . _warn ( '' + str ( mb_quota ) + '' ) break self . _check_timer ( ) url = video . embed_link self . _debug ( '' + url ) filename = self . _get_data_root ( ) + '' + self . _getFilenameFromUrl ( url ) if self . _isAlreadyDownloaded ( filename ) : self . _debug ( \"\" + filename ) total_bytes = total_bytes + self . _getFileSize ( filename ) continue else : partfilename = filename + '' try : streamsize = mms . get_size ( url ) except Exception , e : self . _warn ( '' + str ( e ) ) traceback . print_exc ( file = sys . stdout ) else : self . _debug ( '' + str ( streamsize ) ) mins_remaining = round ( self . _timer_remaining ( ) / ) downloaded = False if self . _isAlreadyDownloaded ( partfilename ) : filesize = self . _getFileSize ( partfilename ) if filesize < streamsize : self . _debug ( '' ) try : isDownloadDone = mms . resume_download ( url , partfilename , mins_remaining ) downloaded = True except Exception , e : self . _warn ( '' + str ( e ) ) traceback . print_exc ( file = sys . stdout ) else : self . _debug ( '' ) try : isDownloadDone = mms . download ( url , partfilename , mins_remaining ) downloaded = True except Exception , e : self . _warn ( '' + str ( e ) ) traceback . print_exc ( file = sys . stdout ) if downloaded : self . _check_timer ( ) filesize = self . _getDownloadedFileSize ( partfilename ) self . _debug ( '' + str ( filesize ) ) if isDownloadDone : self . _renameFile ( partfilename , filename ) self . _debug ( \"\" + filename ) total_bytes = total_bytes + filesize def _verifyDataDir ( self ) : if not os . path . exists ( self . _get_data_root ( ) + '' ) : os . makedirs ( self . _get_data_root ( ) + '' ) def _getFilenameFromUrl ( self , url ) : filename = url . split ( '' ) filename = filename [ len ( filename ) - ] return filename def _getVideosToDownload ( self ) : ret = [ ] object_type = ContentType . objects . get_for_model ( Committee ) videos = Video . objects . filter ( content_type__pk = object_type . id , group = '' ) . order_by ( '' ) for video in videos : qs = get_videos_queryset ( video , group = '' , ignoreHide = True ) if qs . count ( ) == : ret . append ( video ) return ret def _isAlreadyDownloaded ( self , filename ) : return os . path . exists ( filename ) ", "answer": "def _getFileSize ( self , filename ) :"}, {"prompt": " from maya import OpenMaya , OpenMayaMPx class AttrSpec ( object ) : def createfnattr ( self ) : raise NotImplementedError ( ) def getvalue ( self , datahandle ) : raise NotImplementedError ( ) def setvalue ( self , datahandle , value ) : raise NotImplementedError ( ) def create ( self , fnattr , longname , shortname ) : raise NotImplementedError ( ) def setdefault ( self , fnattr , value ) : raise NotImplementedError ( ) def allow_fields ( self ) : return False class _FloatAttr ( AttrSpec ) : def createfnattr ( self ) : return OpenMaya . MFnNumericAttribute ( ) def getvalue ( self , datahandle ) : return datahandle . asFloat ( ) def setvalue ( self , datahandle , value ) : datahandle . setFloat ( value ) def create ( self , fnattr , longname , shortname ) : return fnattr . create ( longname , shortname , OpenMaya . MFnNumericData . kFloat ) def setdefault ( self , fnattr , value ) : fnattr . setDefault ( value ) A_FLOAT = _FloatAttr ( ) class _StringAttr ( AttrSpec ) : def createfnattr ( self ) : return OpenMaya . MFnTypedAttribute ( ) def getvalue ( self , datahandle ) : return datahandle . asString ( ) def setvalue ( self , datahandle , value ) : datahandle . setString ( value ) def create ( self , fnattr , longname , shortname ) : return fnattr . create ( longname , shortname , OpenMaya . MFnData . kString ) def setdefault ( self , fnattr , value ) : fnattr . setDefault ( OpenMaya . MFnStringData ( ) . create ( value ) ) A_STRING = _StringAttr ( ) class _EnumAttr ( AttrSpec ) : def createfnattr ( self ) : return OpenMaya . MFnEnumAttribute ( ) def getvalue ( self , datahandle ) : return datahandle . asInt ( ) def setvalue ( self , datahandle , value ) : datahandle . setInt ( value ) def create ( self , fnattr , longname , shortname ) : return fnattr . create ( longname , shortname ) def setdefault ( self , fnattr , value ) : fnattr . setDefault ( value ) def allow_fields ( self ) : return True A_ENUM = _EnumAttr ( ) class _ColorAttr ( AttrSpec ) : def createfnattr ( self ) : return OpenMaya . MFnNumericAttribute ( ) def getvalue ( self , datahandle ) : return datahandle . asFloatVector ( ) def setvalue ( self , datahandle , value ) : datahandle . setMFloatVector ( OpenMaya . MFloatVector ( * value ) ) def create ( self , fnattr , longname , shortname ) : return fnattr . createColor ( longname , shortname ) def setdefault ( self , fnattr , value ) : fnattr . setDefault ( * value ) A_COLOR = _ColorAttr ( ) class NodeSpec ( object ) : def nodebase ( self ) : raise NotImplementedError ( ) def register ( self , fnplugin , typename , typeid , create , init ) : raise NotImplementedError ( ) def deregister ( self , fnplugin , typeid ) : raise NotImplementedError ( ) class _DependsNode ( NodeSpec ) : def nodebase ( self ) : return ( OpenMayaMPx . MPxNode , ) def register ( self , fnplugin , typename , typeid , create , init ) : fnplugin . registerNode ( typename , typeid , create , init , OpenMayaMPx . MPxNode . kDependNode ) def deregister ( self , fnplugin , typeid ) : fnplugin . deregisterNode ( typeid ) NT_DEPENDSNODE = _DependsNode ( ) class _TransformNode ( NodeSpec ) : xform_typeid = OpenMaya . MTypeId ( ) class TransformMatrix ( OpenMayaMPx . MPxTransformationMatrix ) : pass def nodebase ( self ) : return ( OpenMayaMPx . MPxTransform , ) def _make_node_matrix ( self ) : return OpenMayaMPx . asMPxPtr ( TransformMatrix ( ) ) def register ( self , fnplugin , typename , typeid , create , init ) : fnplugin . registerTransform ( typename , typeid , create , init , self . _make_node_matrix , self . xform_typeid ) def deregister ( self , fnplugin , typeid ) : fnplugin . deregisterNode ( typeid ) NT_TRANSFORMNODE = _TransformNode ( ) def create_attrmaker ( attrspec , ln , sn , affectors = ( ) , default = None , transformer = None , fields = ( ) ) : if not attrspec . allow_fields ( ) and fields : raise RuntimeError ( '' % attrspec ) def createattr ( nodeclass ) : fnattr = attrspec . createfnattr ( ) attrobj = attrspec . create ( fnattr , ln , sn ) for name , value in fields : ", "answer": "fnattr . addField ( name , value )"}, {"prompt": " \"\"\"\"\"\" import os import re import subprocess import time import tempfile import sqlite3 from xml . dom import minidom from glob import glob import FoundationPlist import munkicommon import munkistatus import utils class AdobeInstallProgressMonitor ( object ) : \"\"\"\"\"\" def __init__ ( self , kind = '' , operation = '' ) : '''''' self . kind = kind self . operation = operation self . payload_count = { } def get_current_log ( self ) : '''''' logpath = '' proc = subprocess . Popen ( [ '' , '' , logpath ] , bufsize = - , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) ( output , dummy_err ) = proc . communicate ( ) if output : firstitem = str ( output ) . splitlines ( ) [ ] if firstitem . endswith ( \"\" ) : return os . path . join ( logpath , firstitem ) return None def info ( self ) : '''''' last_adobecode = \"\" logfile = self . get_current_log ( ) if logfile : if self . kind in [ '' , '' ] : regex = r'' elif self . kind in [ '' , '' ] : if self . operation == '' : regex = r'' else : regex = r'' else : if self . operation == '' : regex = r'' else : regex = r'' cmd = [ '' , '' , regex , logfile ] proc = subprocess . Popen ( cmd , bufsize = - , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) ( output , dummy_err ) = proc . communicate ( ) if output : lines = str ( output ) . splitlines ( ) completed_payloads = len ( lines ) if ( not logfile in self . payload_count or completed_payloads > self . payload_count [ logfile ] ) : self . payload_count [ logfile ] = completed_payloads regex = re . compile ( r'' ) lines . reverse ( ) for line in lines : m = regex . match ( line ) try : last_adobecode = m . group ( ) break except ( IndexError , AttributeError ) : pass total_completed_payloads = for key in self . payload_count . keys ( ) : total_completed_payloads += self . payload_count [ key ] return ( total_completed_payloads , last_adobecode ) def mountAdobeDmg ( dmgpath ) : \"\"\"\"\"\" mountpoints = [ ] dmgname = os . path . basename ( dmgpath ) proc = subprocess . Popen ( [ '' , '' , dmgpath , '' , '' , '' ] , bufsize = - , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) ( pliststr , err ) = proc . communicate ( ) if err : munkicommon . display_error ( '' % ( err , dmgname ) ) if pliststr : plist = FoundationPlist . readPlistFromString ( pliststr ) for entity in plist [ '' ] : if '' in entity : mountpoints . append ( entity [ '' ] ) return mountpoints def getCS5uninstallXML ( optionXMLfile ) : '''''' xml = '' dom = minidom . parse ( optionXMLfile ) DeploymentInfo = dom . getElementsByTagName ( '' ) if DeploymentInfo : for info_item in DeploymentInfo : DeploymentUninstall = info_item . getElementsByTagName ( '' ) if DeploymentUninstall : deploymentData = DeploymentUninstall [ ] . getElementsByTagName ( '' ) if deploymentData : Deployment = deploymentData [ ] xml += Deployment . toxml ( '' ) return xml def getCS5mediaSignature ( dirpath ) : '''''' payloads_dir = \"\" for ( path , dummy_dirs , dummy_files ) in os . walk ( dirpath ) : if path . endswith ( '' ) : payloads_dir = path if not payloads_dir : return '' setupxml = os . path . join ( payloads_dir , '' ) if os . path . exists ( setupxml ) and os . path . isfile ( setupxml ) : dom = minidom . parse ( setupxml ) setupElements = dom . getElementsByTagName ( '' ) if setupElements : mediaSignatureElements = setupElements [ ] . getElementsByTagName ( '' ) if mediaSignatureElements : element = mediaSignatureElements [ ] elementvalue = '' for node in element . childNodes : elementvalue += node . nodeValue return elementvalue return \"\" def getPayloadInfo ( dirpath ) : '''''' payloadinfo = { } if os . path . isdir ( dirpath ) : proxy_paths = glob ( os . path . join ( dirpath , '' ) ) if proxy_paths : xmlpath = proxy_paths [ ] dom = minidom . parse ( xmlpath ) else : db_path = os . path . join ( dirpath , '' ) if os . path . exists ( db_path ) : conn = sqlite3 . connect ( db_path ) cur = conn . cursor ( ) cur . execute ( \"\" \"\" ) result = cur . fetchone ( ) cur . close ( ) if result : info_xml = result [ ] . encode ( '' ) dom = minidom . parseString ( info_xml ) else : return payloadinfo payload_info = dom . getElementsByTagName ( '' ) if payload_info : installer_properties = payload_info [ ] . getElementsByTagName ( '' ) if installer_properties : properties = installer_properties [ ] . getElementsByTagName ( '' ) for prop in properties : if '' in prop . attributes . keys ( ) : propname = prop . attributes [ '' ] . value . encode ( '' ) propvalue = '' for node in prop . childNodes : propvalue += node . nodeValue if propname == '' : payloadinfo [ '' ] = propvalue if propname == '' : payloadinfo [ '' ] = propvalue if propname == '' : payloadinfo [ '' ] = propvalue installmetadata = payload_info [ ] . getElementsByTagName ( '' ) if installmetadata : totalsizes = installmetadata [ ] . getElementsByTagName ( '' ) if totalsizes : installsize = '' for node in totalsizes [ ] . childNodes : installsize += node . nodeValue payloadinfo [ '' ] = int ( installsize ) / return payloadinfo def getAdobeSetupInfo ( installroot ) : '''''' info = { } payloads = [ ] for ( path , dummy_dirs , dummy_files ) in os . walk ( installroot ) : if path . endswith ( '' ) : driverfolder = '' mediaSignature = '' setupxml = os . path . join ( path , '' ) if os . path . exists ( setupxml ) : dom = minidom . parse ( setupxml ) drivers = dom . getElementsByTagName ( '' ) if drivers : driver = drivers [ ] if '' in driver . attributes . keys ( ) : driverfolder = driver . attributes [ '' ] . value . encode ( '' ) if driverfolder == '' : setupElements = dom . getElementsByTagName ( '' ) if setupElements : mediaSignatureElements = setupElements [ ] . getElementsByTagName ( '' ) if mediaSignatureElements : element = mediaSignatureElements [ ] for node in element . childNodes : mediaSignature += node . nodeValue for item in munkicommon . listdir ( path ) : payloadpath = os . path . join ( path , item ) payloadinfo = getPayloadInfo ( payloadpath ) if payloadinfo : payloads . append ( payloadinfo ) if ( ( driverfolder and item == driverfolder ) or ( mediaSignature and payloadinfo [ '' ] == mediaSignature ) ) : info [ '' ] = payloadinfo [ '' ] info [ '' ] = payloadinfo [ '' ] info [ '' ] = '' if not payloads : for ( path , dummy_dirs , dummy_files ) in os . walk ( installroot ) : if path . endswith ( \"\" ) : for item in munkicommon . listdir ( path ) : if item . find ( \"\" ) == - : itempath = os . path . join ( path , item ) payloadinfo = getPayloadInfo ( itempath ) if payloadinfo : payloads . append ( payloadinfo ) break if payloads : if len ( payloads ) == : info [ '' ] = payloads [ ] [ '' ] info [ '' ] = payloads [ ] [ '' ] else : if not '' in info : info [ '' ] = \"\" if not '' in info : info [ '' ] = \"\" info [ '' ] = payloads installed_size = for payload in payloads : installed_size = installed_size + payload . get ( '' , ) info [ '' ] = installed_size return info def getAdobePackageInfo ( installroot ) : '''''' info = getAdobeSetupInfo ( installroot ) info [ '' ] = \"\" installerxml = os . path . join ( installroot , \"\" ) if os . path . exists ( installerxml ) : description = '' dom = minidom . parse ( installerxml ) installinfo = dom . getElementsByTagName ( \"\" ) if installinfo : packagedescriptions = installinfo [ ] . getElementsByTagName ( \"\" ) if packagedescriptions : prop = packagedescriptions [ ] for node in prop . childNodes : description += node . nodeValue if description : description_parts = description . split ( '' , ) info [ '' ] = description_parts [ ] if len ( description_parts ) > : info [ '' ] = description_parts [ ] else : info [ '' ] = \"\" return info else : installerxml = os . path . join ( installroot , \"\" ) if os . path . exists ( installerxml ) : dom = minidom . parse ( installerxml ) installinfo = dom . getElementsByTagName ( \"\" ) if installinfo : pkgname_elems = installinfo [ ] . getElementsByTagName ( \"\" ) if pkgname_elems : prop = pkgname_elems [ ] pkgname = \"\" for node in prop . childNodes : pkgname += node . nodeValue info [ '' ] = pkgname if not info . get ( '' ) : info [ '' ] = os . path . basename ( installroot ) return info def getXMLtextElement ( dom_node , name ) : '''''' value = None subelements = dom_node . getElementsByTagName ( name ) if subelements : value = '' for node in subelements [ ] . childNodes : value += node . nodeValue return value def parseOptionXML ( option_xml_file ) : '''''' info = { } dom = minidom . parse ( option_xml_file ) installinfo = dom . getElementsByTagName ( '' ) if installinfo : if '' in installinfo [ ] . attributes . keys ( ) : info [ '' ] = installinfo [ ] . attributes [ '' ] . value if '' in installinfo [ ] . attributes . keys ( ) : info [ '' ] = installinfo [ ] . attributes [ '' ] . value info [ '' ] = getXMLtextElement ( installinfo [ ] , '' ) info [ '' ] = getXMLtextElement ( installinfo [ ] , '' ) info [ '' ] = [ ] medias_elements = installinfo [ ] . getElementsByTagName ( '' ) if medias_elements : media_elements = medias_elements [ ] . getElementsByTagName ( '' ) if media_elements : for media in media_elements : product = { } product [ '' ] = getXMLtextElement ( media , '' ) product [ '' ] = getXMLtextElement ( media , '' ) setup_elements = media . getElementsByTagName ( '' ) if setup_elements : mediaSignatureElements = setup_elements [ ] . getElementsByTagName ( '' ) if mediaSignatureElements : product [ '' ] = '' element = mediaSignatureElements [ ] for node in element . childNodes : product [ '' ] += node . nodeValue info [ '' ] . append ( product ) return info def countPayloads ( dirpath ) : '''''' count = for ( path , dummy_dirs , dummy_files ) in os . walk ( dirpath ) : if path . endswith ( \"\" ) : for subitem in munkicommon . listdir ( path ) : subitempath = os . path . join ( path , subitem ) if os . path . isdir ( subitempath ) : count = count + return count def getPercent ( current , maximum ) : '''''' if maximum == : percentdone = - elif current < : percentdone = - elif current > maximum : percentdone = - elif current == maximum : percentdone = else : percentdone = int ( float ( current ) / float ( maximum ) * ) return percentdone def findSetupApp ( dirpath ) : '''''' for ( path , dummy_dirs , dummy_files ) in os . walk ( dirpath ) : if path . endswith ( \"\" ) : setup_path = os . path . join ( path , \"\" , \"\" , \"\" ) if os . path . exists ( setup_path ) : return setup_path return '' def findInstallApp ( dirpath ) : '''''' for ( path , dummy_dirs , dummy_files ) in os . walk ( dirpath ) : if path . endswith ( \"\" ) : setup_path = os . path . join ( path , \"\" , \"\" , \"\" ) if os . path . exists ( setup_path ) : return setup_path return '' def findAdobePatchInstallerApp ( dirpath ) : '''''' for ( path , dummy_dirs , dummy_files ) in os . walk ( dirpath ) : if path . endswith ( \"\" ) : setup_path = os . path . join ( path , \"\" , \"\" , \"\" ) if os . path . exists ( setup_path ) : return setup_path return '' def findAdobeDeploymentManager ( dirpath ) : '''''' for ( path , dummy_dirs , dummy_files ) in os . walk ( dirpath ) : if path . endswith ( \"\" ) : dm_path = os . path . join ( path , \"\" ) if os . path . exists ( dm_path ) : return dm_path return '' secondsToLive = { } def killStupidProcesses ( ) : '''''' stupid_processes = [ \"\" , \"\" , \"\" , \"\" \"\" , \"\" \"\" \"\" ] for procname in stupid_processes : pid = utils . getPIDforProcessName ( procname ) if pid : if not pid in secondsToLive : secondsToLive [ pid ] = else : secondsToLive [ pid ] = secondsToLive [ pid ] - if secondsToLive [ pid ] == : munkicommon . log ( \"\" % ( pid , procname ) ) try : os . kill ( int ( pid ) , ) except OSError : pass del secondsToLive [ pid ] return def runAdobeInstallTool ( cmd , number_of_payloads = , killAdobeAIR = False , payloads = None , kind = \"\" , operation = \"\" ) : '''''' progress_monitor = AdobeInstallProgressMonitor ( kind = kind , operation = operation ) if munkicommon . munkistatusoutput and not number_of_payloads : munkistatus . percent ( - ) proc = subprocess . Popen ( cmd , shell = False , bufsize = , stdin = subprocess . PIPE , stdout = subprocess . PIPE , stderr = subprocess . STDOUT ) old_payload_completed_count = payloadname = \"\" while proc . poll ( ) == None : time . sleep ( ) ( payload_completed_count , adobe_code ) = progress_monitor . info ( ) if payload_completed_count > old_payload_completed_count : old_payload_completed_count = payload_completed_count if adobe_code and payloads : matched_payloads = [ payload for payload in payloads if payload . get ( '' ) == adobe_code ] if matched_payloads : payloadname = matched_payloads [ ] . get ( '' ) else : payloadname = adobe_code payloadinfo = \"\" + payloadname else : payloadinfo = \"\" if number_of_payloads : munkicommon . display_status_minor ( '' % ( payload_completed_count , number_of_payloads , payloadinfo ) ) else : munkicommon . display_status_minor ( '' , payload_completed_count , payloadinfo ) if munkicommon . munkistatusoutput : munkistatus . percent ( getPercent ( payload_completed_count , number_of_payloads ) ) if killAdobeAIR : if ( not munkicommon . getconsoleuser ( ) or munkicommon . getconsoleuser ( ) == u\"\" ) : killStupidProcesses ( ) retcode = proc . poll ( ) output = proc . stdout . readlines ( ) for line in output : line = line . rstrip ( \"\" ) if line . startswith ( \"\" ) : munkicommon . display_error ( line ) if line . startswith ( \"\" ) : if retcode == : try : retcode = int ( line [ : ] ) except ( ValueError , TypeError ) : retcode = - if retcode != and retcode != : munkicommon . display_error ( '' , retcode , adobeSetupError ( retcode ) ) else : if munkicommon . munkistatusoutput : munkistatus . percent ( ) munkicommon . display_status_minor ( '' ) return retcode def runAdobeSetup ( dmgpath , uninstalling = False , payloads = None ) : '''''' munkicommon . display_status_minor ( '' % os . path . basename ( dmgpath ) ) mountpoints = mountAdobeDmg ( dmgpath ) if mountpoints : setup_path = findSetupApp ( mountpoints [ ] ) if setup_path : deploymentfile = None installxml = os . path . join ( mountpoints [ ] , \"\" ) uninstallxml = os . path . join ( mountpoints [ ] , \"\" ) if uninstalling : operation = '' if os . path . exists ( uninstallxml ) : deploymentfile = uninstallxml else : munkicommon . unmountdmg ( mountpoints [ ] ) munkicommon . display_error ( '' , os . path . basename ( dmgpath ) ) return - else : operation = '' if os . path . exists ( installxml ) : deploymentfile = installxml number_of_payloads = countPayloads ( mountpoints [ ] ) munkicommon . display_status_minor ( '' ) adobe_setup = [ setup_path , '' , '' ] if deploymentfile : adobe_setup . append ( '' % deploymentfile ) retcode = runAdobeInstallTool ( adobe_setup , number_of_payloads , payloads = payloads , kind = '' , operation = operation ) else : munkicommon . display_error ( '' % os . path . basename ( dmgpath ) ) retcode = - munkicommon . unmountdmg ( mountpoints [ ] ) return retcode else : munkicommon . display_error ( '' % dmgpath ) return - def writefile ( stringdata , path ) : '''''' try : fileobject = open ( path , mode = '' , buffering = ) print >> fileobject , stringdata . encode ( '' ) fileobject . close ( ) return path except ( OSError , IOError ) : munkicommon . display_error ( \"\" % stringdata ) return \"\" def doAdobeCS5Uninstall ( adobeInstallInfo , payloads = None ) : '''''' uninstallxml = adobeInstallInfo . get ( '' ) if not uninstallxml : munkicommon . display_error ( \"\" ) return - payloadcount = adobeInstallInfo . get ( '' , ) path = os . path . join ( munkicommon . tmpdir ( ) , \"\" ) deploymentFile = writefile ( uninstallxml , path ) if not deploymentFile : return - setupapp = \"\" setup = os . path . join ( setupapp , \"\" ) if not os . path . exists ( setup ) : munkicommon . display_error ( \"\" % setupapp ) return - uninstall_cmd = [ setup , '' , '' , '' , '' % deploymentFile ] munkicommon . display_status_minor ( '' ) return runAdobeInstallTool ( uninstall_cmd , payloadcount , payloads = payloads , kind = '' , operation = '' ) def runAdobeCCPpkgScript ( dmgpath , payloads = None , operation = '' ) : '''''' munkicommon . display_status_minor ( '' % os . path . basename ( dmgpath ) ) mountpoints = mountAdobeDmg ( dmgpath ) if not mountpoints : munkicommon . display_error ( \"\" % dmgpath ) return - deploymentmanager = findAdobeDeploymentManager ( mountpoints [ ] ) if not deploymentmanager : munkicommon . display_error ( '' , os . path . basename ( dmgpath ) ) munkicommon . unmountdmg ( mountpoints [ ] ) return - basepath = os . path . dirname ( deploymentmanager ) preinstall_script = os . path . join ( basepath , \"\" ) if not os . path . exists ( preinstall_script ) : if operation == '' : munkicommon . display_error ( \"\" % dmgpath ) else : munkicommon . display_error ( \"\" % dmgpath ) munkicommon . unmountdmg ( mountpoints [ ] ) return - number_of_payloads = countPayloads ( basepath ) tmpdir = tempfile . mkdtemp ( prefix = '' , dir = '' ) for dir_name in [ '' '' , '' , '' ] : if os . path . isdir ( os . path . join ( basepath , dir_name ) ) : os . symlink ( os . path . join ( basepath , dir_name ) , os . path . join ( tmpdir , dir_name ) ) for dir_name in [ '' , '' ] : realdir = os . path . join ( basepath , dir_name ) if os . path . isdir ( realdir ) : tmpsubdir = os . path . join ( tmpdir , dir_name ) os . mkdir ( tmpsubdir ) for item in munkicommon . listdir ( realdir ) : os . symlink ( os . path . join ( realdir , item ) , os . path . join ( tmpsubdir , item ) ) os_version_tuple = munkicommon . getOsVersion ( as_tuple = True ) if ( os_version_tuple < ( , ) and ( not munkicommon . getconsoleuser ( ) or munkicommon . getconsoleuser ( ) == u\"\" ) ) : loginwindowPID = utils . getPIDforProcessName ( \"\" ) cmd = [ '' , '' , loginwindowPID ] else : cmd = [ ] pkg_dir = os . path . dirname ( os . path . dirname ( basepath ) ) cmd . extend ( [ preinstall_script , pkg_dir , '' , '' ] ) if operation == '' : munkicommon . display_status_minor ( '' ) retcode = runAdobeInstallTool ( cmd , number_of_payloads , killAdobeAIR = True , payloads = payloads , kind = '' , operation = operation ) dummy_result = subprocess . call ( [ \"\" , \"\" , tmpdir ] ) munkicommon . unmountdmg ( mountpoints [ ] ) return retcode def runAdobeCS5AAMEEInstall ( dmgpath , payloads = None ) : '''''' munkicommon . display_status_minor ( '' % os . path . basename ( dmgpath ) ) mountpoints = mountAdobeDmg ( dmgpath ) if not mountpoints : munkicommon . display_error ( \"\" % dmgpath ) return - deploymentmanager = findAdobeDeploymentManager ( mountpoints [ ] ) if deploymentmanager : basepath = os . path . dirname ( deploymentmanager ) number_of_payloads = countPayloads ( basepath ) tmpdir = tempfile . mkdtemp ( prefix = '' , dir = '' ) os . symlink ( os . path . join ( basepath , \"\" ) , os . path . join ( tmpdir , \"\" ) ) os . symlink ( os . path . join ( basepath , \"\" ) , os . path . join ( tmpdir , \"\" ) ) for dir_name in [ '' , '' ] : realdir = os . path . join ( basepath , dir_name ) if os . path . isdir ( realdir ) : tmpsubdir = os . path . join ( tmpdir , dir_name ) os . mkdir ( tmpsubdir ) for item in munkicommon . listdir ( realdir ) : os . symlink ( os . path . join ( realdir , item ) , os . path . join ( tmpsubdir , item ) ) optionXMLfile = os . path . join ( basepath , \"\" ) os_version_tuple = munkicommon . getOsVersion ( as_tuple = True ) if ( os_version_tuple < ( , ) and ( not munkicommon . getconsoleuser ( ) or munkicommon . getconsoleuser ( ) == u\"\" ) ) : loginwindowPID = utils . getPIDforProcessName ( \"\" ) cmd = [ '' , '' , loginwindowPID ] else : cmd = [ ] cmd . extend ( [ deploymentmanager , '' % optionXMLfile , '' % basepath , '' , '' ] ) munkicommon . display_status_minor ( '' ) retcode = runAdobeInstallTool ( cmd , number_of_payloads , killAdobeAIR = True , payloads = payloads , kind = '' , operation = '' ) dummy_result = subprocess . call ( [ \"\" , \"\" , tmpdir ] ) else : munkicommon . display_error ( '' , os . path . basename ( dmgpath ) ) retcode = - munkicommon . unmountdmg ( mountpoints [ ] ) return retcode def runAdobeCS5PatchInstaller ( dmgpath , copylocal = False , payloads = None ) : '''''' munkicommon . display_status_minor ( '' % os . path . basename ( dmgpath ) ) mountpoints = mountAdobeDmg ( dmgpath ) if mountpoints : if copylocal : updatedir = tempfile . mkdtemp ( prefix = '' , dir = '' ) retcode = subprocess . call ( [ \"\" , \"\" , mountpoints [ ] , updatedir ] ) munkicommon . unmountdmg ( mountpoints [ ] ) if retcode : munkicommon . display_error ( '' % dmgpath ) return - dummy_result = subprocess . call ( [ \"\" , dmgpath ] ) else : updatedir = mountpoints [ ] patchinstaller = findAdobePatchInstallerApp ( updatedir ) if patchinstaller : number_of_payloads = countPayloads ( updatedir ) munkicommon . display_status_minor ( '' ) install_cmd = [ patchinstaller , '' , '' ] retcode = runAdobeInstallTool ( install_cmd , number_of_payloads , payloads = payloads , kind = '' , operation = '' ) else : munkicommon . display_error ( \"\" , os . path . basename ( dmgpath ) ) retcode = - if copylocal : dummy_result = subprocess . call ( [ \"\" , \"\" , updatedir ] ) else : munkicommon . unmountdmg ( mountpoints [ ] ) return retcode else : munkicommon . display_error ( '' % dmgpath ) return - def runAdobeUberTool ( dmgpath , pkgname = '' , uninstalling = False , payloads = None ) : '''''' munkicommon . display_status_minor ( '' % os . path . basename ( dmgpath ) ) mountpoints = mountAdobeDmg ( dmgpath ) if mountpoints : installroot = mountpoints [ ] if uninstalling : ubertool = os . path . join ( installroot , pkgname , \"\" ) else : ubertool = os . path . join ( installroot , pkgname , \"\" ) if os . path . exists ( ubertool ) : info = getAdobePackageInfo ( installroot ) packagename = info [ '' ] action = \"\" operation = \"\" if uninstalling : action = \"\" operation = \"\" munkicommon . display_status_major ( '' % ( action , packagename ) ) if munkicommon . munkistatusoutput : munkistatus . detail ( '' % os . path . basename ( ubertool ) ) number_of_payloads = countPayloads ( installroot ) retcode = runAdobeInstallTool ( [ ubertool ] , number_of_payloads , killAdobeAIR = True , payloads = payloads , kind = '' , operation = operation ) else : munkicommon . display_error ( \"\" % ubertool ) retcode = - munkicommon . unmountdmg ( installroot ) return retcode else : munkicommon . display_error ( \"\" % dmgpath ) return - def findAcrobatPatchApp ( dirpath ) : '''''' for ( path , dummy_dirs , dummy_files ) in os . walk ( dirpath ) : if path . endswith ( \"\" ) : patch_script_path = os . path . join ( path , '' , '' , '' ) if os . path . exists ( patch_script_path ) : return path return '' def updateAcrobatPro ( dmgpath ) : \"\"\"\"\"\" if munkicommon . munkistatusoutput : munkistatus . percent ( - ) munkicommon . display_status_minor ( '' % os . path . basename ( dmgpath ) ) mountpoints = mountAdobeDmg ( dmgpath ) if mountpoints : installroot = mountpoints [ ] pathToAcrobatPatchApp = findAcrobatPatchApp ( installroot ) else : munkicommon . display_error ( \"\" % dmgpath ) return - if not pathToAcrobatPatchApp : munkicommon . display_error ( '' , pathToAcrobatPatchApp ) munkicommon . unmountdmg ( installroot ) return - resourcesDir = os . path . join ( pathToAcrobatPatchApp , '' , '' ) ApplyOperation = os . path . join ( resourcesDir , '' ) callingScriptPath = os . path . join ( resourcesDir , '' ) appList = [ ] appListFile = os . path . join ( resourcesDir , '' ) if os . path . exists ( appListFile ) : fileobj = open ( appListFile , mode = '' , buffering = - ) if fileobj : for line in fileobj . readlines ( ) : appList . append ( line ) fileobj . close ( ) if not appList : munkicommon . display_error ( '' ) munkicommon . unmountdmg ( installroot ) return - payloadNum = - for line in appList : payloadNum = payloadNum + if munkicommon . munkistatusoutput : munkistatus . percent ( getPercent ( payloadNum + , len ( appList ) + ) ) ( appname , status ) = line . split ( \"\" ) munkicommon . display_status_minor ( '' % appname ) pathname = os . path . join ( \"\" , appname ) if os . path . exists ( pathname ) : item = { } item [ '' ] = pathname candidates = [ item ] else : candidates = [ item for item in munkicommon . getAppData ( ) if item [ '' ] . endswith ( '' + appname ) ] if len ( candidates ) == : if status == \"\" : continue else : munkicommon . display_error ( \"\" \"\" \"\" % appname ) munkicommon . unmountdmg ( installroot ) return - if len ( candidates ) > : munkicommon . display_error ( \"\" \"\" \"\" % appname ) munkicommon . unmountdmg ( installroot ) return - munkicommon . display_status_minor ( '' % appname ) apppath = os . path . dirname ( candidates [ ] [ \"\" ] ) cmd = [ ApplyOperation , apppath , appname , resourcesDir , callingScriptPath , str ( payloadNum ) ] proc = subprocess . Popen ( cmd , shell = False , bufsize = - , stdin = subprocess . PIPE , stdout = subprocess . PIPE , stderr = subprocess . STDOUT ) while proc . poll ( ) == None : time . sleep ( ) retcode = proc . poll ( ) if retcode != : munkicommon . display_error ( '' , appname , retcode ) break else : munkicommon . display_status_minor ( '' , appname ) munkicommon . display_status_minor ( '' ) if munkicommon . munkistatusoutput : munkistatus . percent ( ) munkicommon . unmountdmg ( installroot ) return retcode def getBundleInfo ( path ) : \"\"\"\"\"\" infopath = os . path . join ( path , \"\" , \"\" ) if not os . path . exists ( infopath ) : infopath = os . path . join ( path , \"\" , \"\" ) if os . path . exists ( infopath ) : try : plist = FoundationPlist . readPlist ( infopath ) return plist except FoundationPlist . NSPropertyListSerializationException : pass return None def getAdobeInstallInfo ( installdir ) : '''''' adobeInstallInfo = { } if installdir : adobeInstallInfo [ '' ] = getCS5mediaSignature ( installdir ) adobeInstallInfo [ '' ] = countPayloads ( installdir ) optionXMLfile = os . path . join ( installdir , \"\" ) if os . path . exists ( optionXMLfile ) : adobeInstallInfo [ '' ] = getCS5uninstallXML ( optionXMLfile ) return adobeInstallInfo def getAdobeCatalogInfo ( mountpoint , pkgname = \"\" ) : '''''' deploymentmanager = findAdobeDeploymentManager ( mountpoint ) if deploymentmanager : dirpath = os . path . dirname ( deploymentmanager ) option_xml_file = os . path . join ( dirpath , '' ) option_xml_info = { } if os . path . exists ( option_xml_file ) : option_xml_info = parseOptionXML ( option_xml_file ) cataloginfo = getAdobePackageInfo ( dirpath ) if cataloginfo : if option_xml_info . get ( '' ) == u'' : cataloginfo [ '' ] = option_xml_info . get ( '' , '' ) cataloginfo [ '' ] = cataloginfo [ '' ] . replace ( '' , '' ) cataloginfo [ '' ] = True cataloginfo [ '' ] = \"\" cataloginfo [ '' ] = \"\" cataloginfo [ '' ] = \"\" mediasignatures = [ item [ '' ] for item in option_xml_info . get ( '' , [ ] ) if '' in item ] else : cataloginfo [ '' ] = cataloginfo [ '' ] . replace ( '' , '' ) cataloginfo [ '' ] = True cataloginfo [ '' ] = \"\" cataloginfo [ '' ] = \"\" cataloginfo [ '' ] = \"\" cataloginfo [ '' ] = getAdobeInstallInfo ( installdir = dirpath ) mediasignature = cataloginfo [ '' ] . get ( \"\" ) mediasignatures = [ mediasignature ] if mediasignatures : uninstalldir = \"\" installs = [ ] for mediasignature in mediasignatures : signaturefile = mediasignature + \"\" filepath = os . path . join ( uninstalldir , signaturefile ) installitem = { } installitem [ '' ] = filepath installitem [ '' ] = '' installs . append ( installitem ) cataloginfo [ '' ] = installs return cataloginfo installapp = findInstallApp ( mountpoint ) if installapp : cataloginfo = { } cataloginfo [ '' ] = \"\" return cataloginfo installapp = findAdobePatchInstallerApp ( mountpoint ) if os . path . exists ( installapp ) : cataloginfo = getAdobePackageInfo ( mountpoint ) if cataloginfo : cataloginfo [ '' ] = cataloginfo [ '' ] . replace ( '' , '' ) cataloginfo [ '' ] = False cataloginfo [ '' ] = \"\" if pkgname : cataloginfo [ '' ] = pkgname installs = [ ] uninstalldir = \"\" for payload in cataloginfo . get ( '' , [ ] ) : if ( payload . get ( '' , '' ) == cataloginfo [ '' ] ) : if '' in payload : dbfile = payload [ '' ] + \"\" filepath = os . path . join ( uninstalldir , dbfile ) installitem = { } installitem [ '' ] = filepath installitem [ '' ] = '' installs . append ( installitem ) break if installs == [ ] : for payload in cataloginfo . get ( '' , [ ] ) : if '' in payload : if ( \"\" in payload . get ( \"\" ) or \"\" in payload . get ( \"\" ) ) : continue dbfile = payload [ '' ] + \"\" filepath = os . path . join ( uninstalldir , dbfile ) installitem = { } installitem [ '' ] = filepath installitem [ '' ] = '' installs . append ( installitem ) cataloginfo [ '' ] = installs return cataloginfo pkgroot = os . path . join ( mountpoint , pkgname ) adobeinstallxml = os . path . join ( pkgroot , \"\" ) if os . path . exists ( adobeinstallxml ) : cataloginfo = getAdobePackageInfo ( pkgroot ) if cataloginfo : cataloginfo [ '' ] = cataloginfo [ '' ] . replace ( '' , '' ) cataloginfo [ '' ] = True cataloginfo [ '' ] = \"\" cataloginfo [ '' ] = \"\" if pkgname : cataloginfo [ '' ] = pkgname return cataloginfo setuppath = findSetupApp ( mountpoint ) if setuppath : cataloginfo = getAdobeSetupInfo ( mountpoint ) if cataloginfo : cataloginfo [ '' ] = cataloginfo [ '' ] . replace ( '' , '' ) cataloginfo [ '' ] = \"\" if cataloginfo . get ( '' ) == \"\" : cataloginfo [ '' ] = True cataloginfo [ '' ] = \"\" else : cataloginfo [ '' ] = \"\" cataloginfo [ '' ] = False cataloginfo [ '' ] = [ \"\" ] return cataloginfo acrobatpatcherapp = findAcrobatPatchApp ( mountpoint ) if acrobatpatcherapp : cataloginfo = { } cataloginfo [ '' ] = \"\" cataloginfo [ '' ] = False plist = getBundleInfo ( acrobatpatcherapp ) cataloginfo [ '' ] = munkicommon . getVersionString ( plist ) cataloginfo [ '' ] = \"\" cataloginfo [ '' ] = \"\" cataloginfo [ '' ] = [ \"\" ] cataloginfo [ '' ] = '' cataloginfo [ '' ] = [ ] cataloginfo [ '' ] = [ { '' : '' , '' : '' , '' : cataloginfo [ '' ] , '' : '' , '' : '' } ] return cataloginfo return None def adobeSetupError ( errorcode ) : '''''' errormessage = { : \"\" , : \"\" , : \"\" , : \"\" , : \"\" , : \"\" , : \"\" , ", "answer": " : \"\" ,"}, {"prompt": " import numpy as np from sklearn . externals import six from . fixes import in1d , bincount def compute_class_weight ( class_weight , classes , y ) : \"\"\"\"\"\" from sklearn . preprocessing import LabelEncoder if class_weight is None or len ( class_weight ) == : weight = np . ones ( classes . shape [ ] , dtype = np . float64 , order = '' ) elif class_weight == '' : le = LabelEncoder ( ) y_ind = le . fit_transform ( y ) if not all ( np . in1d ( classes , le . classes_ ) ) : raise ValueError ( \"\" ) recip_freq = / bincount ( y_ind ) weight = recip_freq [ le . transform ( classes ) ] / np . mean ( recip_freq ) else : weight = np . ones ( classes . shape [ ] , dtype = np . float64 , order = '' ) if not isinstance ( class_weight , dict ) : raise ValueError ( \"\" \"\" % class_weight ) for c in class_weight : i = np . searchsorted ( classes , c ) if classes [ i ] != c : raise ValueError ( \"\" % c ) ", "answer": "else :"}, {"prompt": " \"\"\"\"\"\" import logging import time from google . appengine . api import apiproxy_stub from google . appengine . api import memcache from google . appengine . api . memcache import memcache_service_pb from google . appengine . runtime import apiproxy_errors MemcacheSetResponse = memcache_service_pb . MemcacheSetResponse MemcacheSetRequest = memcache_service_pb . MemcacheSetRequest MemcacheIncrementRequest = memcache_service_pb . MemcacheIncrementRequest MemcacheIncrementResponse = memcache_service_pb . MemcacheIncrementResponse MemcacheDeleteResponse = memcache_service_pb . MemcacheDeleteResponse MAX_REQUEST_SIZE = << class CacheEntry ( object ) : \"\"\"\"\"\" def __init__ ( self , value , expiration , flags , cas_id , gettime ) : \"\"\"\"\"\" assert isinstance ( value , basestring ) assert len ( value ) <= memcache . MAX_VALUE_SIZE assert isinstance ( expiration , ( int , long ) ) self . _gettime = gettime self . value = value self . flags = flags self . cas_id = cas_id self . created_time = self . _gettime ( ) self . will_expire = expiration != self . locked = False self . _SetExpiration ( expiration ) def _SetExpiration ( self , expiration ) : \"\"\"\"\"\" if expiration > ( * ) : self . expiration_time = expiration else : self . expiration_time = self . _gettime ( ) + expiration def CheckExpired ( self ) : \"\"\"\"\"\" return self . will_expire and self . _gettime ( ) >= self . expiration_time def ExpireAndLock ( self , timeout ) : \"\"\"\"\"\" self . will_expire = True self . locked = True self . _SetExpiration ( timeout ) def CheckLocked ( self ) : \"\"\"\"\"\" return self . locked and not self . CheckExpired ( ) class MemcacheServiceStub ( apiproxy_stub . APIProxyStub ) : \"\"\"\"\"\" def __init__ ( self , gettime = time . time , service_name = '' ) : \"\"\"\"\"\" super ( MemcacheServiceStub , self ) . __init__ ( service_name , max_request_size = MAX_REQUEST_SIZE ) self . _next_cas_id = self . _gettime = lambda : int ( gettime ( ) ) self . _ResetStats ( ) self . _the_cache = { } def _ResetStats ( self ) : \"\"\"\"\"\" self . _hits = self . _misses = self . _byte_hits = ", "answer": "self . _cache_creation_time = self . _gettime ( )"}, {"prompt": " from mako import runtime , filters , cache UNDEFINED = runtime . UNDEFINED __M_dict_builtin = dict __M_locals_builtin = locals _magic_number = _modified_time = _template_filename = '' _template_uri = '' _template_cache = cache . Cache ( __name__ , _modified_time ) ", "answer": "_source_encoding = None"}, {"prompt": " from . read import ReadTestCase , ParameterTypeTestCase from . write import WriteTestCase , DatabaseCommandTestCase from . transaction import AtomicTestCase from . thread_safety import ThreadSafetyTestCase ", "answer": "from . multi_db import MultiDatabaseTestCase"}, {"prompt": " from django . core . management . base import AppCommand , CommandError class Command ( AppCommand ) : ", "answer": "help = \"\""}, {"prompt": " \"\"\"\"\"\" import sys ", "answer": "from oslo_config import cfg"}, {"prompt": " from twisted . internet import defer from . import V2AlphaRestTestCase from synapse . rest . client . v2_alpha import filter from synapse . api . errors import StoreError class FilterTestCase ( V2AlphaRestTestCase ) : USER_ID = \"\" TO_REGISTER = [ filter ] def make_datastore_mock ( self ) : datastore = super ( FilterTestCase , self ) . make_datastore_mock ( ) self . _user_filters = { } def add_user_filter ( user_localpart , definition ) : filters = self . _user_filters . setdefault ( user_localpart , [ ] ) filter_id = len ( filters ) filters . append ( definition ) return defer . succeed ( filter_id ) datastore . add_user_filter = add_user_filter def get_user_filter ( user_localpart , filter_id ) : if user_localpart not in self . _user_filters : raise StoreError ( , \"\" ) filters = self . _user_filters [ user_localpart ] if filter_id >= len ( filters ) : raise StoreError ( , \"\" ) ", "answer": "return defer . succeed ( filters [ filter_id ] )"}, {"prompt": " \"\"\"\"\"\" ", "answer": "from werkzeug . routing import Map , Rule"}, {"prompt": " import os import time from datetime import datetime as dt from datetime import timedelta as delta import math from dogapi import dog_http_api as dog dog . api_key = os . environ . get ( \"\" ) dog . metric ( '' , , host = \"\" ) time . sleep ( ) dog . metric ( '' , , host = \"\" ) now = dt . now ( ) points = [ ] for i in range ( , , - ) : t = time . mktime ( ( now - delta ( minutes = i ) ) . timetuple ( ) ) ", "answer": "points . append ( ( t , math . cos ( i ) + ) )"}, {"prompt": " from __future__ import absolute_import , print_function import os import shutil import sys import tempfile import tarfile if sys . version_info . major > : from urllib . request import urlretrieve else : from urllib import urlretrieve ARCHIVE_URL = '' def copy_indexes ( archive ) : extract_dir = os . path . dirname ( archive ) src_dir = os . path . join ( extract_dir , '' ) dst_dir = os . path . expanduser ( '' ) with tarfile . open ( archive , '' ) as tf : tf . extractall ( extract_dir ) if not os . path . exists ( dst_dir ) : os . makedirs ( dst_dir ) for name in os . listdir ( src_dir ) : if name . endswith ( '' ) : ", "answer": "src = os . path . join ( src_dir , name )"}, {"prompt": " \"\"\"\"\"\" import os from datetime import datetime from twisted . trial . unittest import TestCase from twisted . internet . defer import DeferredList from pymon . storage import api class DatabaseSetupTestCase ( TestCase ) : \"\"\"\"\"\" def setUp ( self ) : \"\"\"\"\"\" self . filename = self . mktemp ( ) def test_connectionSchema ( self ) : db = api . getDatabase ( \"\" ) class DatabaseAPITestCase ( TestCase ) : \"\"\"\"\"\" def setUp ( self ) : \"\"\"\"\"\" self . filename = self . mktemp ( ) self . database = api . getDatabase ( \"\" + self . filename ) self . host = u'' self . service = u'' self . events = [ u'' , u'' , u'' , u'' ] self . conn = self . database . connect ( ) def createHostStatus ( self ) : stat = Status ( ) stat . host = self . host stat . service = self . service stat . ok_count = return self . store . add ( stat ) def createHostEvent ( self , transition , datetime ) : ", "answer": "event = Event ( )"}, {"prompt": " import numpy as np from sklearn . cluster import KMeans import logging import sys from collections import namedtuple from . utils import iterate_splits , predict_cluster logger = logging . getLogger ( __name__ ) logger . setLevel ( logging . WARNING ) logger . addHandler ( logging . StreamHandler ( sys . stdout ) ) def eigenvalue_allocation ( num_buckets , eigenvalues ) : \"\"\"\"\"\" D = len ( eigenvalues ) dims_per_bucket = D / num_buckets eigenvalue_product = np . zeros ( num_buckets , dtype = float ) bucket_size = np . zeros ( num_buckets , dtype = int ) permutation = np . zeros ( ( num_buckets , dims_per_bucket ) , dtype = int ) min_non_zero_eigenvalue = np . min ( np . abs ( eigenvalues [ np . nonzero ( eigenvalues ) ] ) ) eigenvalues = eigenvalues / min_non_zero_eigenvalue sorted_inds = np . argsort ( eigenvalues ) [ : : - ] log_eigs = np . log2 ( abs ( eigenvalues ) ) for ind in sorted_inds : eligible = ( bucket_size < dims_per_bucket ) . nonzero ( ) i = eigenvalue_product [ eligible ] . argmin ( ) bucket = eligible [ ] [ i ] eigenvalue_product [ bucket ] = eigenvalue_product [ bucket ] + log_eigs [ ind ] permutation [ bucket , bucket_size [ bucket ] ] = ind bucket_size [ bucket ] += return np . reshape ( permutation , D ) def compute_local_rotations ( data , C , num_buckets ) : \"\"\"\"\"\" logger . info ( '' ) A , mu , count , assignments , residuals = accumulate_covariance_estimators ( data , C ) R , mu = compute_rotations_from_accumulators ( A , mu , count , num_buckets ) logger . info ( '' ) return R , mu , assignments , residuals def accumulate_covariance_estimators ( data , C ) : \"\"\"\"\"\" V = C . shape [ ] N = data . shape [ ] D = data . shape [ ] A = np . zeros ( ( V , D , D ) ) mu = np . zeros ( ( V , D ) ) count = np . zeros ( V , dtype = int ) assignments = np . zeros ( N , dtype = int ) residuals = np . zeros ( ( N , D ) ) for i in xrange ( N ) : d = data [ i ] cluster = predict_cluster ( d , C ) centroid = C [ cluster ] residual = d - centroid assignments [ i ] = cluster mu [ cluster ] += residual count [ cluster ] += A [ cluster ] += np . outer ( residual , residual ) residuals [ i ] = residual return A , mu , count , assignments , residuals def compute_rotations_from_accumulators ( A , mu , count , num_buckets ) : \"\"\"\"\"\" V , D = mu . shape for i in xrange ( V ) : num_points = count [ i ] mu [ i ] /= num_points ", "answer": "cov = ( A [ i ] + A [ i ] . transpose ( ) ) / ( * ( num_points - ) ) - np . outer ( mu [ i ] , mu [ i ] )"}, {"prompt": " from thefuck . utils import replace_argument from thefuck . specific . git import git_support @ git_support def match ( command ) : return ( '' in command . script and '' in command . stderr ) def get_new_command ( command ) : ", "answer": "return replace_argument ( command . script , '' , '' )"}, {"prompt": " \"\"\"\"\"\" import inspect import logging from . . compat import IS_PYTHON3 logger = logging . getLogger ( __name__ ) debug , info , warn = ( logger . debug , logger . info , logger . warning , ) __all__ = ( '' , '' , '' , '' , '' , '' , '' , '' ) def plugin ( cls ) : \"\"\"\"\"\" cls . _nvim_plugin = True predicate = lambda fn : hasattr ( fn , '' ) for _ , fn in inspect . getmembers ( cls , predicate ) : if IS_PYTHON3 : fn . _nvim_bind = False else : fn . im_func . _nvim_bind = False return cls def rpc_export ( rpc_method_name , sync = False ) : \"\"\"\"\"\" def dec ( f ) : f . _nvim_rpc_method_name = rpc_method_name f . _nvim_rpc_sync = sync f . _nvim_bind = True f . _nvim_prefix_plugin_path = False return f return dec def command ( name , nargs = , complete = None , range = None , count = None , bang = False , register = False , sync = False , eval = None ) : \"\"\"\"\"\" def dec ( f ) : f . _nvim_rpc_method_name = '' . format ( name ) f . _nvim_rpc_sync = sync f . _nvim_bind = True f . _nvim_prefix_plugin_path = True opts = { } if range is not None : opts [ '' ] = '' if range is True else str ( range ) elif count : opts [ '' ] = count if bang : opts [ '' ] = '' if register : opts [ '' ] = '' if nargs : opts [ '' ] = nargs if complete : opts [ '' ] = complete if eval : opts [ '' ] = eval f . _nvim_rpc_spec = { '' : '' , '' : name , '' : sync , '' : opts } return f return dec def autocmd ( name , pattern = '' , sync = False , eval = None ) : \"\"\"\"\"\" def dec ( f ) : f . _nvim_rpc_method_name = '' . format ( name , pattern ) f . _nvim_rpc_sync = sync f . _nvim_bind = True f . _nvim_prefix_plugin_path = True opts = { '' : pattern } if eval : opts [ '' ] = eval f . _nvim_rpc_spec = { '' : '' , '' : name , '' : sync , '' : opts } return f return dec def function ( name , range = False , sync = False , eval = None ) : \"\"\"\"\"\" def dec ( f ) : f . _nvim_rpc_method_name = '' . format ( name ) f . _nvim_rpc_sync = sync ", "answer": "f . _nvim_bind = True"}, {"prompt": " from django import template register = template . Library ( ) ", "answer": "@ register . inclusion_tag ( '' )"}, {"prompt": " '''''' import sys , re , json , urllib , urlparse , datetime from resources . lib . libraries import control from resources . lib . libraries import client from resources . lib . libraries import workers class channels : def __init__ ( self ) : self . list = [ ] ; self . items = [ ] self . uk_datetime = self . uk_datetime ( ) self . systime = ( self . uk_datetime ) . strftime ( '' ) self . imdb_by_query = '' self . sky_now_link = '' self . sky_programme_link = '' def get ( self ) : channels = [ ( '' , '' , '' ) , ( '' , '' , '' ) , ( '' , '' , '' ) , ( '' , '' , '' ) , ( '' , '' , '' ) , ( '' , '' , '' ) , ( '' , '' , '' ) , ( '' , '' , '' ) , ( '' , '' , '' ) , ( '' , '' , '' ) , ( '' , '' , '' ) , ( '' , '' , '' ) , ( '' , '' , '' ) , ( '' , '' , '' ) ] threads = [ ] for i in channels : threads . append ( workers . Thread ( self . sky_list , i [ ] , i [ ] , i [ ] ) ) [ i . start ( ) for i in threads ] [ i . join ( ) for i in threads ] threads = [ ] for i in range ( , len ( self . items ) ) : threads . append ( workers . Thread ( self . items_list , self . items [ i ] ) ) [ i . start ( ) for i in threads ] [ i . join ( ) for i in threads ] try : self . list = sorted ( self . list , key = lambda k : k [ '' ] ) except : pass self . channelDirectory ( self . list ) return self . list def sky_list ( self , num , channel , id ) : try : url = self . sky_now_link % id result = client . request ( url , timeout = '' ) result = json . loads ( result ) match = result [ '' ] [ id ] [ ] [ '' ] dt1 = ( self . uk_datetime ) . strftime ( '' ) dt2 = int ( ( self . uk_datetime ) . strftime ( '' ) ) if ( dt2 < ) : dt2 = elif ( dt2 >= and dt2 < ) : dt2 = elif ( dt2 >= and dt2 < ) : dt2 = elif ( dt2 >= ) : dt2 = url = self . sky_programme_link % ( id , str ( dt1 ) , str ( dt2 ) ) result = client . request ( url , timeout = '' ) result = json . loads ( result ) result = result [ '' ] [ id ] result = [ i for i in result if i [ '' ] == match ] [ ] year = result [ '' ] year = re . findall ( '' , year ) [ ] . strip ( ) year = year . encode ( '' ) title = result [ '' ] title = title . replace ( '' % year , '' ) . strip ( ) title = client . replaceHTMLCodes ( title ) title = title . encode ( '' ) self . items . append ( ( title , year , channel , num ) ) except : pass def items_list ( self , i ) : try : url = self . imdb_by_query % ( urllib . quote_plus ( i [ ] ) , i [ ] ) item = client . request ( url , timeout = '' ) item = json . loads ( item ) title = item [ '' ] title = client . replaceHTMLCodes ( title ) title = title . encode ( '' ) year = item [ '' ] year = re . sub ( '' , '' , str ( year ) ) year = year . encode ( '' ) name = '' % ( title , year ) try : name = name . encode ( '' ) except : pass imdb = item [ '' ] if imdb == None or imdb == '' or imdb == '' : raise Exception ( ) imdb = '' + re . sub ( '' , '' , str ( imdb ) ) imdb = imdb . encode ( '' ) poster = item [ '' ] if poster == None or poster == '' or poster == '' : poster = '' if not ( '' in poster or '' in poster ) : poster = '' poster = re . sub ( '' , '' , poster ) poster = poster . encode ( '' ) genre = item [ '' ] if genre == None or genre == '' or genre == '' : genre = '' genre = genre . replace ( '' , '' ) genre = genre . encode ( '' ) duration = item [ '' ] if duration == None or duration == '' or duration == '' : duration = '' duration = re . sub ( '' , '' , str ( duration ) ) duration = duration . encode ( '' ) rating = item [ '' ] if rating == None or rating == '' or rating == '' or rating == '' : rating = '' rating = rating . encode ( '' ) votes = item [ '' ] try : votes = str ( format ( int ( votes ) , '' ) ) except : pass if votes == None or votes == '' or votes == '' : votes = '' votes = votes . encode ( '' ) mpaa = item [ '' ] if mpaa == None or mpaa == '' or mpaa == '' : mpaa = '' mpaa = mpaa . encode ( '' ) director = item [ '' ] if director == None or director == '' or director == '' : director = '' director = director . replace ( '' , '' ) director = re . sub ( r'' , '' , director ) director = '' . join ( director . split ( ) ) director = director . encode ( '' ) writer = item [ '' ] if writer == None or writer == '' or writer == '' : writer = '' writer = writer . replace ( '' , '' ) writer = re . sub ( r'' , '' , writer ) writer = '' . join ( writer . split ( ) ) writer = writer . encode ( '' ) cast = item [ '' ] if cast == None or cast == '' or cast == '' : cast = '' cast = [ x . strip ( ) for x in cast . split ( '' ) if not x == '' ] try : cast = [ ( x . encode ( '' ) , '' ) for x in cast ] except : cast = [ ] if cast == [ ] : cast = '' ", "answer": "plot = item [ '' ]"}, {"prompt": " from django import template from django . contrib . admin . models import LogEntry register = template . Library ( ) class AdminLogNode ( template . Node ) : def __init__ ( self , limit , varname , user ) : self . limit , self . varname , self . user = limit , varname , user def __repr__ ( self ) : return \"\" def render ( self , context ) : if self . user is None : context [ self . varname ] = LogEntry . objects . all ( ) . select_related ( '' , '' ) [ : self . limit ] else : user_id = self . user if not user_id . isdigit ( ) : user_id = context [ self . user ] . id context [ self . varname ] = LogEntry . objects . filter ( user__id__exact = user_id ) . select_related ( '' , '' ) [ : int ( self . limit ) ] ", "answer": "return ''"}, {"prompt": " from __future__ import absolute_import , unicode_literals ", "answer": "from django . apps import AppConfig"}, {"prompt": " \"\"\"\"\"\" ", "answer": "import falcon"}, {"prompt": " from __future__ import print_function import numpy as np from collections import defaultdict from marmot . util . alignments import train_alignments from marmot . util . force_align import Aligner from marmot . representations . representation_generator import RepresentationGenerator from marmot . experiment . import_utils import mk_tmp_dir class AlignmentRepresentationGenerator ( RepresentationGenerator ) : def __init__ ( self , lex_file , align_model = None , src_file = None , tg_file = None , tmp_dir = None ) : tmp_dir = mk_tmp_dir ( tmp_dir ) if align_model is None : if src_file is not None and tg_file is not None : self . align_model = train_alignments ( src_file , tg_file , tmp_dir , align_model = align_model ) else : print ( \"\" ) return else : self . align_model = align_model self . lex_prob = self . get_align_prob ( lex_file ) def get_alignments ( self , src , tg , align_model ) : ", "answer": "alignments = [ [ [ ] for j in range ( len ( tg [ i ] ) ) ] for i in range ( len ( tg ) ) ]"}, {"prompt": " from molly . conf . provider import Provider class BaseFeedsProvider ( Provider ) : pass from rss import RSSFeedsProvider from ical import ICalFeedsProvider ", "answer": "from talks_cam import TalksCamFeedsProvider "}, {"prompt": " \"\"\"\"\"\" import numpy as np import pyart def test_is_vpt ( ) : radar = pyart . testing . make_empty_ppi_radar ( , , ) assert not pyart . util . is_vpt ( radar ) pyart . util . to_vpt ( radar ) assert pyart . util . is_vpt ( radar ) def test_to_vpt ( ) : radar = pyart . testing . make_empty_ppi_radar ( , , ) radar . instrument_parameters = { '' : { '' : np . array ( [ '' ] * ) } } pyart . util . to_vpt ( radar ) assert pyart . util . is_vpt ( radar ) assert radar . nsweeps == assert radar . azimuth [ '' ] [ ] == assert radar . elevation [ '' ] [ ] == assert len ( radar . instrument_parameters [ '' ] [ '' ] ) == radar = pyart . testing . make_empty_ppi_radar ( , , ) radar . instrument_parameters = { '' : { '' : np . array ( [ '' ] * ) } } pyart . util . to_vpt ( radar , False ) assert pyart . util . is_vpt ( radar ) assert radar . nsweeps == assert radar . azimuth [ '' ] [ ] == ", "answer": "assert radar . elevation [ '' ] [ ] == "}, {"prompt": " import os from pprint import pformat from testscenarios import TestWithScenarios from testtools . content import text_content from git_upstream . tests . base import BaseTestCase from git_upstream . tests . base import get_scenarios import_command = __import__ ( \"\" , globals ( ) , locals ( ) , [ '' ] , - ) LocateChangesWalk = import_command . LocateChangesWalk class TestStrategies ( TestWithScenarios , BaseTestCase ) : scenarios = get_scenarios ( os . path . join ( os . path . dirname ( __file__ ) , ", "answer": "\"\" ) )"}, {"prompt": " try : import uwsgidecorators except ImportError : uwsgidecorators = None from nailgun . logger import logger def call_task_manager_async ( klass , func , cluster_id , * args , ** kwargs ) : \"\"\"\"\"\" if uwsgidecorators : logger . debug ( '' , klass . __name__ , func ) ", "answer": "instance = klass ( cluster_id = cluster_id )"}, {"prompt": " from datetime import datetime from django . contrib import admin from django . db import models from django . db . models import permalink , get_model from django . core . cache import cache from django . http import Http404 from django . utils . translation import ugettext_lazy as _ from django . contrib . contenttypes . models import ContentType from django . contrib . contenttypes import generic class LanguageManager ( models . Manager ) : def by_code_or_alias ( self , code ) : \"\"\"\"\"\" if not code : raise Language . DoesNotExist ( \"\" ) lang = cache . get ( '' % code , None ) if lang is None : lang = Language . objects . get ( models . Q ( code = code ) | models . Q ( code_aliases__contains = '' % code ) ) cache . set ( '' % code , lang ) return lang def by_code_or_alias_or_none ( self , code ) : \"\"\"\"\"\" try : return self . by_code_or_alias ( code ) except Language . DoesNotExist : return None def by_code_or_alias_or_404 ( self , code ) : \"\"\"\"\"\" try : return self . by_code_or_alias ( code ) except Language . DoesNotExist : raise Http404 class Language ( models . Model ) : \"\"\"\"\"\" nplural_choices = ( ( , u'' ) , ( , ) , ( , ) , ( , ) , ( , ) , ( , ) , ( , ) ) name = models . CharField ( _ ( '' ) , unique = True , max_length = , help_text = \"\" ) description = models . CharField ( _ ( '' ) , blank = True , max_length = ) code = models . CharField ( _ ( '' ) , unique = True , max_length = , help_text = ( \"\" \"\" ) ) code_aliases = models . CharField ( _ ( '' ) , max_length = , help_text = ( \"\" ) , null = True , blank = True , default = '' ) specialchars = models . CharField ( _ ( \"\" ) , max_length = , help_text = _ ( \"\" \"\" ) , blank = True ) nplurals = models . SmallIntegerField ( _ ( \"\" ) , default = , choices = nplural_choices ) pluralequation = models . CharField ( _ ( \"\" ) , max_length = , blank = True ) rule_zero = models . CharField ( _ ( \"\" ) , max_length = , blank = True , null = True ) rule_one = models . CharField ( _ ( \"\" ) , max_length = , blank = True , null = True ) rule_two = models . CharField ( _ ( \"\" ) , max_length = , blank = True , null = True ) rule_few = models . CharField ( _ ( \"\" ) , max_length = , blank = True , null = True ) rule_many = models . CharField ( _ ( \"\" ) , max_length = , blank = True , null = True ) rule_other = models . CharField ( _ ( \"\" ) , max_length = , blank = False , null = False , default = \"\" ) objects = LanguageManager ( ) def __unicode__ ( self ) : return u'' % ( self . name , self . code ) class Meta : verbose_name = _ ( '' ) verbose_name_plural = _ ( '' ) db_table = '' ordering = ( '' , ) def save ( self , * args , ** kwargs ) : if not self . code_aliases . startswith ( '' ) : self . code_aliases = '' % self . code_aliases if not self . code_aliases . endswith ( '' ) : self . code_aliases = '' % self . code_aliases super ( Language , self ) . save ( * args , ** kwargs ) def get_rule_name_from_num ( self , num ) : if num == : return '' elif num == : return '' elif num == : return '' elif num == : return '' elif num == : return '' elif num == : ", "answer": "return ''"}, {"prompt": " from . provider import OSFStorageProvider ", "answer": "__version__ = OSFStorageProvider . __version__ "}, {"prompt": " from distutils . core import setup from distutils . extension import Extension try : from Cython . Build import cythonize import numpy except ImportError : print \"\" import sys sys . exit ( ) setup ( ext_modules = cythonize ( Extension ( '' , ", "answer": "sources = ["}, {"prompt": " import posixpath import re from oauthlib import oauth1 from oslo_config import cfg from oslo_log import log as oslo_logging from six . moves . urllib import error from six . moves . urllib import request from cloudbaseinit . metadata . services import base from cloudbaseinit . utils import x509constants opts = [ cfg . StrOpt ( '' , default = None , help = '' ) , cfg . StrOpt ( '' , default = \"\" , help = '' ) , cfg . StrOpt ( '' , default = \"\" , help = '' ) , cfg . StrOpt ( '' , default = \"\" , help = '' ) , cfg . StrOpt ( '' , default = \"\" , help = '' ) , ] CONF = cfg . CONF CONF . register_opts ( opts ) LOG = oslo_logging . getLogger ( __name__ ) class _Realm ( str ) : def __bool__ ( self ) : return True __nonzero__ = __bool__ class MaaSHttpService ( base . BaseMetadataService ) : _METADATA_2012_03_01 = '' def __init__ ( self ) : super ( MaaSHttpService , self ) . __init__ ( ) self . _enable_retry = True self . _metadata_version = self . _METADATA_2012_03_01 def load ( self ) : super ( MaaSHttpService , self ) . load ( ) if not CONF . maas_metadata_url : LOG . debug ( '' ) else : try : self . _get_cache_data ( '' % self . _metadata_version ) return True except Exception as ex : LOG . exception ( ex ) LOG . debug ( '' % CONF . maas_metadata_url ) return False def _get_response ( self , req ) : try : return request . urlopen ( req ) except error . HTTPError as ex : if ex . code == : ", "answer": "raise base . NotExistingMetadataException ( )"}, {"prompt": " from __future__ import unicode_literals from django . db import models , migrations class Migration ( migrations . Migration ) : dependencies = [ ( '' , '' ) , ] operations = [ migrations . CreateModel ( name = '' , fields = [ ( '' , models . AutoField ( verbose_name = '' , serialize = False , auto_created = True , primary_key = True ) ) , ( '' , models . CharField ( db_index = True , max_length = , null = True , verbose_name = '' , blank = True ) ) , ( '' , models . ForeignKey ( related_name = '' , verbose_name = '' , to = '' ) ) , ] , options = { '' : '' , '' : '' , } , bases = ( models . Model , ) , ) , migrations . CreateModel ( name = '' , fields = [ ( '' , models . AutoField ( verbose_name = '' , serialize = False , auto_created = True , primary_key = True ) ) , ( '' , models . BooleanField ( default = False , verbose_name = '' ) ) , ( '' , models . ForeignKey ( related_name = '' , verbose_name = '' , to = '' ) ) , ] , options = { '' : '' , '' : '' , } , bases = ( models . Model , ) , ) , migrations . CreateModel ( name = '' , fields = [ ( '' , models . AutoField ( verbose_name = '' , serialize = False , auto_created = True , primary_key = True ) ) , ( '' , models . CharField ( help_text = '' '' , unique = True , max_length = , verbose_name = '' ) ) , ( '' , models . CharField ( max_length = , verbose_name = '' ) ) , ( '' , models . CharField ( help_text = '' , max_length = , null = True , verbose_name = '' , blank = True ) ) , ( '' , models . TextField ( help_text = '' '' , null = True , verbose_name = '' , blank = True ) ) , ( '' , models . CharField ( blank = True , max_length = , verbose_name = '' , choices = [ ( '' , '' ) , ( '' , '' ) , ( '' , '' ) ] ) ) , ] , options = { '' : ( '' , ) , '' : '' , '' : '' , } , bases = ( models . Model , ) , ", "answer": ") ,"}, {"prompt": " import os class LibdocOutput ( object ) : def __init__ ( self , output_path , format ) : ", "answer": "self . _output_path = output_path"}, {"prompt": " '''''' from __future__ import absolute_import import sys import salt . utils def __virtual__ ( ) : '''''' return '' in __salt__ def _get_mysql_error ( ) : '''''' return sys . modules [ __salt__ [ '' ] . __module__ ] . __context__ . pop ( '' , None ) def present ( name , host = '' , password = None , password_hash = None , allow_passwordless = False , unix_socket = False , password_column = '' , ** connection_args ) : '''''' ret = { '' : name , '' : { } , '' : True , '' : '' . format ( name , host ) } passwordless = not any ( ( password , password_hash ) ) if passwordless : if not salt . utils . is_true ( allow_passwordless ) : ret [ '' ] = '' '' ret [ '' ] = False return ret else : if __salt__ [ '' ] ( name , host , passwordless = True , unix_socket = unix_socket , password_column = password_column , ** connection_args ) : ret [ '' ] += '' return ret ", "answer": "else :"}, {"prompt": " from redis_cache . backends . single import RedisCache from redis_cache . backends . multiple import ShardedRedisCache ", "answer": "from redis_cache . backends . dummy import RedisDummyCache "}, {"prompt": " import codecs import os import rethinkdb as r import db . init_db import db . plugins import db . util import tags def main ( ) : conn = r . connect ( ) try : r . db_create ( '' ) . run ( conn ) except r . RqlRuntimeError : pass conn . use ( '' ) db . init_db . ensure_tables_and_indices ( ) def read_file ( filename ) : full_path = os . path . join ( os . path . dirname ( __file__ ) , filename ) with codecs . open ( full_path , encoding = '' , mode = '' ) as f : return f . read ( ) ctrlp_readme = read_file ( '' ) youcompleteme_readme = read_file ( '' ) db . plugins . insert ( [ { '' : '' , '' : '' , '' : '' , '' : , '' : '' , '' : ctrlp_readme , '' : , ", "answer": "'' : '' ,"}, {"prompt": " import copy import mock from oslotest import base as test_base from ec2api . api import common from ec2api . api import ec2utils from ec2api . api import route_table as route_table_api from ec2api import exception from ec2api . tests . unit import base from ec2api . tests . unit import fakes from ec2api . tests . unit import matchers from ec2api . tests . unit import tools class RouteTableTestCase ( base . ApiTestCase ) : def test_route_table_create ( self ) : self . set_mock_db_items ( fakes . DB_VPC_1 ) self . db_api . add_item . side_effect = ( tools . get_db_api_add_item ( fakes . ID_EC2_ROUTE_TABLE_1 ) ) resp = self . execute ( '' , { '' : fakes . ID_EC2_VPC_1 } ) self . assertThat ( resp [ '' ] , matchers . DictMatches ( tools . purge_dict ( fakes . EC2_ROUTE_TABLE_1 , ( '' , ) ) ) ) self . db_api . add_item . assert_called_once_with ( mock . ANY , '' , { '' : fakes . ID_EC2_VPC_1 , '' : [ { '' : fakes . CIDR_VPC_1 , '' : None } ] } ) self . db_api . get_item_by_id . assert_called_once_with ( mock . ANY , fakes . ID_EC2_VPC_1 ) def test_route_table_create_invalid_parameters ( self ) : self . set_mock_db_items ( ) self . assert_execution_error ( '' , '' , { '' : fakes . ID_EC2_VPC_1 } ) @ mock . patch ( '' ) def test_create_route ( self , routes_updater ) : self . set_mock_db_items ( fakes . DB_ROUTE_TABLE_1 , fakes . DB_ROUTE_TABLE_2 , fakes . DB_VPC_1 , fakes . DB_IGW_1 , fakes . DB_VPN_GATEWAY_1 , fakes . DB_NETWORK_INTERFACE_1 , fakes . DB_NETWORK_INTERFACE_2 ) def do_check ( params , route_table , rollback_route_table_state , update_target = route_table_api . HOST_TARGET ) : resp = self . execute ( '' , params ) self . assertEqual ( True , resp [ '' ] ) self . db_api . update_item . assert_called_once_with ( mock . ANY , route_table ) routes_updater . assert_called_once_with ( mock . ANY , mock . ANY , route_table , update_target = update_target ) self . db_api . update_item . reset_mock ( ) routes_updater . reset_mock ( ) route_table = copy . deepcopy ( fakes . DB_ROUTE_TABLE_1 ) route_table [ '' ] . append ( { '' : fakes . ID_EC2_IGW_1 , '' : '' } ) do_check ( { '' : fakes . ID_EC2_ROUTE_TABLE_1 , '' : '' , '' : fakes . ID_EC2_IGW_1 } , route_table , fakes . DB_ROUTE_TABLE_1 ) route_table = copy . deepcopy ( fakes . DB_ROUTE_TABLE_1 ) route_table [ '' ] . append ( { '' : fakes . ID_EC2_VPN_GATEWAY_1 , '' : '' } ) do_check ( { '' : fakes . ID_EC2_ROUTE_TABLE_1 , '' : '' , '' : fakes . ID_EC2_VPN_GATEWAY_1 } , route_table , fakes . DB_ROUTE_TABLE_1 , update_target = route_table_api . VPN_TARGET ) route_table = copy . deepcopy ( fakes . DB_ROUTE_TABLE_1 ) route_table [ '' ] . append ( { '' : fakes . ID_EC2_NETWORK_INTERFACE_1 , '' : '' } ) do_check ( { '' : fakes . ID_EC2_ROUTE_TABLE_1 , '' : '' , '' : fakes . ID_EC2_NETWORK_INTERFACE_1 } , route_table , fakes . DB_ROUTE_TABLE_1 ) route_table = copy . deepcopy ( fakes . DB_ROUTE_TABLE_1 ) route_table [ '' ] . append ( { '' : fakes . ID_EC2_NETWORK_INTERFACE_2 , '' : '' } ) do_check ( { '' : fakes . ID_EC2_ROUTE_TABLE_1 , '' : '' , '' : fakes . ID_EC2_INSTANCE_1 } , route_table , fakes . DB_ROUTE_TABLE_1 ) do_check ( { '' : fakes . ID_EC2_ROUTE_TABLE_2 , '' : fakes . CIDR_EXTERNAL_NETWORK , '' : fakes . ID_EC2_INSTANCE_1 } , fakes . DB_ROUTE_TABLE_2 , fakes . DB_ROUTE_TABLE_2 ) do_check ( { '' : fakes . ID_EC2_ROUTE_TABLE_2 , '' : '' , '' : fakes . ID_EC2_IGW_1 } , fakes . DB_ROUTE_TABLE_2 , fakes . DB_ROUTE_TABLE_2 ) def test_create_route_invalid_parameters ( self ) : id_ec2_eni_vpc_2 = fakes . random_ec2_id ( '' ) eni_vpc_2 = fakes . gen_db_network_interface ( id_ec2_eni_vpc_2 , fakes . random_os_id ( ) , fakes . ID_EC2_VPC_2 , fakes . random_ec2_id ( '' ) , '' , instance_id = fakes . ID_EC2_INSTANCE_2 ) eni_2_in_instance_1 = fakes . gen_db_network_interface ( fakes . random_ec2_id ( '' ) , fakes . random_os_id ( ) , fakes . ID_EC2_VPC_1 , fakes . random_ec2_id ( '' ) , '' , instance_id = fakes . ID_EC2_INSTANCE_1 ) self . set_mock_db_items ( fakes . DB_ROUTE_TABLE_1 , fakes . DB_ROUTE_TABLE_2 , ", "answer": "fakes . DB_VPC_1 , eni_vpc_2 , fakes . DB_IGW_1 , fakes . DB_IGW_2 ,"}, {"prompt": " from __future__ import print_function from nba_py import player ap = player . PlayerList ( ) print ( ap . info ( ) ) ", "answer": "pc = player . PlayerSummary ( '' )"}, {"prompt": " from logging import getLogger ", "answer": "from os . path import splitext , basename"}, {"prompt": " from django . utils . translation import ugettext_lazy as _ from horizon import tabs ", "answer": "class OverviewTab ( tabs . Tab ) :"}, {"prompt": " from synapse . util . logcontext import LoggingContext import synapse . metrics import logging logger = logging . getLogger ( __name__ ) metrics = synapse . metrics . get_metrics_for ( __name__ ) block_timer = metrics . register_distribution ( \"\" , labels = [ \"\" ] ) block_ru_utime = metrics . register_distribution ( \"\" , labels = [ \"\" ] ", "answer": ")"}, {"prompt": " from __future__ import print_function import os import pyrax ", "answer": "pyrax . set_setting ( \"\" , \"\" )"}, {"prompt": " from transifex . projects . models import Project from transifex . teams . models import Team from transifex . txcommon . tests import base class TestTeamModels ( base . BaseTestCase ) : def test_available_teams ( self ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " \"\"\"\"\"\" try : from local import * except ImportError as e : try : from production_heroku import * except ImportError as e : ", "answer": "pass "}, {"prompt": " from __future__ import unicode_literals from django . db import models , migrations class Migration ( migrations . Migration ) : dependencies = [ ", "answer": "( '' , '' ) ,"}, {"prompt": " from __future__ import absolute_import , division , print_function , unicode_literals from itertools import imap from . decorators import ConfigurationSetting from . search_command import SearchCommand class EventingCommand ( SearchCommand ) : \"\"\"\"\"\" def transform ( self , records ) : \"\"\"\"\"\" raise NotImplementedError ( '' ) def _execute ( self , ifile , process ) : SearchCommand . _execute ( self , ifile , self . transform ) class ConfigurationSettings ( SearchCommand . ConfigurationSettings ) : \"\"\"\"\"\" required_fields = ConfigurationSetting ( doc = '''''' ) clear_required_fields = ConfigurationSetting ( doc = '''''' ) retainsevents = ConfigurationSetting ( readonly = True , value = True , doc = '''''' ) maxinputs = ConfigurationSetting ( doc = '''''' ) ", "answer": "type = ConfigurationSetting ( readonly = True , value = '' , doc = '''''' )"}, {"prompt": " from . . import backend as T class Loss ( object ) : def __init__ ( self , model ) : self . model = model self . _calc_loss = None self . updates = [ ] self . _grads = None def get_inputs ( self ) : inputs = self . model . get_formatted_input ( ) return inputs def get_updates ( self ) : return self . model . get_updates ( ) + self . updates def get_activation ( self , ** kwargs ) : return self . model . get_activation ( ** kwargs ) def get_final_input ( self ) : return self . get_inputs ( ) def compute_loss ( self , y , ** kwargs ) : return self . loss ( self . get_activation ( use_dropout = True , ** kwargs ) , y ) def loss ( self , y_pred , y ) : if y_pred . is_sequence ( ) : return T . mean ( self . sequence_loss ( y_pred , y ) ) return self . _loss ( y_pred . get_data ( ) , y ) def sequence_loss ( self , y_pred , y ) : def step ( y_pred_i , y_i ) : return self . _loss ( y_pred_i , y_i ) output , self . updates = T . scan ( step , [ y_pred . get_data ( ) , y ] ) return output def get_parameters ( self ) : return self . model . get_parameters ( ) def __mul__ ( self , x ) : return MulLoss ( self , x ) def __rmul__ ( self , x ) : return MulLoss ( self , x ) def __add__ ( self , x ) : return AddLoss ( self , x ) def __radd__ ( self , x ) : return AddLoss ( self , x ) def __sub__ ( self , x ) : return SubLoss ( self , x ) def __rsub__ ( self , x ) : return SubLoss ( self , x ) def __div__ ( self , x ) : return DivLoss ( self , x ) def __rdiv__ ( self , x ) : return DivLoss ( self , x ) def __str__ ( self ) : return self . __class__ . __name__ class ArithmeticLoss ( Loss ) : def __init__ ( self , left , right ) : self . left , self . right = left , right self . _calc_loss = None def get_activation ( self , ** kwargs ) : return self . left . get_activation ( ** kwargs ) def get_updates ( self ) : updates = self . left . get_updates ( ) if isinstance ( self . right , Loss ) : for update in self . right . get_updates ( ) : if update not in updates : updates . append ( update ) return updates def get_inputs ( self ) : inputs = self . left . get_inputs ( ) if isinstance ( self . right , Loss ) : ", "answer": "for update in self . right . get_inputs ( ) :"}, {"prompt": " from . bundletypes import Coords , Tracks , Listfile , Rotfile , Bundle from . sfminittypes import ( read_rot_file , write_rot_file , read_trans_soln_file , write_trans_soln_file , read_edge_weight_file , write_edge_weight_file , ", "answer": "read_EGs_file , write_EGs_file )"}, {"prompt": " \"\"\"\"\"\" import cgi import cStringIO import email . Utils import logging import mimetypes import os import re import sys import time import traceback from google . appengine . api import users from google . appengine . ext import admin from google . appengine . ext import webapp from google . appengine . ext . appstats import datamodel_pb from google . appengine . ext . appstats import recording from google . appengine . ext . webapp import _template from google . appengine . ext . webapp import util DEBUG = recording . config . DEBUG def _add_billed_ops_to_map ( billed_ops_map , billed_ops_list ) : \"\"\"\"\"\" for billed_op in billed_ops_list : if billed_op . op ( ) not in billed_ops_map : update_me = datamodel_pb . BilledOpProto ( ) update_me . set_op ( billed_op . op ( ) ) update_me . set_num_ops ( ) billed_ops_map [ billed_op . op ( ) ] = update_me update_me = billed_ops_map [ billed_op . op ( ) ] update_me . set_num_ops ( update_me . num_ops ( ) + billed_op . num_ops ( ) ) def _billed_ops_to_str ( billed_ops ) : \"\"\"\"\"\" ops_as_strs = [ ] for op in billed_ops : op_name = datamodel_pb . BilledOpProto . BilledOp_Name ( op . op ( ) ) ops_as_strs . append ( '' % ( op_name , op . num_ops ( ) ) ) return '' . join ( ops_as_strs ) def _as_percentage_of ( cost_micropennies , total_cost_micropennies ) : \"\"\"\"\"\" if total_cost_micropennies == : return return round ( ( float ( cost_micropennies ) / float ( total_cost_micropennies ) ) * , ) def render ( tmplname , data ) : \"\"\"\"\"\" here = os . path . dirname ( __file__ ) tmpl = os . path . join ( here , '' , tmplname ) data [ '' ] = os . environ data [ '' ] = recording . config . SHELL_OK data [ '' ] = os . getenv ( '' ) try : return _template . render ( tmpl , data ) except Exception , err : logging . exception ( '' , tmpl ) return '' % ( tmplname , err ) class AllStatsInfo ( object ) : \"\"\"\"\"\" def __init__ ( self , calls , cost , billed_ops ) : self . calls = calls self . cost = cost self . billed_ops = billed_ops class PathStatsInfo ( object ) : \"\"\"\"\"\" def __init__ ( self , cost , billed_ops , num_requests , most_recent_requests ) : self . cost = cost self . billed_ops = billed_ops self . num_requests = num_requests self . most_recent_requests = most_recent_requests class PivotInfo ( object ) : \"\"\"\"\"\" def __init__ ( self , name , calls , cost , billed_ops , cost_pct ) : self . name = name self . calls = calls self . cost = cost self . billed_ops = billed_ops self . cost_pct = cost_pct def to_list ( self ) : \"\"\"\"\"\" return [ self . name , self . calls , self . cost , self . billed_ops , self . cost_pct ] @ classmethod def from_list ( cls , values ) : return cls ( values [ ] , values [ ] , values [ ] , values [ ] , values [ ] ) class SummaryHandler ( webapp . RequestHandler ) : \"\"\"\"\"\" def get ( self ) : recording . dont_record ( ) if not self . request . path . endswith ( '' ) : self . redirect ( self . request . path + '' ) return summaries = recording . load_summary_protos ( ) data = self . _get_summary_data ( summaries ) self . response . out . write ( render ( '' , data ) ) def _get_summary_data ( self , summaries ) : \"\"\"\"\"\" allstats = { } pathstats = { } pivot_path_rpc = { } pivot_rpc_path = { } total_cost_micropennies = summaries = sorted ( summaries , key = lambda x : ( - x . start_timestamp_milliseconds ( ) ) ) for index , summary in enumerate ( summaries ) : path_key = recording . config . extract_key ( summary ) if path_key not in pathstats : pathstats [ path_key ] = PathStatsInfo ( , { } , , [ index + ] ) else : pathstats_info = pathstats [ path_key ] pathstats_info . num_requests += if len ( pathstats_info . most_recent_requests ) > : if pathstats_info . most_recent_requests [ - ] : pathstats_info . most_recent_requests . append ( ) else : pathstats_info . most_recent_requests . append ( index + ) if path_key not in pivot_path_rpc : pivot_path_rpc [ path_key ] = { } for x in summary . rpc_stats_list ( ) : rpc_key = x . service_call_name ( ) total_calls = x . total_amount_of_calls ( ) cost_micropennies = x . total_cost_of_calls_microdollars ( ) total_cost_micropennies += cost_micropennies pathstats [ path_key ] . cost += cost_micropennies _add_billed_ops_to_map ( pathstats [ path_key ] . billed_ops , x . total_billed_ops_list ( ) ) if rpc_key in allstats : allstats [ rpc_key ] . calls += total_calls allstats [ rpc_key ] . cost += cost_micropennies else : allstats [ rpc_key ] = AllStatsInfo ( total_calls , cost_micropennies , { } ) _add_billed_ops_to_map ( allstats [ rpc_key ] . billed_ops , x . total_billed_ops_list ( ) ) if rpc_key not in pivot_path_rpc [ path_key ] : pivot_path_rpc [ path_key ] [ rpc_key ] = PivotInfo ( rpc_key , , , { } , ) pivot_path_rpc [ path_key ] [ rpc_key ] . calls += total_calls pivot_path_rpc [ path_key ] [ rpc_key ] . cost += cost_micropennies _add_billed_ops_to_map ( pivot_path_rpc [ path_key ] [ rpc_key ] . billed_ops , x . total_billed_ops_list ( ) ) if rpc_key not in pivot_rpc_path : pivot_rpc_path [ rpc_key ] = { } if path_key not in pivot_rpc_path [ rpc_key ] : pivot_rpc_path [ rpc_key ] [ path_key ] = PivotInfo ( path_key , , , { } , ) pivot_rpc_path [ rpc_key ] [ path_key ] . calls += total_calls pivot_rpc_path [ rpc_key ] [ path_key ] . cost += cost_micropennies _add_billed_ops_to_map ( pivot_rpc_path [ rpc_key ] [ path_key ] . billed_ops , x . total_billed_ops_list ( ) ) allstats_by_count = [ ] for k , v in allstats . iteritems ( ) : for path_vals in pivot_rpc_path [ k ] . itervalues ( ) : path_vals . billed_ops = _billed_ops_to_str ( path_vals . billed_ops . itervalues ( ) ) ", "answer": "path_vals . cost_pct = _as_percentage_of ("}, {"prompt": " from __future__ import unicode_literals ", "answer": "default_app_config = '' "}, {"prompt": " import sys import os import re from . exceptions import InvalidCommand from . action import CmdAction from . task import Task from . cmd_run import Run opt_show_all = { '' : '' , '' : '' , '' : '' , '' : bool , '' : False , '' : \"\" , } opt_keep_trace = { '' : '' , '' : '' , '' : bool , '' : False , '' : \"\" , } class Strace ( Run ) : doc_purpose = \"\" doc_usage = \"\" doc_description = \"\"\"\"\"\" cmd_options = ( opt_show_all , opt_keep_trace ) TRACE_CMD = \"\" TRACE_OUT = '' def execute ( self , params , args ) : \"\"\"\"\"\" if os . path . exists ( self . TRACE_OUT ) : os . unlink ( self . TRACE_OUT ) if len ( args ) != : msg = ( '' '' ) raise InvalidCommand ( msg ) result = Run . execute ( self , params , args ) if ( not params [ '' ] ) and os . path . exists ( self . TRACE_OUT ) : os . unlink ( self . TRACE_OUT ) return result def _execute ( self , show_all ) : \"\"\"\"\"\" selected = self . sel_tasks [ ] for task in self . task_list : if task . name == selected : self . wrap_strace ( task ) break report_strace = Task ( '' , actions = [ ( find_deps , [ self . outstream , self . TRACE_OUT , show_all ] ) ] , verbosity = , task_dep = [ selected ] , uptodate = [ False ] , ) self . task_list . append ( report_strace ) self . sel_tasks . append ( report_strace . name ) return Run . _execute ( self , sys . stdout ) @ classmethod def wrap_strace ( cls , task ) : \"\"\"\"\"\" wrapped_actions = [ ] for action in task . actions : if isinstance ( action , CmdAction ) : cmd = cls . TRACE_CMD % ( action . _action , cls . TRACE_OUT ) wrapped = CmdAction ( cmd , task , save_out = action . save_out ) wrapped_actions . append ( wrapped ) else : wrapped_actions . append ( action ) task . _action_instances = wrapped_actions task . _extend_uptodate ( [ False ] ) def find_deps ( outstream , strace_out , show_all ) : \"\"\"\"\"\" regex = re . compile ( r'' + r'' ) read = set ( ) write = set ( ) cwd = os . getcwd ( ) if not os . path . exists ( strace_out ) : return with open ( strace_out ) as text : for line in text : match = regex . match ( line ) if not match : continue rel_name = match . group ( '' ) name = os . path . abspath ( rel_name ) if not show_all : if not name . startswith ( cwd ) : continue if '' in match . group ( '' ) : ", "answer": "if name not in write :"}, {"prompt": " from __future__ import absolute_import import time import logging import collections from tornado import web from tornado import gen from . . views import BaseHandler logger = logging . getLogger ( __name__ ) class ControlHandler ( BaseHandler ) : INSPECT_METHODS = ( '' , '' , '' , '' , '' , '' , '' , '' ) worker_cache = collections . defaultdict ( dict ) @ gen . coroutine def update_cache ( self , workername = None ) : ", "answer": "yield self . update_workers ( workername = workername ,"}, {"prompt": " from sqlalchemy import Column , ForeignKey , Integer , Float , String from sqlalchemy . sql . expression import asc , desc , or_ , and_ from sqlalchemy . orm import aliased from db . database import db_session from db . database import Base from models . users import UsersTable from utils import * class Accounts ( object ) : object = None def __init__ ( self , user_id , user_type = None ) : if not user_type : user_type = '' if UsersTable . query . filter ( and_ ( UsersTable . id == user_id , UsersTable . is_private == True ) ) . first ( ) else '' if user_type == '' : self . object = NormalUserAccounts ( user_id ) else : self . object = PrivateUserAccounts ( user_id ) def __getattr__ ( self , name ) : print \"\" , name , '' , self . object return getattr ( self . object , name ) class AccountsBase ( ) : user_id = None accounts = None accounts_and_loans = None transfers = None alias1 = None alias2 = None transfer = None def __init__ ( self , user_id ) : self . user_id = user_id def get_accounts ( self ) : if not self . accounts : self . accounts = AccountsTable . query . filter ( AccountsTable . user == self . user_id ) . filter ( AccountsTable . type != \"\" ) . order_by ( asc ( AccountsTable . type ) ) . order_by ( asc ( AccountsTable . id ) ) return self . accounts def get_accounts_and_loans ( self ) : if not self . accounts_and_loans : self . accounts_and_loans = AccountsTable . query . filter ( AccountsTable . user == self . user_id ) . filter ( AccountsTable . balance != ) . outerjoin ( ( UsersTable , AccountsTable . name == UsersTable . id ) ) . add_columns ( UsersTable . name , UsersTable . slug ) . order_by ( asc ( AccountsTable . type ) ) . order_by ( asc ( AccountsTable . id ) ) return self . accounts_and_loans def change_account_balance ( self , account_id , amount ) : a = AccountsTable . query . filter ( AccountsTable . id == account_id ) . first ( ) if a : a . balance = float ( amount ) db_session . add ( a ) db_session . commit ( ) def modify_account_balance ( self , account_id , amount ) : a = AccountsTable . query . filter ( AccountsTable . id == account_id ) . first ( ) ", "answer": "if a :"}, {"prompt": " \"\"\"\"\"\" __author__ = '' import logging import json import os import re import time import urllib from viewfinder . backend . base import util , secrets from viewfinder . backend . base . environ import ServerEnvironment from viewfinder . backend . www import www_util from tornado . ioloop import IOLoop from tornado import httpclient , options , web _GOOGLE_OAUTH2_DEVICECODE_URL = '' _GOOGLE_OAUTH2_TOKEN_URL = '' _GOOGLE_OAUTH2_SCOPES = '' '' '' options . define ( '' , '' , help = '' ) options . define ( '' , False , help = '' ) class ScenarioLoginError ( Exception ) : \"\"\"\"\"\" pass class Scenario ( object ) : \"\"\"\"\"\" _http_error_dict = { : '' , : '' , : '' } def __init__ ( self , name , handler , frequency , description = None ) : self . name = name self . handler = handler self . description = description self . frequency = frequency self . _timeout = None def StartLoop ( self , device ) : \"\"\"\"\"\" logger = logging . LoggerAdapter ( logging . getLogger ( ) , { '' : self . name } ) def _OnComplete ( ) : self . _timeout = IOLoop . current ( ) . add_timeout ( time . time ( ) + self . frequency , _RunIteration ) def _OnException ( typ , val , tb ) : if ( typ , val , tb ) != ( None , None , None ) : if typ is web . HTTPError : message = self . _http_error_dict . get ( val . status_code , '' % ( val . status_code , val . log_message ) ) logger . error ( message ) else : logger . error ( '' , self . name , exc_info = ( typ , val , tb ) ) _OnComplete ( ) def _RunIteration ( ) : with util . Barrier ( _OnComplete , _OnException ) as b : self . handler ( device , logger , b . Callback ( ) ) _RunIteration ( ) def StopLoop ( self ) : \"\"\"\"\"\" if self . _timeout is not None : IOLoop . current ( ) . remove_timeout ( self . _timeout ) class ScenarioDevice ( object ) : \"\"\"\"\"\" def __init__ ( self , name ) : self . name = name self . _svc_url = '' % ( ServerEnvironment . GetHost ( ) , options . options . port ) self . _user_cookie = None if options . options . watchdog_auth_reset : self . _ClearAuthentication ( ) else : self . _LoadAuthentication ( ) def SendRequest ( self , service_path , callback , method = '' , ** kwargs ) : \"\"\"\"\"\" if self . _user_cookie is None : raise ScenarioLoginError ( '' % self . name ) http_client = httpclient . AsyncHTTPClient ( ) url = self . _GetUrl ( service_path ) headers = { '' : '' % ( self . _user_cookie ) , ", "answer": "'' : '' }"}, {"prompt": " \"\"\"\"\"\" __version__ = '' import sys , getopt , string , glob , os , traceback , re def _getopt_flags ( options ) : \"\"\"\"\"\" s = [ ] l = [ ] for o in options : if o . prefix == '' : s . append ( o . name ) if o . takes_argument : s . append ( '' ) else : if o . takes_argument : l . append ( o . name + '' ) else : l . append ( o . name ) return string . join ( s , '' ) , l def invisible_input ( prompt = '' ) : \"\"\"\"\"\" import getpass entry = getpass . getpass ( prompt ) if entry is None : raise KeyboardInterrupt return entry def option_dict ( options ) : \"\"\"\"\"\" d = { } for option in options : d [ option . name ] = option return d getpasswd = invisible_input _integerRE = re . compile ( '' ) _integerRangeRE = re . compile ( '' ) def srange ( s , split = string . split , integer = _integerRE , integerRange = _integerRangeRE ) : \"\"\"\"\"\" l = [ ] append = l . append for entry in split ( s , '' ) : m = integer . match ( entry ) if m : append ( int ( m . groups ( ) [ ] ) ) continue m = integerRange . match ( entry ) if m : start , end = map ( int , m . groups ( ) ) l [ len ( l ) : ] = range ( start , end + ) return l class Option : \"\"\"\"\"\" default = None helptext = '' prefix = '' takes_argument = has_default = tab = def __init__ ( self , name , help = None ) : if not name [ : ] == '' : raise TypeError ( '' ) if name [ : ] == '' : self . prefix = '' self . name = name [ : ] else : self . name = name [ : ] if help : self . help = help def __str__ ( self ) : o = self name = o . prefix + o . name if o . takes_argument : name = name + '' if len ( name ) > self . tab : name = name + '' + '' * ( self . tab + + len ( o . prefix ) ) else : name = '' % ( self . tab , name ) description = o . help if o . has_default : description = description + '' % o . default return '' % ( name , description ) class ArgumentOption ( Option ) : \"\"\"\"\"\" def __init__ ( self , name , help = None , default = None ) : Option . __init__ ( self , name , help ) if default is not None : self . default = default self . has_default = self . takes_argument = class SwitchOption ( Option ) : \"\"\"\"\"\" def __init__ ( self , name , help = None , default = None ) : Option . __init__ ( self , name , help ) if default is not None : self . default = default self . has_default = class Application : \"\"\"\"\"\" options = [ ] preset_options = [ SwitchOption ( '' , '' ) , SwitchOption ( '' , '' ) , SwitchOption ( '' , '' ) , SwitchOption ( '' , '' ) , SwitchOption ( '' , '' ) , SwitchOption ( '' , '' ) ] header = '' name = '' synopsis = '' version = '' about = '' examples = '' copyright = ( '' '' '' '' '' ) globbing = debug = verbose = values = None files = None def __init__ ( self , argv = None ) : if argv is None : argv = sys . argv self . filename = os . path . split ( argv [ ] ) [ ] if not self . name : self . name = os . path . split ( self . filename ) [ ] else : self . name = self . name if not self . header : self . header = self . name else : self . header = self . header self . arguments = argv [ : ] self . option_map = option_dict ( self . options ) for option in self . preset_options : if not self . option_map . has_key ( option . name ) : self . add_option ( option ) self . files = [ ] try : rc = self . startup ( ) if rc is not None : raise SystemExit ( rc ) rc = self . parse ( ) if rc is not None : raise SystemExit ( rc ) rc = self . main ( ) if rc is None : rc = except SystemExit , rc : pass except KeyboardInterrupt : print print '' rc = except : print print '' if self . debug : print traceback . print_exc ( ) rc = raise SystemExit ( rc ) def add_option ( self , option ) : \"\"\"\"\"\" self . options . append ( option ) self . option_map [ option . name ] = option def startup ( self ) : \"\"\"\"\"\" return None def exit ( self , rc = ) : \"\"\"\"\"\" raise SystemExit ( rc ) def parse ( self ) : \"\"\"\"\"\" self . values = values = { } for o in self . options : if o . has_default : values [ o . prefix + o . name ] = o . default else : values [ o . prefix + o . name ] = flags , lflags = _getopt_flags ( self . options ) try : optlist , files = getopt . getopt ( self . arguments , flags , lflags ) if self . globbing : l = [ ] for f in files : gf = glob . glob ( f ) if not gf : l . append ( f ) else : l [ len ( l ) : ] = gf files = l self . optionlist = optlist self . files = files + self . files except getopt . error , why : self . help ( why ) sys . exit ( ) rc = self . handle_files ( self . files ) if rc is not None : sys . exit ( rc ) for optionname , value in optlist : try : value = string . atoi ( value ) except ValueError : pass handlername = '' + string . replace ( optionname , '' , '' ) try : handler = getattr ( self , handlername ) except AttributeError : if value == '' : if values . has_key ( optionname ) : values [ optionname ] = values [ optionname ] + else : values [ optionname ] = else : values [ optionname ] = value else : rc = handler ( value ) if rc is not None : raise SystemExit ( rc ) rc = self . check_files ( self . files ) if rc is not None : sys . exit ( rc ) def check_files ( self , filelist ) : \"\"\"\"\"\" return None def help ( self , note = '' ) : self . print_header ( ) if self . synopsis : print '' try : synopsis = self . synopsis % self . name except ( NameError , KeyError , TypeError ) : synopsis = self . synopsis % self . __dict__ print '' + synopsis print self . print_options ( ) if self . version : ", "answer": "print ''"}, {"prompt": " import os import re import pip import sys import urllib from distutils . dir_util import remove_tree from distutils import log as logger try : from setuptools import Command except ImportError : from distutils . core import Command from packaging import package_dir class bdist_prestoadmin ( Command ) : description = '' user_options = [ ( '' , '' , '' ) , ( '' , '' , '' ) , ( '' , None , '' ) , ( '' , '' , '' + '' ) , ( '' , None , '' + '' + '' + '' ) ] default_virtualenv_version = '' def build_wheel ( self , build_dir ) : cmd = self . reinitialize_command ( '' ) cmd . dist_dir = build_dir self . run_command ( '' ) cmd . finalize_options ( ) wheel_name = cmd . get_archive_basename ( ) logger . info ( '' , wheel_name + '' , build_dir ) return wheel_name def generate_install_script ( self , wheel_name , build_dir ) : template = open ( os . path . join ( package_dir , '' ) , '' ) install_script = open ( os . path . join ( build_dir , '' ) , '' ) ", "answer": "if self . online_install :"}, {"prompt": " '''''' import logging logger = logging . getLogger ( __name__ ) import os import threading import urllib import uuid pause_lock = threading . Lock ( ) pause_condition = threading . Condition ( pause_lock ) THREAD_RUNNING = \"\" THREAD_STOP = \"\" THREAD_STOPPING = \"\" THREAD_PAUSE = \"\" THREAD_RESUME = \"\" class InterruptException ( Exception ) : def __init__ ( self , * args ) : super ( self . __class__ , self ) . __init__ ( * args ) class Checkpoint ( object ) : '''''' def __init__ ( self ) : self . state = THREAD_RUNNING def set_state ( self , state ) : with pause_lock : if state == THREAD_RESUME : state = THREAD_RUNNING self . state = state pause_condition . notify_all ( ) def wait ( self ) : with pause_lock : if self . state == THREAD_STOP : raise InterruptException ( ) while self . state == THREAD_PAUSE : pause_condition . wait ( ) exts_that_need_allow_open_files = ( \"\" , \"\" , \"\" , ", "answer": "\"\" , \"\" , \"\" ,"}, {"prompt": " \"\"\"\"\"\" class error ( Exception ) : ", "answer": "\"\"\"\"\"\" "}, {"prompt": " \"\"\"\"\"\" from flash import Flash flash_algo = { '' : , '' : [ , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ] , '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : False } ; class Flash_lpc11u24 ( Flash ) : def __init__ ( self , target ) : super ( Flash_lpc11u24 , self ) . __init__ ( target , flash_algo ) def programPage ( self , flashPtr , bytes ) : write_size = ", "answer": "for i in range ( , ) :"}, {"prompt": " import colorsys black = ( , , ) white = ( , , ) red = ( , , ) green = ( , , ) blue = ( , , ) yellow = ( , , ) cyan = ( , , ) magenta = ( , , ) orange = ( , , ) def gray ( luminance ) : ", "answer": "return ( luminance , luminance , luminance )"}, {"prompt": " from . pointcloud import PointCloud , bounding_box from . mesh import TriMesh , ColouredTriMesh , TexturedTriMesh from . groupops import mean_pointcloud ", "answer": "from . graph import ( UndirectedGraph , DirectedGraph , Tree , PointUndirectedGraph ,"}, {"prompt": " from django . core . urlresolvers import reverse from django . shortcuts import redirect from django . contrib . auth import logout def logout_with_redirect ( request ) : \"\"\"\"\"\" logout ( request ) ", "answer": "return redirect ( reverse ( '' ) ) "}, {"prompt": " import unittest , sys from dash_test_util import * from dashlivesim . dashlib import dash_proxy from dashlivesim . dashlib import mpdprocessor class TestMPDProcessing ( unittest . TestCase ) : \"\" def setUp ( self ) : self . oldBaseUrlState = mpdprocessor . SET_BASEURL mpdprocessor . SET_BASEURL = False def tearDown ( self ) : mpdprocessor . SET_BASEURL = self . oldBaseUrlState def testMPDhandling ( self ) : mpdprocessor . SET_BASEURL = True urlParts = [ '' , '' , '' ] dp = dash_proxy . DashProvider ( \"\" , urlParts , None , VOD_CONFIG_DIR , CONTENT_ROOT , now = ) d = dp . handle_request ( ) self . assertTrue ( d . find ( \"\" ) > ) def testMPDwithChangedAST ( self ) : \"\" testOutputFile = \"\" rm_outfile ( testOutputFile ) urlParts = [ '' , '' , '' , '' ] dp = dash_proxy . DashProvider ( \"\" , urlParts , None , VOD_CONFIG_DIR , CONTENT_ROOT , now = ) d = dp . handle_request ( ) write_data_to_outfile ( d , testOutputFile ) self . assertTrue ( d . find ( '' ) > ) self . assertTrue ( d . find ( '' ) > ) self . assertTrue ( d . find ( '' ) < ) def testMPDwithStartandDur ( self ) : urlParts = [ '' , '' , '' , '' , '' ] dp = dash_proxy . DashProvider ( \"\" , urlParts , None , VOD_CONFIG_DIR , CONTENT_ROOT , now = ) d = dp . handle_request ( ) if dash_proxy . PUBLISH_TIME : self . assertTrue ( d . find ( '' ) > ) self . assertTrue ( d . find ( '' ) > ) def testMPDwithStartand2Durations ( self ) : urlParts = [ '' , '' , '' , '' , '' , '' ] dp = dash_proxy . DashProvider ( \"\" , urlParts , None , VOD_CONFIG_DIR , CONTENT_ROOT , now = ) d = dp . handle_request ( ) if dash_proxy . PUBLISH_TIME : self . assertTrue ( d . find ( '' ) > ) self . assertTrue ( d . find ( '' ) > ) dp = dash_proxy . DashProvider ( \"\" , urlParts , None , VOD_CONFIG_DIR , CONTENT_ROOT , now = ) d = dp . handle_request ( ) if dash_proxy . PUBLISH_TIME : self . assertTrue ( d . find ( '' ) > ) self . assertTrue ( d . find ( '' ) > ) def testHttpsBaseURL ( self ) : \"\" mpdprocessor . SET_BASEURL = True urlParts = [ '' , '' , '' ] is_https = dp = dash_proxy . DashProvider ( \"\" , urlParts , None , VOD_CONFIG_DIR , CONTENT_ROOT , now = , is_https = is_https ) d = dp . handle_request ( ) self . assertTrue ( d . find ( \"\" ) > ) class TestInitSegmentProcessing ( unittest . TestCase ) : def testInit ( self ) : urlParts = [ '' , '' , '' , '' ] dp = dash_proxy . DashProvider ( \"\" , urlParts , None , VOD_CONFIG_DIR , CONTENT_ROOT , now = ) d = dp . handle_request ( ) self . assertEqual ( len ( d ) , ) class TestMediaSegments ( unittest . TestCase ) : def testMediaSegmentForTfdt32 ( self ) : testOutputFile = \"\" rm_outfile ( testOutputFile ) now = segment = \"\" urlParts = [ '' , '' , '' , '' , segment ] dp = dash_proxy . DashProvider ( \"\" , urlParts , None , VOD_CONFIG_DIR , CONTENT_ROOT , now = now ) d = dp . handle_request ( ) write_data_to_outfile ( d , testOutputFile ) self . assertEqual ( len ( d ) , ) def testMediaSegmentTooEarly ( self ) : urlParts = [ '' , '' , '' , '' ] dp = dash_proxy . DashProvider ( \"\" , urlParts , None , VOD_CONFIG_DIR , CONTENT_ROOT , now = ) d = dp . handle_request ( ) self . assertEqual ( d [ '' ] , False ) def testMediaSegmentTooEarlyWithAST ( self ) : urlParts = [ '' , '' , '' , '' , '' ] dp = dash_proxy . DashProvider ( \"\" , urlParts , None , VOD_CONFIG_DIR , CONTENT_ROOT , now = ) d = dp . handle_request ( ) self . assertEqual ( d [ '' ] , False ) dp = dash_proxy . DashProvider ( \"\" , urlParts , None , VOD_CONFIG_DIR , CONTENT_ROOT , now = ) d = dp . handle_request ( ) self . assertEqual ( len ( d ) , ) def testMediaSegmentBeforeTimeShiftBufferDepth ( self ) : now = segment = \"\" % ( ( now - ) / ) urlParts = [ '' , '' , '' , segment ] dp = dash_proxy . DashProvider ( \"\" , urlParts , None , VOD_CONFIG_DIR , CONTENT_ROOT , now = now ) d = dp . handle_request ( ) self . assertEqual ( d [ '' ] , False ) def testLastMediaSegment ( self ) : \"\" urlParts = [ '' , '' , '' , '' , '' , '' , '' ] dp = dash_proxy . DashProvider ( \"\" , urlParts , None , VOD_CONFIG_DIR , CONTENT_ROOT , now = ) d = dp . handle_request ( ) self . assertEqual ( d . find ( \"\" ) , ) ", "answer": "def testMultiPeriod ( self ) :"}, {"prompt": " from pytest import raises import pytest from epo_ops . exceptions import InvalidDate from epo_ops . utils import quote , validate_date def test_encoding ( ) : assert quote ( '' ) == ( '' ", "answer": "''"}, {"prompt": " from distutils . core import setup setup ( name = '' , version = '' , description = \"\" , author = '' , author_email = '' , license = '' , packages = [ '' ] , install_requires = [ '' ] ", "answer": ") "}, {"prompt": " import numpy as np from . base import Transform , Alignment , Invertible from . rbf import R2LogR2RBF class ThinPlateSplines ( Alignment , Transform , Invertible ) : r\"\"\"\"\"\" def __init__ ( self , source , target , kernel = None , min_singular_val = ) : Alignment . __init__ ( self , source , target ) if self . n_dims != : raise ValueError ( '' ) if kernel is None : kernel = R2LogR2RBF ( source . points ) self . min_singular_val = min_singular_val self . kernel = kernel self . k = self . kernel . apply ( self . source . points ) self . p = np . concatenate ( [ np . ones ( [ self . n_points , ] ) , self . source . points ] , axis = ) o = np . zeros ( [ , ] ) top_l = np . concatenate ( [ self . k , self . p ] , axis = ) bot_l = np . concatenate ( [ self . p . T , o ] , axis = ) self . l = np . concatenate ( [ top_l , bot_l ] , axis = ) self . v , self . y , self . coefficients = None , None , None self . _build_coefficients ( ) def _build_coefficients ( self ) : self . v = self . target . points . T . copy ( ) self . y = np . hstack ( [ self . v , np . zeros ( [ , ] ) ] ) _u , _s , _v = np . linalg . svd ( self . l ) keep = _s . shape [ ] - sum ( _s < self . min_singular_val ) inv_l = _u [ : , : keep ] . dot ( / _s [ : keep , None ] * _v [ : keep , : ] ) self . coefficients = inv_l . dot ( self . y . T ) def _sync_state_from_target ( self ) : self . _build_coefficients ( ) def _apply ( self , points , ** kwargs ) : r\"\"\"\"\"\" if points . shape [ ] != self . n_dims : raise ValueError ( '' ) x = points [ ... , ] [ : , None ] y = points [ ... , ] [ : , None ] c_affine_c = self . coefficients [ - ] c_affine_x = self . coefficients [ - ] c_affine_y = self . coefficients [ - ] f_affine = c_affine_c + c_affine_x * x + c_affine_y * y kernel_dist = self . kernel . apply ( points ) c_affine_free = self . coefficients [ : - ] f_affine_free = kernel_dist . dot ( c_affine_free ) return f_affine + f_affine_free @ property def has_true_inverse ( self ) : r\"\"\"\"\"\" return False ", "answer": "def pseudoinverse ( self ) :"}, {"prompt": " import time from wlauto import GameWorkload , Parameter class EpicCitadel ( GameWorkload ) : name = '' description = \"\"\"\"\"\" package = '' activity = '' ", "answer": "install_timeout = "}, {"prompt": " \"\"\"\"\"\" __author__ = \"\" __copyright__ = \"\" from shlex import split import gdata . service try : import books except ImportError : import gdata . books as books BOOK_SERVER = \"\" GENERAL_FEED = \"\" ITEM_FEED = \"\" LIBRARY_FEED = \"\" ANNOTATION_FEED = \"\" PARTNER_FEED = \"\" BOOK_SERVICE = \"\" ACCOUNT_TYPE = \"\" class BookService ( gdata . service . GDataService ) : def __init__ ( self , email = None , password = None , source = None , server = BOOK_SERVER , account_type = ACCOUNT_TYPE , exception_handlers = tuple ( ) , ** kwargs ) : \"\"\"\"\"\" gdata . service . GDataService . __init__ ( self , email = email , password = password , service = BOOK_SERVICE , source = source , server = server , ** kwargs ) self . exception_handlers = exception_handlers def search ( self , q , start_index = \"\" , max_results = \"\" , min_viewability = \"\" , feed = GENERAL_FEED , converter = books . BookFeed . FromString ) : \"\"\"\"\"\" if not isinstance ( q , gdata . service . Query ) : q = gdata . service . Query ( text_query = q ) if feed : q . feed = feed q [ '' ] = start_index q [ '' ] = max_results q [ '' ] = min_viewability return self . Get ( uri = q . ToUri ( ) , converter = converter ) def search_by_keyword ( self , q = '' , feed = GENERAL_FEED , start_index = \"\" , max_results = \"\" , min_viewability = \"\" , ** kwargs ) : \"\"\"\"\"\" for k , v in kwargs . items ( ) : if not v : continue k = k . lower ( ) if k == '' : q = \"\" % ( q , v ) elif k == '' : q = '' % ( q , v . strip ( '' ) ) elif k == '' : q = '' % ( q , '' . join ( '' % x for x in split ( v ) ) ) elif k == '' : q = '' % ( q , '' . join ( '' % x for x in split ( v ) ) ) elif k in ( '' , '' , '' ) : q = '' % ( q , '' . join ( '' % ( k , x ) for x in split ( v ) ) ) elif k == '' : q = '' % ( q , '' . join ( '' % ( k , x ) for x in split ( v ) ) ) elif k == '' : q = '' % ( q , v ) elif k == '' : q = '' % ( q , v ) elif k == '' : q = '' % ( q , v ) else : raise ValueError ( \"\" ) return self . search ( q . strip ( ) , start_index = start_index , feed = feed , max_results = max_results , min_viewability = min_viewability ) def search_library ( self , q , id = '' , ** kwargs ) : \"\"\"\"\"\" if '' in kwargs : raise ValueError ( \"\" ) feed = LIBRARY_FEED % id return self . search ( q , feed = feed , ** kwargs ) def search_library_by_keyword ( self , id = '' , ** kwargs ) : \"\"\"\"\"\" if '' in kwargs : raise ValueError ( \"\" ) feed = LIBRARY_FEED % id return self . search_by_keyword ( feed = feed , ** kwargs ) def search_annotations ( self , q , id = '' , ** kwargs ) : \"\"\"\"\"\" if '' in kwargs : raise ValueError ( \"\" ) feed = ANNOTATION_FEED % id return self . search ( q , feed = feed , ** kwargs ) def search_annotations_by_keyword ( self , id = '' , ** kwargs ) : \"\"\"\"\"\" if '' in kwargs : raise ValueError ( \"\" ) feed = ANNOTATION_FEED % id return self . search_by_keyword ( feed = feed , ** kwargs ) def add_item_to_library ( self , item ) : \"\"\"\"\"\" feed = LIBRARY_FEED % '' return self . Post ( data = item , uri = feed , converter = books . Book . FromString ) def remove_item_from_library ( self , item ) : \"\"\"\"\"\" ", "answer": "return self . Delete ( item . GetEditLink ( ) . href )"}, {"prompt": " import os from os . path import dirname , join , isfile from shutil import rmtree import unittest from cvsgit . command . init import init from cvsgit . command . clone import Clone from cvsgit . command . pull import pull from cvsgit . command . verify import Verify from cvsgit . git import Git from cvsgit . utils import Tempdir class Test ( unittest . TestCase ) : ", "answer": "def test_clone ( self ) :"}, {"prompt": " class BaseDocumentQuery ( object ) : \"\"\"\"\"\" def __init__ ( self , query_index , backend = None ) : ", "answer": "self . query_index = query_index"}, {"prompt": " from struct import pack , unpack from datetime import datetime from calendar import timegm from time import time from binascii import hexlify , unhexlify from zlib import crc32 from io import BytesIO from random import choice from happybase import Connection from frontera . utils . url import parse_domain_from_url_fast from msgpack import Unpacker , Packer from frontera import DistributedBackend from frontera . core . components import Metadata , Queue , States from frontera . core . models import Request from distributed_frontera . worker . partitioner import Crc32NamePartitioner from distributed_frontera . worker . utils import chunks _pack_functions = { '' : str , '' : lambda x : pack ( '' , ) , '' : lambda x : pack ( '' , x ) , '' : lambda x : pack ( '' , x ) , '' : lambda x : pack ( '' , x ) , '' : str , '' : str , '' : lambda x : pack ( '' , x ) , '' : str } def unpack_score ( blob ) : return unpack ( \"\" , blob ) [ ] def prepare_hbase_object ( obj = None , ** kwargs ) : if not obj : obj = dict ( ) for k , v in kwargs . iteritems ( ) : if k in [ '' , '' ] : cf = '' elif k == '' : cf = '' else : cf = '' func = _pack_functions [ k ] obj [ cf + '' + k ] = func ( v ) return obj def utcnow_timestamp ( ) : d = datetime . utcnow ( ) return timegm ( d . timetuple ( ) ) class HBaseQueue ( Queue ) : GET_RETRIES = def __init__ ( self , connection , partitions , logger , table_name , drop = False ) : self . connection = connection self . partitions = [ i for i in range ( , partitions ) ] self . partitioner = Crc32NamePartitioner ( self . partitions ) self . logger = logger self . table_name = table_name tables = set ( self . connection . tables ( ) ) if drop and self . table_name in tables : self . connection . delete_table ( self . table_name , disable = True ) tables . remove ( self . table_name ) if self . table_name not in tables : self . connection . create_table ( self . table_name , { '' : { '' : , '' : } } ) def frontier_start ( self ) : pass def frontier_stop ( self ) : pass def schedule ( self , batch ) : to_schedule = [ ] for fprint , score , request , schedule in batch : if schedule : if '' not in request . meta : _ , hostname , _ , _ , _ , _ = parse_domain_from_url_fast ( request . url ) if not hostname : ", "answer": "self . logger . error ( \"\" % ( request . url , fprint ) )"}, {"prompt": " \"\"\"\"\"\" import weakref import py from pypy . rlib import rgc from pypy . rlib . jit import JitDriver from pypy . jit . backend . llvm . runner import LLVMCPU class X ( object ) : next = None def get_test ( main ) : main . _dont_inline_ = True def g ( n ) : x = X ( ) x . foo = main ( n , x ) x . foo = return weakref . ref ( x ) g . _dont_inline_ = True def entrypoint ( args ) : r_list = [ ] for i in range ( ) : r = g ( ) r_list . append ( r ) rgc . collect ( ) rgc . collect ( ) ; rgc . collect ( ) freed = for r in r_list : if r ( ) is None : freed += print freed return return entrypoint def compile_and_run ( f , gc , ** kwds ) : from pypy . annotation . listdef import s_list_of_strings from pypy . translator . translator import TranslationContext from pypy . jit . metainterp . warmspot import apply_jit from pypy . translator . c import genc t = TranslationContext ( ) t . config . translation . gc = gc t . config . translation . gcconfig . debugprint = True for name , value in kwds . items ( ) : setattr ( t . config . translation , name , value ) t . buildannotator ( ) . build_types ( f , [ s_list_of_strings ] ) t . buildrtyper ( ) . specialize ( ) if kwds [ '' ] : apply_jit ( t , CPUClass = LLVMCPU ) cbuilder = genc . CStandaloneBuilder ( t , f , t . config ) cbuilder . generate_source ( ) cbuilder . compile ( ) data = cbuilder . cmdexec ( '' ) return data . splitlines ( ) [ - ] . strip ( ) def test_compile_boehm ( ) : myjitdriver = JitDriver ( greens = [ ] , reds = [ '' , '' ] ) ", "answer": "def main ( n , x ) :"}, {"prompt": " from __future__ import unicode_literals import pickle from django . utils . crypto import salted_hmac from django . utils import six def form_hmac ( form ) : \"\"\"\"\"\" data = [ ] for bf in form : if form . empty_permitted and not form . has_changed ( ) : value = bf . data or '' ", "answer": "else :"}, {"prompt": " from django . conf import settings from appconf import AppConf from collections import defaultdict class PinaxLikesAppConf ( AppConf ) : LIKABLE_MODELS = defaultdict ( dict ) def configure_likable_models ( self , value ) : DEFAULT_LIKE_CONFIG = { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , } for model in value : custom_data = value [ model ] . copy ( ) default_data = DEFAULT_LIKE_CONFIG . copy ( ) value [ model ] = default_data value [ model ] . update ( custom_data ) return value class Meta : ", "answer": "prefix = \"\" "}, {"prompt": " from fabric . api import task , env , sudo , cd tool_name = '' env . hosts = [ '' ] env . sudo_user = '' . format ( tool_name ) env . sudo_prefix = '' env . use_ssh_config = True home_dir = '' . format ( tool_name ) code_dir = '' . format ( home_dir ) @ task ", "answer": "def deploy ( * args ) :"}, {"prompt": " \"\"\"\"\"\" __author__ = '' from pyon . core . bootstrap import get_sys_name , CFG from pyon . datastore . datastore_common import DatastoreFactory , DataStore from pyon . util . log import log from pyon . util . arg_check import validate_true class DatastoreManager ( object ) : \"\"\"\"\"\" def __init__ ( self , container = None ) : self . _datastores = { } self . container = container def start ( self ) : pass def stop ( self ) : log . debug ( \"\" , len ( self . _datastores ) ) some_datastore = None for ds in self . _datastores . itervalues ( ) : if not some_datastore and hasattr ( ds , \"\" ) : some_datastore = ds try : ds . close ( ) except Exception as ex : log . exception ( \"\" ) self . _datastores = { } if some_datastore : try : some_datastore . close_all ( ) except Exception as ex : log . exception ( \"\" ) @ classmethod def get_scoped_name ( cls , ds_name ) : return ( \"\" % ( get_sys_name ( ) , ds_name ) ) . lower ( ) def get_datastore ( self , ds_name , profile = None , config = None ) : \"\"\"\"\"\" validate_true ( ds_name , '' ) if ( ds_name , profile ) in self . _datastores : log . debug ( \"\" % ( ds_name , profile ) ) return self . _datastores [ ( ds_name , profile ) ] log . info ( \"\" % ( ds_name , ds_name , profile ) ) new_ds = DatastoreManager . get_datastore_instance ( ds_name , profile ) if not new_ds . datastore_exists ( ds_name ) : new_ds . create_datastore ( ds_name , create_indexes = True , profile = profile ) else : ", "answer": "new_ds . define_profile_views ( profile = profile , keepviews = True )"}, {"prompt": " \"\"\"\"\"\" __all__ = [ '' , '' , '' , '' , '' , '' , '' , ", "answer": "'' ,"}, {"prompt": " if not request . env . web2py_runtime_gae : db = DAL ( '' ) else : db = DAL ( '' ) session . connect ( request , response , db = db ) response . generic_patterns = [ '' ] if request . is_local else [ ] from gluon . tools import Auth , Crud , Service , PluginManager , prettydate auth = Auth ( db , hmac_key = Auth . get_or_create_key ( ) ) crud , service , plugins = Crud ( db ) , Service ( ) , PluginManager ( ) auth . define_tables ( ) mail = auth . settings . mailer mail . settings . server = '' or '' ", "answer": "mail . settings . sender = ''"}, {"prompt": " __author__ = '' import logging as logger import types from ib . ext . EWrapper import EWrapper from ib . client . Portfolio import Account , AccountMessage , PortfolioMessage from ib . client . Queries import Contracts , Executions def showmessage ( message , mapping ) : try : del ( mapping [ '' ] ) except ( KeyError , ) : pass items = mapping . items ( ) items . sort ( ) print '' % ( message , ) for k , v in items : print '' % ( k , v ) class Observable ( object ) : \"\"\"\"\"\" def __init__ ( self ) : self . listeners = { } self . logger = logger . getLogger ( ) def register ( self , listener , events = None ) : \"\"\"\"\"\" if events is not None and type ( events ) not in ( types . TupleType , types . ListType ) : events = ( events , ) self . listeners [ listener ] = events def dispatch ( self , event = None , msg = None ) : \"\"\"\"\"\" for listener , events in self . listeners . items ( ) : if events is None or event is None or event in events : try : listener ( self , event , msg ) except ( Exception , ) : self . unregister ( listener ) errmsg = \"\" \"\" \"\" . format ( listener . func_name , event ) self . logger . exception ( errmsg ) def unregister ( self , listener ) : \"\"\"\"\"\" del self . listeners [ listener ] class SyncWrapper ( EWrapper , Observable ) : suppress = False emitter = [ ] account = Account ( ) contracts = Contracts ( ) executions = Executions ( ) order_messages = [ ] ref_id = None order_id = def __init__ ( self , subs = { } ) : super ( SyncWrapper , self ) . __init__ ( ) self . subscriptions = subs def accountDownloadEnd ( self , accountName ) : msg = { '' : accountName } if self . suppress is False : showmessage ( '' , vars ( ) ) def bondContractDetails ( self , reqId , contractDetails ) : self . contracts . append ( reqId , contractDetails ) if self . suppress is False : showmessage ( '' , vars ( ) ) def commissionReport ( self , commissionReport ) : msg = { '' : commissionReport } if self . suppress is False : showmessage ( '' , vars ( ) ) def connectionClosed ( self ) : if self . suppress is False : showmessage ( '' , vars ( ) ) def contractDetails ( self , reqId , contractDetails ) : self . contracts . append ( reqId , contractDetails ) if self . suppress is False : showmessage ( '' , vars ( ) ) def contractDetailsEnd ( self , reqId ) : msg = { '' : reqId } if self . suppress is False : showmessage ( '' , vars ( ) ) def currentTime ( self , time ) : msg = { '' : time } if self . suppress is False : showmessage ( '' , vars ( ) ) def deltaNeutralValidation ( self , reqId , underComp ) : msg = { '' : reqId , '' : underComp } if self . suppress is False : showmessage ( '' , vars ( ) ) def error_0 ( self , strval ) : msg = { '' : strval } if self . suppress is False : showmessage ( '' , vars ( ) ) def error_1 ( self , id , errorCode , errorMsg ) : msg = { '' : id , '' : errorCode , '' : errorMsg } if self . suppress is False : showmessage ( '' , vars ( ) ) def execDetails ( self , reqId , contract , execution ) : msg = { '' : reqId , '' : contract , '' : execution } self . executions . append ( reqId , execution ) if self . suppress is False : showmessage ( '' , msg ) def execDetailsEnd ( self , reqId ) : msg = { '' : reqId } if self . suppress is False : showmessage ( '' , vars ( ) ) def fundamentalData ( self , reqId , data ) : msg = { '' : reqId , '' : data } if self . suppress is False : showmessage ( '' , vars ( ) ) def historicalData ( self , reqId , date , open , high , low , close , volume , count , WAP , hasGaps ) : msg = { '' : reqId , '' : date , '' : open , ", "answer": "'' : high ,"}, {"prompt": " __author__ = '' import os , inspect from pyon . core . governance . conversation . core . transition import TransitionFactory from pyon . core . governance . conversation . core . local_type import LocalType from pyon . core . governance . conversation . core . fsm import ExceptionFSM , ExceptionFailAssertion from pyon . core . governance . conversation . parsing . base_parser import ANTLRScribbleParser from pyon . util . int_test import IonIntegrationTestCase from pyon . util . log import log from nose . plugins . attrib import attr def purchasingAtBuyer_events ( ) : events = [ ] events . append ( TransitionFactory . create ( LocalType . SEND , '' , '' ) ) events . append ( TransitionFactory . create ( LocalType . RESV , '' , '' ) ) events . append ( TransitionFactory . create ( LocalType . SEND , '' , '' ) ) events . append ( TransitionFactory . create ( LocalType . RESV , '' , '' ) ) return events def locateChoiceAtBuyer_events ( ) : events = [ ] events . append ( TransitionFactory . create ( LocalType . RESV , '' , '' ) ) events . append ( TransitionFactory . create ( LocalType . SEND , '' , '' ) ) events . append ( TransitionFactory . create ( LocalType . RESV , '' , '' ) ) events . append ( TransitionFactory . create ( LocalType . RESV , '' , '' ) ) events . append ( TransitionFactory . create ( LocalType . RESV , '' , '' ) ) events . append ( TransitionFactory . create ( LocalType . SEND , '' , '' ) ) return events def recAtBuyer_events ( ) : events = [ ] events . append ( TransitionFactory . create ( LocalType . SEND , '' , '' ) ) events . append ( TransitionFactory . create ( LocalType . RESV , '' , '' ) ) events . append ( TransitionFactory . create ( LocalType . SEND , '' , '' ) ) events . append ( TransitionFactory . create ( LocalType . RESV , '' , '' ) ) return events def recAndChoice_events ( ) : events = [ ] events . append ( TransitionFactory . create ( LocalType . SEND , '' , '' ) ) events . append ( TransitionFactory . create ( LocalType . SEND , '' , '' ) ) events . append ( TransitionFactory . create ( LocalType . RESV , '' , '' ) ) return events def parallelAtSeller1_events ( ) : events = [ ] events . append ( TransitionFactory . create ( LocalType . RESV , '' , '' ) ) events . append ( TransitionFactory . create ( LocalType . SEND , '' , '' ) ) events . append ( TransitionFactory . create ( LocalType . SEND , '' , '' ) ) return events def Interrupt_events ( ) : events = [ ] events . append ( TransitionFactory . create ( LocalType . SEND , '' , '' ) ) events . append ( TransitionFactory . create ( LocalType . RESV , '' , '' ) ) events . append ( TransitionFactory . create ( LocalType . SEND , '' , '' ) ) events . append ( TransitionFactory . create ( LocalType . RESV , '' , '' ) ) events . append ( TransitionFactory . create ( LocalType . RESV , '' , '' ) ) events . append ( TransitionFactory . create ( LocalType . SEND , '' , '' ) ) return events def main_auction_events ( ) : events = [ ] events . append ( TransitionFactory . create ( LocalType . SEND , '' , '' ) ) events . append ( TransitionFactory . create ( LocalType . RESV , '' , '' ) ) events . append ( TransitionFactory . create ( LocalType . SEND , '' , '' ) ) return events def logic_events ( ) : events = [ ] events . append ( TransitionFactory . create ( LocalType . SEND , '' , '' ) ) events . append ( TransitionFactory . create ( LocalType . RESV , '' , '' ) ) events . append ( TransitionFactory . create ( LocalType . SEND , '' , '' ) ) ", "answer": "events . append ( TransitionFactory . create ( LocalType . RESV , '' , '' ) )"}, {"prompt": " from mock import patch , MagicMock from unittest import TestCase import pandas as pd from pandashells . bin . p_smooth import main , get_input_args , validate_args class GetInputArgsTests ( TestCase ) : @ patch ( '' , '' . split ( ) ) def test_right_number_of_args ( self ) : args = get_input_args ( ) self . assertEqual ( len ( args . __dict__ ) , ) class ValidateArgs ( TestCase ) : def test_okay ( self ) : args = MagicMock ( quiet = False ) cols = [ '' ] df = MagicMock ( columns = [ '' ] ) validate_args ( args , cols , df ) @ patch ( '' ) def test_bad_cols ( self , stderr_mock ) : args = MagicMock ( quiet = False ) cols = [ '' ] df = MagicMock ( columns = [ '' ] ) with self . assertRaises ( SystemExit ) : validate_args ( args , cols , df ) class MainTests ( TestCase ) : @ patch ( '' , '' . split ( ) ) @ patch ( '' ) @ patch ( '' ) def test_cli ( self , df_from_input_mock , df_to_output_mock ) : df_in = pd . DataFrame ( { '' : range ( , ) , '' : range ( , ) , } ) df_from_input_mock . return_value = df_in main ( ) dfout = df_to_output_mock ", "answer": "self . assertEqual ("}, {"prompt": " __author__ = '' __all__ = [ '' ] import capnp from pathlib import Path ", "answer": "import tempfile"}, {"prompt": " from __future__ import print_function import unittest import time ", "answer": "from mwclient . util import parse_timestamp"}, {"prompt": " import numpy as np llf = np . array ( [ - ] ) nobs = np . array ( [ ] ) k = np . array ( [ ] ) k_exog = np . array ( [ ] ) sigma = np . array ( [ ] ) chi2 = np . array ( [ ] ) df_model = np . array ( [ ] ) k_ar = np . array ( [ ] ) k_ma = np . array ( [ ] ) params = np . array ( [ , - , - , ] ) cov_params = np . array ( [ , - , - , , - , , , - , - , , , , , - , , ] ) . reshape ( , ) xb = np . array ( [ , , , , , , , , , , , , , , , , , , , , , , , , , , , , ", "answer": " ,"}, {"prompt": " import logging from django . forms import ValidationError from django import http from django . utils . translation import ugettext_lazy as _ from django . views . decorators . debug import sensitive_variables from horizon import exceptions from horizon import forms from horizon import messages ", "answer": "from horizon . utils import validators"}, {"prompt": " from __future__ import unicode_literals import sys import os import io import json def find ( node ) : if len ( node ) == : yield node [ ] for key in node [ ] : find ( node [ ] [ key ] ) def search ( needle , haystack ) : if needle [ ] not in haystack : return False node = haystack [ needle [ ] ] needle = needle [ : ] i , j = , while j < len ( needle ) : if needle [ i : j + ] in node [ ] : node = node [ ] [ needle [ i : j + ] ] i = j + j += if i != j : return False if len ( node ) == : print '' , node [ ] rest = [ ] for key in node [ ] : rest . append ( list ( find ( node [ ] [ key ] ) ) ) print '' , sum ( sum ( rest , [ ] ) , [ ] ) ", "answer": "if __name__ == '' :"}, {"prompt": " from __future__ import ( unicode_literals , division , absolute_import , print_function ) REMOVE_THIS_KEY = object ( ) def mergeargs ( argvalue , remove = False ) : if not argvalue : return None r = { } for subval in argvalue : mergedicts ( r , dict ( [ subval ] ) , remove = remove ) return r def _clear_special_values ( d ) : '''''' l = [ d ] while l : i = l . pop ( ) pops = [ ] for k , v in i . items ( ) : if v is REMOVE_THIS_KEY : pops . append ( k ) elif isinstance ( v , dict ) : l . append ( v ) for k in pops : i . pop ( k ) def mergedicts ( d1 , d2 , remove = True ) : '''''' _setmerged ( d1 , d2 ) for k in d2 : if k in d1 and isinstance ( d1 [ k ] , dict ) and isinstance ( d2 [ k ] , dict ) : mergedicts ( d1 [ k ] , d2 [ k ] , remove ) elif remove and d2 [ k ] is REMOVE_THIS_KEY : d1 . pop ( k , None ) else : if remove and isinstance ( d2 [ k ] , dict ) : _clear_special_values ( d2 [ k ] ) d1 [ k ] = d2 [ k ] def mergedefaults ( d1 , d2 ) : '''''' for k in d2 : if k in d1 and isinstance ( d1 [ k ] , dict ) and isinstance ( d2 [ k ] , dict ) : mergedefaults ( d1 [ k ] , d2 [ k ] ) else : d1 . setdefault ( k , d2 [ k ] ) def _setmerged ( d1 , d2 ) : if hasattr ( d1 , '' ) : d1 . setmerged ( d2 ) def mergedicts_copy ( d1 , d2 ) : '''''' ret = d1 . copy ( ) _setmerged ( ret , d2 ) for k in d2 : if k in d1 and isinstance ( d1 [ k ] , dict ) and isinstance ( d2 [ k ] , dict ) : ret [ k ] = mergedicts_copy ( d1 [ k ] , d2 [ k ] ) else : ret [ k ] = d2 [ k ] return ret def updated ( d , * args , ** kwargs ) : ", "answer": "''''''"}, {"prompt": " import time from oslo_utils import timeutils from saharaclient . api import base as sab from tempest import config from tempest import exceptions from tempest . lib . common . utils import data_utils from tempest . lib import decorators from tempest import test from sahara . tests . tempest . scenario . data_processing . client_tests import base TEMPEST_CONF = config . CONF class JobExecutionTest ( base . BaseDataProcessingTest ) : def _check_register_image ( self , image_id ) : self . client . images . update_image ( image_id , TEMPEST_CONF . scenario . ssh_user , '' ) reg_image = self . client . images . get ( image_id ) self . assertDictContainsSubset ( { '' : TEMPEST_CONF . scenario . ssh_user } , reg_image . metadata ) def _check_image_get ( self , image_id ) : image = self . client . images . get ( image_id ) self . assertEqual ( image_id , image . id ) def _check_image_list ( self , image_id ) : image_list = self . client . images . list ( ) images_info = [ image . id for image in image_list ] self . assertIn ( image_id , images_info ) def _check_adding_tags ( self , image_id ) : self . client . images . update_tags ( image_id , [ '' , '' ] ) image = self . client . images . get ( image_id ) self . assertDictContainsSubset ( { '' : '' , '' : '' } , image . metadata ) def _check_deleting_tags ( self , image_id ) : self . client . images . update_tags ( image_id , [ ] ) image = self . client . images . get ( image_id ) self . assertNotIn ( '' , image . metadata ) self . assertNotIn ( '' , image . metadata ) def _check_unregister_image ( self , image_id ) : self . client . images . unregister_image ( image_id ) image_list = self . client . images . list ( ) self . assertNotIn ( image_id , [ image . id for image in image_list ] ) def _check_cluster_create ( self ) : worker = self . create_node_group_template ( data_utils . rand_name ( '' ) , ** self . worker_template ) master = self . create_node_group_template ( data_utils . rand_name ( '' ) , ** self . master_template ) cluster_templ = self . cluster_template . copy ( ) cluster_templ [ '' ] = [ { '' : '' , '' : master . id , '' : } , { '' : '' , '' : worker . id , '' : } ] if TEMPEST_CONF . service_available . neutron : cluster_templ [ '' ] = self . get_private_network_id ( ) cluster_template = self . create_cluster_template ( data_utils . rand_name ( '' ) , ** cluster_templ ) cluster_name = data_utils . rand_name ( '' ) self . cluster_info = { '' : cluster_name , '' : '' , '' : '' , '' : cluster_template . id , '' : TEMPEST_CONF . data_processing . fake_image_id } cluster = self . create_cluster ( ** self . cluster_info ) self . check_cluster_active ( cluster . id ) self . assertEqual ( cluster_name , cluster . name ) self . assertDictContainsSubset ( self . cluster_info , cluster . __dict__ ) return cluster . id , cluster . name def _check_cluster_list ( self , cluster_id , cluster_name ) : cluster_list = self . client . clusters . list ( ) clusters_info = [ ( clust . id , clust . name ) for clust in cluster_list ] self . assertIn ( ( cluster_id , cluster_name ) , clusters_info ) def _check_cluster_get ( self , cluster_id , cluster_name ) : cluster = self . client . clusters . get ( cluster_id ) self . assertEqual ( cluster_name , cluster . name ) self . assertDictContainsSubset ( self . cluster_info , cluster . __dict__ ) def _check_cluster_update ( self , cluster_id ) : values = { '' : data_utils . rand_name ( '' ) , '' : '' } cluster = self . client . clusters . update ( cluster_id ) self . assertDictContainsSubset ( values , cluster . __dict__ ) def _check_cluster_scale ( self , cluster_id ) : big_worker = self . create_node_group_template ( data_utils . rand_name ( '' ) , ** self . worker_template ) scale_body = { '' : [ { '' : , '' : '' } , { \"\" : , \"\" : '' } ] , '' : [ { '' : , '' : '' , '' : big_worker . id } ] } self . client . clusters . scale ( cluster_id , scale_body ) self . check_cluster_active ( cluster_id ) cluster = self . client . clusters . get ( cluster_id ) for ng in cluster . node_groups : if ng [ '' ] == scale_body [ '' ] [ ] [ '' ] : self . assertDictContainsSubset ( scale_body [ '' ] [ ] , ng ) elif ng [ '' ] == scale_body [ '' ] [ ] [ '' ] : self . assertDictContainsSubset ( scale_body [ '' ] [ ] , ng ) elif ng [ '' ] == scale_body [ '' ] [ ] [ '' ] : self . assertDictContainsSubset ( scale_body [ '' ] [ ] , ng ) def _check_cluster_delete ( self , cluster_id ) : self . client . clusters . delete ( cluster_id ) cluster = self . client . clusters . get ( cluster_id ) self . assertEqual ( '' , cluster . status ) timeout = TEMPEST_CONF . data_processing . cluster_timeout s_time = timeutils . utcnow ( ) while timeutils . delta_seconds ( s_time , timeutils . utcnow ( ) ) < timeout : try : self . client . clusters . get ( cluster_id ) except sab . APIException : return time . sleep ( TEMPEST_CONF . data_processing . request_timeout ) raise exceptions . TimeoutException ( '' '' % timeout ) def _check_job_execution_create ( self , cluster_id ) : container_name = data_utils . rand_name ( '' ) self . create_container ( container_name ) input_file_name = data_utils . rand_name ( '' ) self . object_client . create_object ( container_name , input_file_name , '' ) input_file_url = '' % ( container_name , input_file_name ) input_source_name = data_utils . rand_name ( '' ) input_source = self . create_data_source ( input_source_name , input_file_url , '' , '' , { '' : '' , '' : '' } ) output_dir_name = data_utils . rand_name ( '' ) output_dir_url = '' % ( container_name , output_dir_name ) output_source_name = data_utils . rand_name ( '' ) output_source = self . create_data_source ( output_source_name , output_dir_url , '' , '' , { '' : '' , '' : '' } ) job_binary = { '' : data_utils . rand_name ( '' ) , '' : input_file_url , '' : '' , '' : { '' : '' , '' : '' } } job_binary = self . create_job_binary ( ** job_binary ) job_name = data_utils . rand_name ( '' ) job = self . create_job ( job_name , '' , [ job_binary . id ] ) self . job_exec_info = { '' : job . id , '' : cluster_id , '' : input_source . id , '' : output_source . id , '' : { } } job_execution = self . create_job_execution ( ** self . job_exec_info ) return job_execution . id def _check_job_execution_list ( self , job_exec_id ) : job_exec_list = self . client . job_executions . list ( ) self . assertIn ( job_exec_id , [ job_exec . id for job_exec in job_exec_list ] ) def _check_job_execution_get ( self , job_exec_id ) : job_exec = self . client . job_executions . get ( job_exec_id ) job_exec_info = self . job_exec_info . copy ( ) del job_exec_info [ '' ] self . assertDictContainsSubset ( job_exec_info , job_exec . __dict__ ) def _check_job_execution_update ( self , job_exec_id ) : values = { '' : True } job_exec = self . client . job_executions . update ( job_exec_id , ** values ) self . assertDictContainsSubset ( values , job_exec . __dict__ ) def _check_job_execution_delete ( self , job_exec_id ) : self . client . job_executions . delete ( job_exec_id ) job_exec_list = self . client . jobs . list ( ) self . assertNotIn ( job_exec_id , [ job_exec . id for job_exec in job_exec_list ] ) @ decorators . skip_because ( bug = \"\" ) @ test . attr ( type = '' ) @ test . services ( '' ) def test_job_executions ( self ) : image_id = TEMPEST_CONF . data_processing . fake_image_id self . _check_register_image ( image_id ) self . _check_image_get ( image_id ) self . _check_image_list ( image_id ) self . _check_adding_tags ( image_id ) cluster_id , cluster_name = self . _check_cluster_create ( ) self . _check_cluster_list ( cluster_id , cluster_name ) self . _check_cluster_get ( cluster_id , cluster_name ) self . _check_cluster_update ( cluster_id ) self . _check_cluster_scale ( cluster_id ) job_exec_id = self . _check_job_execution_create ( cluster_id ) self . _check_job_execution_list ( job_exec_id ) self . _check_job_execution_get ( job_exec_id ) self . _check_job_execution_update ( job_exec_id ) self . _check_job_execution_delete ( job_exec_id ) self . _check_cluster_delete ( cluster_id ) ", "answer": "self . _check_deleting_tags ( image_id )"}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import , division from twisted . web import static ", "answer": "class Test ( static . Data ) :"}, {"prompt": " import httplib import urllib import struct import time import kt_error try : import cPickle as pickle except ImportError : import pickle KT_HTTP_HEADER = { '' : '' , } KT_PACKER_CUSTOM = KT_PACKER_PICKLE = KT_PACKER_JSON = KT_PACKER_STRING = class ProtocolHandler : def __init__ ( self , pickle_protocol = ) : self . err = kt_error . KyotoTycoonError ( ) self . pickle_protocol = pickle_protocol self . pack = self . _pickle_packer self . unpack = self . _pickle_unpacker self . pack_type = KT_PACKER_PICKLE def error ( self ) : return self . err def open ( self , host , port , timeout ) : try : self . conn = httplib . HTTPConnection ( host , port , timeout ) except Exception , e : raise e return True def close ( self ) : try : self . conn . close ( ) except Exception , e : raise e return True def echo ( self ) : self . conn . request ( '' , '' ) res = self . conn . getresponse ( ) body = res . read ( ) if res . status != : self . err . set_error ( err . EMISC ) return False self . err . set_success ( ) return True def get ( self , key , db = None ) : if key is None : return False path = key if db : path = '' % ( db , key ) path = urllib . quote ( path . encode ( '' ) , safe = '' ) self . conn . request ( '' , path ) rv = self . conn . getresponse ( ) body = rv . read ( ) if rv . status == : self . err . set_error ( self . err . NOTFOUND ) return None self . err . set_success ( ) return self . unpack ( body ) def set_bulk ( self , kv_dict , expire , atomic , db ) : if not isinstance ( kv_dict , dict ) : return False if len ( kv_dict ) < : self . err . set_error ( self . err . LOGIC ) return False path = '' if db : db = urllib . quote ( db , safe = '' ) path += '' + db request_body = '' if atomic : request_body = '' for k , v in kv_dict . items ( ) : k = urllib . quote ( k , safe = '' ) v = urllib . quote ( self . pack ( v ) , safe = '' ) request_body += '' + k + '' + v + '' self . conn . request ( '' , path , body = request_body , headers = KT_HTTP_HEADER ) res = self . conn . getresponse ( ) body = res . read ( ) if res . status != : self . err . set_error ( self . err . EMISC ) return False self . err . set_success ( ) return int ( self . _tsv_to_dict ( body ) [ '' ] ) def remove_bulk ( self , keys , atomic , db ) : if not isinstance ( keys , list ) : self . err . set_error ( self . err . LOGIC ) return if len ( keys ) < : self . err . set_error ( self . err . LOGIC ) return path = '' if db : db = urllib . quote ( db , safe = '' ) path += '' + db request_body = '' if atomic : request_body = '' for key in keys : request_body += '' + urllib . quote ( key , safe = '' ) + '' self . conn . request ( '' , path , body = request_body , headers = KT_HTTP_HEADER ) res = self . conn . getresponse ( ) body = res . read ( ) if res . status != : self . err . set_error ( self . err . EMISC ) return False self . err . set_success ( ) return int ( self . _tsv_to_dict ( body ) [ '' ] ) def get_bulk ( self , keys , atomic , db ) : if not isinstance ( keys , list ) : self . err . set_error ( self . err . LOGIC ) return None if len ( keys ) < : self . err . set_error ( self . err . LOGIC ) return { } path = '' if db : db = urllib . quote ( db , safe = '' ) path += '' + db request_body = '' if atomic : request_body = '' for key in keys : request_body += '' + urllib . quote ( key , safe = '' ) + '' self . conn . request ( '' , path , body = request_body , headers = KT_HTTP_HEADER ) res = self . conn . getresponse ( ) body = res . read ( ) if res . status != : self . err . set_error ( self . err . EMISC ) return None rv = { } res_dict = self . _tsv_to_dict ( body ) n = res_dict . pop ( '' ) if n == : self . err . set_error ( self . err . NOTFOUND ) return None for k , v in res_dict . items ( ) : if v is not None : rv [ urllib . unquote ( k [ : ] ) ] = self . unpack ( urllib . unquote ( v ) ) self . err . set_success ( ) return rv def get_int ( self , key , db = None ) : if key is None : self . err . set_error ( self . err . LOGIC ) return False path = key if db : path = '' % ( db , key ) path = urllib . quote ( path . encode ( '' ) , safe = '' ) self . conn . request ( '' , path ) rv = self . conn . getresponse ( ) buf = rv . read ( ) if rv . status != : self . err . set_error ( self . err . NOTFOUND ) return None self . err . set_success ( ) return struct . unpack ( '' , buf ) [ ] def vacuum ( self , db ) : path = '' if db : db = urllib . quote ( db , safe = '' ) path += '' + db self . conn . request ( '' , path ) res = self . conn . getresponse ( ) body = res . read ( ) if res . status != : self . err . set_error ( self . err . EMISC ) self . err . set_success ( ) return res . status == def match_prefix ( self , prefix , max , db ) : if prefix is None : self . err . set_error ( self . err . LOGIC ) return None rv = [ ] request_dict = { } request_dict [ '' ] = prefix if max : request_dict [ '' ] = max if db : request_dict [ '' ] = db request_body = self . _dict_to_tsv ( request_dict ) self . conn . request ( '' , '' , body = request_body , headers = KT_HTTP_HEADER ) res = self . conn . getresponse ( ) body = res . read ( ) if res . status != : self . err . set_error ( self . err . EMISC ) return False res_dict = self . _tsv_to_dict ( body ) n = res_dict . pop ( '' ) if n == : self . err . set_error ( self . err . NOTFOUND ) return None for k in res_dict . keys ( ) : rv . append ( k [ : ] ) self . err . set_success ( ) return rv def match_regex ( self , regex , max , db ) : if regex is None : self . err . set_error ( self . err . LOGIC ) return None path = '' if db : path += '' + db request_dict = { '' : regex } if max : request_dict [ '' ] = max request_body = self . _dict_to_tsv ( request_dict ) self . conn . request ( '' , path , body = request_body , headers = KT_HTTP_HEADER ) res = self . conn . getresponse ( ) body = res . read ( ) if res . status != : self . err . set_error ( self . err . EMISC ) return None rv = [ ] res_dict = self . _tsv_to_dict ( body ) if res_dict . pop ( '' ) < : self . err . set_error ( self . err . NOTFOUND ) return [ ] for k in res_dict . keys ( ) : rv . append ( k [ : ] ) self . err . set_success ( ) return rv def set ( self , key , value , expire , db ) : if key is None : self . err . set_error ( self . err . LOGIC ) return False if db : key = '' % ( db , key ) key = urllib . quote ( key . encode ( '' ) , safe = '' ) value = self . pack ( value ) self . err . set_success ( ) status = self . _rest_put ( '' , key , value , expire ) if status != : self . err . set_error ( self . err . EMISC ) return False self . err . set_success ( ) return True def add ( self , key , value , expire , db ) : if key is None : self . err . set_error ( self . err . LOGIC ) return False if db : key = '' % ( db , key ) key = urllib . quote ( key . encode ( '' ) , safe = '' ) value = self . pack ( value ) status = self . _rest_put ( '' , key , value , expire ) if status != : self . err . set_error ( self . err . EMISC ) return False self . err . set_success ( ) return True def cas ( self , key , old_val , new_val , expire , db ) : if key is None : self . err . set_error ( self . err . LOGIC ) return False path = '' if db : path += '' + db request_dict = { '' : key } if old_val : request_dict [ '' ] = urllib . quote ( self . pack ( old_val ) , safe = '' ) if new_val : request_dict [ '' ] = urllib . quote ( self . pack ( new_val ) , safe = '' ) if expire : request_dict [ '' ] = expire request_body = self . _dict_to_tsv ( request_dict ) self . conn . request ( '' , path , body = request_body , headers = KT_HTTP_HEADER ) res = self . conn . getresponse ( ) body = res . read ( ) if res . status != : self . err . set_error ( self . err . EMISC ) return False self . err . set_success ( ) return True def remove ( self , key , db ) : if key is None : self . err . set_error ( self . err . LOGIC ) return False if db : key = '' % ( db , key ) key = urllib . quote ( key . encode ( '' ) , safe = '' ) self . conn . request ( '' , key ) rv = self . conn . getresponse ( ) body = rv . read ( ) if rv . status != : self . err . set_error ( self . err . NOTFOUND ) return False self . err . set_success ( ) return True def replace ( self , key , value , expire , db ) : if key is None : self . err . set_error ( self . err . LOGIC ) return False if db : key = '' % ( db , key ) key = urllib . quote ( key . encode ( '' ) , safe = '' ) value = self . pack ( value ) status = self . _rest_put ( '' , key , value , expire ) if status != : self . err . set_error ( self . err . NOTFOUND ) return False self . err . set_success ( ) return True def append ( self , key , value , expire , db ) : self . err . set_error ( self . err . LOGIC ) if key is None : return False elif not isinstance ( value , str ) : return False if self . pack_type == KT_PACKER_PICKLE : data = self . get ( key ) if data is None : data = value else : data = data + value if self . set ( key , data , expire , db ) is True : self . err . set_success ( ) return True self . err . set_error ( self . err . EMISC ) return False def increment ( self , key , delta , expire , db ) : if key is None : self . err . set_error ( self . err . LOGIC ) return False path = '' if db : path += '' + db delta = int ( delta ) request_body = '' % ( key , delta ) self . conn . request ( '' , path , body = request_body , headers = KT_HTTP_HEADER ) res = self . conn . getresponse ( ) body = res . read ( ) if res . status != : self . err . set_error ( self . err . EMISC ) return None self . err . set_success ( ) return int ( self . _tsv_to_dict ( body ) [ '' ] ) def increment_double ( self , key , delta , expire , db ) : if key is None : self . err . set_error ( self . err . LOGIC ) return False path = '' if db : path += '' + db delta = float ( delta ) request_body = '' % ( key , delta ) self . conn . request ( '' , path , body = request_body , headers = KT_HTTP_HEADER ) res = self . conn . getresponse ( ) body = res . read ( ) if res . status != : self . err . set_error ( self . err . EMISC ) return None self . err . set_success ( ) return float ( self . _tsv_to_dict ( body ) [ '' ] ) def report ( self ) : self . conn . request ( '' , '' ) res = self . conn . getresponse ( ) body = res . read ( ) if res . status != : self . err . set_error ( self . err . EMISC ) ", "answer": "return None"}, {"prompt": " from logging import getLogger from yaml . scanner import ScannerError from pylons import response from turbulenz_local . lib . servicestatus import ServiceStatus from turbulenz_local . decorators import jsonify , secure_post from turbulenz_local . controllers import BaseController from turbulenz_local . models . gamelist import get_game_by_slug from turbulenz_local . models . apiv1 . badges import Badges , BadgesUnsupportedException from turbulenz_local . models . userlist import get_current_user from turbulenz_local . lib . exceptions import ApiException LOG = getLogger ( __name__ ) class BadgesController ( BaseController ) : \"\"\"\"\"\" badges_service = ServiceStatus . check_status_decorator ( '' ) @ classmethod @ jsonify def badges_user_list ( cls , slug = None ) : try : game = get_game_by_slug ( slug ) if game is None : raise ApiException ( '' ) user = get_current_user ( ) badges_obj = Badges . get_singleton ( game ) badges = badges_obj . badges badges_total_dict = dict ( ( b [ '' ] , b . get ( '' ) ) for b in badges ) userbadges = badges_obj . find_userbadges_by_user ( user . username ) for key , userbadge in userbadges . iteritems ( ) : del userbadge [ '' ] try : total = badges_total_dict [ key ] except KeyError : continue userbadge [ '' ] = total userbadge [ '' ] = ( userbadge [ '' ] >= total ) response . status_int = return { '' : True , '' : userbadges . values ( ) } except BadgesUnsupportedException : return { '' : False , '' : [ ] } except ApiException as message : response . status_int = return { '' : False , '' : str ( message ) } @ classmethod @ badges_service @ jsonify def badges_list ( cls , slug ) : try : game = get_game_by_slug ( slug ) if game is None : raise ApiException ( '' ) badges = Badges . get_singleton ( game ) . badges for badge in badges : if '' not in badge : badge [ '' ] = None if '' not in badge : badge [ '' ] = None return { '' : True , '' : badges } except BadgesUnsupportedException : return { '' : False , '' : [ ] } except ApiException as message : response . status_int = return { '' : False , '' : str ( message ) } except ScannerError as message : response . status_int = return { '' : False , '' : '' % ( message ) } @ classmethod @ badges_service @ secure_post def badges_user_add ( cls , slug , params = None ) : try : session = cls . _get_gamesession ( params ) game = session . game ", "answer": "if game is None :"}, {"prompt": " \"\"\"\"\"\" import datetime from django . template import Template , Context import mock from tests import case class ResultForTest ( case . DBTestCase ) : \"\"\"\"\"\" def result_for ( self , runcaseversion , user , environment , render ) : \"\"\"\"\"\" t = Template ( \"\" + render ) return t . render ( Context ( { \"\" : runcaseversion , \"\" : user , \"\" : environment } ) ) def test_result_exists ( self ) : \"\"\"\"\"\" r = self . F . ResultFactory ( ) self . assertEqual ( self . result_for ( r . runcaseversion , r . tester , r . environment , \"\" ) , str ( r . id ) ) def test_dupe_complete_results_keeps_both_finds_latest ( self ) : \"\"\"\"\"\" with mock . patch ( \"\" ) as mock_utcnow : mock_utcnow . return_value = datetime . datetime ( , , ) r = self . F . ResultFactory ( status = \"\" , ) mock_utcnow . return_value = datetime . datetime ( , , ) r2 = self . F . ResultFactory ( tester = r . tester , runcaseversion = r . runcaseversion , environment = r . environment , status = \"\" , ) self . assertEqual ( self . result_for ( r . runcaseversion , r . tester , r . environment , \"\" ) , str ( r2 . id ) , ) self . assertEqual ( self . model . Result . objects . count ( ) , ) def test_dupe_incomplete_results_keeps_both_finds_latest ( self ) : \"\"\"\"\"\" with mock . patch ( \"\" ) as mock_utcnow : mock_utcnow . return_value = datetime . datetime ( , , ) r = self . F . ResultFactory ( ) mock_utcnow . return_value = datetime . datetime ( , , ) r2 = self . F . ResultFactory ( tester = r . tester , runcaseversion = r . runcaseversion , environment = r . environment , ) self . assertEqual ( self . result_for ( r . runcaseversion , r . tester , r . environment , \"\" ) , str ( r2 . id ) , ) self . assertEqual ( self . model . Result . objects . count ( ) , ) def test_dupe_latest_results_sets_non_latest_to_false ( self ) : \"\"\"\"\"\" with mock . patch ( \"\" ) as mock_utcnow : mock_utcnow . return_value = datetime . datetime ( , , ) res1 = self . F . ResultFactory ( status = \"\" , ) mock_utcnow . return_value = datetime . datetime ( , , ) res2 = self . F . ResultFactory ( tester = res1 . tester , runcaseversion = res1 . runcaseversion , environment = res1 . environment , status = \"\" , ) mock_utcnow . return_value = datetime . datetime ( , , ) self . model . Result . objects . filter ( pk = res1 . pk ) . update ( is_latest = True , ) self . assertEqual ( self . result_for ( res1 . runcaseversion , res1 . tester , res1 . environment , \"\" , ) , str ( res2 . id ) ) self . assertEqual ( self . model . Result . objects . count ( ) , ) self . assertEqual ( self . model . Result . objects . get ( is_latest = True ) . pk , res2 . pk ) def test_result_does_not_exist ( self ) : \"\"\"\"\"\" rcv = self . F . RunCaseVersionFactory . create ( ) env = self . F . EnvironmentFactory . create ( ) user = self . F . UserFactory . create ( ) self . assertEqual ( self . result_for ( rcv , user , env , \"\" \"\" ) , \"\" . format ( rcv . id , env . id , user . id ) ) class StepResultForTest ( case . DBTestCase ) : \"\"\"\"\"\" def result_for ( self , result , step , render ) : \"\"\"\"\"\" t = Template ( \"\" + render ) return t . render ( Context ( { \"\" : result , \"\" : step } ) ) def test_stepresult_exists ( self ) : \"\"\"\"\"\" sr = self . F . StepResultFactory ( ) self . assertEqual ( self . result_for ( sr . result , sr . step , \"\" ) , str ( sr . id ) ) def test_step_result_does_not_exist ( self ) : \"\"\"\"\"\" r = self . F . ResultFactory . create ( ) step = self . F . CaseStepFactory . create ( ) self . assertEqual ( self . result_for ( r , step , \"\" ", "answer": "\"\" ) ,"}, {"prompt": " \"\"\"\"\"\" __revision__ = \"\" import sys , os , re from stat import ST_MODE from distutils import sysconfig from distutils . core import Command from distutils . dep_util import newer from distutils . util import convert_path from distutils import log first_line_re = re . compile ( '' ) class build_scripts ( Command ) : description = \"\" user_options = [ ( '' , '' , \"\" ) , ( '' , '' , \"\" ) , ( '' , '' , \"\" ) , ] boolean_options = [ '' ] def initialize_options ( self ) : self . build_dir = None self . scripts = None self . force = None self . executable = None self . outfiles = None def finalize_options ( self ) : ", "answer": "self . set_undefined_options ( '' ,"}, {"prompt": " def _fix_import_path ( ) : \"\"\"\"\"\" import sys , os try : import wtforms except ImportError : parent_dir = os . path . abspath ( os . path . join ( os . path . dirname ( os . path . abspath ( __file__ ) ) , '' ) ) build_lib = os . path . join ( parent_dir , '' , '' ) if os . path . isdir ( build_lib ) : sys . path . insert ( , build_lib ) else : sys . path . insert ( , parent_dir ) _fix_import_path ( ) extensions = [ '' ] templates_path = [ '' ] source_suffix = '' master_doc = '' project = '' copyright = '' version = '' release = '' today_fmt = '' pygments_style = '' html_style = '' html_static_path = [ '' ] html_last_updated_fmt = '' htmlhelp_basename = '' latex_documents = [ ", "answer": "( '' , '' , '' ,"}, {"prompt": " import util import numpy as np import random import sys def getBestBarList ( midiFileName , beatsPerBar = ) : barLists = util . getNGramBarList ( midiFileName , n = beatsPerBar ) return barLists [ ] def euclideanDistance ( mat_a , index_mat , index ) : diff_mat = np . subtract ( mat_a , np . tile ( index_mat [ index ] , ( mat_a . shape [ ] , ) ) ) dists = [ np . linalg . norm ( vec ) for vec in diff_mat ] return dists def cosineDistance ( mat_a , index_mat , index ) : dot_mat = np . dot ( mat_a , index_mat [ index ] . reshape ( - , ) ) . transpose ( ) dists = [ dot_mat [ , i ] / ( np . linalg . norm ( mat_a [ i ] ) * np . linalg . norm ( index_mat [ index ] ) ) for i in range ( dot_mat . shape [ ] ) ] return dists def getClosestCentroid ( centroids_mat , data_mat , index ) : dists = euclideanDistance ( centroids_mat , data_mat , index ) return np . argmin ( dists ) def getClosestCentroidFromVector ( centroids_mat , vector ) : return getClosestCentroid ( centroids_mat , [ vector ] , ) def getFeatureCentroids ( midiFiles , beatsPerBar = , numCentroids = , maxIterations = ) : bestBarList = [ ] for midiFileName in midiFiles : bestBarList += getBestBarList ( midiFileName , beatsPerBar = beatsPerBar ) numExamples = len ( bestBarList ) data_mat = np . array ( [ bar . getKMeansFeatures ( ) for bar in bestBarList ] ) print '' indices = range ( numExamples ) random . shuffle ( indices ) centroids_mat = data_mat [ indices [ : numCentroids ] ] iterations = corr_centers = [ - ] * numExamples n_dashes = print \"\" , for _ in range ( maxIterations ) : if _ * / maxIterations > n_dashes : for i in range ( ( ( _ * ) / maxIterations ) - n_dashes ) : sys . stdout . write ( '' ) sys . stdout . flush ( ) n_dashes += iterations += corr_points = [ [ ] for placeholder in range ( numCentroids ) ] new_corr_centers = [ ] for index in range ( numExamples ) : center = getClosestCentroid ( centroids_mat , data_mat , index ) new_corr_centers . append ( center ) corr_points [ center ] . append ( index ) for index in range ( numCentroids ) : rel_points = data_mat [ corr_points [ index ] ] . transpose ( ) centroids_mat [ index ] = np . array ( [ np . mean ( pt_points ) if pt_points . any ( ) else for pt_points in rel_points ] ) if new_corr_centers == corr_centers : break ", "answer": "corr_centers = list ( new_corr_centers )"}, {"prompt": " '''''' from attributes import * from core import BaseElement , PointAttrib , DeltaPointAttrib , RotateAttrib class altGlyphDef ( BaseElement , CoreAttrib ) : \"\"\"\"\"\" def __init__ ( self , ** kwargs ) : BaseElement . __init__ ( self , '' ) self . setKWARGS ( ** kwargs ) class altGlyphItem ( BaseElement , CoreAttrib ) : \"\"\"\"\"\" def __init__ ( self , ** kwargs ) : BaseElement . __init__ ( self , '' ) self . setKWARGS ( ** kwargs ) class glyphRef ( BaseElement , CoreAttrib , ExternalAttrib , StyleAttrib , FontAttrib , XLinkAttrib , PaintAttrib , PointAttrib , DeltaPointAttrib ) : \"\"\"\"\"\" def __init__ ( self , ** kwargs ) : BaseElement . __init__ ( self , '' ) self . setKWARGS ( ** kwargs ) def set_glyphRef ( self , glyphRef ) : self . _attributes [ '' ] = glyphRef def get_glyphRef ( self ) : return self . _attributes . get ( '' ) def set_format ( self , format ) : self . _attributes [ '' ] = format def get_format ( self ) : return self . _attributes . get ( '' ) def set_lengthAdjust ( self , lengthAdjust ) : self . _attributes [ '' ] = lengthAdjust def get_lengthAdjust ( self ) : return self . _attributes . get ( '' ) class altGlyph ( glyphRef , ConditionalAttrib , GraphicalEventsAttrib , OpacityAttrib , GraphicsAttrib , CursorAttrib , FilterAttrib , MaskAttrib , ClipAttrib , TextContentAttrib , RotateAttrib ) : \"\"\"\"\"\" def __init__ ( self , ** kwargs ) : BaseElement . __init__ ( self , '' ) self . setKWARGS ( ** kwargs ) def set_textLength ( self , textLength ) : self . _attributes [ '' ] = textLength def get_textLength ( self ) : return self . _attributes . get ( '' ) class textPath ( BaseElement , CoreAttrib , ConditionalAttrib , ExternalAttrib , StyleAttrib , XLinkAttrib , FontAttrib , PaintAttrib , GraphicalEventsAttrib , OpacityAttrib , GraphicsAttrib , CursorAttrib , FilterAttrib , MaskAttrib , ClipAttrib , TextContentAttrib ) : \"\"\"\"\"\" def __init__ ( self , ** kwargs ) : BaseElement . __init__ ( self , '' ) self . setKWARGS ( ** kwargs ) def set_startOffset ( self , startOffset ) : self . _attributes [ '' ] = startOffset def get_startOffset ( self ) : return self . _attributes . get ( '' ) def set_textLength ( self , textLength ) : self . _attributes [ '' ] = textLength def get_textLength ( self ) : return self . _attributes . get ( '' ) def set_lengthAdjust ( self , lengthAdjust ) : self . _attributes [ '' ] = lengthAdjust def get_lengthAdjust ( self ) : return self . _attributes . get ( '' ) def set_method ( self , method ) : self . _attributes [ '' ] = method def get_method ( self ) : return self . _attributes . get ( '' ) def set_spacing ( self , spacing ) : self . _attributes [ '' ] = spacing ", "answer": "def get_spacing ( self ) :"}, {"prompt": " '''''' from __future__ import absolute_import import logging import json import salt . utils import salt . utils . decorators as decorators log = logging . getLogger ( __name__ ) __func_alias__ = { '' : '' , '' : '' , '' : '' } __virtualname__ = '' @ decorators . memoize def _check_imgadm ( ) : '''''' return salt . utils . which ( '' ) def _exit_status ( retcode ) : '''''' ret = { : '' , ", "answer": " : '' ,"}, {"prompt": " \"\"\"\"\"\" from cortex_m import CortexM from . memory_map import ( FlashRegion , RamRegion , MemoryMap ) import logging DBGMCU_CR = DBGMCU_VAL = class STM32F103RC ( CortexM ) : memoryMap = MemoryMap ( FlashRegion ( start = , length = , blocksize = , isBootMemory = True ) , RamRegion ( start = , length = ) ) def __init__ ( self , link ) : super ( STM32F103RC , self ) . __init__ ( link , self . memoryMap ) def init ( self ) : logging . debug ( '' ) ", "answer": "CortexM . init ( self )"}, {"prompt": " import gzip import os import struct import numpy as np from . constants import FIFF from . . fixes import partial from . . externals . six import text_type from . . externals . jdcal import jd2jcal class Tag ( object ) : \"\"\"\"\"\" def __init__ ( self , kind , type_ , size , next , pos = None ) : self . kind = int ( kind ) self . type = int ( type_ ) self . size = int ( size ) self . next = int ( next ) self . pos = pos if pos is not None else next self . pos = int ( self . pos ) self . data = None def __repr__ ( self ) : out = ( \"\" % ( self . kind , self . type , self . size , self . next , self . pos ) ) if hasattr ( self , '' ) : out += \"\" % self . data out += \"\" return out def __cmp__ ( self , tag ) : return int ( self . kind == tag . kind and self . type == tag . type and self . size == tag . size and self . next == tag . next and self . pos == tag . pos and self . data == tag . data ) def read_big ( fid , size = None ) : \"\"\"\"\"\" buf_size = if size is None : if not isinstance ( fid , gzip . GzipFile ) : size = os . fstat ( fid . fileno ( ) ) . st_size - fid . tell ( ) if size is not None : segments = np . r_ [ np . arange ( , size , buf_size ) , size ] buf = bytearray ( b'' * size ) for start , end in zip ( segments [ : - ] , segments [ : ] ) : data = fid . read ( int ( end - start ) ) if len ( data ) != end - start : raise ValueError ( '' ) buf [ start : end ] = data buf = bytes ( buf ) else : buf = [ b'' ] new = fid . read ( buf_size ) while len ( new ) > : buf . append ( new ) new = fid . read ( buf_size ) buf = b'' . join ( buf ) return buf def read_tag_info ( fid ) : \"\"\"\"\"\" tag = _read_tag_header ( fid ) if tag is None : return None if tag . next == : fid . seek ( tag . size , ) elif tag . next > : fid . seek ( tag . next , ) return tag def _fromstring_rows ( fid , tag_size , dtype = None , shape = None , rlims = None ) : \"\"\"\"\"\" if shape is not None : item_size = np . dtype ( dtype ) . itemsize if not len ( shape ) == : raise ValueError ( '' ) want_shape = np . prod ( shape ) have_shape = tag_size // item_size if want_shape != have_shape : raise ValueError ( '' % ( want_shape , have_shape ) ) if not len ( rlims ) == : raise ValueError ( '' ) n_row_out = rlims [ ] - rlims [ ] if n_row_out <= : raise ValueError ( '' ) row_size = item_size * shape [ ] start_skip = int ( rlims [ ] * row_size ) read_size = int ( n_row_out * row_size ) end_pos = int ( fid . tell ( ) + tag_size ) fid . seek ( start_skip , ) out = np . fromstring ( fid . read ( read_size ) , dtype = dtype ) fid . seek ( end_pos ) else : out = np . fromstring ( fid . read ( tag_size ) , dtype = dtype ) return out def _loc_to_coil_trans ( loc ) : \"\"\"\"\"\" loc = loc . astype ( np . float64 ) coil_trans = np . concatenate ( [ loc . reshape ( , ) . T [ : , [ , , , ] ] , np . array ( [ , , , ] ) . reshape ( , ) ] ) return coil_trans def _coil_trans_to_loc ( coil_trans ) : \"\"\"\"\"\" coil_trans = coil_trans . astype ( np . float64 ) return np . roll ( coil_trans . T [ : , : ] , , ) . flatten ( ) def _loc_to_eeg_loc ( loc ) : \"\"\"\"\"\" if loc [ : ] . any ( ) : return np . array ( [ loc [ : ] , loc [ : ] ] ) . T else : return loc [ : ] [ : , np . newaxis ] . copy ( ) _is_matrix = _matrix_coding_dense = _matrix_coding_CCS = _matrix_coding_RCS = _data_type = def _read_tag_header ( fid ) : \"\"\"\"\"\" s = fid . read ( * ) if len ( s ) == : return None return Tag ( * struct . unpack ( '' , s ) ) def _read_matrix ( fid , tag , shape , rlims , matrix_coding ) : \"\"\"\"\"\" matrix_coding = matrix_coding >> if shape is not None : raise ValueError ( '' '' ) if matrix_coding == _matrix_coding_dense : pos = fid . tell ( ) fid . seek ( tag . size - , ) ndim = int ( np . fromstring ( fid . read ( ) , dtype = '' ) ) fid . seek ( - ( ndim + ) * , ) dims = np . fromstring ( fid . read ( * ndim ) , dtype = '' ) [ : : - ] fid . seek ( pos , ) if ndim > : raise Exception ( '' '' ) matrix_type = _data_type & tag . type if matrix_type == FIFF . FIFFT_INT : data = np . fromstring ( read_big ( fid , * dims . prod ( ) ) , dtype = '' ) elif matrix_type == FIFF . FIFFT_JULIAN : data = np . fromstring ( read_big ( fid , * dims . prod ( ) ) , dtype = '' ) elif matrix_type == FIFF . FIFFT_FLOAT : data = np . fromstring ( read_big ( fid , * dims . prod ( ) ) , dtype = '' ) elif matrix_type == FIFF . FIFFT_DOUBLE : data = np . fromstring ( read_big ( fid , * dims . prod ( ) ) , dtype = '' ) elif matrix_type == FIFF . FIFFT_COMPLEX_FLOAT : data = np . fromstring ( read_big ( fid , * * dims . prod ( ) ) , dtype = '' ) data = ( data [ : : ] + * data [ : : ] ) elif matrix_type == FIFF . FIFFT_COMPLEX_DOUBLE : data = np . fromstring ( read_big ( fid , * * dims . prod ( ) ) , dtype = '' ) data = ( data [ : : ] + * data [ : : ] ) else : raise Exception ( '' % matrix_type ) data . shape = dims elif matrix_coding in ( _matrix_coding_CCS , _matrix_coding_RCS ) : from scipy import sparse pos = fid . tell ( ) fid . seek ( tag . size - , ) ndim = int ( np . fromstring ( fid . read ( ) , dtype = '' ) ) fid . seek ( - ( ndim + ) * , ) dims = np . fromstring ( fid . read ( * ( ndim + ) ) , dtype = '' ) if ndim != : raise Exception ( '' '' ) fid . seek ( pos , ) nnz = int ( dims [ ] ) nrow = int ( dims [ ] ) ncol = int ( dims [ ] ) sparse_data = np . fromstring ( fid . read ( * nnz ) , dtype = '' ) shape = ( dims [ ] , dims [ ] ) if matrix_coding == _matrix_coding_CCS : tmp_indices = fid . read ( * nnz ) sparse_indices = np . fromstring ( tmp_indices , dtype = '' ) tmp_ptrs = fid . read ( * ( ncol + ) ) sparse_ptrs = np . fromstring ( tmp_ptrs , dtype = '' ) if ( sparse_ptrs [ - ] > len ( sparse_indices ) or np . any ( sparse_ptrs < ) ) : sparse_indices = np . concatenate ( ( np . fromstring ( tmp_indices [ : * ( nrow + ) ] , dtype = '' ) , np . fromstring ( tmp_indices [ * ( nrow + ) : ] , dtype = '' ) ) ) sparse_ptrs = np . fromstring ( tmp_ptrs , dtype = '' ) data = sparse . csc_matrix ( ( sparse_data , sparse_indices , sparse_ptrs ) , shape = shape ) else : sparse_indices = np . fromstring ( fid . read ( * nnz ) , dtype = '' ) sparse_ptrs = np . fromstring ( fid . read ( * ( nrow + ) ) , dtype = '' ) data = sparse . csr_matrix ( ( sparse_data , sparse_indices , sparse_ptrs ) , shape = shape ) else : raise Exception ( '' '' ) return data def _read_simple ( fid , tag , shape , rlims , dtype ) : \"\"\"\"\"\" return _fromstring_rows ( fid , tag . size , dtype = dtype , shape = shape , rlims = rlims ) def _read_string ( fid , tag , shape , rlims ) : \"\"\"\"\"\" d = _fromstring_rows ( fid , tag . size , dtype = '' , shape = shape , rlims = rlims ) return text_type ( d . tostring ( ) . decode ( '' , '' ) ) def _read_complex_float ( fid , tag , shape , rlims ) : \"\"\"\"\"\" if shape is not None : shape = ( shape [ ] , shape [ ] * ) d = _fromstring_rows ( fid , tag . size , dtype = \"\" , shape = shape , rlims = rlims ) d = d [ : : ] + * d [ : : ] return d def _read_complex_double ( fid , tag , shape , rlims ) : \"\"\"\"\"\" if shape is not None : shape = ( shape [ ] , shape [ ] * ) d = _fromstring_rows ( fid , tag . size , dtype = \"\" , shape = shape , rlims = rlims ) d = d [ : : ] + * d [ : : ] return d def _read_id_struct ( fid , tag , shape , rlims ) : \"\"\"\"\"\" return dict ( version = int ( np . fromstring ( fid . read ( ) , dtype = \"\" ) ) , machid = np . fromstring ( fid . read ( ) , dtype = \"\" ) , secs = int ( np . fromstring ( fid . read ( ) , dtype = \"\" ) ) , usecs = int ( np . fromstring ( fid . read ( ) , dtype = \"\" ) ) ) def _read_dig_point_struct ( fid , tag , shape , rlims ) : \"\"\"\"\"\" return dict ( kind = int ( np . fromstring ( fid . read ( ) , dtype = \"\" ) ) , ident = int ( np . fromstring ( fid . read ( ) , dtype = \"\" ) ) , r = np . fromstring ( fid . read ( ) , dtype = \"\" ) , coord_frame = FIFF . FIFFV_COORD_UNKNOWN ) def _read_coord_trans_struct ( fid , tag , shape , rlims ) : \"\"\"\"\"\" from . . transforms import Transform fro = int ( np . fromstring ( fid . read ( ) , dtype = \"\" ) ) to = int ( np . fromstring ( fid . read ( ) , dtype = \"\" ) ) rot = np . fromstring ( fid . read ( ) , dtype = \"\" ) . reshape ( , ) move = np . fromstring ( fid . read ( ) , dtype = \"\" ) trans = np . r_ [ np . c_ [ rot , move ] , np . array ( [ [ ] , [ ] , [ ] , [ ] ] ) . T ] data = Transform ( fro , to , trans ) fid . seek ( , ) return data _coord_dict = { FIFF . FIFFV_MEG_CH : FIFF . FIFFV_COORD_DEVICE , FIFF . FIFFV_REF_MEG_CH : FIFF . FIFFV_COORD_DEVICE , FIFF . FIFFV_EEG_CH : FIFF . FIFFV_COORD_HEAD , } def _read_ch_info_struct ( fid , tag , shape , rlims ) : \"\"\"\"\"\" d = dict ( scanno = int ( np . fromstring ( fid . read ( ) , dtype = \"\" ) ) , logno = int ( np . fromstring ( fid . read ( ) , dtype = \"\" ) ) , kind = int ( np . fromstring ( fid . read ( ) , dtype = \"\" ) ) , range = float ( np . fromstring ( fid . read ( ) , dtype = \"\" ) ) , cal = float ( np . fromstring ( fid . read ( ) , dtype = \"\" ) ) , coil_type = int ( np . fromstring ( fid . read ( ) , dtype = \"\" ) ) , loc = np . fromstring ( fid . read ( ) , dtype = \"\" ) . astype ( np . float64 ) , unit = int ( np . fromstring ( fid . read ( ) , dtype = \"\" ) ) , unit_mul = int ( np . fromstring ( fid . read ( ) , dtype = \"\" ) ) , ) ch_name = np . fromstring ( fid . read ( ) , dtype = \"\" ) ch_name = ch_name [ : np . argmax ( ch_name == b'' ) ] . tostring ( ) d [ '' ] = ch_name . decode ( ) d [ '' ] = _coord_dict . get ( d [ '' ] , FIFF . FIFFV_COORD_UNKNOWN ) return d def _read_old_pack ( fid , tag , shape , rlims ) : \"\"\"\"\"\" offset = float ( np . fromstring ( fid . read ( ) , dtype = \"\" ) ) scale = float ( np . fromstring ( fid . read ( ) , dtype = \"\" ) ) data = np . fromstring ( fid . read ( tag . size - ) , dtype = \"\" ) data = data * scale data += offset return data def _read_dir_entry_struct ( fid , tag , shape , rlims ) : \"\"\"\"\"\" return [ _read_tag_header ( fid ) for _ in range ( tag . size // - ) ] def _read_julian ( fid , tag , shape , rlims ) : \"\"\"\"\"\" return jd2jcal ( int ( np . fromstring ( fid . read ( ) , dtype = \"\" ) ) ) _call_dict = { FIFF . FIFFT_STRING : _read_string , FIFF . FIFFT_COMPLEX_FLOAT : _read_complex_float , FIFF . FIFFT_COMPLEX_DOUBLE : _read_complex_double , FIFF . FIFFT_ID_STRUCT : _read_id_struct , FIFF . FIFFT_DIG_POINT_STRUCT : _read_dig_point_struct , FIFF . FIFFT_COORD_TRANS_STRUCT : _read_coord_trans_struct , FIFF . FIFFT_CH_INFO_STRUCT : _read_ch_info_struct , FIFF . FIFFT_OLD_PACK : _read_old_pack , FIFF . FIFFT_DIR_ENTRY_STRUCT : _read_dir_entry_struct , FIFF . FIFFT_JULIAN : _read_julian , } _simple_dict = { FIFF . FIFFT_BYTE : '' , FIFF . FIFFT_SHORT : '' , FIFF . FIFFT_INT : '' , FIFF . FIFFT_USHORT : '' , FIFF . FIFFT_UINT : '' , FIFF . FIFFT_FLOAT : '' , FIFF . FIFFT_DOUBLE : '' , FIFF . FIFFT_DAU_PACK16 : '' , } for key , dtype in _simple_dict . items ( ) : _call_dict [ key ] = partial ( _read_simple , dtype = dtype ) def read_tag ( fid , pos = None , shape = None , rlims = None ) : \"\"\"\"\"\" if pos is not None : fid . seek ( pos , ) tag = _read_tag_header ( fid ) if tag . size > : matrix_coding = _is_matrix & tag . type if matrix_coding != : tag . data = _read_matrix ( fid , tag , shape , rlims , matrix_coding ) else : fun = _call_dict . get ( tag . type ) if fun is not None : tag . data = fun ( fid , tag , shape , rlims ) else : raise Exception ( '' % tag . type ) if tag . next != FIFF . FIFFV_NEXT_SEQ : fid . seek ( tag . next , ) return tag ", "answer": "def find_tag ( fid , node , findkind ) :"}, {"prompt": " from collections import defaultdict import os from django . conf import settings from django . core . management . base import NoArgsCommand from django . db import models from django . db . models . loading import cache class Command ( NoArgsCommand ) : help = \"\" def handle_noargs ( self , ** options ) : if settings . MEDIA_ROOT == '' : print \"\" return media = [ ] for root , dirs , files in os . walk ( settings . MEDIA_ROOT ) : for f in files : media . append ( os . path . abspath ( os . path . join ( root , f ) ) ) model_dict = defaultdict ( list ) for app in cache . get_apps ( ) : model_list = cache . get_models ( app ) for model in model_list : for field in model . _meta . fields : if issubclass ( field . __class__ , models . FileField ) : model_dict [ model ] . append ( field ) ", "answer": "referenced = [ ]"}, {"prompt": " \"\"\"\"\"\" import datetime import calendar from . filter import BaseParser , str_tuple from . exception import CanNotFormatError , UnexpectedTypeError bp = BaseParser . main dp = BaseParser . parse_diff def parse ( value ) : return bp ( value ) def count ( value1 , value2 ) : _val1 , _val2 = parse ( value1 ) , parse ( value2 ) if type ( _val1 ) == type ( _val2 ) : return _val1 - _val2 else : _val1 = _val1 if isinstance ( _val1 , datetime . datetime ) else midnight ( _val1 ) _val2 = _val2 if isinstance ( _val2 , datetime . datetime ) else midnight ( _val2 ) return _val1 - _val2 _date = datetime . date . today ( ) _datetime = datetime . datetime . now ( ) _year = _date . year _month = _date . month _day = _date . day _SEVEN_DAYS = datetime . timedelta ( days = ) _ONE_DAY = datetime . timedelta ( days = ) def today ( year = None ) : \"\"\"\"\"\" return datetime . date ( int ( year ) , _date . month , _date . day ) if year else _date def tomorrow ( date = None ) : \"\"\"\"\"\" if not date : return _date + datetime . timedelta ( days = ) else : current_date = parse ( date ) return current_date + datetime . timedelta ( days = ) def yesterday ( date = None ) : \"\"\"\"\"\" if not date : return _date - datetime . timedelta ( days = ) else : current_date = parse ( date ) return current_date - datetime . timedelta ( days = ) def daysrange ( first = None , second = None , wipe = False ) : \"\"\"\"\"\" _first , _second = parse ( first ) , parse ( second ) ( _start , _end ) = ( _second , _first ) if _first > _second else ( _first , _second ) days_between = ( _end - _start ) . days date_list = [ _end - datetime . timedelta ( days = x ) for x in range ( , days_between + ) ] if wipe and len ( date_list ) >= : date_list = date_list [ : - ] return date_list def lastday ( year = _year , month = _month ) : \"\"\"\"\"\" last_day = calendar . monthrange ( year , month ) [ ] return datetime . date ( year = year , month = month , day = last_day ) def midnight ( arg = None ) : \"\"\"\"\"\" if arg : _arg = parse ( arg ) if isinstance ( _arg , datetime . date ) : return datetime . datetime . combine ( _arg , datetime . datetime . min . time ( ) ) elif isinstance ( _arg , datetime . datetime ) : return datetime . datetime . combine ( _arg . date ( ) , datetime . datetime . min . time ( ) ) else : return datetime . datetime . combine ( _date , datetime . datetime . min . time ( ) ) def before ( base = _datetime , diff = None ) : \"\"\"\"\"\" _base = parse ( base ) if isinstance ( _base , datetime . date ) : _base = midnight ( _base ) if not diff : return _base result_dict = dp ( diff ) for unit in result_dict : _val = result_dict [ unit ] if not _val : continue if unit == '' : _base = _base . replace ( year = ( _base . year - _val ) ) elif unit == '' : if _base . month <= _val : _month_diff = - ( _val - _base . month ) _base = _base . replace ( year = _base . year - ) . replace ( month = _month_diff ) else : _base = _base . replace ( month = _base . month - _val ) elif unit in [ '' , '' , '' , '' ] : _base = _base - datetime . timedelta ( ** { unit : _val } ) return _base def after ( base = _datetime , diff = None ) : \"\"\"\"\"\" _base = parse ( base ) if isinstance ( _base , datetime . date ) : _base = midnight ( _base ) result_dict = dp ( diff ) for unit in result_dict : _val = result_dict [ unit ] if not _val : continue if unit == '' : _base = _base . replace ( year = ( _base . year + _val ) ) elif unit == '' : if _base . month + _val <= : _base = _base . replace ( month = _base . month + _val ) else : _month_diff = ( _base . month + _val ) - _base = _base . replace ( year = _base . year + ) . replace ( month = _month_diff ) elif unit in [ '' , '' , '' , '' ] : _base = _base + datetime . timedelta ( ** { unit : _val } ) return _base def _datetime_to_date ( arg ) : \"\"\"\"\"\" _arg = parse ( arg ) if isinstance ( _arg , datetime . datetime ) : _arg = _arg . date ( ) return _arg def this_week ( arg = _date , clean = False ) : _arg = _datetime_to_date ( arg ) return _arg - datetime . timedelta ( days = _arg . weekday ( ) ) , _arg + datetime . timedelta ( days = - _arg . weekday ( ) ) if clean else _arg + datetime . timedelta ( days = - _arg . weekday ( ) ) + _ONE_DAY def last_week ( arg = _date , clean = False ) : this_week_tuple = this_week ( arg ) return this_week_tuple [ ] - _SEVEN_DAYS , this_week_tuple [ ] - _SEVEN_DAYS if clean else this_week_tuple [ ] - _SEVEN_DAYS + _ONE_DAY def next_week ( arg = _date , clean = False ) : this_week_tuple = this_week ( arg ) return this_week_tuple [ ] + _SEVEN_DAYS , this_week_tuple [ ] + _SEVEN_DAYS if clean else this_week_tuple [ ] + _SEVEN_DAYS + _ONE_DAY def this_month ( arg = _date , clean = False ) : _arg = _datetime_to_date ( arg ) return datetime . date ( _arg . year , _arg . month , ) , lastday ( _arg . year , _arg . month ) if clean else lastday ( _arg . year , _arg . month ) + _ONE_DAY def last_month ( arg = _date , clean = False ) : _arg = _datetime_to_date ( arg ) this_month_first_day = datetime . date ( _arg . year , _arg . month , ) ", "answer": "last_month_last_day = this_month_first_day - _ONE_DAY"}, {"prompt": " from __future__ import ( absolute_import , division , generators , nested_scopes , print_function , unicode_literals , with_statement ) import logging from pants . task . changed_file_task_mixin import ChangedFileTaskMixin from pants . task . noop_exec_task import NoopExecTask logger = logging . getLogger ( __name__ ) class ChangedTargetTask ( ChangedFileTaskMixin , NoopExecTask ) : \"\"\"\"\"\" @ classmethod def register_options ( cls , register ) : super ( ChangedTargetTask , cls ) . register_options ( register ) cls . register_change_file_options ( register ) @ classmethod def alternate_target_roots ( cls , options , address_mapper , build_graph ) : change_calculator = cls . change_calculator ( options , address_mapper , build_graph ) changed_addresses = change_calculator . changed_target_addresses ( ) readable = '' . join ( sorted ( '' . format ( addr . reference ( ) ) for addr in changed_addresses ) ) ", "answer": "logger . info ( '' . format ( len ( changed_addresses ) , readable ) )"}, {"prompt": " \"\"\"\"\"\" import logging from modularodm import Q from framework . mongo import database from framework . transactions . context import TokuTransaction ", "answer": "from website import settings"}, {"prompt": " from muntjac . api import HorizontalLayout , Button , Label , TextArea from muntjac . data . property import IValueChangeListener class TextAreaExample ( HorizontalLayout , IValueChangeListener ) : _initialText = '' def __init__ ( self ) : super ( TextAreaExample , self ) . __init__ ( ) self . setSpacing ( True ) self . setWidth ( '' ) self . _editor = TextArea ( None , self . _initialText ) self . _editor . setRows ( ) self . _editor . setColumns ( ) self . _editor . addListener ( self , IValueChangeListener ) self . _editor . setImmediate ( True ) self . addComponent ( self . _editor ) self . addComponent ( Button ( '>' ) ) self . _plainText = Label ( self . _initialText ) self . _plainText . setContentMode ( Label . CONTENT_XHTML ) self . addComponent ( self . _plainText ) self . setExpandRatio ( self . _plainText , ) def valueChange ( self , event ) : text = self . _editor . getValue ( ) if text is not None : text = text . replace ( '' , '' ) ", "answer": "self . _plainText . setValue ( text ) "}, {"prompt": " \"\"\"\"\"\" from __future__ import print_function as _print_function from __future__ import absolute_import as _absolute_import import logging as _logging import copy as _copy import pickle as _pickle import debacl . utils as _utl _logging . basicConfig ( level = _logging . INFO , datefmt = '' , format = '' ) try : import numpy as _np import networkx as _nx from prettytable import PrettyTable as _PrettyTable except : raise ImportError ( \"\" + \"\" ) try : import matplotlib . pyplot as _plt from matplotlib . collections import LineCollection as _LineCollection _HAS_MPL = True except : _HAS_MPL = False _logging . warning ( \"\" + \"\" ) class ConnectedComponent ( object ) : \"\"\"\"\"\" def __init__ ( self , idnum , parent , children , start_level , end_level , start_mass , end_mass , members ) : self . idnum = idnum self . parent = parent self . children = children self . start_level = start_level self . end_level = end_level self . start_mass = start_mass self . end_mass = end_mass self . members = members class LevelSetTree ( object ) : \"\"\"\"\"\" def __init__ ( self , density = [ ] , levels = [ ] ) : self . density = density self . levels = levels self . num_levels = len ( levels ) self . prune_threshold = None self . nodes = { } self . _subgraphs = { } def __repr__ ( self ) : \"\"\"\"\"\" return self . __str__ ( ) def __str__ ( self ) : \"\"\"\"\"\" summary = _PrettyTable ( [ \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ] ) for node_id , v in self . nodes . items ( ) : summary . add_row ( [ node_id , v . start_level , v . end_level , v . start_mass , v . end_mass , len ( v . members ) , v . parent , v . children ] ) for col in [ \"\" , \"\" , \"\" , \"\" ] : summary . float_format [ col ] = \"\" return summary . get_string ( ) def prune ( self , threshold ) : \"\"\"\"\"\" return self . _merge_by_size ( threshold ) def save ( self , filename ) : \"\"\"\"\"\" with open ( filename , '' ) as f : _pickle . dump ( self , f , _pickle . HIGHEST_PROTOCOL ) def plot ( self , form = '' , horizontal_spacing = '' , color_nodes = [ ] , colormap = '' ) : \"\"\"\"\"\" if not isinstance ( color_nodes , list ) : raise TypeError ( \"\" ) if not set ( color_nodes ) . issubset ( self . nodes . keys ( ) ) : raise ValueError ( \"\" + \"\" + \"\" + \"\" ) gap = min_node_width = node_coords = { } split_coords = { } ix_root = _np . array ( [ k for k , v in self . nodes . iteritems ( ) if v . parent is None ] ) n_root = len ( ix_root ) census = _np . array ( [ len ( self . nodes [ x ] . members ) for x in ix_root ] , dtype = _np . float ) n = sum ( census ) seniority = _np . argsort ( census ) [ : : - ] ix_root = ix_root [ seniority ] census = census [ seniority ] if horizontal_spacing == '' : weights = census / n intervals = _np . cumsum ( weights ) intervals = _np . insert ( intervals , , ) else : intervals = _np . linspace ( , , n_root + ) for i , ix in enumerate ( ix_root ) : if form == '' : branch = self . _construct_mass_map ( ix , , ( intervals [ i ] , intervals [ i + ] ) , horizontal_spacing ) else : branch = self . _construct_branch_map ( ix , ( intervals [ i ] , intervals [ i + ] ) , form , horizontal_spacing , sort = True ) branch_node_coords , branch_split_coords , _ , _ = branch node_coords . update ( branch_node_coords ) split_coords . update ( branch_split_coords ) node_widths = { k : max ( min_node_width , * len ( node . members ) / n ) for k , node in self . nodes . items ( ) } primary_ticks = [ ( x [ ] [ ] , x [ ] [ ] ) for x in node_coords . values ( ) ] primary_ticks = _np . unique ( _np . array ( primary_ticks ) . flatten ( ) ) primary_labels = [ str ( round ( tick , ) ) for tick in primary_ticks ] fig , ax = _plt . subplots ( ) ax . set_position ( [ , , , ] ) ax . set_xlim ( ( - , ) ) ax . set_xticks ( [ ] ) ax . set_xticklabels ( [ ] ) ax . yaxis . grid ( color = '' ) ax . set_yticks ( primary_ticks ) ax . set_yticklabels ( primary_labels ) if form == '' : kappa_max = max ( primary_ticks ) ax . set_ylim ( ( - * gap * kappa_max , * kappa_max ) ) ax . set_ylabel ( \"\" ) elif form == '' : ax . set_ylabel ( \"\" ) ymin = min ( [ v . start_level for v in self . nodes . itervalues ( ) ] ) ymax = max ( [ v . end_level for v in self . nodes . itervalues ( ) ] ) rng = ymax - ymin ax . set_ylim ( ymin - gap * rng , ymax + * rng ) elif form == '' : ax . set_ylabel ( \"\" ) ymin = min ( [ v . start_mass for v in self . nodes . itervalues ( ) ] ) ymax = max ( [ v . end_mass for v in self . nodes . itervalues ( ) ] ) rng = ymax - ymin ax . set_ylim ( ymin - gap * rng , ymax + * ymax ) else : raise ValueError ( '' ) node_colors = { k : [ , , , ] for k , v in self . nodes . items ( ) } palette = _plt . get_cmap ( colormap ) colorset = palette ( _np . linspace ( , , len ( color_nodes ) ) ) for i , ix in enumerate ( color_nodes ) : subtree = self . _make_subtree ( ix ) for ix_sub in subtree . nodes . keys ( ) : node_colors [ ix_sub ] = list ( colorset [ i ] ) line_coords = [ node_coords [ c ] for c in node_coords . keys ( ) ] line_widths = [ node_widths [ c ] for c in node_coords . keys ( ) ] line_colors = [ node_colors [ c ] for c in node_coords . keys ( ) ] node_lines = _LineCollection ( line_coords , linewidths = line_widths , colors = line_colors ) ax . add_collection ( node_lines ) line_coords = [ split_coords [ c ] for c in split_coords . keys ( ) ] line_colors = [ node_colors [ c ] for c in split_coords . keys ( ) ] split_lines = _LineCollection ( line_coords , colors = line_colors ) ax . add_collection ( split_lines ) return fig , node_coords , split_coords , node_colors def get_clusters ( self , method = '' , fill_background = False , ** kwargs ) : \"\"\"\"\"\" if method == '' : labels = self . _leaf_cluster ( ) elif method == '' : required = set ( [ '' ] ) if not set ( kwargs . keys ( ) ) . issuperset ( required ) : raise ValueError ( \"\" + \"\" ) else : k = kwargs . get ( '' ) labels = self . _first_K_cluster ( k ) elif method == '' : required = set ( [ '' , '' ] ) if not set ( kwargs . keys ( ) ) . issuperset ( required ) : raise ValueError ( \"\" + \"\" ) else : threshold = kwargs . get ( '' ) form = kwargs . get ( '' ) labels = self . _upper_set_cluster ( threshold , form ) elif method == '' : required = set ( [ '' ] ) if not set ( kwargs . keys ( ) ) . issuperset ( required ) : raise ValueError ( \"\" + \"\" ) else : k = kwargs . get ( '' ) labels = self . _first_K_level_cluster ( k ) else : raise ValueError ( \"\" ) if fill_background : n = len ( self . density ) full_labels = _np . vstack ( ( _np . arange ( n ) , [ - ] * n ) ) . T full_labels [ labels [ : , ] , ] = labels [ : , ] labels = full_labels return labels def get_leaf_nodes ( self ) : \"\"\"\"\"\" return [ k for k , v in self . nodes . items ( ) if v . children == [ ] ] def branch_partition ( self ) : \"\"\"\"\"\" points = [ ] labels = [ ] for ix , node in self . nodes . items ( ) : branch_members = node . members . copy ( ) for ix_child in node . children : child_node = self . nodes [ ix_child ] branch_members . difference_update ( child_node . members ) ", "answer": "points . extend ( branch_members )"}, {"prompt": " \"\"\"\"\"\" import sys , os , urllib , time , traceback , cgi , re , socket from cPickle import load , dump from itertools import chain from django . conf import settings from django . core . exceptions import ObjectDoesNotExist from graphite . util import getProfile , getProfileByUsername from graphite . logger import log from graphite . account . models import Profile , MyGraph , Variable , View , Window def printException ( ) : out = \"\" out += traceback . format_exc ( ) out += \"\" return stdout ( out ) def stdout ( text , lineBreak = True ) : text = text . replace ( '' , \"\" ) text = text . replace ( '' , '' ) br = '' if lineBreak : br = \"\" return \"\"\"\"\"\" % ( text , br ) def stderr ( text ) : return \"\"\"\"\"\" % text . replace ( '' , \"\" ) def _set ( request , name , value ) : profile = getProfile ( request ) try : variable = profile . variable_set . get ( name = name ) variable . value = value except ObjectDoesNotExist : variable = Variable ( profile = profile , name = name , value = value ) variable . save ( ) return '' def _unset ( request , name ) : profile = getProfile ( request ) try : variable = profile . variable_set . get ( name = name ) variable . delete ( ) except ObjectDoesNotExist : return stderr ( \"\" % name ) return '' def _echo ( request , args ) : return stdout ( args ) def _vars ( request ) : profile = getProfile ( request ) out = '' for variable in profile . variable_set . all ( ) : out += '' % ( variable . name , variable . value ) out += '' return stdout ( out ) def _clear ( request ) : return \"\" def _create ( request , window ) : out = '' w = window . replace ( '' , '' ) out += \"\" % ( w , w , w ) out += \"\" % w out += \"\" % w out += \"\" % w out += \"\" % w out += \"\" % w out += \"\" % ( w , w ) out += \"\" % w out += \"\" out += \"\" out += \"\" out += \"\" out += \"\" out += \"\" out += \"\" out += \"\" out += \"\" out += \"\" % ( w , w , w ) out += \"\" out += \"\" % ( w , w ) return out def _draw ( request , targets , _from = None , until = None , template = None , window = None , interval = None ) : out = '' params = [ ( '' , t ) for t in targets ] if _from : params . append ( ( '' , _from ) ) if until : params . append ( ( '' , until ) ) if template : params . append ( ( '' , template ) ) url = '' + urllib . urlencode ( params ) if window : w = window out += \"\" % w out += \"\" % w out += \"\" out += \"\" out += \"\" % w out += \"\" out += \"\" % url out += \"\" out += \"\" out += \"\" out += \"\" out += \"\" out += \"\" out += \"\" out += \"\" if interval : i = int ( interval ) out += \"\" % ( w , i ) out += \"\" % ( w , w , w ) else : return stdout ( \"\" % url ) return out def _redraw ( request , window , interval ) : out = '' w = window i = int ( interval ) out += \"\" % w out += \"\" out += \"\" % w out += \"\" out += \"\" % ( w , w ) out += \"\" % ( w , i ) out += \"\" % ( w , w , w ) out += \"\" return out def _email ( request , window , addressList ) : ", "answer": "out = ''"}, {"prompt": " from neutron_lib . api import validators from oslo_config import cfg from oslo_log import log as logging from neutron . _i18n import _LE , _LI from neutron . callbacks import events from neutron . callbacks import registry from neutron . callbacks import resources from neutron . db import dns_db from neutron . db import models_v2 from neutron . extensions import dns from neutron import manager from neutron . plugins . common import utils as plugin_utils from neutron . plugins . ml2 import db from neutron . plugins . ml2 import driver_api as api from neutron . services . externaldns import driver LOG = logging . getLogger ( __name__ ) class DNSExtensionDriver ( api . ExtensionDriver ) : _supported_extension_alias = '' @ property def extension_alias ( self ) : return self . _supported_extension_alias def process_create_network ( self , plugin_context , request_data , db_data ) : dns_domain = request_data . get ( dns . DNSDOMAIN ) if not validators . is_attr_set ( dns_domain ) : return if dns_domain : plugin_context . session . add ( dns_db . NetworkDNSDomain ( network_id = db_data [ '' ] , dns_domain = dns_domain ) ) db_data [ dns . DNSDOMAIN ] = dns_domain def process_update_network ( self , plugin_context , request_data , db_data ) : new_value = request_data . get ( dns . DNSDOMAIN ) if not validators . is_attr_set ( new_value ) : return current_dns_domain = db_data . get ( dns . DNSDOMAIN ) if current_dns_domain == new_value : return net_id = db_data [ '' ] if current_dns_domain : net_dns_domain = plugin_context . session . query ( dns_db . NetworkDNSDomain ) . filter_by ( network_id = net_id ) . one ( ) if new_value : net_dns_domain [ '' ] = new_value db_data [ dns . DNSDOMAIN ] = new_value else : plugin_context . session . delete ( net_dns_domain ) db_data [ dns . DNSDOMAIN ] = '' elif new_value : plugin_context . session . add ( dns_db . NetworkDNSDomain ( network_id = net_id , dns_domain = new_value ) ) db_data [ dns . DNSDOMAIN ] = new_value def process_create_port ( self , plugin_context , request_data , db_data ) : if not request_data [ dns . DNSNAME ] : return network = self . _get_network ( plugin_context , db_data [ '' ] ) if not network [ dns . DNSDOMAIN ] : return if self . external_dns_not_needed ( plugin_context , network ) : return plugin_context . session . add ( dns_db . PortDNS ( port_id = db_data [ '' ] , current_dns_name = request_data [ dns . DNSNAME ] , current_dns_domain = network [ dns . DNSDOMAIN ] , previous_dns_name = '' , previous_dns_domain = '' ) ) def process_update_port ( self , plugin_context , request_data , db_data ) : dns_name = request_data . get ( dns . DNSNAME ) has_fixed_ips = '' in request_data if dns_name is None and not has_fixed_ips : return network = self . _get_network ( plugin_context , db_data [ '' ] ) if not network [ dns . DNSDOMAIN ] : return if self . external_dns_not_needed ( plugin_context , network ) : return dns_domain = network [ dns . DNSDOMAIN ] dns_data_db = plugin_context . session . query ( dns_db . PortDNS ) . filter_by ( port_id = db_data [ '' ] ) . one_or_none ( ) if dns_data_db : is_dns_name_changed = ( dns_name is not None and dns_data_db [ '' ] != dns_name ) if is_dns_name_changed or ( has_fixed_ips and dns_data_db [ '' ] ) : dns_data_db [ '' ] = ( dns_data_db [ '' ] ) dns_data_db [ '' ] = ( dns_data_db [ '' ] ) if is_dns_name_changed : dns_data_db [ '' ] = dns_name if dns_name : dns_data_db [ '' ] = dns_domain else : dns_data_db [ '' ] = '' ", "answer": "return"}, {"prompt": " from __future__ import ( absolute_import , division , generators , nested_scopes , print_function , unicode_literals , with_statement ) import os from pex . fetcher import Fetcher , PyPIFetcher from pex . http import Context from pkg_resources import Requirement from pants . subsystem . subsystem import Subsystem class PythonSetup ( Subsystem ) : \"\"\"\"\"\" options_scope = '' @ classmethod def register_options ( cls , register ) : super ( PythonSetup , cls ) . register_options ( register ) register ( '' , advanced = True , default = '' , help = '' ) register ( '' , advanced = True , default = '' , help = '' ) register ( '' , advanced = True , default = '' , help = '' ) register ( '' , advanced = True , type = list , default = [ '' ] , help = '' ) register ( '' , advanced = True , default = None , metavar = '' , help = '' '' ) register ( '' , advanced = True , default = None , metavar = '' , help = '' '' ) register ( '' , advanced = True , default = None , metavar = '' , help = '' '' ) register ( '' , advanced = True , type = int , metavar = '' , default = * * , help = '' '' ) register ( '' , advanced = True , default = None , metavar = '' , help = '' '' ) @ property def interpreter_requirement ( self ) : return self . get_options ( ) . interpreter_requirement @ property def setuptools_version ( self ) : return self . get_options ( ) . setuptools_version @ property def wheel_version ( self ) : return self . get_options ( ) . wheel_version @ property def platforms ( self ) : return self . get_options ( ) . platforms @ property def interpreter_cache_dir ( self ) : return ( self . get_options ( ) . interpreter_cache_dir or os . path . join ( self . scratch_dir , '' ) ) @ property def chroot_cache_dir ( self ) : return ( self . get_options ( ) . chroot_cache_dir or os . path . join ( self . scratch_dir , '' ) ) @ property def resolver_cache_dir ( self ) : return ( self . get_options ( ) . resolver_cache_dir or ", "answer": "os . path . join ( self . scratch_dir , '' ) )"}, {"prompt": " class UAgentInfo ( object ) : \"\"\"\"\"\" engineWebKit = \"\" deviceIphone = \"\" deviceIpod = \"\" deviceIpad = \"\" deviceMacPpc = \"\" deviceAndroid = \"\" deviceGoogleTV = \"\" deviceXoom = \"\" deviceHtcFlyer = \"\" deviceSymbian = \"\" deviceS60 = \"\" deviceS70 = \"\" deviceS80 = \"\" deviceS90 = \"\" deviceWinPhone7 = \"\" deviceWinMob = \"\" deviceWindows = \"\" deviceIeMob = \"\" devicePpc = \"\" enginePie = \"\" deviceBB = \"\" vndRIM = \"\" deviceBBStorm = \"\" deviceBBBold = \"\" deviceBBBoldTouch = \"\" deviceBBTour = \"\" deviceBBCurve = \"\" deviceBBCurveTouch = \"\" deviceBBTorch = \"\" deviceBBPlaybook = \"\" devicePalm = \"\" deviceWebOS = \"\" deviceWebOShp = \"\" engineBlazer = \"\" engineXiino = \"\" deviceKindle = \"\" engineSilk = \"\" deviceNuvifone = \"\" vndwap = \"\" wml = \"\" deviceTablet = \"\" deviceBrew = \"\" deviceDanger = \"\" deviceHiptop = \"\" devicePlaystation = \"\" deviceNintendoDs = \"\" deviceNintendo = \"\" deviceWii = \"\" deviceXbox = \"\" deviceArchos = \"\" engineOpera = \"\" engineNetfront = \"\" engineUpBrowser = \"\" engineOpenWeb = \"\" deviceMidp = \"\" uplink = \"\" engineTelecaQ = \"\" devicePda = \"\" mini = \"\" mobile = \"\" mobi = \"\" maemo = \"\" linux = \"\" qtembedded = \"\" mylocom2 = \"\" manuSonyEricsson = \"\" manuericsson = \"\" manuSamsung1 = \"\" manuSony = \"\" manuHtc = \"\" svcDocomo = \"\" svcKddi = \"\" svcVodafone = \"\" disUpdate = \"\" def __init__ ( self , userAgent , httpAccept ) : \"\"\"\"\"\" self . __userAgent = userAgent . lower ( ) if userAgent else \"\" self . __httpAccept = httpAccept . lower ( ) if httpAccept else \"\" self . __isIphone = False self . __isAndroidPhone = False self . __isTierTablet = False self . __isTierIphone = False self . __isTierRichCss = False self . __isTierGenericMobile = False self . initDeviceScan ( ) def getUserAgent ( self ) : \"\"\"\"\"\" return self . __userAgent def getHttpAccept ( self ) : \"\"\"\"\"\" return self . __httpAccept def getIsIphone ( self ) : \"\"\"\"\"\" return self . __isIphone def getIsTierTablet ( self ) : \"\"\"\"\"\" return self . __isTierTablet def getIsTierIphone ( self ) : \"\"\"\"\"\" return self . __isTierIphone def getIsTierRichCss ( self ) : \"\"\"\"\"\" return self . __isTierRichCss def getIsTierGenericMobile ( self ) : \"\"\"\"\"\" return self . __isTierGenericMobile def initDeviceScan ( self ) : \"\"\"\"\"\" self . __isIphone = self . detectIphoneOrIpod ( ) self . __isAndroidPhone = self . detectAndroidPhone ( ) self . __isTierTablet = self . detectTierTablet ( ) self . __isTierIphone = self . detectTierIphone ( ) self . __isTierRichCss = self . detectTierRichCss ( ) self . __isTierGenericMobile = self . detectTierOtherPhones ( ) def detectIphone ( self ) : \"\"\"\"\"\" return UAgentInfo . deviceIphone in self . __userAgent and not self . detectIpad ( ) and not self . detectIpod ( ) def detectIpod ( self ) : \"\"\"\"\"\" return UAgentInfo . deviceIpod in self . __userAgent def detectIpad ( self ) : \"\"\"\"\"\" return UAgentInfo . deviceIpad in self . __userAgent and self . detectWebkit ( ) def detectIphoneOrIpod ( self ) : \"\"\"\"\"\" return UAgentInfo . deviceIphone in self . __userAgent or UAgentInfo . deviceIpod in self . __userAgent def detectIos ( self ) : \"\"\"\"\"\" return self . detectIphoneOrIpod ( ) or self . detectIpad ( ) def detectAndroid ( self ) : \"\"\"\"\"\" if UAgentInfo . deviceAndroid in self . __userAgent or self . detectGoogleTV ( ) : return True return UAgentInfo . deviceHtcFlyer in self . __userAgent def detectAndroidPhone ( self ) : \"\"\"\"\"\" if self . detectAndroid ( ) and UAgentInfo . mobile in self . __userAgent : return True if self . detectOperaAndroidPhone ( ) : return True return UAgentInfo . deviceHtcFlyer in self . __userAgent def detectAndroidTablet ( self ) : \"\"\"\"\"\" if not self . detectAndroid ( ) : return False ", "answer": "if self . detectOperaMobile ( ) :"}, {"prompt": " \"\"\"\"\"\" import getpass , pickle , time , socket import os import StringIO from hashlib import md5 from email . Message import Message from email . Generator import Generator from zope . interface import implements , Interface from twisted . news . nntp import NNTPError from twisted . mail import smtp from twisted . internet import defer from twisted . enterprise import adbapi from twisted . persisted import dirdbm ERR_NOGROUP , ERR_NOARTICLE = range ( , ) OVERVIEW_FMT = [ '' , '' , '' , '' , '' , '' , '' , '' ] def hexdigest ( md5 ) : return '' . join ( map ( lambda x : hex ( ord ( x ) ) [ : ] , md5 . digest ( ) ) ) class Article : def __init__ ( self , head , body ) : self . body = body self . headers = { } header = None for line in head . split ( '' ) : if line [ ] in '' : i = list ( self . headers [ header ] ) i [ ] += '' + line else : i = line . split ( '' , ) header = i [ ] . lower ( ) self . headers [ header ] = tuple ( i ) if not self . getHeader ( '' ) : s = str ( time . time ( ) ) + self . body id = hexdigest ( md5 ( s ) ) + '' + socket . gethostname ( ) self . putHeader ( '' , '' % id ) if not self . getHeader ( '' ) : self . putHeader ( '' , str ( len ( self . body ) ) ) if not self . getHeader ( '' ) : self . putHeader ( '' , str ( self . body . count ( '' ) ) ) if not self . getHeader ( '' ) : self . putHeader ( '' , time . ctime ( time . time ( ) ) ) def getHeader ( self , header ) : h = header . lower ( ) if h in self . headers : return self . headers [ h ] [ ] else : return '' def putHeader ( self , header , value ) : self . headers [ header . lower ( ) ] = ( header , value ) def textHeaders ( self ) : headers = [ ] for i in self . headers . values ( ) : headers . append ( '' % i ) return '' . join ( headers ) + '' def overview ( self ) : xover = [ ] for i in OVERVIEW_FMT : xover . append ( self . getHeader ( i ) ) return xover class NewsServerError ( Exception ) : pass class INewsStorage ( Interface ) : \"\"\"\"\"\" def listRequest ( ) : \"\"\"\"\"\" def subscriptionRequest ( ) : \"\"\"\"\"\" def postRequest ( message ) : \"\"\"\"\"\" def overviewRequest ( ) : \"\"\"\"\"\" def xoverRequest ( group , low , high ) : \"\"\"\"\"\" def xhdrRequest ( group , low , high , header ) : \"\"\"\"\"\" def listGroupRequest ( group ) : \"\"\"\"\"\" def groupRequest ( group ) : \"\"\"\"\"\" def articleExistsRequest ( id ) : \"\"\"\"\"\" def articleRequest ( group , index , id = None ) : \"\"\"\"\"\" def headRequest ( group , index ) : \"\"\"\"\"\" def bodyRequest ( group , index ) : \"\"\"\"\"\" class NewsStorage : \"\"\"\"\"\" def listRequest ( self ) : raise NotImplementedError ( ) def subscriptionRequest ( self ) : raise NotImplementedError ( ) def postRequest ( self , message ) : raise NotImplementedError ( ) def overviewRequest ( self ) : return defer . succeed ( OVERVIEW_FMT ) def xoverRequest ( self , group , low , high ) : raise NotImplementedError ( ) def xhdrRequest ( self , group , low , high , header ) : raise NotImplementedError ( ) def listGroupRequest ( self , group ) : raise NotImplementedError ( ) def groupRequest ( self , group ) : raise NotImplementedError ( ) def articleExistsRequest ( self , id ) : raise NotImplementedError ( ) def articleRequest ( self , group , index , id = None ) : raise NotImplementedError ( ) def headRequest ( self , group , index ) : raise NotImplementedError ( ) def bodyRequest ( self , group , index ) : raise NotImplementedError ( ) class _ModerationMixin : \"\"\"\"\"\" sendmail = staticmethod ( smtp . sendmail ) def notifyModerators ( self , moderators , article ) : \"\"\"\"\"\" group = article . getHeader ( '' ) subject = article . getHeader ( '' ) if self . _sender is None : sender = '' + socket . gethostname ( ) else : sender = self . _sender msg = Message ( ) msg [ '' ] = smtp . messageid ( ) msg [ '' ] = sender msg [ '' ] = '' . join ( moderators ) msg [ '' ] = '' % ( group , subject ) msg [ '' ] = '' payload = Message ( ) for header , value in article . headers . values ( ) : payload . add_header ( header , value ) payload . set_payload ( article . body ) msg . attach ( payload ) out = StringIO . StringIO ( ) gen = Generator ( out , False ) gen . flatten ( msg ) msg = out . getvalue ( ) return self . sendmail ( self . _mailhost , sender , moderators , msg ) class PickleStorage ( _ModerationMixin ) : \"\"\"\"\"\" implements ( INewsStorage ) sharedDBs = { } def __init__ ( self , filename , groups = None , moderators = ( ) , mailhost = None , sender = None ) : \"\"\"\"\"\" self . datafile = filename self . load ( filename , groups , moderators ) self . _mailhost = mailhost self . _sender = sender def getModerators ( self , groups ) : moderators = [ ] for group in groups : moderators . extend ( self . db [ '' ] . get ( group , None ) ) return filter ( None , moderators ) def listRequest ( self ) : \"\" l = self . db [ '' ] r = [ ] for i in l : if len ( self . db [ i ] . keys ( ) ) : low = min ( self . db [ i ] . keys ( ) ) high = max ( self . db [ i ] . keys ( ) ) + else : low = high = if self . db [ '' ] . has_key ( i ) : flags = '' else : flags = '' r . append ( ( i , high , low , flags ) ) return defer . succeed ( r ) def subscriptionRequest ( self ) : return defer . succeed ( [ '' ] ) def postRequest ( self , message ) : cleave = message . find ( '' ) headers , article = message [ : cleave ] , message [ cleave + : ] a = Article ( headers , article ) groups = a . getHeader ( '' ) . split ( ) xref = [ ] moderators = self . getModerators ( groups ) if moderators and not a . getHeader ( '' ) : return self . notifyModerators ( moderators , a ) for group in groups : if group in self . db : if len ( self . db [ group ] . keys ( ) ) : index = max ( self . db [ group ] . keys ( ) ) + else : index = xref . append ( ( group , str ( index ) ) ) self . db [ group ] [ index ] = a if len ( xref ) == : return defer . fail ( None ) a . putHeader ( '' , '' % ( socket . gethostname ( ) . split ( ) [ ] , '' . join ( map ( lambda x : '' . join ( x ) , xref ) ) ) ) self . flush ( ) return defer . succeed ( None ) def overviewRequest ( self ) : return defer . succeed ( OVERVIEW_FMT ) def xoverRequest ( self , group , low , high ) : if not self . db . has_key ( group ) : return defer . succeed ( [ ] ) r = [ ] for i in self . db [ group ] . keys ( ) : if ( low is None or i >= low ) and ( high is None or i <= high ) : r . append ( [ str ( i ) ] + self . db [ group ] [ i ] . overview ( ) ) return defer . succeed ( r ) def xhdrRequest ( self , group , low , high , header ) : if not self . db . has_key ( group ) : return defer . succeed ( [ ] ) r = [ ] for i in self . db [ group ] . keys ( ) : if low is None or i >= low and high is None or i <= high : r . append ( ( i , self . db [ group ] [ i ] . getHeader ( header ) ) ) return defer . succeed ( r ) def listGroupRequest ( self , group ) : if self . db . has_key ( group ) : return defer . succeed ( ( group , self . db [ group ] . keys ( ) ) ) else : return defer . fail ( None ) def groupRequest ( self , group ) : if self . db . has_key ( group ) : if len ( self . db [ group ] . keys ( ) ) : num = len ( self . db [ group ] . keys ( ) ) low = min ( self . db [ group ] . keys ( ) ) high = max ( self . db [ group ] . keys ( ) ) else : num = low = high = flags = '' return defer . succeed ( ( group , num , high , low , flags ) ) else : return defer . fail ( ERR_NOGROUP ) def articleExistsRequest ( self , id ) : for group in self . db [ '' ] : for a in self . db [ group ] . values ( ) : if a . getHeader ( '' ) == id : return defer . succeed ( ) return defer . succeed ( ) def articleRequest ( self , group , index , id = None ) : if id is not None : raise NotImplementedError if self . db . has_key ( group ) : if self . db [ group ] . has_key ( index ) : a = self . db [ group ] [ index ] return defer . succeed ( ( index , a . getHeader ( '' ) , StringIO . StringIO ( a . textHeaders ( ) + '' + a . body ) ) ) else : return defer . fail ( ERR_NOARTICLE ) else : return defer . fail ( ERR_NOGROUP ) def headRequest ( self , group , index ) : if self . db . has_key ( group ) : if self . db [ group ] . has_key ( index ) : a = self . db [ group ] [ index ] return defer . succeed ( ( index , a . getHeader ( '' ) , a . textHeaders ( ) ) ) else : return defer . fail ( ERR_NOARTICLE ) else : return defer . fail ( ERR_NOGROUP ) def bodyRequest ( self , group , index ) : if self . db . has_key ( group ) : if self . db [ group ] . has_key ( index ) : a = self . db [ group ] [ index ] return defer . succeed ( ( index , a . getHeader ( '' ) , StringIO . StringIO ( a . body ) ) ) else : return defer . fail ( ERR_NOARTICLE ) else : return defer . fail ( ERR_NOGROUP ) def flush ( self ) : f = open ( self . datafile , '' ) pickle . dump ( self . db , f ) f . close ( ) def load ( self , filename , groups = None , moderators = ( ) ) : if filename in PickleStorage . sharedDBs : self . db = PickleStorage . sharedDBs [ filename ] else : try : self . db = pickle . load ( open ( filename ) ) PickleStorage . sharedDBs [ filename ] = self . db except IOError : self . db = PickleStorage . sharedDBs [ filename ] = { } self . db [ '' ] = groups if groups is not None : for i in groups : self . db [ i ] = { } self . db [ '' ] = dict ( moderators ) self . flush ( ) class Group : name = None flags = '' minArticle = maxArticle = articles = None def __init__ ( self , name , flags = '' ) : self . name = name self . flags = flags self . articles = { } class NewsShelf ( _ModerationMixin ) : \"\"\"\"\"\" implements ( INewsStorage ) def __init__ ( self , mailhost , path , sender = None ) : \"\"\"\"\"\" self . path = path self . _mailhost = self . mailhost = mailhost self . _sender = sender if not os . path . exists ( path ) : os . mkdir ( path ) self . dbm = dirdbm . Shelf ( os . path . join ( path , \"\" ) ) if not len ( self . dbm . keys ( ) ) : self . initialize ( ) def initialize ( self ) : self . dbm [ '' ] = dirdbm . Shelf ( os . path . join ( self . path , '' ) ) self . dbm [ '' ] = dirdbm . Shelf ( os . path . join ( self . path , '' ) ) self . dbm [ '' ] = [ ] self . dbm [ '' ] = dirdbm . Shelf ( os . path . join ( self . path , '' ) ) def addGroup ( self , name , flags ) : self . dbm [ '' ] [ name ] = Group ( name , flags ) def addSubscription ( self , name ) : self . dbm [ '' ] = self . dbm [ '' ] + [ name ] def addModerator ( self , group , email ) : self . dbm [ '' ] [ group ] = email def listRequest ( self ) : result = [ ] for g in self . dbm [ '' ] . values ( ) : result . append ( ( g . name , g . maxArticle , g . minArticle , g . flags ) ) return defer . succeed ( result ) def subscriptionRequest ( self ) : return defer . succeed ( self . dbm [ '' ] ) def getModerator ( self , groups ) : for group in groups : try : ", "answer": "return self . dbm [ '' ] [ group ]"}, {"prompt": " \"\"\"\"\"\" import datetime as dt from flask import Flask from flask . ext import restful from webargs import fields , validate from webargs . flaskparser import use_args , use_kwargs , parser app = Flask ( __name__ ) api = restful . Api ( app ) class IndexResource ( restful . Resource ) : \"\"\"\"\"\" hello_args = { '' : fields . Str ( missing = '' ) } @ use_args ( hello_args ) def get ( self , args ) : return { '' : '' . format ( args [ '' ] ) } class AddResource ( restful . Resource ) : \"\"\"\"\"\" add_args = { '' : fields . Float ( required = True ) , '' : fields . Float ( required = True ) , } @ use_kwargs ( add_args ) def post ( self , x , y ) : \"\"\"\"\"\" return { '' : x + y } class DateAddResource ( restful . Resource ) : dateadd_args = { '' : fields . DateTime ( required = False ) , '' : fields . Int ( required = True , validate = validate . Range ( min = ) ) , '' : fields . Str ( missing = '' , validate = validate . OneOf ( [ '' , '' ] ) ) } @ use_kwargs ( dateadd_args ) def post ( self , value , addend , unit ) : \"\"\"\"\"\" value = value or dt . datetime . utcnow ( ) if unit == '' : delta = dt . timedelta ( minutes = addend ) else : delta = dt . timedelta ( days = addend ) result = value + delta return { '' : result . isoformat ( ) } @ parser . error_handler def handle_request_parsing_error ( err ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " import time from tqdm import * for i in tqdm ( range ( ) , desc = \"\" , leave = True ) : time . sleep ( ) for i in trange ( ) : ", "answer": "time . sleep ( )"}, {"prompt": " '''''' from __future__ import absolute_import import logging from salt . ext . six . moves import shlex_quote as _cmd_quote import salt . utils . validate . net from salt . exceptions import CommandExecutionError log = logging . getLogger ( __name__ ) HAS_PYBLUEZ = False try : import bluetooth HAS_PYBLUEZ = True except ImportError : pass __func_alias__ = { '' : '' } __virtualname__ = '' def __virtual__ ( ) : '''''' if HAS_PYBLUEZ : return __virtualname__ return ( False , '' ) def version ( ) : '''''' cmd = '' out = __salt__ [ '' ] ( cmd ) . splitlines ( ) bluez_version = out [ ] pybluez_version = '' try : pybluez_version = bluetooth . __version__ except Exception as exc : pass return { '' : bluez_version , '' : pybluez_version } def address_ ( ) : '''''' ret = { } cmd = '' out = __salt__ [ '' ] ( cmd ) . splitlines ( ) dev = '' for line in out : if line . startswith ( '' ) : comps = line . split ( '' ) dev = comps [ ] ret [ dev ] = { '' : dev , '' : '' . format ( dev ) , } if '' in line : comps = line . split ( ) ret [ dev ] [ '' ] = comps [ ] if '' in line : ret [ dev ] [ '' ] = '' if '' in line : ret [ dev ] [ '' ] = '' return ret def power ( dev , mode ) : '''''' if dev not in address_ ( ) : raise CommandExecutionError ( '' ) if mode == '' or mode is True : state = '' mode = '' else : state = '' mode = '' cmd = '' . format ( dev , state ) __salt__ [ '' ] ( cmd ) . splitlines ( ) info = address_ ( ) if info [ dev ] [ '' ] == mode : return True return False def discoverable ( dev ) : '''''' if dev not in address_ ( ) : ", "answer": "raise CommandExecutionError ("}, {"prompt": " from toolz import * import pickle def test_compose ( ) : ", "answer": "f = compose ( str , sum )"}, {"prompt": " import sys import os sys . path . insert ( , os . path . abspath ( '' ) ) ", "answer": "from django . conf import settings"}, {"prompt": " from __future__ import unicode_literals import inspect from docutils import nodes from docutils . parsers import rst from docutils . parsers . rst import directives from docutils . statemachine import ViewList from sphinx . util . nodes import nested_parse_with_titles from stevedore import extension def _get_docstring ( plugin ) : return inspect . getdoc ( plugin ) or '' def _simple_list ( mgr ) : for name in sorted ( mgr . names ( ) ) : ext = mgr [ name ] doc = _get_docstring ( ext . plugin ) or '' summary = doc . splitlines ( ) [ ] . strip ( ) yield ( '' % ( ext . name , summary ) , ext . entry_point . module_name ) def _detailed_list ( mgr , over = '' , under = '' , titlecase = False ) : for name in sorted ( mgr . names ( ) ) : ext = mgr [ name ] if over : yield ( over * len ( ext . name ) , ext . entry_point . module_name ) if titlecase : yield ( ext . name . title ( ) , ext . entry_point . module_name ) else : yield ( ext . name , ext . entry_point . module_name ) if under : yield ( under * len ( ext . name ) , ext . entry_point . module_name ) yield ( '' , ext . entry_point . module_name ) doc = _get_docstring ( ext . plugin ) if doc : yield ( doc , ext . entry_point . module_name ) else : yield ( '' % ext . entry_point , ext . entry_point . module_name ) yield ( '' , ext . entry_point . module_name ) class ListPluginsDirective ( rst . Directive ) : \"\"\"\"\"\" option_spec = { '' : directives . class_option , '' : directives . flag , '' : directives . flag , '' : directives . single_char_or_unicode , '' : directives . single_char_or_unicode , } has_content = True def run ( self ) : env = self . state . document . settings . env app = env . app namespace = '' . join ( self . content ) . strip ( ) app . info ( '' % namespace ) overline_style = self . options . get ( '' , '' ) underline_style = self . options . get ( '' , '' ) def report_load_failure ( mgr , ep , err ) : app . warn ( u'' % ( ep . module_name , err ) ) mgr = extension . ExtensionManager ( namespace , on_load_failure_callback = report_load_failure , ) result = ViewList ( ) titlecase = '' in self . options if '' in self . options : data = _detailed_list ( mgr , over = overline_style , under = underline_style , titlecase = titlecase ) else : data = _simple_list ( mgr ) for text , source in data : for line in text . splitlines ( ) : result . append ( line , source ) node = nodes . section ( ) node . document = self . state . document nested_parse_with_titles ( self . state , result , node ) return node . children def setup ( app ) : ", "answer": "app . info ( '' )"}, {"prompt": " \"\"\"\"\"\" import os from conary . build import filter from conary . lib . cfg import CfgEnum , CfgList , CfgString , ConfigFile , ParseError from conary . lib . cfg import directive EXCLUDE , INCLUDE = range ( ) class CfgImplementsItem ( CfgEnum ) : validValueDict = { '' : ( '' , '' , '' , '' ) , '' : ( '' , '' ) , '' : ( '' , '' ) } def __init__ ( self ) : validValues = [ ] for fileType , actionList in self . validValueDict . iteritems ( ) : validValues . extend ( '' . join ( ( fileType , x ) ) for x in actionList ) self . validValues = validValues CfgEnum . __init__ ( self ) def checkEntry ( self , val ) : if val . find ( \"\" ) < : raise ParseError , '' % val CfgEnum . checkEntry ( self , val ) CfgImplements = CfgList ( CfgImplementsItem ) class CfgDataSource ( CfgEnum ) : validValues = [ '' , '' , '' ] class TagFile ( ConfigFile ) : file = CfgString name = CfgString description = CfgString datasource = ( CfgDataSource , '' ) implements = CfgImplements def __init__ ( self , filename , macros = { } , warn = False ) : ConfigFile . __init__ ( self ) self . tag = os . path . basename ( filename ) self . tagFile = filename self . macros = macros self . filterlist = [ ] self . read ( filename , exception = True ) if '' in self . __dict__ : for item in self . __dict__ [ '' ] : if item . find ( \"\" ) < : raise ParseError , '' % item key , val = item . split ( \"\" ) if key == '' : if warn : raise ParseError , '' % ( key , filename ) continue @ directive def include ( self , val ) : if not self . macros : return self . filterlist . append ( ( INCLUDE , filter . Filter ( val , self . macros ) ) ) @ directive def exclude ( self , val ) : if not self . macros : return self . filterlist . append ( ( EXCLUDE , filter . Filter ( val , self . macros ) ) ) def match ( self , filename ) : ", "answer": "for keytype , filter in self . filterlist :"}, {"prompt": " import webbrowser from ice . logs import logger class LaunchSteamTask ( object ) : def __call__ ( self , app_settings , users , dry_run ) : ", "answer": "webbrowser . open_new ( \"\" ) "}, {"prompt": " from south . db import db from django . db import models from image_filer . models import * class Migration : def forwards ( self , orm ) : db . create_table ( '' , ( ( '' , orm [ '' ] ) , ( '' , orm [ '' ] ) , ) ) db . send_create_signal ( '' , [ '' ] ) def backwards ( self , orm ) : db . delete_table ( '' ) models = { '' : { '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) } , '' : { '' : { '' : \"\" } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) } , '' : { '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : \"\" , '' : \"\" } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : \"\" } ) } , '' : { '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) } , '' : { '' : { '' : \"\" } , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , ", "answer": "'' : ( '' , [ ] , { '' : '' } ) ,"}, {"prompt": " import numpy as np from numba import from_dtype , cuda from numba import unittest_support as unittest ", "answer": "from numba . cuda . testing import skip_on_cudasim"}, {"prompt": " from __future__ import unicode_literals from django . db import models , migrations import jsonfield . fields import django . utils . timezone from django . conf import settings import model_utils . fields class Migration ( migrations . Migration ) : dependencies = [ migrations . swappable_dependency ( settings . AUTH_USER_MODEL ) , ] operations = [ migrations . CreateModel ( name = '' , fields = [ ( '' , models . AutoField ( verbose_name = '' , serialize = False , auto_created = True , primary_key = True ) ) , ( '' , model_utils . fields . AutoCreatedField ( default = django . utils . timezone . now , verbose_name = '' , editable = False ) ) , ( '' , model_utils . fields . AutoLastModifiedField ( default = django . utils . timezone . now , verbose_name = '' , editable = False ) ) , ( '' , models . CharField ( unique = True , max_length = ) ) , ( '' , models . CharField ( max_length = , blank = True ) ) , ( '' , models . CharField ( max_length = , blank = True ) ) , ( '' , models . DecimalField ( null = True , max_digits = , decimal_places = ) ) , ( '' , models . DecimalField ( null = True , max_digits = , decimal_places = ) ) , ( '' , models . TextField ( blank = True ) ) , ( '' , models . NullBooleanField ( ) ) , ( '' , models . NullBooleanField ( ) ) , ( '' , models . NullBooleanField ( ) ) , ( '' , models . DecimalField ( null = True , max_digits = , decimal_places = ) ) , ( '' , models . BooleanField ( default = False ) ) , ( '' , models . DateTimeField ( null = True , blank = True ) ) , ] , options = { '' : False , } , bases = ( models . Model , ) , ) , migrations . CreateModel ( name = '' , fields = [ ( '' , models . AutoField ( verbose_name = '' , serialize = False , auto_created = True , primary_key = True ) ) , ( '' , model_utils . fields . AutoCreatedField ( default = django . utils . timezone . now , verbose_name = '' , editable = False ) ) , ( '' , model_utils . fields . AutoLastModifiedField ( default = django . utils . timezone . now , verbose_name = '' , editable = False ) ) , ( '' , models . CharField ( max_length = ) ) , ( '' , models . IntegerField ( ) ) , ( '' , models . DateTimeField ( ) ) , ( '' , models . CharField ( max_length = ) ) , ( '' , models . BooleanField ( default = False ) ) , ( '' , models . DateTimeField ( null = True , blank = True ) ) , ( '' , models . DateTimeField ( null = True ) ) , ( '' , models . DateTimeField ( null = True ) ) , ( '' , models . DateTimeField ( null = True , blank = True ) ) , ( '' , models . DateTimeField ( null = True , blank = True ) ) , ( '' , models . DateTimeField ( null = True , blank = True ) ) , ( '' , models . DecimalField ( max_digits = , decimal_places = ) ) , ] , options = { '' : False , } , bases = ( models . Model , ) , ) , migrations . CreateModel ( name = '' , fields = [ ( '' , models . AutoField ( verbose_name = '' , serialize = False , auto_created = True , primary_key = True ) ) , ( '' , model_utils . fields . AutoCreatedField ( default = django . utils . timezone . now , verbose_name = '' , editable = False ) ) , ( '' , model_utils . fields . AutoLastModifiedField ( default = django . utils . timezone . now , verbose_name = '' , editable = False ) ) , ( '' , models . CharField ( unique = True , max_length = ) ) , ( '' , models . CharField ( max_length = , blank = True ) ) , ( '' , models . CharField ( max_length = , blank = True ) ) , ( '' , models . CharField ( max_length = , blank = True ) ) , ( '' , models . DateTimeField ( null = True , editable = False ) ) , ( '' , models . OneToOneField ( null = True , to = settings . AUTH_USER_MODEL ) ) , ] , options = { '' : False , } , bases = ( models . Model , ) , ) , migrations . CreateModel ( name = '' , fields = [ ( '' , models . AutoField ( verbose_name = '' , serialize = False , auto_created = True , primary_key = True ) ) , ( '' , model_utils . fields . AutoCreatedField ( default = django . utils . timezone . now , verbose_name = '' , editable = False ) ) , ( '' , model_utils . fields . AutoLastModifiedField ( default = django . utils . timezone . now , verbose_name = '' , editable = False ) ) , ( '' , models . CharField ( unique = True , max_length = ) ) , ( '' , models . CharField ( max_length = ) ) , ( '' , models . BooleanField ( default = False ) ) , ( '' , jsonfield . fields . JSONField ( default = dict ) ) , ( '' , jsonfield . fields . JSONField ( null = True ) ) , ( '' , models . NullBooleanField ( ) ) , ( '' , models . BooleanField ( default = False ) ) , ( '' , models . ForeignKey ( to = '' , null = True ) ) , ] , options = { '' : False , } , bases = ( models . Model , ) , ) , migrations . CreateModel ( name = '' , fields = [ ( '' , models . AutoField ( verbose_name = '' , serialize = False , auto_created = True , primary_key = True ) ) , ( '' , model_utils . fields . AutoCreatedField ( default = django . utils . timezone . now , verbose_name = '' , editable = False ) ) , ( '' , model_utils . fields . AutoLastModifiedField ( default = django . utils . timezone . now , verbose_name = '' , editable = False ) ) , ( '' , models . TextField ( ) ) , ( '' , models . CharField ( max_length = ) ) , ( '' , models . TextField ( ) ) , ( '' , models . ForeignKey ( to = '' , null = True ) ) , ] , options = { '' : False , } , bases = ( models . Model , ) , ) , migrations . CreateModel ( name = '' , fields = [ ( '' , models . AutoField ( verbose_name = '' , serialize = False , auto_created = True , primary_key = True ) ) , ( '' , model_utils . fields . AutoCreatedField ( default = django . utils . timezone . now , verbose_name = '' , editable = False ) ) , ( '' , model_utils . fields . AutoLastModifiedField ( default = django . utils . timezone . now , verbose_name = '' , editable = False ) ) , ( '' , models . CharField ( max_length = ) ) , ( '' , models . NullBooleanField ( ) ) , ( '' , models . PositiveIntegerField ( null = True ) ) , ( '' , models . BooleanField ( default = False ) ) , ( '' , models . BooleanField ( default = False ) ) , ( '' , models . DateTimeField ( ) ) , ( '' , models . DateTimeField ( ) ) , ( '' , models . DecimalField ( max_digits = , decimal_places = ) ) , ( '' , models . DecimalField ( max_digits = , decimal_places = ) ) , ( '' , models . DateTimeField ( ) ) , ( '' , models . CharField ( max_length = , blank = True ) ) , ( '' , models . ForeignKey ( related_name = '' , to = '' ) ) , ] , options = { '' : [ '' ] , } , bases = ( models . Model , ) , ) , migrations . CreateModel ( name = '' , fields = [ ( '' , models . AutoField ( verbose_name = '' , serialize = False , auto_created = True , primary_key = True ) ) , ( '' , model_utils . fields . AutoCreatedField ( default = django . utils . timezone . now , verbose_name = '' , editable = False ) ) , ( '' , model_utils . fields . AutoLastModifiedField ( default = django . utils . timezone . now , verbose_name = '' , editable = False ) ) , ( '' , models . CharField ( max_length = ) ) , ( '' , models . DecimalField ( max_digits = , decimal_places = ) ) , ( '' , models . CharField ( max_length = ) ) , ( '' , models . DateTimeField ( ) ) , ( '' , models . DateTimeField ( ) ) , ( '' , models . BooleanField ( default = False ) ) , ( '' , models . CharField ( max_length = ) ) , ( '' , models . CharField ( max_length = , blank = True ) ) , ( '' , models . CharField ( max_length = , blank = True ) ) , ( '' , models . IntegerField ( null = True ) ) , ( '' , models . ForeignKey ( related_name = '' , to = '' ) ) , ] , options = { '' : False , } , bases = ( models . Model , ) , ) , migrations . CreateModel ( name = '' , fields = [ ( '' , models . AutoField ( verbose_name = '' , serialize = False , auto_created = True , primary_key = True ) ) , ( '' , model_utils . fields . AutoCreatedField ( default = django . utils . timezone . now , verbose_name = '' , editable = False ) ) , ( '' , model_utils . fields . AutoLastModifiedField ( default = django . utils . timezone . now , verbose_name = '' , editable = False ) ) , ( '' , models . CharField ( unique = True , max_length = ) ) , ( '' , models . CharField ( max_length = ) ) , ( '' , models . CharField ( max_length = , choices = [ ( '' , '' ) , ( '' , '' ) , ( '' , '' ) ] ) ) , ( '' , models . CharField ( max_length = , verbose_name = '' , choices = [ ( '' , '' ) , ( '' , '' ) , ( '' , '' ) ] ) ) , ( '' , models . IntegerField ( default = , null = True , verbose_name = '' ) ) , ( '' , models . DecimalField ( verbose_name = '' , max_digits = , decimal_places = ) ) , ( '' , models . IntegerField ( null = True ) ) , ] , ", "answer": "options = {"}, {"prompt": " import sys from os import path dir = path . dirname ( __file__ ) sys . path . extend ( [ path . join ( dir , \"\" ) , path . join ( dir , \"\" ) ] ) extensions = [ '' , '' , ] templates_path = [ '' ] source_suffix = '' master_doc = '' project = u'' copyright = u'' version = '' release = '' exclude_patterns = [ ] pygments_style = '' html_theme = '' html_static_path = [ '' ] htmlhelp_basename = '' latex_elements = { } latex_documents = [ ( '' , '' , u'' , u'' , '' ) , ] man_pages = [ ( '' , '' , u'' , [ u'' ] , ) ] texinfo_documents = [ ( '' , '' , u'' , ", "answer": "u'' , '' , '' ,"}, {"prompt": " from __future__ import unicode_literals import logging from django . core . files . storage import FileSystemStorage class MockLoggingHandler ( logging . Handler ) : \"\"\"\"\"\" def __init__ ( self , * args , ** kwargs ) : self . reset ( ) super ( MockLoggingHandler , self ) . __init__ ( * args , ** kwargs ) def emit ( self , record ) : self . messages [ record . levelname . lower ( ) ] . append ( record . getMessage ( ) ) def reset ( self ) : self . messages = { '' : [ ] , '' : [ ] , '' : [ ] , '' : [ ] , '' : [ ] } slog = logging . getLogger ( '' ) class TestStorageMixin ( object ) : def open ( self , name , * args , ** kwargs ) : slog . debug ( '' % name ) return super ( TestStorageMixin , self ) . open ( name , * args , ** kwargs ) def save ( self , name , * args , ** kwargs ) : slog . debug ( '' % name ) return super ( TestStorageMixin , self ) . save ( name , * args , ** kwargs ) def get_valid_name ( self , name , * args , ** kwargs ) : slog . debug ( '' % name ) return super ( TestStorageMixin , self ) . get_valid_name ( name , * args , ** kwargs ) def get_available_name ( self , name , * args , ** kwargs ) : slog . debug ( '' % name ) return super ( TestStorageMixin , self ) . get_available_name ( name , * args , ** kwargs ) def path ( self , name , * args , ** kwargs ) : return super ( TestStorageMixin , self ) . path ( name , * args , ** kwargs ) def delete ( self , name , * args , ** kwargs ) : slog . debug ( '' % name ) return super ( TestStorageMixin , self ) . delete ( name , * args , ** kwargs ) def exists ( self , name , * args , ** kwargs ) : slog . debug ( '' % name ) ", "answer": "return super ( TestStorageMixin , self ) . exists ( name , * args , ** kwargs )"}, {"prompt": " from __future__ import absolute_import \"\"\"\"\"\" import random import re import string import time import urllib import urlparse UNICODE_ASCII_CHARACTER_SET = ( string . ascii_letters . decode ( '' ) + string . digits . decode ( '' ) ) always_safe = ( u'' u'' u'' u'' ) def quote ( s , safe = u'' ) : encoded = s . encode ( \"\" ) quoted = urllib . quote ( encoded , safe ) return quoted . decode ( \"\" ) def unquote ( s ) : encoded = s . encode ( \"\" ) unquoted = urllib . unquote ( encoded ) return unquoted . decode ( \"\" ) def urlencode ( params ) : utf8_params = encode_params_utf8 ( params ) urlencoded = urllib . urlencode ( utf8_params ) return urlencoded . decode ( \"\" ) def encode_params_utf8 ( params ) : \"\"\"\"\"\" encoded = [ ] for k , v in params : encoded . append ( ( k . encode ( '' ) if isinstance ( k , unicode ) else k , v . encode ( '' ) if isinstance ( v , unicode ) else v ) ) return encoded def decode_params_utf8 ( params ) : \"\"\"\"\"\" decoded = [ ] for k , v in params : decoded . append ( ( k . decode ( '' ) if isinstance ( k , str ) else k , v . decode ( '' ) if isinstance ( v , str ) else v ) ) return decoded urlencoded = set ( always_safe ) | set ( u'' ) def urldecode ( query ) : \"\"\"\"\"\" if query and not set ( query ) <= urlencoded : raise ValueError ( '' ) invalid_hex = u'' if len ( re . findall ( invalid_hex , query ) ) : raise ValueError ( '' ) query = query . decode ( '' ) if isinstance ( query , str ) else query params = urlparse . parse_qsl ( query , keep_blank_values = True ) return decode_params_utf8 ( params ) def extract_params ( raw ) : \"\"\"\"\"\" if isinstance ( raw , basestring ) : try : params = urldecode ( raw ) except ValueError : params = None elif hasattr ( raw , '' ) : ", "answer": "try :"}, {"prompt": " from django . conf import settings from balancer . routers import RandomRouter from . import BalancerTestCase class RandomRouterTestCase ( BalancerTestCase ) : def setUp ( self ) : super ( RandomRouterTestCase , self ) . setUp ( ) self . router = RandomRouter ( ) def test_random_db_selection ( self ) : \"\"\"\"\"\" for i in range ( ) : self . assertTrue ( self . router . get_random_db ( ) in settings . DATABASE_POOL . keys ( ) , \"\" ) def test_relations ( self ) : \"\"\"\"\"\" self . obj1 . _state . db = '' self . obj2 . _state . db = '' ", "answer": "self . assertTrue ( self . router . allow_relation ( self . obj1 , self . obj2 ) )"}, {"prompt": " import random from string import letters from django . contrib . auth import get_user_model from django . test import TestCase try : from django . test import override_settings except ImportError : from django . test . utils import override_settings from tidings . models import Watch , WatchFilter def user ( save = False , ** kwargs ) : defaults = { '' : '' } if '' not in kwargs : defaults [ '' ] = '' . join ( random . choice ( letters ) for x in xrange ( ) ) defaults . update ( kwargs ) u = get_user_model ( ) ( ** defaults ) if save : u . save ( ) return u def watch ( save = False , ** kwargs ) : defaults = { '' : kwargs . get ( '' ) or user ( ) , ", "answer": "'' : True ,"}, {"prompt": " import rospy import MySQLdb as mdb import sys from rapp_platform_ros_communications . srv import ( fetchDataSrv , fetchDataSrvResponse , writeDataSrv , writeDataSrvResponse , deleteDataSrv , deleteDataSrvResponse , updateDataSrv , updateDataSrvResponse , whatRappsCanRunSrv , whatRappsCanRunSrvResponse ) from rapp_platform_ros_communications . msg import ( StringArrayMsg ) from std_msgs . msg import ( String ) class MySQLdbWrapper : def __init__ ( self ) : self . serv_topic = rospy . get_param ( \"\" ) if ( not self . serv_topic ) : rospy . logerror ( \"\" ) self . serv = rospy . Service ( self . serv_topic , fetchDataSrv , self . tblUserFetchDataHandler ) self . serv_topic = rospy . get_param ( \"\" ) if ( not self . serv_topic ) : rospy . logerror ( \"\" ) self . serv = rospy . Service ( self . serv_topic , writeDataSrv , self . tblUserWriteDataHandler ) self . serv_topic = rospy . get_param ( \"\" ) if ( not self . serv_topic ) : rospy . logerror ( \"\" ) self . serv = rospy . Service ( self . serv_topic , deleteDataSrv , self . tblUserDeleteDataHandler ) self . serv_topic = rospy . get_param ( \"\" ) if ( not self . serv_topic ) : rospy . logerror ( \"\" ) self . serv = rospy . Service ( self . serv_topic , updateDataSrv , self . tblUserUpdateDataHandler ) self . serv_topic = rospy . get_param ( \"\" ) if ( not self . serv_topic ) : rospy . logerror ( \"\" ) self . serv = rospy . Service ( self . serv_topic , fetchDataSrv , self . tblModelFetchDataHandler ) self . serv_topic = rospy . get_param ( \"\" ) if ( not self . serv_topic ) : rospy . logerror ( \"\" ) self . serv = rospy . Service ( self . serv_topic , writeDataSrv , self . tblModelWriteDataHandler ) self . serv_topic = rospy . get_param ( \"\" ) if ( not self . serv_topic ) : rospy . logerror ( \"\" ) self . serv = rospy . Service ( self . serv_topic , deleteDataSrv , self . tblModelDeleteDataHandler ) self . serv_topic = rospy . get_param ( \"\" ) if ( not self . serv_topic ) : rospy . logerror ( \"\" ) self . serv = rospy . Service ( self . serv_topic , updateDataSrv , self . tblModelUpdateDataHandler ) self . serv_topic = rospy . get_param ( \"\" ) if ( not self . serv_topic ) : rospy . logerror ( \"\" ) self . serv = rospy . Service ( self . serv_topic , fetchDataSrv , self . tblRappFetchDataHandler ) self . serv_topic = rospy . get_param ( \"\" ) if ( not self . serv_topic ) : rospy . logerror ( \"\" ) self . serv = rospy . Service ( self . serv_topic , writeDataSrv , self . tblRappWriteDataHandler ) self . serv_topic = rospy . get_param ( \"\" ) if ( not self . serv_topic ) : rospy . logerror ( \"\" ) self . serv = rospy . Service ( self . serv_topic , deleteDataSrv , self . tblRappDeleteDataHandler ) self . serv_topic = rospy . get_param ( \"\" ) if ( not self . serv_topic ) : rospy . logerror ( \"\" ) self . serv = rospy . Service ( self . serv_topic , updateDataSrv , self . tblRappUpdateDataHandler ) self . serv_topic = rospy . get_param ( \"\" ) if ( not self . serv_topic ) : rospy . logerror ( \"\" ) self . serv = rospy . Service ( self . serv_topic , fetchDataSrv , self . tblRobotFetchDataHandler ) self . serv_topic = rospy . get_param ( \"\" ) if ( not self . serv_topic ) : rospy . logerror ( \"\" ) self . serv = rospy . Service ( self . serv_topic , writeDataSrv , self . tblRobotWriteDataHandler ) self . serv_topic = rospy . get_param ( \"\" ) if ( not self . serv_topic ) : rospy . logerror ( \"\" ) self . serv = rospy . Service ( self . serv_topic , deleteDataSrv , self . tblRobotDeleteDataHandler ) self . serv_topic = rospy . get_param ( \"\" ) if ( not self . serv_topic ) : rospy . logerror ( \"\" ) self . serv = rospy . Service ( self . serv_topic , updateDataSrv , self . tblRobotUpdateDataHandler ) self . serv_topic = rospy . get_param ( \"\" ) if ( not self . serv_topic ) : rospy . logerror ( \"\" ) self . serv = rospy . Service ( self . serv_topic , fetchDataSrv , self . tblAppsRobotsFetchDataHandler ) self . serv_topic = rospy . get_param ( \"\" ) if ( not self . serv_topic ) : rospy . logerror ( \"\" ) self . serv = rospy . Service ( self . serv_topic , writeDataSrv , self . tblAppsRobotsWriteDataHandler ) self . serv_topic = rospy . get_param ( \"\" ) if ( not self . serv_topic ) : rospy . logerror ( \"\" ) self . serv = rospy . Service ( self . serv_topic , deleteDataSrv , self . tblAppsRobotsDeleteDataHandler ) self . serv_topic = rospy . get_param ( \"\" ) if ( not self . serv_topic ) : rospy . logerror ( \"\" ) self . serv = rospy . Service ( self . serv_topic , updateDataSrv , self . tblAppsRobotsUpdateDataHandler ) self . serv_topic = rospy . get_param ( \"\" ) if ( not self . serv_topic ) : rospy . logerror ( \"\" ) self . serv = rospy . Service ( self . serv_topic , fetchDataSrv , self . tblUsersOntologyInstancesFetchDataHandler ) self . serv_topic = rospy . get_param ( \"\" ) if ( not self . serv_topic ) : rospy . logerror ( \"\" ) self . serv = rospy . Service ( self . serv_topic , writeDataSrv , self . tblUsersOntologyInstancesWriteDataHandler ) self . serv_topic = rospy . get_param ( \"\" ) if ( not self . serv_topic ) : rospy . logerror ( \"\" ) self . serv = rospy . Service ( self . serv_topic , deleteDataSrv , self . tblUsersOntologyInstancesDeleteDataHandler ) self . serv_topic = rospy . get_param ( \"\" ) if ( not self . serv_topic ) : rospy . logerror ( \"\" ) self . serv = rospy . Service ( self . serv_topic , updateDataSrv , self . tblUsersOntologyInstancesUpdateDataHandler ) self . serv_topic = rospy . get_param ( \"\" ) if ( not self . serv_topic ) : rospy . logerror ( \"\" ) self . serv = rospy . Service ( self . serv_topic , fetchDataSrv , self . viewUsersRobotsAppsFetchDataHandler ) self . serv_topic = rospy . get_param ( \"\" ) if ( not self . serv_topic ) : rospy . logerror ( \"\" ) self . serv = rospy . Service ( self . serv_topic , whatRappsCanRunSrv , self . whatRappsCanRunDataHandler ) def writeData ( self , req , tblName ) : try : res = writeDataSrvResponse ( ) db_username , db_password = self . getLogin ( ) con = mdb . connect ( '' , db_username , db_password , '' ) ; cur = con . cursor ( ) returncols = self . constructCommaColumns ( req . req_cols ) if ( len ( returncols ) > ) : returncols = \"\" + returncols + \"\" print returncols values = \"\" for i in range ( len ( req . req_data ) ) : if ( i == ) : values = values + \"\" + self . constructCommaColumns ( req . req_data [ i ] . s ) + \"\" else : values = values + \"\" + self . constructCommaColumns ( req . req_data [ i ] . s ) + \"\" query = \"\" + tblName + \"\" + returncols + \"\" + values cur . execute ( \"\" + tblName + \"\" ) cur . execute ( query ) cur . execute ( \"\" ) res . success . data = True res . trace . append ( \"\" ) except mdb . Error , e : res . trace . append ( ( \"\" % ( e . args [ ] , e . args [ ] ) ) ) res . success . data = False print \"\" % ( e . args [ ] , e . args [ ] ) except IndexError : res . trace . append ( \"\" ) res . success . data = False print \"\" except IOError : print \"\" res . success . data = False res . trace . append ( \"\" ) return res def deleteData ( self , req , tblName ) : try : res = deleteDataSrvResponse ( ) db_username , db_password = self . getLogin ( ) con = mdb . connect ( '' , db_username , db_password , '' ) ; cur = con . cursor ( ) where = self . constructAndQuery ( req . where_data ) query = \"\" + tblName + where cur . execute ( \"\" + tblName + \"\" ) cur . execute ( query ) cur . execute ( \"\" ) res . success . data = True res . trace . append ( \"\" ) except mdb . Error , e : res . trace . append ( ( \"\" % ( e . args [ ] , e . args [ ] ) ) ) res . success . data = False print \"\" % ( e . args [ ] , e . args [ ] ) except IndexError : res . trace . append ( \"\" ) res . success . data = False print \"\" except IOError : print \"\" res . success . data = False res . trace . append ( \"\" ) return res def updateData ( self , req , tblName ) : try : res = updateDataSrvResponse ( ) db_username , db_password = self . getLogin ( ) con = mdb . connect ( '' , db_username , db_password , '' ) ; cur = con . cursor ( ) returncols = self . constructCommaColumns ( req . set_cols ) where = self . constructAndQuery ( req . where_data ) query = \"\" + tblName + \"\" + returncols + where print query cur . execute ( \"\" + tblName + \"\" ) cur . execute ( query ) cur . execute ( \"\" ) res . success . data = True res . trace . append ( \"\" ) except mdb . Error , e : res . trace . append ( ( \"\" % ( e . args [ ] , e . args [ ] ) ) ) res . success . data = False print \"\" % ( e . args [ ] , e . args [ ] ) except IndexError : res . trace . append ( \"\" ) res . success . data = False print \"\" except IOError : print \"\" res . success . data = False res . trace . append ( \"\" ) return res def fetchData ( self , req , tblName ) : try : res = fetchDataSrvResponse ( ) db_username , db_password = self . getLogin ( ) con = mdb . connect ( '' , db_username , db_password , '' ) ; cur = con . cursor ( ) returncols = self . constructCommaColumns ( req . req_cols ) where = self . constructAndQuery ( req . where_data ) query = \"\" + returncols + \"\" + tblName + where cur . execute ( query ) result_set = cur . fetchall ( ) for i in range ( len ( result_set ) ) : line = StringArrayMsg ( ) for j in range ( len ( result_set [ i ] ) ) : temp_s = String ( result_set [ i ] [ j ] ) line . s . append ( ( str ( result_set [ i ] [ j ] ) ) ) res . res_data . append ( line ) con . close ( ) if ( returncols == \"\" ) : res . res_cols = self . getTableColumnNames ( tblName ) else : res . res_cols = req . req_cols res . success . data = True res . trace . append ( \"\" ) except mdb . Error , e : res . trace . append ( ( \"\" % ( e . args [ ] , e . args [ ] ) ) ) res . success . data = False print \"\" % ( e . args [ ] , e . args [ ] ) except IndexError : res . trace . append ( \"\" ) res . success . data = False print \"\" except IOError : print \"\" res . success . data = False res . trace . append ( \"\" ) return res def whatRappsCanRun ( self , req , tblName ) : try : res = whatRappsCanRunSrvResponse ( ) db_username , db_password = self . getLogin ( ) con = mdb . connect ( '' , db_username , db_password , '' ) ; cur = con . cursor ( ) query = \"\" + req . model_id + \"\" + req . core_agent_version + \"\" ; cur . execute ( query ) result_set = cur . fetchall ( ) for i in range ( len ( result_set ) ) : line = StringArrayMsg ( ) for j in range ( len ( result_set [ i ] ) ) : temp_s = String ( result_set [ i ] [ j ] ) line . s . append ( ( str ( result_set [ i ] [ j ] ) ) ) res . res_data . append ( line ) con . close ( ) res . success . data = True res . trace . append ( \"\" ) except mdb . Error , e : res . trace . append ( ( \"\" % ( e . args [ ] , e . args [ ] ) ) ) res . success . data = False print \"\" % ( e . args [ ] , e . args [ ] ) except IndexError : res . trace . append ( \"\" ) res . success . data = False print \"\" except IOError : print \"\" res . success . data = False res . trace . append ( \"\" ) return res def constructCommaColumns ( self , cols ) : if ( len ( cols ) < ) : return \"\" elif ( cols [ ] == \"\" ) : return \"\" else : returncols = \"\" for i in range ( len ( cols ) ) : if i == : returncols = returncols + cols [ i ] else : returncols = returncols + \"\" + cols [ i ] return returncols def constructAndQuery ( self , cols ) : returnquery = \"\" if ( len ( cols ) == ) : return \"\" else : for i in range ( len ( cols ) ) : if i == : returnquery = returnquery + cols [ i ] . s [ ] + \"\" + cols [ i ] . s [ ] + \"\" else : returnquery = returnquery + \"\" + cols [ i ] . s [ ] + \"\" + cols [ i ] . s [ ] + \"\" returnquery = \"\" + returnquery return returnquery def getTableColumnNames ( self , tblName ) : db_username , db_password = self . getLogin ( ) try : con = mdb . connect ( '' , db_username , db_password , '' ) ; cur = con . cursor ( ) cur . execute ( \"\" + tblName ) result_set = cur . fetchall ( ) Columns = [ ] for row in result_set : Columns = Columns + [ String ( str ( row [ ] ) ) ] return Columns except mdb . Error , e : print \"\" % ( e . args [ ] , e . args [ ] ) def getLogin ( self ) : fh = open ( \"\" , \"\" ) db_username = fh . readline ( ) db_username = db_username . split ( ) [ ] db_password = fh . readline ( ) db_password = db_password . split ( ) [ ] return db_username , db_password def checkConnection ( self ) : try : db_username , db_password = self . getLogin ( ) con = mdb . connect ( '' , db_username , db_password , '' ) cur = con . cursor ( ) cur . execute ( \"\" ) ver = cur . fetchone ( ) print \"\" % ver con . close ( ) except mdb . Error , e : print \"\" % ( e . args [ ] , e . args [ ] ) def tblUserFetchDataHandler ( self , req ) : res = fetchDataSrvResponse ( ) res = self . fetchData ( req , \"\" ) return res def tblUserWriteDataHandler ( self , req ) : res = writeDataSrvResponse ( ) res = self . writeData ( req , \"\" ) return res def tblUserDeleteDataHandler ( self , req ) : res = deleteDataSrvResponse ( ) res = self . deleteData ( req , \"\" ) return res def tblUserUpdateDataHandler ( self , req ) : res = updateDataSrvResponse ( ) res = self . updateData ( req , \"\" ) return res def tblModelFetchDataHandler ( self , req ) : res = fetchDataSrvResponse ( ) res = self . fetchData ( req , \"\" ) return res def tblModelWriteDataHandler ( self , req ) : res = writeDataSrvResponse ( ) res = self . writeData ( req , \"\" ) return res def tblModelDeleteDataHandler ( self , req ) : res = deleteDataSrvResponse ( ) res = self . deleteData ( req , \"\" ) return res def tblModelUpdateDataHandler ( self , req ) : res = updateDataSrvResponse ( ) res = self . updateData ( req , \"\" ) return res def tblRappFetchDataHandler ( self , req ) : res = fetchDataSrvResponse ( ) res = self . fetchData ( req , \"\" ) return res def tblRappWriteDataHandler ( self , req ) : res = writeDataSrvResponse ( ) res = self . writeData ( req , \"\" ) return res def tblRappDeleteDataHandler ( self , req ) : res = deleteDataSrvResponse ( ) res = self . deleteData ( req , \"\" ) return res def tblRappUpdateDataHandler ( self , req ) : res = updateDataSrvResponse ( ) res = self . updateData ( req , \"\" ) return res def tblRobotFetchDataHandler ( self , req ) : res = fetchDataSrvResponse ( ) res = self . fetchData ( req , \"\" ) return res def tblRobotWriteDataHandler ( self , req ) : res = writeDataSrvResponse ( ) res = self . writeData ( req , \"\" ) return res def tblRobotDeleteDataHandler ( self , req ) : res = deleteDataSrvResponse ( ) res = self . deleteData ( req , \"\" ) return res def tblRobotUpdateDataHandler ( self , req ) : res = updateDataSrvResponse ( ) res = self . updateData ( req , \"\" ) return res def tblAppsRobotsFetchDataHandler ( self , req ) : res = fetchDataSrvResponse ( ) res = self . fetchData ( req , \"\" ) return res def tblAppsRobotsWriteDataHandler ( self , req ) : res = writeDataSrvResponse ( ) res = self . writeData ( req , \"\" ) ", "answer": "return res"}, {"prompt": " from __future__ import unicode_literals from . common import InfoExtractor class TenPlayIE ( InfoExtractor ) : _VALID_URL = r'' _TEST = { '' : '' , '' : { ", "answer": "'' : '' ,"}, {"prompt": " from django . contrib . gis import admin from models import Geoname class GeonameAdmin ( admin . OSMGeoAdmin ) : ", "answer": "search_fields = ( '' , )"}, {"prompt": " import spidermonkey import sys from os . path import join , dirname , basename , abspath from optparse import OptionParser usage = \"\"\"\"\"\" currentdir = abspath ( dirname ( dirname ( __file__ ) ) ) builddir = abspath ( \"\" ) sys . path . append ( join ( builddir , \"\" ) ) import pyjs file_name = None app_library_dirs = [ currentdir , join ( builddir , \"\" ) , join ( builddir , \"\" ) , join ( builddir , \"\" ) ] cx = None def pysm_print_fn ( arg ) : print arg def pysm_import_module ( parent_name , module_name ) : if module_name == '' or module_name == '' : return if module_name == file_name : return exec \"\" % module_name cx . add_global ( module_name , _module ) def main ( ) : global file_name parser = OptionParser ( usage = usage ) pyjs . add_compile_options ( parser ) parser . add_option ( \"\" , \"\" , ", "answer": "dest = \"\" ,"}, {"prompt": " from __future__ import division import datetime import unittest from stream_framework . aggregators . base import RecentVerbAggregator , NotificationAggregator from stream_framework . tests . utils import FakeActivity from stream_framework . verbs . base import Love as LoveVerb , Comment as CommentVerb def implementation ( meth ) : def wrapped_test ( self , * args , ** kwargs ) : if self . aggregator_class is None : raise unittest . SkipTest ( '' ) return meth ( self , * args , ** kwargs ) return wrapped_test class BaseAggregatorTest ( unittest . TestCase ) : aggregator_class = None first_activities_group = [ ] second_activities_group = [ ] @ property def today ( self ) : return datetime . datetime . now ( ) . replace ( minute = ) @ property def yesterday ( self ) : return self . today - datetime . timedelta ( days = ) @ implementation def test_aggregate ( self ) : aggregator = self . aggregator_class ( ) activities = self . first_activities_group + self . second_activities_group aggregated = aggregator . aggregate ( activities ) self . assertEqual ( len ( aggregated ) , ) self . assertEqual ( aggregated [ ] . activities , self . first_activities_group ) self . assertEqual ( aggregated [ ] . activities , self . second_activities_group ) @ implementation def test_empty_merge ( self ) : aggregator = self . aggregator_class ( ) activities = self . first_activities_group + self . second_activities_group new , changed , deleted = aggregator . merge ( [ ] , activities ) self . assertEqual ( len ( new ) , ) self . assertEqual ( new [ ] . activities , self . first_activities_group ) self . assertEqual ( new [ ] . activities , self . second_activities_group ) ", "answer": "self . assertEqual ( len ( changed ) , )"}, {"prompt": " import mock from twisted . trial . unittest import TestCase from tryfer import log from twisted . python import log as twisted_log class LogTests ( TestCase ) : def setUp ( self ) : self . mock_log_patcher = mock . patch ( '' ) self . mock_log = self . mock_log_patcher . start ( ) def tearDown ( self ) : log . set_debugging ( False ) self . mock_log_patcher . stop ( ) def test_default_debug_off ( self ) : log . debug ( '' ) self . assertEqual ( self . mock_log . msg . call_count , ) def test_set_debugging_default ( self ) : log . set_debugging ( ) log . debug ( '' ) self . mock_log . msg . assert_called_once_with ( '' , logLevel = '' ) def test_set_debugging_explicit ( self ) : log . set_debugging ( True ) log . debug ( '' ) ", "answer": "self . mock_log . msg . assert_called_once_with ( '' , logLevel = '' )"}, {"prompt": " from framework . latentmodule import LatentModule import random class Main ( LatentModule ) : def __init__ ( self ) : LatentModule . __init__ ( self ) self . trials1 = self . trials2 = self . a_probability = def run ( self ) : self . marker ( ) self . write ( '' , ) self . write ( '' , '' ) self . write ( '' , ) for k in range ( self . trials1 ) : self . crosshair ( ) if random . random ( ) < self . a_probability : self . marker ( ) ", "answer": "self . write ( '' , scale = )"}, {"prompt": " \"\"\"\"\"\" import sys , os import re import logging import shutil import time import glob from threading import Lock from watchdog . observers import Observer from watchdog . events import LoggingEventHandler from watchdog . events import FileSystemEventHandler class PyPdfWatcher ( FileSystemEventHandler ) : \"\"\"\"\"\" events = { } events_lock = Lock ( ) def __init__ ( self , monitor_dir , config ) : FileSystemEventHandler . __init__ ( self ) self . monitor_dir = monitor_dir if not config : config = { } self . scan_interval = config . get ( '' , ) def start ( self ) : self . observer = Observer ( ) self . observer . schedule ( self , self . monitor_dir ) self . observer . start ( ) print ( \"\" % ( self . monitor_dir ) ) while True : logging . info ( \"\" % self . scan_interval ) time . sleep ( self . scan_interval ) newFile = self . check_queue ( ) if newFile : yield newFile self . observer . join ( ) def stop ( self ) : self . observer . stop ( ) def rename_file_with_spaces ( self , pdf_filename ) : \"\"\"\"\"\" filepath , filename = os . path . split ( pdf_filename ) if '' in filename : newFilename = os . path . join ( filepath , filename . replace ( '' , '' ) ) logging . debug ( \"\" ) logging . debug ( \"\" % ( pdf_filename , newFilename ) ) shutil . move ( pdf_filename , newFilename ) return newFilename else : return pdf_filename def check_for_new_pdf ( self , ev_path ) : \"\"\"\"\"\" if ev_path . endswith ( \"\" ) : if not ev_path . endswith ( \"\" ) : PyPdfWatcher . events_lock . acquire ( ) if not ev_path in PyPdfWatcher . events : PyPdfWatcher . events [ ev_path ] = time . time ( ) logging . info ( \"\" % ev_path ) ", "answer": "else :"}, {"prompt": " from django . http import HttpResponse from django . core . exceptions import ImproperlyConfigured from django . core . cache import get_cache from django . utils . http import http_date from imagefit . conf import settings from imagefit . models import Image , Presets ", "answer": "import os"}, {"prompt": " from statsmodels . compat . python import lrange , lmap , iterkeys , iteritems import numpy as np from scipy import stats from statsmodels . iolib . table import SimpleTable from statsmodels . tools . decorators import nottest def _kurtosis ( a ) : '''''' try : res = stats . kurtosis ( a ) except ValueError : res = np . nan return res def _skew ( a ) : '''''' try : res = stats . skew ( a ) except ValueError : res = np . nan return res _sign_test_doc = '''''' @ nottest def sign_test ( samp , mu0 = ) : samp = np . asarray ( samp ) pos = np . sum ( samp > mu0 ) neg = np . sum ( samp < mu0 ) M = ( pos - neg ) / p = stats . binom_test ( min ( pos , neg ) , pos + neg , ) return M , p sign_test . __doc__ = _sign_test_doc class Describe ( object ) : '''''' def __init__ ( self , dataset ) : self . dataset = dataset self . univariate = dict ( obs = [ len , None , None ] , mean = [ np . mean , None , None ] , std = [ np . std , None , None ] , min = [ np . min , None , None ] , max = [ np . max , None , None ] , ptp = [ np . ptp , None , None ] , var = [ np . var , None , None ] , mode_val = [ self . _mode_val , None , None ] , mode_bin = [ self . _mode_bin , None , None ] , median = [ np . median , None , None ] , skew = [ stats . skew , None , None ] , uss = [ lambda x : np . sum ( np . asarray ( x ) ** , axis = ) , None , None ] , kurtosis = [ stats . kurtosis , None , None ] , percentiles = [ self . _percentiles , None , None ] , ) self . _arraytype = None self . _columns_list = None def _percentiles ( self , x ) : p = [ stats . scoreatpercentile ( x , per ) for per in ( , , , , , , , , ) ] return p def _mode_val ( self , x ) : return stats . mode ( x ) [ ] [ ] def _mode_bin ( self , x ) : return stats . mode ( x ) [ ] [ ] def _array_typer ( self ) : \"\"\"\"\"\" if not ( self . dataset . dtype . names ) : \"\"\"\"\"\" self . _arraytype = '' elif self . dataset . dtype . names : \"\"\"\"\"\" self . _arraytype = '' else : assert self . _arraytype == '' or self . _arraytype == '' def _is_dtype_like ( self , col ) : \"\"\"\"\"\" def string_like ( ) : try : self . dataset [ col ] [ ] + '' except ( TypeError , ValueError ) : return False return True def number_like ( ) : try : self . dataset [ col ] [ ] + except ( TypeError , ValueError ) : return False return True if number_like ( ) == True and string_like ( ) == False : return '' elif number_like ( ) == False and string_like ( ) == True : return '' else : assert ( number_like ( ) == True or string_like ( ) == True ) , '' + str ( self . dataset [ col ] [ ] ) def summary ( self , stats = '' , columns = '' , orientation = '' ) : \"\"\"\"\"\" if self . _arraytype == None : self . _array_typer ( ) if stats == '' : stats = ( '' , '' , '' , '' , '' ) elif stats == '' : stats = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ] else : for astat in stats : pass import scipy . stats def _fun ( per ) : return lambda x : scipy . stats . scoreatpercentile ( x , per ) perdict = dict ( ( '' % per , [ _fun ( per ) , None , None ] ) for per in ( , , , , , , , , ) ) if '' in stats : self . univariate . update ( perdict ) idx = stats . index ( '' ) stats [ idx : idx + ] = sorted ( iterkeys ( perdict ) ) if any ( [ aitem [ ] for aitem in iteritems ( self . univariate ) if aitem [ ] in stats ] ) : if columns == '' : self . _columns_list = [ ] if self . _arraytype == '' : self . _columns_list = self . dataset . dtype . names else : self . _columns_list = lrange ( self . dataset . shape [ ] ) else : self . _columns_list = columns if self . _arraytype == '' : for col in self . _columns_list : assert ( col in self . dataset . dtype . names ) ", "answer": "else :"}, {"prompt": " from django . db import models from django . template . defaultfilters import slugify from django . utils . timezone import is_aware from django . utils . timezone import make_naive import pytz def model_content_type ( cls ) : return '' % ( cls . _meta . app_label , cls . _meta . object_name ) def create_reference ( reference ) : if isinstance ( reference , ( models . Model , ) ) : return create_model_reference ( reference ) return reference def create_model_reference ( model_instance ) : '''''' content_type = model_content_type ( model_instance . __class__ ) content_id = model_instance . pk return '' % ( content_type , content_id ) class Activity ( object ) : @ property def activity_author_feed ( self ) : '''''' pass @ classmethod def activity_related_models ( cls ) : '''''' pass @ property def extra_activity_data ( self ) : '''''' pass @ property def activity_actor_attr ( self ) : '''''' return self . user @ property def activity_object_attr ( self ) : '''''' raise NotImplementedError ( '' % self . __class__ . __name__ ) @ property def activity_actor_id ( self ) : return self . activity_actor_attr . pk @ property def activity_actor ( self ) : return create_reference ( self . activity_actor_attr ) @ property def activity_verb ( self ) : model_name = slugify ( self . __class__ . __name__ ) return model_name @ property def activity_object ( self ) : return create_reference ( self . activity_object_attr ) @ property def activity_foreign_id ( self ) : return self . activity_object @ property def activity_time ( self ) : atime = self . created_at if is_aware ( self . created_at ) : atime = make_naive ( atime , pytz . utc ) ", "answer": "return atime"}, {"prompt": " import requests ", "answer": "controller_url = \"\""}, {"prompt": " from __future__ import print_function , unicode_literals import unittest import test . unit . configuration as configuration_module import voodoo . configuration as ConfigurationManager from weblab . data . experiments import ExperimentInstanceId from weblab . data . experiments import ExperimentId from weblab . core . coordinator . resource import Resource from weblab . core . coordinator . sql . coordinator import Coordinator import weblab . core . coordinator . sql . resource_manager as ResourcesManager import weblab . core . coordinator . sql . db as CoordinationDatabaseManager import weblab . core . coordinator . sql . model as CoordinatorModel import weblab . core . coordinator . exc as CoordExc class ResourcesManagerTestCase ( unittest . TestCase ) : def setUp ( self ) : self . cfg_manager = ConfigurationManager . ConfigurationManager ( ) self . cfg_manager . append_module ( configuration_module ) self . coordinator = Coordinator ( None , self . cfg_manager ) self . coordinator . _clean ( ) self . coordinator . stop ( ) coordination_database = CoordinationDatabaseManager . CoordinationDatabaseManager ( self . cfg_manager ) self . session_maker = coordination_database . session_maker self . resources_manager = ResourcesManager . ResourcesManager ( self . session_maker ) self . resources_manager . _clean ( ) def test_add_resource ( self ) : session = self . session_maker ( ) try : resource_types = session . query ( CoordinatorModel . ResourceType ) . all ( ) self . assertEquals ( , len ( resource_types ) , \"\" ) self . resources_manager . add_resource ( session , Resource ( \"\" , \"\" ) ) self . _check_resource_added ( session ) session . commit ( ) finally : session . close ( ) session = self . session_maker ( ) try : self . resources_manager . add_resource ( session , Resource ( \"\" , \"\" ) ) self . _check_resource_added ( session ) session . commit ( ) finally : session . close ( ) def _check_resource_added ( self , session ) : resource_types = session . query ( CoordinatorModel . ResourceType ) . all ( ) self . assertEquals ( , len ( resource_types ) ) resource_type = resource_types [ ] self . assertEquals ( \"\" , resource_type . name ) resource_instances = resource_type . instances self . assertEquals ( , len ( resource_instances ) ) resource_instance = resource_instances [ ] self . assertEquals ( \"\" , resource_instance . name ) self . assertEquals ( resource_type , resource_instance . resource_type ) slot = resource_instance . slot self . assertNotEquals ( None , slot ) self . assertEquals ( resource_instance , slot . resource_instance ) def test_add_experiment_instance_id ( self ) : session = self . session_maker ( ) try : resource_types = session . query ( CoordinatorModel . ResourceType ) . all ( ) self . assertEquals ( , len ( resource_types ) , \"\" ) exp_id = ExperimentInstanceId ( \"\" , \"\" , \"\" ) session . commit ( ) finally : session . close ( ) self . resources_manager . add_experiment_instance_id ( \"\" , exp_id , Resource ( \"\" , \"\" ) ) session = self . session_maker ( ) try : self . _check_resource_added ( session ) self . _check_experiment_instance_id_added ( session ) session . commit ( ) finally : session . close ( ) def test_add_experiment_instance_id_redundant ( self ) : session = self . session_maker ( ) try : resource_types = session . query ( CoordinatorModel . ResourceType ) . all ( ) self . assertEquals ( , len ( resource_types ) , \"\" ) finally : session . close ( ) exp_id = ExperimentInstanceId ( \"\" , \"\" , \"\" ) self . resources_manager . add_experiment_instance_id ( \"\" , exp_id , Resource ( \"\" , \"\" ) ) self . resources_manager . add_experiment_instance_id ( \"\" , exp_id , Resource ( \"\" , \"\" ) ) session = self . session_maker ( ) try : self . _check_resource_added ( session ) self . _check_experiment_instance_id_added ( session ) self . assertRaises ( CoordExc . InvalidExperimentConfigError , self . resources_manager . add_experiment_instance_id , \"\" , exp_id , Resource ( \"\" , \"\" ) ) self . assertRaises ( CoordExc . InvalidExperimentConfigError , self . resources_manager . add_experiment_instance_id , \"\" , exp_id , Resource ( \"\" , \"\" ) ) session . commit ( ) finally : session . close ( ) def test_get_resource_instance_by_experiment_instance_id ( self ) : session = self . session_maker ( ) try : exp_id = ExperimentInstanceId ( \"\" , \"\" , \"\" ) self . resources_manager . add_experiment_instance_id ( \"\" , exp_id , Resource ( \"\" , \"\" ) ) session . commit ( ) finally : session . close ( ) resource = self . resources_manager . get_resource_instance_by_experiment_instance_id ( exp_id ) expected_resource = Resource ( \"\" , \"\" ) self . assertEquals ( expected_resource , resource ) def test_get_resource_instance_by_experiment_instance_id_failing ( self ) : session = self . session_maker ( ) try : exp_id = ExperimentInstanceId ( \"\" , \"\" , \"\" ) self . resources_manager . add_experiment_instance_id ( \"\" , exp_id , Resource ( \"\" , \"\" ) ) session . commit ( ) finally : session . close ( ) exp_invalid_type = ExperimentInstanceId ( \"\" , \"\" , \"\" ) self . assertRaises ( CoordExc . ExperimentNotFoundError , self . resources_manager . get_resource_instance_by_experiment_instance_id , exp_invalid_type ) exp_invalid_inst = ExperimentInstanceId ( \"\" , \"\" , \"\" ) self . assertRaises ( CoordExc . ExperimentNotFoundError , self . resources_manager . get_resource_instance_by_experiment_instance_id , exp_invalid_inst ) def test_get_resource_types_by_experiment_id ( self ) : session = self . session_maker ( ) try : exp_id = ExperimentInstanceId ( \"\" , \"\" , \"\" ) self . resources_manager . add_experiment_instance_id ( \"\" , exp_id , Resource ( \"\" , \"\" ) ) session . commit ( ) finally : session . close ( ) exp_type_id = ExperimentId ( \"\" , \"\" ) resource_types = self . resources_manager . get_resource_types_by_experiment_id ( exp_type_id ) self . assertEquals ( , len ( resource_types ) ) self . assertTrue ( u\"\" in resource_types ) def test_get_resource_types_by_experiment_id_error ( self ) : session = self . session_maker ( ) try : exp_id = ExperimentInstanceId ( \"\" , \"\" , \"\" ) self . resources_manager . add_experiment_instance_id ( \"\" , exp_id , Resource ( \"\" , \"\" ) ) session . commit ( ) finally : session . close ( ) self . assertRaises ( CoordExc . ExperimentNotFoundError , self . resources_manager . get_resource_types_by_experiment_id , ExperimentId ( \"\" , \"\" ) ) def _check_experiment_instance_id_added ( self , session ) : experiment_types = session . query ( CoordinatorModel . ExperimentType ) . all ( ) self . assertEquals ( , len ( experiment_types ) ) experiment_type = experiment_types [ ] self . assertEquals ( \"\" , experiment_type . cat_name ) self . assertEquals ( \"\" , experiment_type . exp_name ) experiment_instances = experiment_type . instances self . assertEquals ( , len ( experiment_instances ) ) experiment_instance = experiment_instances [ ] self . assertEquals ( \"\" , experiment_instance . experiment_instance_id ) self . assertEquals ( experiment_type , experiment_instance . experiment_type ) resource_instance = experiment_instance . resource_instance self . assertEquals ( \"\" , resource_instance . name ) resource_type = resource_instance . resource_type self . assertTrue ( resource_type in experiment_type . resource_types ) self . assertTrue ( experiment_type in resource_type . experiment_types ) def test_remove_resource_instance_id ( self ) : session = self . session_maker ( ) try : exp_id = ExperimentInstanceId ( \"\" , \"\" , \"\" ) self . resources_manager . add_experiment_instance_id ( \"\" , exp_id , Resource ( \"\" , \"\" ) ) experiment_instances = session . query ( CoordinatorModel . ExperimentInstance ) . all ( ) self . assertEquals ( , len ( experiment_instances ) ) self . resources_manager . remove_resource_instance_id ( session , exp_id ) experiment_instances = session . query ( CoordinatorModel . ExperimentInstance ) . all ( ) self . assertEquals ( , len ( experiment_instances ) ) session . commit ( ) finally : session . close ( ) def test_remove_resource_instance ( self ) : session = self . session_maker ( ) try : exp_id = ExperimentInstanceId ( \"\" , \"\" , \"\" ) resource_instance = Resource ( \"\" , \"\" ) self . resources_manager . add_experiment_instance_id ( \"\" , exp_id , resource_instance ) experiment_instances = session . query ( CoordinatorModel . ExperimentInstance ) . all ( ) self . assertEquals ( , len ( experiment_instances ) ) resource_instances = session . query ( CoordinatorModel . ResourceInstance ) . all ( ) self . assertEquals ( , len ( resource_instances ) ) self . resources_manager . remove_resource_instance ( session , resource_instance ) resource_instances = session . query ( CoordinatorModel . ResourceInstance ) . all ( ) self . assertEquals ( , len ( resource_instances ) ) experiment_instances = session . query ( CoordinatorModel . ExperimentInstance ) . all ( ) self . assertEquals ( , len ( experiment_instances ) ) session . commit ( ) finally : session . close ( ) def test_list_resources ( self ) : session = self . session_maker ( ) try : exp_id1 = ExperimentInstanceId ( \"\" , \"\" , \"\" ) resource_instance1 = Resource ( \"\" , \"\" ) self . resources_manager . add_experiment_instance_id ( \"\" , exp_id1 , resource_instance1 ) exp_id2 = ExperimentInstanceId ( \"\" , \"\" , \"\" ) resource_instance2 = Resource ( \"\" , \"\" ) self . resources_manager . add_experiment_instance_id ( \"\" , exp_id2 , resource_instance2 ) session . commit ( ) ", "answer": "finally :"}, {"prompt": " \"\"\"\"\"\" from oslo_config import cfg from oslo_log import log as logging from oslo_utils import importutils from nova . scheduler import filter_scheduler from nova . scheduler import weights CONF = cfg . CONF LOG = logging . getLogger ( __name__ ) solver_opts = [ cfg . StrOpt ( '' , default = '' '' , help = '' '' ) , ] CONF . register_opts ( solver_opts , group = '' ) class ConstraintSolverScheduler ( filter_scheduler . FilterScheduler ) : \"\"\"\"\"\" def __init__ ( self , * args , ** kwargs ) : super ( ConstraintSolverScheduler , self ) . __init__ ( * args , ** kwargs ) self . hosts_solver = importutils . import_object ( CONF . solver_scheduler . scheduler_host_solver ) def _schedule ( self , context , request_spec , filter_properties ) : \"\"\"\"\"\" instance_type = request_spec . get ( \"\" , None ) instance_uuids = request_spec . get ( \"\" , None ) config_options = self . _get_configuration_options ( ) if instance_uuids : num_instances = len ( instance_uuids ) ", "answer": "else :"}, {"prompt": " from calvin . runtime . south . plugins . io . display import base_display class Display ( base_display . DisplayBase ) : \"\"\"\"\"\" def show_text ( self , text ) : ", "answer": "print text "}, {"prompt": " import datetime from django . db import models from django . utils . text import slugify from ftpdata . models import Candidate from legislators . models import Legislator from api . nulls_last_queryset import NullsLastManager from data_references import STATES_FIPS_DICT , STATE_CHOICES_DICT , STATE_CHOICES , ELECTION_TYPE_CHOICES , ELECTION_TYPE_DICT , CANDIDATE_STATUS_CHOICES , CANDIDATE_STATUS_DICT , type_hash_full , type_hash , committee_designation_hash class Update_Time ( models . Model ) : key = models . SlugField ( max_length = ) update_time = models . DateTimeField ( ) def save ( self , * args , ** kwargs ) : '''''' self . update_time = datetime . datetime . today ( ) super ( Update_Time , self ) . save ( * args , ** kwargs ) class District ( models . Model ) : cycle = models . CharField ( max_length = , blank = True , null = True , help_text = \"\" ) state = models . CharField ( max_length = , blank = True , null = True , choices = STATE_CHOICES , help_text = \"\" ) incumbent_legislator = models . ForeignKey ( Legislator , null = True ) office = models . CharField ( max_length = , null = True , choices = ( ( '' , '' ) , ( '' , '' ) , ( '' , '' ) ) , help_text = \"\" ) office_district = models . CharField ( max_length = , blank = True , null = True , help_text = \"\" ) term_class = models . IntegerField ( blank = True , null = True , help_text = \"\" ) incumbent_name = models . CharField ( max_length = , blank = True , null = True , help_text = \"\" ) incumbent_pty = models . CharField ( max_length = , blank = True , null = True , help_text = \"\" ) incumbent_party = models . CharField ( max_length = , blank = True , null = True , help_text = \"\" ) election_year = models . IntegerField ( blank = True , null = True , help_text = \"\" ) next_election_date = models . DateField ( blank = True , null = True , help_text = \"\" ) next_election_code = models . CharField ( max_length = , blank = True , null = True , choices = ELECTION_TYPE_CHOICES ) special_election_scheduled = models . NullBooleanField ( default = False , null = True , help_text = \"\" ) open_seat = models . NullBooleanField ( default = False , null = True , help_text = \"\" ) dem_frac_historical = models . FloatField ( null = True , help_text = \"\" ) rep_frac_historical = models . FloatField ( null = True , help_text = \"\" ) altered_by_2010_redistricting = models . BooleanField ( default = False , help_text = \"\" ) candidate_raised = models . DecimalField ( max_digits = , decimal_places = , null = True , default = , help_text = \"\" ) candidate_spending = models . DecimalField ( max_digits = , decimal_places = , null = True , default = , help_text = \"\" ) coordinated_spending = models . DecimalField ( max_digits = , decimal_places = , null = True , default = ) outside_spending = models . DecimalField ( max_digits = , decimal_places = , null = True , default = , help_text = \"\" ) total_spending = models . DecimalField ( max_digits = , decimal_places = , null = True , default = ) electioneering_spending = models . DecimalField ( max_digits = , decimal_places = , null = True , default = ) rothenberg_rating_id = models . IntegerField ( null = True ) rothenberg_rating_text = models . CharField ( null = True , max_length = , help_text = \"\" ) rothenberg_update_time = models . DateTimeField ( null = True ) district_notes = models . TextField ( null = True , blank = True , help_text = \"\" ) general_is_decided = models . NullBooleanField ( default = False , null = True , help_text = \"\" ) def get_district_fips ( self ) : if self . office == '' : return None elif self . office == '' : state_fips = STATES_FIPS_DICT [ self . state ] district = self . office_district district = district . zfill ( ) return state_fips + district else : return None def rothenberg_rating_short ( self ) : if self . rothenberg_rating_id == : return '' elif self . rothenberg_rating_id == : return '' return self . rothenberg_rating_text def display_map ( self ) : if self . office == '' : if self . state not in [ '' ] : return True return False def district_formatted ( self ) : if self . office == '' : return \"\" % ( self . state ) elif self . office == '' : if self . office_district : return \"\" % ( self . state , self . office_district ) else : return \"\" % ( self . state ) elif self . office == '' : return \"\" return \"\" def get_rothenberg_link ( self ) : state_slug = STATE_CHOICES_DICT [ self . state ] . lower ( ) . replace ( '' , '' ) return \"\" + state_slug def __unicode__ ( self ) : if self . office == '' : return \"\" % ( self . cycle , self . state , self . term_class ) elif self . office == '' : if self . office_district : return \"\" % ( self . cycle , self . state , self . office_district ) else : return \"\" % ( self . cycle , self . state ) elif self . office == '' : return \"\" return \"\" def get_absolute_url ( self ) : url = \"\" if self . office == '' : url = \"\" % ( self . cycle , self . office , self . state , self . office_district ) elif self . office == '' : url = \"\" % ( self . cycle , self . office , self . state , self . term_class ) elif self . office == '' : url = \"\" return url def get_feed_url ( self ) : url = \"\" if self . office == '' : url = \"\" % ( self . election_year , self . office , self . state , self . office_district ) elif self . office == '' : url = \"\" % ( self . election_year , self . office , self . state , self . term_class ) elif self . office == '' : url = \"\" % ( self . election_year ) return url def race_name ( self ) : name = \"\" if self . office == '' : name = \"\" % ( STATE_CHOICES_DICT [ self . state ] , self . office_district ) elif self . office == '' : name = \"\" % ( STATE_CHOICES_DICT [ self . state ] ) elif self . office == '' : name = \"\" return name def get_filtered_ie_url ( self ) : return \"\" % self . pk def next_election ( self ) : if self . next_election_code : return ELECTION_TYPE_DICT [ self . next_election_code ] else : return \"\" class Meta : ordering = [ '' , '' , '' ] class Candidate_Overlay ( models . Model ) : is_incumbent = models . BooleanField ( default = False , help_text = \"\" ) curated_election_year = models . IntegerField ( null = True , help_text = \"\" ) display = models . BooleanField ( default = False , help_text = \"\" ) district = models . ForeignKey ( '' , null = True , help_text = \"\" ) cycle = models . CharField ( max_length = , blank = True , null = True , help_text = \"\" ) transparency_id = models . CharField ( max_length = , blank = True , null = True , help_text = \"\" ) is_minor_candidate = models . BooleanField ( default = False , help_text = \"\" ) not_seeking_reelection = models . BooleanField ( default = False , help_text = \"\" ) other_office_sought = models . CharField ( max_length = , blank = True , null = True , help_text = \"\" ) other_fec_id = models . CharField ( max_length = , blank = True , null = True , help_text = \"\" ) name = models . CharField ( max_length = , blank = True , null = True , help_text = \"\" ) pty = models . CharField ( max_length = , blank = True , null = True , help_text = \"\" ) party = models . CharField ( max_length = , blank = True , null = True , help_text = \"\" ) fec_id = models . CharField ( max_length = , blank = True , null = True , help_text = \"\" ) pcc = models . CharField ( max_length = , blank = True , null = True , help_text = \"\" ) election_year = models . PositiveIntegerField ( blank = True , null = True , help_text = \"\" ) state = models . CharField ( max_length = , blank = True , null = True , help_text = \"\" ) office = models . CharField ( max_length = , null = True , choices = ( ( '' , '' ) , ( '' , '' ) , ( '' , '' ) ) ) office_district = models . CharField ( max_length = , blank = True , null = True , help_text = \"\" ) ", "answer": "term_class = models . IntegerField ( blank = True , null = True , help_text = \"\" )"}, {"prompt": " from __future__ import ( absolute_import , division , print_function , unicode_literals ) import difflib import glob import inspect import io from lxml import etree import os import unittest import warnings from prov . identifier import Namespace , QualifiedName from prov . constants import PROV import prov . model as prov from prov . tests . test_model import AllTestsBase from prov . tests . utility import RoundTripTestCase EX_NS = ( '' , '' ) EX_TR = ( '' , '' ) DATA_PATH = os . path . join ( os . path . dirname ( os . path . abspath ( inspect . getfile ( inspect . currentframe ( ) ) ) ) , \"\" ) def remove_empty_tags ( tree ) : if tree . text is not None and tree . text . strip ( ) == \"\" : tree . text = None for elem in tree : if etree . iselement ( elem ) : remove_empty_tags ( elem ) def compare_xml ( doc1 , doc2 ) : \"\"\"\"\"\" try : doc1 . seek ( , ) except AttributeError : pass try : doc2 . seek ( , ) except AttributeError : pass obj1 = etree . parse ( doc1 ) obj2 = etree . parse ( doc2 ) for c in obj1 . getroot ( ) . xpath ( \"\" ) : p = c . getparent ( ) p . remove ( c ) for c in obj2 . getroot ( ) . xpath ( \"\" ) : p = c . getparent ( ) p . remove ( c ) remove_empty_tags ( obj1 . getroot ( ) ) remove_empty_tags ( obj2 . getroot ( ) ) buf = io . BytesIO ( ) obj1 . write_c14n ( buf ) buf . seek ( , ) str1 = buf . read ( ) . decode ( ) str1 = [ _i . strip ( ) for _i in str1 . splitlines ( ) if _i . strip ( ) ] buf = io . BytesIO ( ) obj2 . write_c14n ( buf ) buf . seek ( , ) str2 = buf . read ( ) . decode ( ) str2 = [ _i . strip ( ) for _i in str2 . splitlines ( ) if _i . strip ( ) ] unified_diff = difflib . unified_diff ( str1 , str2 ) err_msg = \"\" . join ( unified_diff ) if err_msg : msg = \"\" raise AssertionError ( msg + err_msg ) class ProvXMLTestCase ( unittest . TestCase ) : def test_serialization_example_6 ( self ) : \"\"\"\"\"\" document = prov . ProvDocument ( ) ex_ns = document . add_namespace ( * EX_NS ) document . add_namespace ( * EX_TR ) document . entity ( \"\" , ( ( prov . PROV_TYPE , ex_ns [ \"\" ] ) , ( \"\" , \"\" ) ) ) with io . BytesIO ( ) as actual : document . serialize ( format = '' , destination = actual ) compare_xml ( os . path . join ( DATA_PATH , \"\" ) , actual ) def test_serialization_example_7 ( self ) : \"\"\"\"\"\" document = prov . ProvDocument ( ) document . add_namespace ( * EX_NS ) document . activity ( \"\" , \"\" , \"\" , [ ( prov . PROV_TYPE , prov . Literal ( \"\" , prov . XSD_QNAME ) ) , ( \"\" , \"\" ) ] ) with io . BytesIO ( ) as actual : document . serialize ( format = '' , destination = actual ) compare_xml ( os . path . join ( DATA_PATH , \"\" ) , actual ) def test_serialization_example_8 ( self ) : \"\"\"\"\"\" document = prov . ProvDocument ( ) document . add_namespace ( * EX_NS ) e1 = document . entity ( \"\" ) a1 = document . activity ( \"\" ) document . wasGeneratedBy ( entity = e1 , activity = a1 , time = \"\" , other_attributes = { \"\" : \"\" } ) e2 = document . entity ( \"\" ) document . wasGeneratedBy ( entity = e2 , activity = a1 , time = \"\" , other_attributes = { \"\" : \"\" } ) with io . BytesIO ( ) as actual : document . serialize ( format = '' , destination = actual ) compare_xml ( os . path . join ( DATA_PATH , \"\" ) , actual ) def test_deserialization_example_6 ( self ) : \"\"\"\"\"\" actual_doc = prov . ProvDocument . deserialize ( source = os . path . join ( DATA_PATH , \"\" ) , format = \"\" ) expected_document = prov . ProvDocument ( ) ex_ns = expected_document . add_namespace ( * EX_NS ) expected_document . add_namespace ( * EX_TR ) expected_document . entity ( \"\" , ( ( prov . PROV_TYPE , ex_ns [ \"\" ] ) , ( \"\" , \"\" ) ) ) self . assertEqual ( actual_doc , expected_document ) def test_deserialization_example_7 ( self ) : \"\"\"\"\"\" actual_doc = prov . ProvDocument . deserialize ( source = os . path . join ( DATA_PATH , \"\" ) , format = \"\" ) expected_document = prov . ProvDocument ( ) ex_ns = Namespace ( * EX_NS ) expected_document . add_namespace ( ex_ns ) expected_document . activity ( \"\" , \"\" , \"\" , [ ( prov . PROV_TYPE , QualifiedName ( ex_ns , \"\" ) ) , ( \"\" , \"\" ) ] ) self . assertEqual ( actual_doc , expected_document ) def test_deserialization_example_04_and_05 ( self ) : \"\"\"\"\"\" ", "answer": "xml_string = \"\"\"\"\"\""}, {"prompt": " __author__ = '' from pyon . public import Container , ImmediateProcess from pyon . util . context import LocalContextMixin from pyon . core . governance import get_actor_header from interface . services . examples . hello . ihello_service import HelloServiceProcessClient from interface . services . icontainer_agent import ContainerAgentProcessClient class FakeProcess ( LocalContextMixin ) : name = '' id = '' ", "answer": "class HelloClientProcess ( ImmediateProcess ) :"}, {"prompt": " from whirlwind . core . request import BaseRequest from whirlwind . db . mongo import Mongo from application . models . user import User import datetime , hashlib from tornado . web import authenticated from whirlwind . view . decorators import route @ route ( '' ) class LogoutHandler ( BaseRequest ) : def get ( self ) : self . session [ '' ] = None self . session . destroy ( ) self . redirect ( \"\" ) @ route ( '' ) class LoginHandler ( BaseRequest ) : def get ( self ) : template_values = { } template_values [ '' ] = self . get_argument ( '' , '' ) self . render_template ( '' , ** template_values ) def post ( self ) : username = self . get_argument ( \"\" , None ) password = self . get_argument ( \"\" , None ) if not username or not password : self . flash . error = \"\" self . redirect ( \"\" ) return pw = hashlib . sha1 ( password ) . hexdigest ( ) username = User . normalize ( username ) user = User . lookup ( username ) if not user or user [ '' ] != pw : self . flash . error = \"\" self . redirect ( \"\" ) return if user . is_suspended ( ) : self . flash . error = \"\" self . redirect ( \"\" ) return user . history . last_login = datetime . datetime . utcnow ( ) Mongo . db . ui . users . update ( { '' : username } , { '' : { '' : user . history . last_login } , ", "answer": "'' : { '' : }"}, {"prompt": " \"\"\"\"\"\" from oslo_config import cfg from oslo_log import log as logging import nova . api . openstack from nova . api . openstack . compute import extension_info from nova . api . openstack . compute . legacy_v2 import consoles as v2_consoles from nova . api . openstack . compute . legacy_v2 import extensions as v2_extensions from nova . api . openstack . compute . legacy_v2 import flavors as v2_flavors from nova . api . openstack . compute . legacy_v2 import image_metadata as v2_image_metadata from nova . api . openstack . compute . legacy_v2 import images as v2_images from nova . api . openstack . compute . legacy_v2 import ips as v2_ips from nova . api . openstack . compute . legacy_v2 import limits as v2_limits from nova . api . openstack . compute . legacy_v2 import server_metadata as v2_server_metadata from nova . api . openstack . compute . legacy_v2 import servers as v2_servers from nova . api . openstack . compute . legacy_v2 import versions as legacy_v2_versions from nova . i18n import _LW allow_instance_snapshots_opt = cfg . BoolOpt ( '' , default = True , help = '' ) CONF = cfg . CONF CONF . register_opt ( allow_instance_snapshots_opt ) LOG = logging . getLogger ( __name__ ) class APIRouter ( nova . api . openstack . APIRouter ) : \"\"\"\"\"\" ExtensionManager = v2_extensions . ExtensionManager def __init__ ( self , ext_mgr = None , init_only = None ) : LOG . warning ( _LW ( \"\" \"\" \"\" \"\" \"\" \"\" ) ) super ( APIRouter , self ) . __init__ ( ext_mgr = ext_mgr , init_only = init_only ) def _setup_routes ( self , mapper , ext_mgr , init_only ) : if init_only is None or '' in init_only : self . resources [ '' ] = legacy_v2_versions . create_resource ( ) mapper . connect ( \"\" , \"\" , controller = self . resources [ '' ] , action = '' , conditions = { \"\" : [ '' ] } ) mapper . redirect ( \"\" , \"\" ) if init_only is None or '' in init_only : self . resources [ '' ] = v2_consoles . create_resource ( ) mapper . resource ( \"\" , \"\" , controller = self . resources [ '' ] , parent_resource = dict ( member_name = '' , collection_name = '' ) ) if init_only is None or '' in init_only or '' in init_only or '' in init_only : self . resources [ '' ] = v2_servers . create_resource ( ext_mgr ) mapper . resource ( \"\" , \"\" , controller = self . resources [ '' ] , collection = { '' : '' } , member = { '' : '' } ) if init_only is None or '' in init_only : self . resources [ '' ] = v2_ips . create_resource ( ) mapper . resource ( \"\" , \"\" , controller = self . resources [ '' ] , parent_resource = dict ( member_name = '' , collection_name = '' ) ) if init_only is None or '' in init_only : self . resources [ '' ] = v2_images . create_resource ( ) mapper . resource ( \"\" , \"\" , controller = self . resources [ '' ] , collection = { '' : '' } ) if init_only is None or '' in init_only : self . resources [ '' ] = v2_limits . create_resource ( ) mapper . resource ( \"\" , \"\" , controller = self . resources [ '' ] ) if init_only is None or '' in init_only : self . resources [ '' ] = v2_flavors . create_resource ( ) mapper . resource ( \"\" , \"\" , controller = self . resources [ '' ] , collection = { '' : '' } , member = { '' : '' } ) if init_only is None or '' in init_only : v2immeta = v2_image_metadata self . resources [ '' ] = v2immeta . create_resource ( ) image_metadata_controller = self . resources [ '' ] mapper . resource ( \"\" , \"\" , controller = image_metadata_controller , parent_resource = dict ( member_name = '' , collection_name = '' ) ) mapper . connect ( \"\" , \"\" , controller = image_metadata_controller , action = '' , conditions = { \"\" : [ '' ] } ) if init_only is None or '' in init_only : self . resources [ '' ] = v2_server_metadata . create_resource ( ) server_metadata_controller = self . resources [ '' ] mapper . resource ( \"\" , \"\" , ", "answer": "controller = server_metadata_controller ,"}, {"prompt": " from nose . tools import * from tests . base import ApiTestCase from tests . factories import InstitutionFactory , AuthUserFactory , RegistrationFactory , RetractedRegistrationFactory from framework . auth import Auth from api . base . settings . defaults import API_BASE class TestInstitutionRegistrationList ( ApiTestCase ) : def setUp ( self ) : super ( TestInstitutionRegistrationList , self ) . setUp ( ) self . institution = InstitutionFactory ( ) self . registration1 = RegistrationFactory ( is_public = True , is_registration = True ) self . registration1 . primary_institution = self . institution self . registration1 . save ( ) self . user1 = AuthUserFactory ( ) self . user2 = AuthUserFactory ( ) self . registration2 = RegistrationFactory ( creator = self . user1 , is_public = False , is_registration = True ) self . registration2 . primary_institution = self . institution self . registration2 . add_contributor ( self . user2 , auth = Auth ( self . user1 ) ) self . registration2 . save ( ) self . registration3 = RegistrationFactory ( creator = self . user2 , is_public = False , is_registration = True ) self . registration3 . primary_institution = self . institution self . registration3 . save ( ) self . institution_node_url = '' . format ( API_BASE , self . institution . _id ) def test_return_all_public_nodes ( self ) : res = self . app . get ( self . institution_node_url ) assert_equal ( res . status_code , ) ids = [ each [ '' ] for each in res . json [ '' ] ] assert_in ( self . registration1 . _id , ids ) assert_not_in ( self . registration2 . _id , ids ) assert_not_in ( self . registration3 . _id , ids ) def test_return_private_nodes_with_auth ( self ) : res = self . app . get ( self . institution_node_url , auth = self . user1 . auth ) assert_equal ( res . status_code , ) ids = [ each [ '' ] for each in res . json [ '' ] ] assert_in ( self . registration1 . _id , ids ) assert_in ( self . registration2 . _id , ids ) assert_not_in ( self . registration3 . _id , ids ) def test_return_private_nodes_mixed_auth ( self ) : res = self . app . get ( self . institution_node_url , auth = self . user2 . auth ) assert_equal ( res . status_code , ) ids = [ each [ '' ] for each in res . json [ '' ] ] assert_in ( self . registration1 . _id , ids ) ", "answer": "assert_in ( self . registration2 . _id , ids )"}, {"prompt": " \"\"\"\"\"\" import sys import CGAT . Experiment as E from bx . align import maf from bx . align . tools import get_components_for_species import CGAT . Blat as Blat def threaditer ( reader , species ) : '''''' for m in reader : components = get_components_for_species ( m , species ) if components is not None : yield components def main ( argv = None ) : \"\"\"\"\"\" if not argv : argv = sys . argv parser = E . OptionParser ( version = \"\" , usage = globals ( ) [ \"\" ] ) parser . add_option ( \"\" , \"\" , dest = \"\" , type = \"\" , help = \"\" ) parser . add_option ( \"\" , \"\" , dest = \"\" , type = \"\" , help = \"\" ) parser . set_defaults ( query = None , target = None , ", "answer": ")"}, {"prompt": " \"\"\"\"\"\" from . Representation import Representation import numpy as np __copyright__ = \"\" __credits__ = [ \"\" , \"\" , \"\" , \"\" , \"\" ] __license__ = \"\" __author__ = \"\" class IndependentDiscretization ( Representation ) : \"\"\"\"\"\" def __init__ ( self , domain , discretization = ) : self . setBinsPerDimension ( domain , discretization ) self . features_num = int ( sum ( self . bins_per_dim ) ) self . maxFeatureIDperDimension = np . cumsum ( self . bins_per_dim ) - super ( IndependentDiscretization , self ) . __init__ ( domain , discretization ) def phi_nonTerminal ( self , s ) : F_s = np . zeros ( self . features_num , '' ) F_s [ self . activeInitialFeatures ( s ) ] = return F_s def getDimNumber ( self , f ) : dim = np . searchsorted ( self . maxFeatureIDperDimension , f ) return dim def getFeatureName ( self , feat_id ) : if hasattr ( self . domain , '' ) : dim = np . searchsorted ( self . maxFeatureIDperDimension , feat_id ) index_in_dim = feat_id if dim != : index_in_dim = feat_id - self . maxFeatureIDperDimension [ dim - ] ", "answer": "print self . domain . DimNames [ dim ]"}, {"prompt": " import urllib2 token = '' ", "answer": "channel = ''"}, {"prompt": " from mock import MagicMock , patch from jumpgate . compute . drivers . sl . availability_zones import ( AvailabilityZonesV2 ) import unittest class TestAvailabilityZonesV2 ( unittest . TestCase ) : def setUp ( self ) : self . req , self . resp = MagicMock ( ) , MagicMock ( ) self . tenant_id = '' self . instance = AvailabilityZonesV2 ( ) @ patch ( '' ) def test_on_get ( self , mockOptions ) : mockOptions . return_value = { '' : [ { '' : { '' : { '' : '' } } } , { '' : { '' : { '' : '' } } } , { '' : { '' : { '' : '' } } } ] } self . instance . on_get ( self . req , self . resp , self . tenant_id ) self . assertEquals ( list ( self . resp . body . keys ( ) ) , [ '' ] ) self . assertEquals ( self . resp . body [ '' ] , [ { '' : { '' : True } , '' : None , '' : '' } , { '' : { '' : True } , '' : None , '' : '' } , { '' : { '' : True } , '' : None , '' : '' } ] ) self . assertEquals ( self . resp . status , ) ", "answer": "def tearDown ( self ) :"}, {"prompt": " class MyClass : def my_func ( self ) : if self . xxxx : ", "answer": "self . xxxx ( )"}, {"prompt": " from xierpa3 . components . component import Component class Sidebar ( Component ) : ", "answer": "C = Component . C "}, {"prompt": " \"\"\"\"\"\" import numpy as np import warnings from scipy import sparse from . base import KNeighborsMixin , RadiusNeighborsMixin from . . base import BaseEstimator from . . utils . validation import check_array from . . utils import check_random_state from . . metrics . pairwise import pairwise_distances from . . random_projection import GaussianRandomProjection __all__ = [ \"\" ] HASH_DTYPE = '' MAX_HASH_SIZE = np . dtype ( HASH_DTYPE ) . itemsize * def _find_matching_indices ( tree , bin_X , left_mask , right_mask ) : \"\"\"\"\"\" left_index = np . searchsorted ( tree , bin_X & left_mask ) right_index = np . searchsorted ( tree , bin_X | right_mask , side = '' ) return left_index , right_index def _find_longest_prefix_match ( tree , bin_X , hash_size , left_masks , right_masks ) : \"\"\"\"\"\" hi = np . empty_like ( bin_X , dtype = np . intp ) hi . fill ( hash_size ) lo = np . zeros_like ( bin_X , dtype = np . intp ) res = np . empty_like ( bin_X , dtype = np . intp ) left_idx , right_idx = _find_matching_indices ( tree , bin_X , left_masks [ hi ] , right_masks [ hi ] ) found = right_idx > left_idx res [ found ] = lo [ found ] = hash_size r = np . arange ( bin_X . shape [ ] ) kept = r [ lo < hi ] while kept . shape [ ] : mid = ( lo . take ( kept ) + hi . take ( kept ) ) // left_idx , right_idx = _find_matching_indices ( tree , bin_X . take ( kept ) , left_masks [ mid ] , right_masks [ mid ] ) found = right_idx > left_idx mid_found = mid [ found ] lo [ kept [ found ] ] = mid_found + res [ kept [ found ] ] = mid_found hi [ kept [ ~ found ] ] = mid [ ~ found ] kept = r [ lo < hi ] return res class ProjectionToHashMixin ( object ) : \"\"\"\"\"\" @ staticmethod def _to_hash ( projected ) : if projected . shape [ ] % != : raise ValueError ( '' '' ) out = np . packbits ( ( projected > ) . astype ( int ) ) . view ( dtype = HASH_DTYPE ) return out . reshape ( projected . shape [ ] , - ) def fit_transform ( self , X , y = None ) : self . fit ( X ) return self . transform ( X ) def transform ( self , X , y = None ) : return self . _to_hash ( super ( ProjectionToHashMixin , self ) . transform ( X ) ) class GaussianRandomProjectionHash ( ProjectionToHashMixin , GaussianRandomProjection ) : \"\"\"\"\"\" def __init__ ( self , n_components = , random_state = None ) : super ( GaussianRandomProjectionHash , self ) . __init__ ( n_components = n_components , random_state = random_state ) def _array_of_arrays ( list_of_arrays ) : \"\"\"\"\"\" out = np . empty ( len ( list_of_arrays ) , dtype = object ) out [ : ] = list_of_arrays return out class LSHForest ( BaseEstimator , KNeighborsMixin , RadiusNeighborsMixin ) : \"\"\"\"\"\" def __init__ ( self , n_estimators = , radius = , n_candidates = , n_neighbors = , min_hash_match = , radius_cutoff_ratio = , random_state = None ) : self . n_estimators = n_estimators self . radius = radius self . random_state = random_state self . n_candidates = n_candidates self . n_neighbors = n_neighbors self . min_hash_match = min_hash_match self . radius_cutoff_ratio = radius_cutoff_ratio def _compute_distances ( self , query , candidates ) : \"\"\"\"\"\" if candidates . shape == ( , ) : return np . empty ( , dtype = np . int ) , np . empty ( , dtype = float ) if sparse . issparse ( self . _fit_X ) : candidate_X = self . _fit_X [ candidates ] else : candidate_X = self . _fit_X . take ( candidates , axis = , mode = '' ) distances = pairwise_distances ( query , candidate_X , metric = '' ) [ ] distance_positions = np . argsort ( distances ) distances = distances . take ( distance_positions , mode = '' , axis = ) return distance_positions , distances def _generate_masks ( self ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " import unittest from cubes . cells import Cell , PointCut , SetCut , RangeCut from cubes . cells import string_from_path , cut_from_string , path_from_string from cubes . cells import cut_from_dict from cubes . errors import CubesError , ArgumentError from cubes . errors import HierarchyError , NoSuchDimensionError from . common import CubesTestCaseBase , create_provider class CutsTestCase ( CubesTestCaseBase ) : def setUp ( self ) : super ( CutsTestCase , self ) . setUp ( ) self . provider = create_provider ( \"\" ) self . cube = self . provider . cube ( \"\" ) self . dim_date = self . cube . dimension ( \"\" ) def test_cut_depth ( self ) : dim = self . cube . dimension ( \"\" ) self . assertEqual ( , PointCut ( dim , [ ] ) . level_depth ( ) ) self . assertEqual ( , PointCut ( dim , [ , , ] ) . level_depth ( ) ) self . assertEqual ( , RangeCut ( dim , [ ] , [ ] ) . level_depth ( ) ) self . assertEqual ( , RangeCut ( dim , [ , , ] , [ ] ) . level_depth ( ) ) self . assertEqual ( , SetCut ( dim , [ [ ] , [ ] ] ) . level_depth ( ) ) self . assertEqual ( , SetCut ( dim , [ [ ] , [ ] , [ , , ] ] ) . level_depth ( ) ) def test_cut_from_dict ( self ) : d = { \"\" : \"\" , \"\" : [ ] , \"\" : \"\" , \"\" : , \"\" : None , \"\" : False , \"\" : False } cut = cut_from_dict ( d ) tcut = PointCut ( \"\" , [ ] ) self . assertEqual ( tcut , cut ) self . assertEqual ( dict ( d ) , tcut . to_dict ( ) ) self . _assert_invert ( d , cut , tcut ) d = { \"\" : \"\" , \"\" : [ ] , \"\" : [ , ] , \"\" : \"\" , \"\" : , \"\" : None , \"\" : False , \"\" : False } cut = cut_from_dict ( d ) tcut = RangeCut ( \"\" , [ ] , [ , ] ) self . assertEqual ( tcut , cut ) self . assertEqual ( dict ( d ) , tcut . to_dict ( ) ) self . _assert_invert ( d , cut , tcut ) d = { \"\" : \"\" , \"\" : [ [ ] , [ , ] ] , \"\" : \"\" , \"\" : , \"\" : None , \"\" : False , \"\" : False } cut = cut_from_dict ( d ) tcut = SetCut ( \"\" , [ [ ] , [ , ] ] ) self . assertEqual ( tcut , cut ) self . assertEqual ( dict ( d ) , tcut . to_dict ( ) ) self . _assert_invert ( d , cut , tcut ) self . assertRaises ( ArgumentError , cut_from_dict , { \"\" : \"\" } ) def _assert_invert ( self , d , cut , tcut ) : cut . invert = True tcut . invert = True d [ \"\" ] = True self . assertEqual ( tcut , cut ) self . assertEqual ( dict ( d ) , tcut . to_dict ( ) ) class StringConversionsTestCase ( unittest . TestCase ) : def test_cut_string_conversions ( self ) : cut = PointCut ( \"\" , [ \"\" ] ) self . assertEqual ( \"\" , str ( cut ) ) self . assertEqual ( cut , cut_from_string ( \"\" ) ) cut = PointCut ( \"\" , [ \"\" , \"\" , \"\" ] ) self . assertEqual ( \"\" , str ( cut ) ) self . assertEqual ( cut , cut_from_string ( \"\" ) ) cut = PointCut ( \"\" , [ \"\" ] ) self . assertEqual ( r\"\" , str ( cut ) ) self . assertEqual ( cut , cut_from_string ( \"\" ) ) cut = PointCut ( \"\" , [ \"\" ] ) self . assertEqual ( \"\" , str ( cut ) ) self . assertEqual ( cut , cut_from_string ( \"\" ) ) cut = PointCut ( \"\" , [ \"\" ] ) self . assertEqual ( \"\" , str ( cut ) ) self . assertEqual ( cut , cut_from_string ( \"\" ) ) def test_special_characters ( self ) : self . assertEqual ( '' , string_from_path ( [ \"\" , \"\" , ] ) ) def test_string_from_path ( self ) : self . assertEqual ( '' , string_from_path ( [ \"\" , \"\" , ] ) ) self . assertEqual ( '' , string_from_path ( [ ] ) ) self . assertEqual ( '' , string_from_path ( None ) ) def test_path_from_string ( self ) : self . assertEqual ( [ \"\" , \"\" , \"\" ] , path_from_string ( '' ) ) self . assertEqual ( [ ] , path_from_string ( '' ) ) self . assertEqual ( [ ] , path_from_string ( None ) ) def test_set_cut_string ( self ) : cut = SetCut ( \"\" , [ [ \"\" ] , [ \"\" , \"\" ] , [ \"\" , \"\" , \"\" ] ] ) self . assertEqual ( \"\" , str ( cut ) ) self . assertEqual ( cut , cut_from_string ( \"\" ) ) cut = SetCut ( \"\" , [ [ \"\" ] ] ) self . assertEqual ( \"\" , str ( cut ) ) self . assertEqual ( PointCut ( \"\" , [ \"\" ] ) , cut_from_string ( \"\" ) ) cut = SetCut ( \"\" , [ [ \"\" ] ] ) self . assertEqual ( \"\" , str ( cut ) ) self . assertEqual ( PointCut ( \"\" , [ \"\" ] ) , cut_from_string ( \"\" ) ) def test_range_cut_string ( self ) : cut = RangeCut ( \"\" , [ \"\" ] , [ \"\" ] ) self . assertEqual ( \"\" , str ( cut ) ) self . assertEqual ( cut , cut_from_string ( \"\" ) ) cut = RangeCut ( \"\" , [ \"\" ] , None ) self . assertEqual ( \"\" , str ( cut ) ) ", "answer": "cut = cut_from_string ( \"\" )"}, {"prompt": " \"\"\"\"\"\" revision = '' ", "answer": "down_revision = ''"}, {"prompt": " from atom . api import Typed , ForwardTyped , Enum , Range , observe from enaml . core . declarative import d_ from . toolkit_object import ToolkitObject , ProxyToolkitObject from . widget import Widget class ProxyStatusItem ( ProxyToolkitObject ) : \"\"\"\"\"\" declaration = ForwardTyped ( lambda : StatusItem ) def set_mode ( eslf , mode ) : raise NotImplementedError def set_stretch ( self , stretch ) : raise NotImplementedError class StatusItem ( ToolkitObject ) : \"\"\"\"\"\" mode = d_ ( Enum ( '' , '' ) ) stretch = d_ ( Range ( low = ) ) proxy = Typed ( ProxyStatusItem ) def status_widget ( self ) : \"\"\"\"\"\" for child in reversed ( self . children ) : ", "answer": "if isinstance ( child , Widget ) :"}, {"prompt": " import tornado . web class BaseHandler ( tornado . web . RequestHandler ) : @ property ", "answer": "def db ( self ) :"}, {"prompt": " import unittest from tests . test_utils import makeBandit import random import sys from collections import Counter class MonteCarloTest ( unittest . TestCase ) : \"\"\"\"\"\" def draw ( self , arm_name ) : if random . random ( ) > self . true_arm_probs [ arm_name ] : return return def run_algo ( self , bandit , num_sims , horizon ) : chosen_arms = [ for i in range ( num_sims * horizon ) ] rewards = [ for i in range ( num_sims * horizon ) ] cumulative_rewards = [ for i in range ( num_sims * horizon ) ] sim_nums = [ for i in range ( num_sims * horizon ) ] times = [ for i in range ( num_sims * horizon ) ] for sim in range ( num_sims ) : sim = sim + for t in range ( horizon ) : t = t + index = ( sim - ) * horizon + t - sim_nums [ index ] = sim times [ index ] = t chosen_arm = bandit . suggest_arm ( ) chosen_arms [ index ] = chosen_arm [ '' ] bandit . pull_arm ( chosen_arm [ '' ] ) reward = self . draw ( chosen_arm [ '' ] ) rewards [ index ] = reward if t == : cumulative_rewards [ index ] = reward else : cumulative_rewards [ index ] = cumulative_rewards [ index - ] + reward if reward : bandit . reward_arm ( chosen_arm [ '' ] , reward ) return [ sim_nums , times , chosen_arms , rewards , cumulative_rewards ] def save_results ( self , results , output_stream ) : for sim in range ( len ( results [ ] ) ) : output_stream . write ( \"\" . join ( [ str ( results [ j ] [ sim ] ) for j in range ( len ( results ) ) ] ) + \"\" ) sys . stdout . flush ( ) class EpsilonGreedyTest ( MonteCarloTest ) : bandit_name = '' true_arm_probs = dict ( green = , blue = , red = ) def test_bandit ( self ) : results = self . run_algo ( makeBandit ( self . bandit_name , epsilon = ) , , ) data = Counter ( results [ ] ) assert data . most_common ( ) [ ] [ ] is '' class SoftmaxTest ( MonteCarloTest ) : true_arm_probs = dict ( green = , red = , blue = ) def test_bandit ( self ) : results = self . run_algo ( makeBandit ( '' , tau = ) , , ) data = Counter ( results [ ] ) assert data . most_common ( ) [ ] [ ] is '' class AnnealingSoftmaxTest ( MonteCarloTest ) : true_arm_probs = dict ( green = , red = , blue = ) def test_bandit ( self ) : results = self . run_algo ( makeBandit ( '' , tau = ) , , ) data = Counter ( results [ ] ) assert data . most_common ( ) [ ] [ ] is '' ", "answer": "class ThompsonBanditTest ( MonteCarloTest ) :"}, {"prompt": " from . cli import main ", "answer": "main ( ) "}, {"prompt": " from robotide . publish import RideTestCaseRemoved , RideVariableAdded , RideVariableRemoved , RideVariableMovedUp , RideVariableMovedDown , RideUserKeywordRemoved , RideUserKeywordAdded , RideTestCaseAdded from robotide . publish . messages import RideItemMovedUp , RideItemMovedDown from robotide . robotapi import is_list_var , is_scalar_var , is_dict_var from robotide import utils from . basecontroller import ControllerWithParent from . macrocontrollers import TestCaseController , UserKeywordController from robotide . utils import overrides , variablematcher from . settingcontrollers import MetadataController , ImportController , VariableController class _WithListOperations ( object ) : def move_up ( self , index ) : if index > : self . _swap ( index - , index ) def move_down ( self , index ) : if index < len ( self . _items ) - : self . _swap ( index , index + ) def _swap ( self , ind1 , ind2 ) : self . _items [ ind1 ] , self . _items [ ind2 ] = self . _items [ ind2 ] , self . _items [ ind1 ] self . mark_dirty ( ) def delete ( self , index ) : if isinstance ( self . _items , list ) : self . _items . pop ( index ) else : self . _items . data . pop ( index ) self . mark_dirty ( ) @ property def _items ( self ) : raise NotImplementedError ( self . __class__ ) def mark_dirty ( self ) : raise NotImplementedError ( self . __class__ ) class _TableController ( ControllerWithParent ) : def __init__ ( self , parent_controller , table ) : self . _parent = parent_controller self . _table = table class VariableTableController ( _TableController , _WithListOperations ) : def __init__ ( self , parent_controller , table ) : _TableController . __init__ ( self , parent_controller , table ) self . _variable_cache = { } def _get ( self , variable ) : if variable not in self . _variable_cache : self . _variable_cache [ variable ] = VariableController ( self , variable ) return self . _variable_cache [ variable ] def __iter__ ( self ) : return iter ( self . _get ( v ) for v in self . _table ) def __getitem__ ( self , index ) : return self . _get ( self . _items [ index ] ) def index ( self , ctrl ) : return [ v for v in self ] . index ( ctrl ) @ property def _items ( self ) : return self . _table . variables def move_up ( self , index ) : ctrl = self [ index ] _WithListOperations . move_up ( self , index ) other = self [ index ] self . mark_dirty ( ) RideVariableMovedUp ( item = ctrl , other = other ) . publish ( ) def move_down ( self , index ) : ctrl = self [ index ] _WithListOperations . move_down ( self , index ) other = self [ index ] self . mark_dirty ( ) RideVariableMovedDown ( item = ctrl , other = other ) . publish ( ) def add_variable ( self , name , value , comment = None ) : self . _table . add ( name , value , comment ) self . mark_dirty ( ) var_controller = self [ - ] self . notify_variable_added ( var_controller ) return var_controller def validate_scalar_variable_name ( self , name , item = None ) : return self . _validate_name ( _ScalarVarValidator ( ) , name , item ) def validate_list_variable_name ( self , name , item = None ) : return self . _validate_name ( _ListVarValidator ( ) , name , item ) def validate_dict_variable_name ( self , name , item = None ) : return self . _validate_name ( _DictVarValidator ( ) , name , item ) def _validate_name ( self , validator , name , item = None ) : return VariableNameValidation ( self , validator , name , item ) def delete ( self , index ) : self . remove_var ( self [ index ] ) def remove_var ( self , var_controller ) : self . _items . remove ( var_controller . data ) del self . _variable_cache [ var_controller . data ] self . mark_dirty ( ) self . notify_variable_removed ( var_controller ) def notify_variable_added ( self , ctrl ) : self . datafile_controller . update_namespace ( ) RideVariableAdded ( datafile = self . datafile , name = ctrl . name , item = ctrl , index = ctrl . index ) . publish ( ) def notify_variable_removed ( self , ctrl ) : self . datafile_controller . update_namespace ( ) RideVariableRemoved ( datafile = self . datafile , name = ctrl . name , item = ctrl ) . publish ( ) def contains_variable ( self , name ) : vars_as_list = [ ] for var in self . _items : vars_as_list += var . as_list ( ) return any ( variablematcher . value_contains_variable ( string , name ) for string in vars_as_list ) class _ScalarVarValidator ( object ) : __call__ = lambda self , name : is_scalar_var ( name ) name = '' prefix = '' class _ListVarValidator ( object ) : __call__ = lambda self , name : is_list_var ( name ) name = '' prefix = '' class _DictVarValidator ( object ) : __call__ = lambda self , name : is_dict_var ( name ) name = '' prefix = '' class _NameValidation ( object ) : def __init__ ( self , table , name , named_ctrl = None ) : self . _table = table self . error_message = '' self . _named_ctrl = named_ctrl self . _validate ( name . strip ( ) ) def _name_taken ( self , name ) : return any ( utils . eq ( name , item . name , ignore = [ '' ] ) for item in self . _table if item != self . _named_ctrl ) class VariableNameValidation ( _NameValidation ) : def __init__ ( self , table , validator , name , named_ctrl = None ) : self . _validator = validator _NameValidation . __init__ ( self , table , name , named_ctrl ) def _validate ( self , name ) : if not self . _validator ( name ) : self . error_message = '' % ( self . _validator . name , self . _validator . prefix ) if self . _name_taken ( name ) : self . error_message = '' class MacroNameValidation ( _NameValidation ) : def _validate ( self , name ) : if not name : self . error_message = '' % self . _table . item_type if self . _name_taken ( name ) : self . error_message = '' % self . _table . item_type if \"\" in name : self . error_message = '' % self . _table . item_type class _MacroTable ( _TableController ) : ", "answer": "@ property"}, {"prompt": " \"\"\"\"\"\" import os import sys import time sys . path . insert ( , os . path . join ( os . path . dirname ( os . path . dirname ( __file__ ) ) , '' ) ) from snmp import SNMPCollector as parent_SNMPCollector from diamond . metric import Metric class SNMPRawCollector ( parent_SNMPCollector ) : def process_config ( self ) : super ( SNMPRawCollector , self ) . process_config ( ) self . skip_list = [ ] def get_default_config ( self ) : \"\"\"\"\"\" default_config = super ( SNMPRawCollector , self ) . get_default_config ( ) default_config . update ( { '' : { } , '' : '' , '' : '' , } ) return default_config def _precision ( self , value ) : \"\"\"\"\"\" value = str ( value ) decimal = value . rfind ( '' ) if decimal == - : return return len ( value ) - decimal - def _skip ( self , device , oid , reason = None ) : self . skip_list . append ( ( device , oid ) ) if reason is not None : self . log . warn ( '' . format ( oid , device , reason ) ) def _get_value_walk ( self , device , oid , host , port , community ) : data = self . walk ( oid , host , port , community ) if data is None : self . _skip ( device , oid , '' ) return self . log . debug ( '' . format ( device , data ) ) if len ( data ) != : self . _skip ( device , oid , '' . format ( len ( data ) ) ) return value = data . items ( ) [ ] [ ] return value def _get_value ( self , device , oid , host , port , community ) : data = self . get ( oid , host , port , community ) if data is None : self . _skip ( device , oid , '' ) return self . log . debug ( '' . format ( device , data ) ) if len ( data ) == : self . _skip ( device , oid , '' ) return if oid not in data : self . _skip ( device , oid , '' ) return value = data [ oid ] if value == '' : self . _skip ( device , oid , '' ) return if value == '' : return self . _get_value_walk ( device , oid , host , port , community ) return value def collect_snmp ( self , device , host , port , community ) : \"\"\"\"\"\" self . log . debug ( '' . format ( device ) ) dev_config = self . config [ '' ] [ device ] if '' in dev_config : for oid , metricName in dev_config [ '' ] . items ( ) : if ( device , oid ) in self . skip_list : self . log . debug ( '' . format ( oid , metricName , device ) ) continue timestamp = time . time ( ) value = self . _get_value ( device , oid , host , port , community ) if value is None : continue self . log . debug ( ", "answer": "'' . format ("}, {"prompt": " \"\"\"\"\"\" import logging import yamlconf from . . datasources import revision_oriented from . . dependencies import Context logger = logging . getLogger ( __name__ ) class Extractor ( Context ) : \"\"\"\"\"\" def extract ( self , rev_ids , dependents , context = None , caches = None , cache = None , profile = None ) : raise NotImplementedError ( ) @ classmethod def from_config ( cls , config , name , section_key = \"\" ) : section = config [ section_key ] [ name ] if '' in section : return yamlconf . import_module ( section [ '' ] ) elif '' in section : Class = yamlconf . import_module ( section [ '' ] ) return Class . from_config ( config , name ) class OfflineExtractor ( Extractor ) : \"\"\"\"\"\" def __init__ ( self ) : super ( ) . __init__ ( ) logger . warning ( \"\" + \"\" ) def extract ( self , rev_ids , dependents , context = None , caches = None , cache = None , profile = None ) : caches = caches or { } if hasattr ( rev_ids , \"\" ) : return self . _extract_many ( rev_ids , dependents , context = context , caches = caches , cache = cache , profile = profile ) else : rev_id = rev_ids cache = cache or caches return self . _extract ( rev_id , dependents , context = context , cache = cache , profile = profile ) def _extract ( self , rev_id , dependents , context = None , cache = None , profile = None ) : solve_cache = { revision_oriented . revision . id : rev_id } solve_cache . update ( cache or { } ) return self . solve ( dependents , context = context , cache = solve_cache , ", "answer": "profile = profile )"}, {"prompt": " import socket import pytest from urllib3 . util import parse_url , Url from nameko . amqp import verify_amqp_uri @ pytest . fixture def uris ( rabbit_config ) : amqp_uri = rabbit_config [ '' ] scheme , auth , host , port , path , _ , _ = parse_url ( amqp_uri ) bad_port = Url ( scheme , auth , host , port + , path ) . url bad_user = Url ( scheme , '' , host , port , path ) . url bad_vhost = Url ( scheme , auth , host , port , '' ) . url return { '' : amqp_uri , '' : bad_port , '' : bad_user , '' : bad_vhost , } def test_good ( uris ) : amqp_uri = uris [ '' ] verify_amqp_uri ( amqp_uri ) def test_bad_user ( uris ) : ", "answer": "amqp_uri = uris [ '' ]"}, {"prompt": " \"\"\"\"\"\" from eve . methods . get import get , getitem from eve . methods . post import post from eve . methods . patch import patch from eve . methods . put import put ", "answer": "from eve . methods . delete import delete , deleteitem "}, {"prompt": " import os from setuptools import setup , find_packages from django_seo_js import VERSION ROOT_DIR = os . path . dirname ( __file__ ) SOURCE_DIR = os . path . join ( ROOT_DIR ) reqs = [ ] with open ( \"\" , \"\" ) as f : for line in f . readlines ( ) : reqs . append ( line . strip ( ) ) test_reqs = [ ] with open ( \"\" , \"\" ) as f : for line in f . readlines ( ) : test_reqs . append ( line . strip ( ) ) try : import pypandoc long_description = pypandoc . convert ( '' , '' ) except ( IOError , ImportError ) : ", "answer": "long_description = ''"}, {"prompt": " \"\"\"\"\"\" from django . template import Library register = Library ( ) @ register . filter def url ( sort , field ) : return sort . url ( field ) @ register . filter ", "answer": "def dir ( sort , field ) :"}, {"prompt": " from cassiopeia import baseriotapi from . . import int_test_handler def test_all ( ) : print ( \"\" ) test_summoners_by_name ( ) ", "answer": "test_summoners_by_id ( )"}, {"prompt": " import numpy as np import numpy . random as npr import kayak from . import * def test_scalar_value ( ) : npr . seed ( ) for ii in xrange ( NUM_TRIALS ) : np_X = npr . randn ( ) X = kayak . Parameter ( np_X ) out = kayak . NExp ( X ) assert close_float ( out . value , - np . exp ( - np . abs ( np_X ) ) ) def test_scalar_grad ( ) : npr . seed ( ) for ii in xrange ( NUM_TRIALS ) : while True : np_X = npr . randn ( ) if np . abs ( np_X ) > : break X = kayak . Parameter ( np_X ) out = kayak . NExp ( X ) assert kayak . util . checkgrad ( X , out ) < MAX_GRAD_DIFF def test_scalar_value_2 ( ) : npr . seed ( ) for ii in xrange ( NUM_TRIALS ) : np_X = npr . randn ( ) wt = np . exp ( npr . randn ( ) ) X = kayak . Parameter ( np_X ) out = kayak . NExp ( X , weight = wt ) assert close_float ( out . value , wt * ( - np . exp ( - np . abs ( np_X ) ) ) ) def test_scalar_grad_2 ( ) : npr . seed ( ) for ii in xrange ( NUM_TRIALS ) : while True : np_X = npr . randn ( ) if np . abs ( np_X ) > : break wt = np . exp ( npr . randn ( ) ) X = kayak . Parameter ( np_X ) out = kayak . NExp ( X , weight = wt ) assert kayak . util . checkgrad ( X , out ) < MAX_GRAD_DIFF def test_vector_value ( ) : npr . seed ( ) for ii in xrange ( NUM_TRIALS ) : np_X = npr . randn ( , ) wt = np . exp ( npr . randn ( ) ) X = kayak . Parameter ( np_X ) out = kayak . NExp ( X , weight = wt ) assert close_float ( out . value , wt * np . sum ( - np . exp ( - np . abs ( np_X ) ) ) ) def test_vector_grad ( ) : npr . seed ( ) for ii in xrange ( NUM_TRIALS ) : while True : np_X = npr . randn ( ) if np . all ( np . abs ( np_X ) > ) : break wt = np . exp ( npr . randn ( ) ) X = kayak . Parameter ( np_X ) out = kayak . NExp ( X , weight = wt ) assert kayak . util . checkgrad ( X , out ) < MAX_GRAD_DIFF def test_matrix_value ( ) : npr . seed ( ) for ii in xrange ( NUM_TRIALS ) : np_X = npr . randn ( , ) wt = np . exp ( npr . randn ( ) ) X = kayak . Parameter ( np_X ) out = kayak . NExp ( X , weight = wt ) assert close_float ( out . value , wt * np . sum ( - np . exp ( - np . abs ( np_X ) ) ) ) def test_matrix_grad ( ) : npr . seed ( ) for ii in xrange ( NUM_TRIALS ) : while True : np_X = npr . randn ( ) if np . all ( np . abs ( np_X ) > ) : break wt = np . exp ( npr . randn ( ) ) X = kayak . Parameter ( np_X ) out = kayak . NExp ( X , weight = wt ) assert kayak . util . checkgrad ( X , out ) < MAX_GRAD_DIFF def test_tensor_value ( ) : npr . seed ( ) for ii in xrange ( NUM_TRIALS ) : np_X = npr . randn ( , , ) wt = np . exp ( npr . randn ( ) ) X = kayak . Parameter ( np_X ) out = kayak . NExp ( X , weight = wt ) assert close_float ( out . value , wt * np . sum ( - np . exp ( - np . abs ( np_X ) ) ) ) def test_tensor_grad ( ) : npr . seed ( ) for ii in xrange ( NUM_TRIALS ) : while True : np_X = npr . randn ( ) if np . all ( np . abs ( np_X ) > ) : ", "answer": "break"}, {"prompt": " DATE_FORMAT = '' TIME_FORMAT = '' DATETIME_FORMAT = '' YEAR_MONTH_FORMAT = '' MONTH_DAY_FORMAT = '' SHORT_DATE_FORMAT = '' ", "answer": "DECIMAL_SEPARATOR = ''"}, {"prompt": " from sqlalchemy . orm . exc import NoResultFound from shiva import models as m from shiva . app import db from shiva . utils import get_logger q = db . session . query log = get_logger ( ) class CacheManager ( object ) : \"\"\"\"\"\" def __init__ ( self , ram_cache = True , use_db = True ) : log . debug ( '' ) if not ram_cache : log . debug ( '' ) self . ram_cache = ram_cache self . use_db = use_db self . artists = { } self . albums = { } self . hashes = set ( ) def get_artist ( self , name ) : artist = self . artists . get ( name ) if not artist : if self . use_db : try : artist = q ( m . Artist ) . filter_by ( name = name ) . one ( ) except NoResultFound : pass if artist and self . ram_cache : self . add_artist ( artist ) return artist def add_artist ( self , artist ) : if self . ram_cache : self . artists [ artist . name ] = artist def get_album ( self , name , artist ) : album = self . albums . get ( artist . name , { } ) . get ( name ) if not album : if self . use_db : try : album = q ( m . Album ) . filter_by ( name = name ) . one ( ) except NoResultFound : pass if album and self . ram_cache : self . add_album ( album , artist ) return album def add_album ( self , album , artist ) : if self . ram_cache : if not self . albums . get ( artist . name ) : self . albums [ artist . name ] = { } self . albums [ artist . name ] [ album . name ] = album def add_hash ( self , hash ) : if self . ram_cache : self . hashes . add ( hash ) def hash_exists ( self , hash ) : if hash in self . hashes : return True if self . use_db : return bool ( q ( m . Track ) . filter_by ( hash = hash ) . count ( ) ) return False def clear ( self ) : self . artists = { } self . albums = { } ", "answer": "self . hashes = set ( ) "}, {"prompt": " from __future__ import division import warnings import numpy as np import scipy . sparse as sp from . base import BaseEstimator , ClassifierMixin , RegressorMixin from . utils import check_random_state from . utils . validation import check_array from . utils . validation import check_consistent_length from . utils . random import random_choice_csc from . utils . stats import _weighted_percentile from . utils . multiclass import class_distribution class DummyClassifier ( BaseEstimator , ClassifierMixin ) : \"\"\"\"\"\" def __init__ ( self , strategy = \"\" , random_state = None , constant = None ) : self . strategy = strategy self . random_state = random_state self . constant = constant def fit ( self , X , y , sample_weight = None ) : \"\"\"\"\"\" if self . strategy not in ( \"\" , \"\" , \"\" , \"\" , \"\" ) : raise ValueError ( \"\" ) if self . strategy == \"\" and sp . issparse ( y ) : y = y . toarray ( ) warnings . warn ( '' '' '' '' , UserWarning ) self . sparse_output_ = sp . issparse ( y ) if not self . sparse_output_ : y = np . atleast_1d ( y ) self . output_2d_ = y . ndim == if y . ndim == : y = np . reshape ( y , ( - , ) ) self . n_outputs_ = y . shape [ ] if self . strategy == \"\" : if self . constant is None : raise ValueError ( \"\" \"\" ) else : constant = np . reshape ( np . atleast_1d ( self . constant ) , ( - , ) ) if constant . shape [ ] != self . n_outputs_ : raise ValueError ( \"\" \"\" % self . n_outputs_ ) ( self . classes_ , self . n_classes_ , self . class_prior_ ) = class_distribution ( y , sample_weight ) if ( self . strategy == \"\" and any ( constant [ k ] not in self . classes_ [ k ] for k in range ( self . n_outputs_ ) ) ) : raise ValueError ( \"\" \"\" ) if self . n_outputs_ == and not self . output_2d_ : self . n_classes_ = self . n_classes_ [ ] self . classes_ = self . classes_ [ ] self . class_prior_ = self . class_prior_ [ ] return self def predict ( self , X ) : \"\"\"\"\"\" if not hasattr ( self , \"\" ) : raise ValueError ( \"\" ) X = check_array ( X , accept_sparse = [ '' , '' , '' ] ) n_samples = int ( X . shape [ ] ) rs = check_random_state ( self . random_state ) n_classes_ = self . n_classes_ classes_ = self . classes_ class_prior_ = self . class_prior_ constant = self . constant if self . n_outputs_ == : n_classes_ = [ n_classes_ ] classes_ = [ classes_ ] class_prior_ = [ class_prior_ ] constant = [ constant ] if self . strategy == \"\" : proba = self . predict_proba ( X ) if self . n_outputs_ == : proba = [ proba ] if self . sparse_output_ : class_prob = None if self . strategy in ( \"\" , \"\" ) : classes_ = [ np . array ( [ cp . argmax ( ) ] ) for cp in class_prior_ ] elif self . strategy == \"\" : ", "answer": "class_prob = class_prior_"}, {"prompt": " import os import re from smtplib import SMTPException from django import forms from django . conf import settings from django . core . files . storage import default_storage as storage from django . contrib . auth import forms as auth_forms from django . contrib . auth . tokens import default_token_generator from django . forms . util import ErrorList from django . utils . safestring import mark_safe from django . utils . translation import ugettext as _ , ugettext_lazy as _lazy import commonware . log import happyforms from olympia import amo from olympia . accounts . views import fxa_error_message from olympia . amo . fields import ReCaptchaField , HttpHttpsOnlyURLField from olympia . users import notifications as email from olympia . amo . urlresolvers import reverse from olympia . amo . utils import clean_nl , has_links , log_cef , slug_validator from olympia . translations import LOCALES from . import tasks from . models import ( UserProfile , UserNotification , BlacklistedName , BlacklistedEmailDomain , BlacklistedPassword ) from . widgets import ( NotificationsSelectMultiple , RequiredCheckboxInput , RequiredEmailInput , RequiredInputMixin , RequiredTextarea ) log = commonware . log . getLogger ( '' ) admin_re = re . compile ( '' ) class PasswordMixin : min_length = error_msg = { '' : _lazy ( '' ) % min_length } @ classmethod def widget ( cls , ** kw ) : attrs = { '' : '' , '' : cls . min_length , } if kw . pop ( '' , False ) : attrs . update ( RequiredInputMixin . required_attrs ) return forms . PasswordInput ( attrs = attrs , ** kw ) def clean_password ( self , field = '' , instance = '' ) : data = self . cleaned_data [ field ] if not data : return data user = getattr ( self , instance , None ) if user and user . pk and user . needs_tougher_password : if not admin_re . search ( data ) : raise forms . ValidationError ( _ ( '' ) ) if BlacklistedPassword . blocked ( data ) : raise forms . ValidationError ( _ ( '' ) ) return data class AuthenticationForm ( auth_forms . AuthenticationForm ) : username = forms . CharField ( max_length = , widget = RequiredEmailInput ) password = forms . CharField ( max_length = , min_length = PasswordMixin . min_length , error_messages = PasswordMixin . error_msg , widget = PasswordMixin . widget ( render_value = False , required = True ) ) rememberme = forms . BooleanField ( required = False ) recaptcha = ReCaptchaField ( ) recaptcha_shown = forms . BooleanField ( widget = forms . HiddenInput , required = False ) def __init__ ( self , request = None , use_recaptcha = False , * args , ** kw ) : super ( AuthenticationForm , self ) . __init__ ( * args , ** kw ) if not use_recaptcha or not settings . NOBOT_RECAPTCHA_PRIVATE_KEY : del self . fields [ '' ] def clean ( self ) : if ( '' in self . errors and '' in self . data and < len ( self . data [ '' ] ) < PasswordMixin . min_length ) : msg = _ ( '' '' '' ) % ( PasswordMixin . min_length , reverse ( '' ) ) self . _errors [ '' ] = ErrorList ( [ mark_safe ( msg ) ] ) if '' in self . errors : return { } return super ( AuthenticationForm , self ) . clean ( ) class PasswordResetForm ( auth_forms . PasswordResetForm ) : email = forms . EmailField ( widget = RequiredEmailInput ) def __init__ ( self , * args , ** kwargs ) : self . request = kwargs . pop ( '' , None ) super ( PasswordResetForm , self ) . __init__ ( * args , ** kwargs ) def clean_email ( self ) : email = self . cleaned_data [ '' ] self . users_cache = UserProfile . objects . filter ( email__iexact = email ) try : if self . users_cache . get ( ) . fxa_migrated ( ) : raise forms . ValidationError ( _ ( '' '' ) ) except UserProfile . DoesNotExist : pass return email def save ( self , ** kw ) : if not self . users_cache : log . info ( \"\" . format ( ** self . cleaned_data ) ) return for user in self . users_cache : log . info ( u'' % user ) if user . needs_tougher_password : log_cef ( '' , , self . request , username = user , signature = '' , msg = '' ) else : log_cef ( '' , , self . request , username = user , signature = '' , msg = '' ) try : self . base_save ( ** kw ) except SMTPException , e : log . error ( \"\" % ( user , e ) ) def base_save ( self , domain_override = None , subject_template_name = '' , email_template_name = '' , use_https = False , token_generator = default_token_generator , from_email = None , request = None , html_email_template_name = None ) : \"\"\"\"\"\" from django . core . mail import send_mail from django . contrib . auth import get_user_model from django . contrib . sites . models import get_current_site from django . template import loader from django . utils . encoding import force_bytes from django . utils . http import urlsafe_base64_encode UserModel = get_user_model ( ) email = self . cleaned_data [ \"\" ] active_users = UserModel . _default_manager . filter ( email__iexact = email , deleted = False ) for user in active_users : if not user . has_usable_password ( ) : continue if not domain_override : current_site = get_current_site ( request ) site_name = current_site . name domain = current_site . domain else : site_name = domain = domain_override c = { '' : user . email , '' : domain , '' : site_name , '' : urlsafe_base64_encode ( force_bytes ( user . pk ) ) , '' : user , '' : token_generator . make_token ( user ) , '' : '' if use_https else '' , } subject = loader . render_to_string ( subject_template_name , c ) subject = '' . join ( subject . splitlines ( ) ) email = loader . render_to_string ( email_template_name , c ) if html_email_template_name : html_email = loader . render_to_string ( html_email_template_name , c ) else : html_email = None send_mail ( subject , email , from_email , [ user . email ] , html_message = html_email ) class SetPasswordForm ( auth_forms . SetPasswordForm , PasswordMixin ) : new_password1 = forms . CharField ( label = _lazy ( u'' ) , min_length = PasswordMixin . min_length , error_messages = PasswordMixin . error_msg , widget = PasswordMixin . widget ( required = True ) ) def __init__ ( self , * args , ** kwargs ) : self . request = kwargs . pop ( '' , None ) super ( SetPasswordForm , self ) . __init__ ( * args , ** kwargs ) def clean_new_password1 ( self ) : return self . clean_password ( field = '' , instance = '' ) def save ( self , ** kw ) : amo . log ( amo . LOG . CHANGE_PASSWORD , user = self . user ) log . info ( u'' % self . user ) log_cef ( '' , , self . request , username = self . user . username , signature = '' , msg = '' ) super ( SetPasswordForm , self ) . save ( ** kw ) class UserDeleteForm ( forms . Form ) : email = forms . CharField ( max_length = , required = True , widget = RequiredEmailInput ) confirm = forms . BooleanField ( required = True , widget = RequiredCheckboxInput ) def __init__ ( self , * args , ** kwargs ) : self . request = kwargs . pop ( '' , None ) super ( UserDeleteForm , self ) . __init__ ( * args , ** kwargs ) self . fields [ '' ] . widget . attrs [ '' ] = ( self . request . user . email ) def clean_email ( self ) : user_email = self . request . user . email if not user_email == self . cleaned_data [ '' ] : raise forms . ValidationError ( _ ( '' ) . format ( email = user_email ) ) def clean ( self ) : amouser = self . request . user if amouser . is_developer : log . warning ( u'' % self . request . user ) raise forms . ValidationError ( \"\" ) class UsernameMixin : def clean_username ( self ) : name = self . cleaned_data [ '' ] if not name : if self . instance . has_anonymous_username ( ) : name = self . instance . username else : name = self . instance . anonymize_username ( ) if name . isdigit ( ) : raise forms . ValidationError ( _ ( '' ) ) slug_validator ( name , lower = False , message = _ ( '' '' ) ) if BlacklistedName . blocked ( name ) : raise forms . ValidationError ( _ ( '' ) ) if ( UserProfile . objects . exclude ( id = self . instance . id ) . filter ( username__iexact = name ) . exists ( ) ) : raise forms . ValidationError ( _ ( '' ) ) return name class UserRegisterForm ( happyforms . ModelForm , UsernameMixin , PasswordMixin ) : \"\"\"\"\"\" username = forms . CharField ( max_length = , required = False ) email = forms . EmailField ( widget = RequiredEmailInput ) display_name = forms . CharField ( label = _lazy ( u'' ) , max_length = , required = False ) location = forms . CharField ( label = _lazy ( u'' ) , max_length = , required = False ) occupation = forms . CharField ( label = _lazy ( u'' ) , max_length = , required = False ) password = forms . CharField ( max_length = , min_length = PasswordMixin . min_length , error_messages = PasswordMixin . error_msg , widget = PasswordMixin . widget ( render_value = False , required = True ) ) password2 = forms . CharField ( max_length = , widget = PasswordMixin . widget ( render_value = False , required = True ) ) recaptcha = ReCaptchaField ( ) homepage = HttpHttpsOnlyURLField ( label = _lazy ( u'' ) , required = False ) class Meta : model = UserProfile fields = ( '' , '' , '' , '' , '' , '' , '' , '' , '' ) def __init__ ( self , * args , ** kwargs ) : instance = kwargs . get ( '' ) if instance and instance . has_anonymous_username ( ) : kwargs . setdefault ( '' , { } ) kwargs [ '' ] [ '' ] = '' super ( UserRegisterForm , self ) . __init__ ( * args , ** kwargs ) if not settings . NOBOT_RECAPTCHA_PRIVATE_KEY : del self . fields [ '' ] errors = { '' : _ ( '' '' '' ) } self . fields [ '' ] . error_messages = errors def clean_email ( self ) : d = self . cleaned_data [ '' ] . split ( '' ) [ - ] if BlacklistedEmailDomain . blocked ( d ) : raise forms . ValidationError ( _ ( '' '' '' ) ) return self . cleaned_data [ '' ] def clean_display_name ( self ) : name = self . cleaned_data [ '' ] if BlacklistedName . blocked ( name ) : raise forms . ValidationError ( _ ( '' ) ) return name def clean ( self ) : super ( UserRegisterForm , self ) . clean ( ) data = self . cleaned_data p1 = data . get ( '' ) p2 = data . get ( '' ) if p1 and p1 != p2 : msg = _ ( '' ) self . _errors [ '' ] = ErrorList ( [ msg ] ) if p2 : ", "answer": "del data [ '' ]"}, {"prompt": " \"\"\"\"\"\" import sys try : from PySide import QtCore from PySide import QtGui except ImportError : from PyQt4 import QtCore from PyQt4 import QtGui def config_theme_path ( ) : if sys . platform != \"\" : return theme_name = str ( QtGui . QIcon . themeName ( ) ) if theme_name != \"\" : QtGui . QIcon . setThemeName ( \"\" ) search_paths = list ( QtGui . QIcon . themeSearchPaths ( ) ) custom_path = \"\" if custom_path not in search_paths : search_paths . append ( custom_path ) QtGui . QIcon . setThemeSearchPaths ( search_paths ) class Demo ( QtGui . QMainWindow ) : def __init__ ( self ) : super ( Demo , self ) . __init__ ( ) x , y , w , h = , , , self . setGeometry ( x , y , w , h ) self . setUnifiedTitleAndToolBarOnMac ( True ) config_theme_path ( ) icon = QtGui . QIcon . fromTheme ( '' ) exit_a = QtGui . QAction ( icon , '' , self ) exit_a . setShortcut ( '' ) ", "answer": "exit_a . triggered . connect ( self . close )"}, {"prompt": " import shared import socket import time PROTECT_URL = '' blah = shared . SecondBucketCounter ( ) agg = shared . AggregatorConnector ( ) agg . write ( '' % PROTECT_URL ) def processData ( data ) : ", "answer": "if data [ '' ] == \"\" :"}, {"prompt": " def get_or_create ( model , ** kwargs ) : from sqlalchemy . orm . exc import NoResultFound try : return model . query . filter_by ( ** kwargs ) . one ( ) except NoResultFound : return model ( ** kwargs ) def make_list ( str_or_list ) : ", "answer": "''''''"}, {"prompt": " import subprocess ", "answer": "from freezer . tests . freezer_tempest_plugin . tests . api import base"}, {"prompt": " import time from pubnub import PubnubTwisted as Pubnub pubkey = \"\" subkey = \"\" pubnub = Pubnub ( pubkey , subkey ) pubnub_enc = Pubnub ( pubkey , subkey , cipher_key = \"\" ) def test_1 ( ) : channel = \"\" + str ( time . time ( ) ) message = \"\" def _cb ( resp , ch = None ) : assert resp == message pubnub . unsubscribe ( channel ) def _connect ( resp ) : def _cb1 ( resp , ch = None ) : assert resp [ ] == def _err1 ( resp ) : assert False pubnub . publish ( channel , message , callback = _cb1 , error = _err1 ) def _error ( resp ) : assert False pubnub . subscribe ( channel , callback = _cb , connect = _connect , error = _error ) def test_2 ( ) : channel = \"\" + str ( time . time ( ) ) message = [ , ] def _cb ( resp , ch = None ) : assert resp == message pubnub . unsubscribe ( channel ) def _connect ( resp ) : def _cb1 ( resp , ch = None ) : assert resp [ ] == def _err1 ( resp ) : print ( resp ) assert False pubnub . publish ( channel , message , callback = _cb1 , error = _err1 ) def _error ( resp ) : assert False pubnub . subscribe ( channel , callback = _cb , connect = _connect , error = _error ) def test_3 ( ) : channel = \"\" + str ( time . time ( ) ) message = { \"\" : \"\" } def _cb ( resp , ch = None ) : assert resp == message pubnub . unsubscribe ( channel ) def _connect ( resp ) : def _cb1 ( resp , ch = None ) : assert resp [ ] == def _err1 ( resp ) : assert False pubnub . publish ( channel , message , callback = _cb1 , error = _err1 ) def _error ( resp ) : assert False pubnub . subscribe ( channel , callback = _cb , connect = _connect , error = _error ) def test_4 ( ) : channel = \"\" + str ( time . time ( ) ) message = def _cb ( resp , ch = None ) : assert resp == message pubnub . unsubscribe ( channel ) def _connect ( resp ) : def _cb1 ( resp , ch = None ) : assert resp [ ] == def _err1 ( resp ) : assert False pubnub . publish ( channel , message , callback = _cb1 , error = _err1 ) def _error ( resp ) : assert False pubnub . subscribe ( channel , callback = _cb , connect = _connect , error = _error ) def test_5 ( ) : channel = \"\" + str ( time . time ( ) ) message = \"\" def _cb ( resp , ch = None ) : assert resp == message pubnub . unsubscribe ( channel ) def _connect ( resp ) : def _cb1 ( resp , ch = None ) : assert resp [ ] == def _err1 ( resp ) : assert False pubnub . publish ( channel , message , callback = _cb1 , error = _err1 ) def _error ( resp ) : assert False pubnub . subscribe ( channel , callback = _cb , connect = _connect , error = _error ) def test_6 ( ) : channel = \"\" + str ( time . time ( ) ) message = \"\" def _cb ( resp , ch = None ) : assert resp == message pubnub_enc . unsubscribe ( channel ) def _connect ( resp ) : def _cb1 ( resp , ch = None ) : assert resp [ ] == def _err1 ( resp ) : assert False pubnub_enc . publish ( channel , message , callback = _cb1 , error = _err1 ) def _error ( resp ) : assert False pubnub_enc . subscribe ( channel , callback = _cb , connect = _connect , error = _error ) def test_7 ( ) : channel = \"\" + str ( time . time ( ) ) message = [ , ] def _cb ( resp , ch = None ) : assert resp == message pubnub_enc . unsubscribe ( channel ) def _connect ( resp ) : def _cb1 ( resp , ch = None ) : assert resp [ ] == def _err1 ( resp ) : assert False pubnub_enc . publish ( channel , message , callback = _cb1 , error = _err1 ) def _error ( resp ) : assert False pubnub_enc . subscribe ( channel , callback = _cb , connect = _connect , error = _error ) def test_8 ( ) : channel = \"\" + str ( time . time ( ) ) message = { \"\" : \"\" } def _cb ( resp , ch = None ) : assert resp == message pubnub_enc . unsubscribe ( channel ) def _connect ( resp ) : def _cb1 ( resp , ch = None ) : assert resp [ ] == def _err1 ( resp ) : assert False pubnub_enc . publish ( channel , message , callback = _cb1 , error = _err1 ) def _error ( resp ) : assert False pubnub_enc . subscribe ( channel , callback = _cb , connect = _connect , error = _error ) def test_9 ( ) : channel = \"\" + str ( time . time ( ) ) message = def _cb ( resp , ch = None ) : assert resp == message pubnub_enc . unsubscribe ( channel ) def _connect ( resp ) : def _cb1 ( resp , ch = None ) : assert resp [ ] == def _err1 ( resp ) : ", "answer": "assert False"}, {"prompt": " from msrest . serialization import Model class Sku ( Model ) : \"\"\"\"\"\" _attribute_map = { ", "answer": "'' : { '' : '' , '' : '' } ,"}, {"prompt": " from __future__ import print_function import numpy as np import matplotlib . pyplot as plt import statsmodels . api as sm plt . rcParams [ '' ] = data = sm . datasets . anes96 . load_pandas ( ) party_ID = np . arange ( ) labels = [ \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ] age = [ data . exog [ '' ] [ data . endog == id ] for id in party_ID ] fig = plt . figure ( ) ax = fig . add_subplot ( ) sm . graphics . violinplot ( age , ax = ax , labels = labels , plot_opts = { '' : , '' : '' , '' : '' , '' : } ) ax . set_xlabel ( \"\" ) ax . set_ylabel ( \"\" ) ax . set_title ( \"\" ) fig2 = plt . figure ( ) ax = fig2 . add_subplot ( ) sm . graphics . beanplot ( age , ax = ax , labels = labels , plot_opts = { '' : , '' : '' , '' : '' , '' : } ) ax . set_xlabel ( \"\" ) ax . set_ylabel ( \"\" ) ax . set_title ( \"\" ) fig3 = plt . figure ( ) ax = fig3 . add_subplot ( ) plot_opts = { '' : , '' : '' , '' : '' , '' : , '' : ( , , ) , '' : '' , '' : , '' : '' , ", "answer": "'' : '' }"}, {"prompt": " \"\"\"\"\"\" from functools import partial from pyramid . path import DottedNameResolver from . base import ICache from . redis_cache import RedisCache from . sql import SQLCache def includeme ( config ) : \"\"\"\"\"\" settings = config . get_settings ( ) resolver = DottedNameResolver ( __name__ ) dotted_cache = settings . get ( '' , '' ) if dotted_cache == '' : dotted_cache = '' elif dotted_cache == '' : dotted_cache = '' elif dotted_cache == '' : dotted_cache = '' cache_impl = resolver . resolve ( dotted_cache ) kwargs = cache_impl . configure ( settings ) cache = cache_impl ( ** kwargs ) cache . reload_if_needed ( ) ", "answer": "config . add_request_method ( partial ( cache_impl , ** kwargs ) , name = '' ,"}, {"prompt": " from __future__ import print_function import getpass import inspect import json import os import sys import textwrap from oslo_utils import encodeutils from oslo_utils import strutils import prettytable import six from six import moves from ironicclient . common . i18n import _ class MissingArgs ( Exception ) : \"\"\"\"\"\" def __init__ ( self , missing ) : self . missing = missing msg = _ ( \"\" ) % \"\" . join ( missing ) super ( MissingArgs , self ) . __init__ ( msg ) def validate_args ( fn , * args , ** kwargs ) : \"\"\"\"\"\" argspec = inspect . getargspec ( fn ) num_defaults = len ( argspec . defaults or [ ] ) required_args = argspec . args [ : len ( argspec . args ) - num_defaults ] def isbound ( method ) : return getattr ( method , '' , None ) is not None if isbound ( fn ) : required_args . pop ( ) missing = [ arg for arg in required_args if arg not in kwargs ] missing = missing [ len ( args ) : ] if missing : raise MissingArgs ( missing ) def arg ( * args , ** kwargs ) : \"\"\"\"\"\" def _decorator ( func ) : add_arg ( func , * args , ** kwargs ) return func return _decorator def env ( * args , ** kwargs ) : \"\"\"\"\"\" for arg in args : value = os . environ . get ( arg ) if value : return value return kwargs . get ( '' , '' ) def add_arg ( func , * args , ** kwargs ) : \"\"\"\"\"\" if not hasattr ( func , '' ) : func . arguments = [ ] if ( args , kwargs ) not in func . arguments : func . arguments . insert ( , ( args , kwargs ) ) def unauthenticated ( func ) : \"\"\"\"\"\" func . unauthenticated = True return func def isunauthenticated ( func ) : \"\"\"\"\"\" return getattr ( func , '' , False ) def print_list ( objs , fields , formatters = None , sortby_index = , mixed_case_fields = None , field_labels = None , json_flag = False ) : \"\"\"\"\"\" if json_flag : print ( json . dumps ( [ o . _info for o in objs ] , indent = , separators = ( '' , '' ) ) ) return formatters = formatters or { } mixed_case_fields = mixed_case_fields or [ ] field_labels = field_labels or fields if len ( field_labels ) != len ( fields ) : raise ValueError ( _ ( \"\" \"\" ) , { '' : field_labels , '' : fields } ) if sortby_index is None : ", "answer": "kwargs = { }"}, {"prompt": " import os import unittest import figgypy . config class TestConfig ( unittest . TestCase ) : def test_config_pass_on_int ( self ) : os . environ [ '' ] = '' c = figgypy . config . Config ( '' ) self . assertEqual ( c . number , ) def test_config_load_with_gpg ( self ) : os . environ [ '' ] = '' c = figgypy . config . Config ( '' ) self . assertEqual ( c . db [ '' ] , '' ) self . assertEqual ( c . db [ '' ] , '' ) def test_config_load_without_gpg ( self ) : figgypy . decrypt . GPG_IMPORTED = False c = figgypy . config . Config ( '' ) encrypted_password = ( '' '' '' '' '' '' '' '' '' '' ", "answer": "''"}, {"prompt": " from . main import main if __name__ == '' : ", "answer": "main ( ) "}, {"prompt": " def resolveDotted ( dotted_or_ep ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " import csv from datetime import datetime from StringIO import StringIO from collections import namedtuple DATE_FMT = \"\" Customer = namedtuple ( '' , ( '' , '' , '' , '' , '' , '' , '' , '' ) ) def parse ( row ) : \"\"\"\"\"\" row [ ] = int ( row [ ] ) ", "answer": "row [ ] = datetime . strptime ( row [ ] , DATE_FMT )"}, {"prompt": " import_partial_relations = False ", "answer": "relation_builder = ''"}, {"prompt": " import numpy as np from . . util import view_as_blocks , pad def block_reduce ( image , block_size , func = np . sum , cval = ) : \"\"\"\"\"\" if len ( block_size ) != image . ndim : raise ValueError ( \"\" \"\" ) pad_width = [ ] for i in range ( len ( block_size ) ) : if block_size [ i ] < : raise ValueError ( \"\" \"\" \"\" ) if image . shape [ i ] % block_size [ i ] != : after_width = block_size [ i ] - ( image . shape [ i ] % block_size [ i ] ) else : after_width = pad_width . append ( ( , after_width ) ) image = pad ( image , pad_width = pad_width , mode = '' , constant_values = cval ) ", "answer": "out = view_as_blocks ( image , block_size )"}, {"prompt": " from pyramid . view import view_config @ view_config ( route_name = '' , renderer = '' ) def home ( request ) : ", "answer": "return { }"}, {"prompt": " from collections import Counter import logging from django import template from django . conf import settings from django . utils import timezone from django . utils . safestring import mark_safe from django . core . cache import cache from django . contrib . sites . models import Site from opps . channels . models import Channel from opps . contrib . middleware . global_request import get_request from opps . containers . models import Container , ContainerBox , Mirror from magicdate import magicdate register = template . Library ( ) logger = logging . getLogger ( ) @ register . assignment_tag def get_tags_counter ( queryset = None , n = None ) : if queryset is None : queryset = Container . objects . all_published ( ) counter = Counter ( ) qs = queryset . filter ( tags__isnull = False ) . exclude ( tags = \"\" ) . order_by ( ) print qs . count ( ) for tags in qs . values_list ( \"\" , flat = True ) . distinct ( ) : l = [ i . strip ( ) for i in tags . split ( \"\" ) if i . strip ( ) ] counter . update ( l ) return counter . most_common ( n ) @ register . filter def values_list_flat ( queryset , field = '' ) : return queryset . values_list ( field , flat = True ) @ register . assignment_tag def get_recommendations ( query_slice , child_class , container ) : \"\"\"\"\"\" if not query_slice : query_slice = \"\" bits = [ ] for x in query_slice . split ( '' ) : if len ( x ) == : bits . append ( None ) else : bits . append ( int ( x ) ) return container . recommendation ( child_class , bits ) @ register . assignment_tag ( takes_context = True ) def load_boxes ( context , slugs = None , ** filters ) : if slugs : filters [ '' ] = ordered_slugs = slugs . split ( '' ) request = context [ '' ] current_site = getattr ( request , '' , Site . objects . get ( pk = settings . SITE_ID ) ) filters [ '' ] = [ current_site ] master_site = settings . OPPS_CONTAINERS_SITE_ID or if current_site . id != master_site : filters [ '' ] . append ( master_site ) filters [ '' ] = timezone . now ( ) filters [ '' ] = True boxes = ContainerBox . objects . filter ( ** filters ) . order_by ( '' ) fallback = getattr ( settings , '' , False ) exclude_ids = [ ] if slugs : def ob ( i , o = ordered_slugs ) : return ( i . site_id != current_site , i . site_id , o . index ( i . slug ) ) boxes = sorted ( boxes , key = ob , reverse = True ) for box in boxes : if box . queryset : results = box . get_queryset ( exclude_ids = exclude_ids ) else : results = box . ordered_containers ( exclude_ids = exclude_ids ) if box . queryset : for i in results : if i . pk not in exclude_ids and isinstance ( i , Container ) : exclude_ids . append ( i . pk ) elif fallback : for i in results : if i . container_id and i . container_id not in exclude_ids : exclude_ids . append ( i . container_id ) else : for i in results : if i . pk not in exclude_ids : exclude_ids . append ( i . pk ) results = { } for box in boxes : if box . slug not in results : results [ box . slug ] = box get_request ( ) . container_boxes = results return results @ register . simple_tag ( takes_context = True ) def get_containerbox ( context , slug , template_name = None , channel = None , ** extra_context ) : request = context [ '' ] current_site = getattr ( request , '' , Site . objects . get ( pk = settings . SITE_ID ) ) is_mobile = getattr ( request , '' , False ) cachekey = \"\" . format ( slug , template_name , is_mobile , current_site . id ) render = cache . get ( cachekey ) if render : return render box = getattr ( get_request ( ) , '' , { } ) . get ( slug , None ) if not box : filters = { } filters [ '' ] = current_site . id filters [ '' ] = slug filters [ '' ] = timezone . now ( ) filters [ '' ] = True if channel is not None : filters [ '' ] = channel master_site = settings . OPPS_CONTAINERS_SITE_ID or try : box = ContainerBox . objects . get ( ** filters ) except ContainerBox . DoesNotExist : box = None if current_site . id != master_site and not box or not getattr ( box , '' , False ) : filters [ '' ] = master_site try : box = ContainerBox . objects . get ( ** filters ) except ContainerBox . DoesNotExist : box = None if not box : box = ContainerBox . objects . none ( ) t = template . loader . get_template ( '' ) if template_name : t = template . loader . get_template ( template_name ) context = { '' : box , '' : slug , '' : context , '' : request } context . update ( extra_context ) render = t . render ( template . Context ( context ) ) cache . set ( cachekey , render , settings . OPPS_CACHE_EXPIRE ) return render @ register . simple_tag def get_all_containerbox ( channel_long_slug = None , template_name = None ) : \"\"\"\"\"\" cachekey = \"\" . format ( channel_long_slug , template_name ) render = cache . get ( cachekey ) if render : return render filters = { } filters [ '' ] = timezone . now ( ) filters [ '' ] = True filters [ '' ] = settings . SITE_ID if settings . OPPS_CONTAINERS_SITE_ID : filters [ '' ] = settings . OPPS_CONTAINERS_SITE_ID boxes = ContainerBox . objects . filter ( ** filters ) if channel_long_slug : boxes = boxes . filter ( channel_long_slug = channel_long_slug ) t = template . loader . get_template ( '' ) if template_name : t = template . loader . get_template ( template_name ) render = t . render ( template . Context ( { '' : boxes } ) ) cache . set ( cachekey , render , settings . OPPS_CACHE_EXPIRE ) return render @ register . simple_tag def get_post_content ( post , template_name = '' , content_field = '' , related_name = '' , get_related = True , safe = True , divider = \"\" , placeholder = settings . OPPS_RELATED_POSTS_PLACEHOLDER ) : \"\"\"\"\"\" if not hasattr ( post , content_field ) : return None content = getattr ( post , content_field , '' ) content = content . replace ( '' , '' ) if not get_related : return content related_posts = getattr ( post , related_name , None ) if not related_posts . exists ( ) : return mark_safe ( content ) t = template . loader . get_template ( template_name ) ", "answer": "related_rendered = t . render ( template . Context ( {"}, {"prompt": " import os from flask import Flask from flask_mwoauth import MWOAuth ", "answer": "from builtins import input"}, {"prompt": " def dunderkey ( * args ) : \"\"\"\"\"\" return '' . join ( args ) def dunder_partition ( key ) : \"\"\"\"\"\" parts = key . rsplit ( '' , ) return tuple ( parts ) if len ( parts ) > else ( parts [ ] , None ) def dunder_init ( key ) : \"\"\"\"\"\" return dunder_partition ( key ) [ ] def dunder_last ( key ) : \"\"\"\"\"\" return dunder_partition ( key ) [ ] def dunder_get ( _dict , key ) : \"\"\"\"\"\" parts = key . split ( '' , ) try : result = _dict [ parts [ ] ] except KeyError : return None else : return result if len ( parts ) == else dunder_get ( result , parts [ ] ) def undunder_keys ( _dict ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " import sys , os sys . path . append ( os . path . abspath ( os . path . join ( os . path . dirname ( __file__ ) , os . pardir ) ) ) sys . path . append ( os . path . abspath ( os . path . join ( os . path . dirname ( __file__ ) , os . pardir , os . pardir ) ) ) import manage os . environ [ '' ] = '' from systems import models def main ( ) : print '' for sys in models . System . objects . all ( ) : if sys . keyvalue_set . filter ( key = '' ) : old_hostname = sys . keyvalue_set . filter ( key = '' ) [ ] . value ", "answer": "else :"}, {"prompt": " \"\"\"\"\"\" __all__ = [ '' ] ", "answer": "from email import errors"}, {"prompt": " __author__ = '' import json import urllib import mongoctl_globals from utils import * from minify_json import minify_json from errors import MongoctlException from bson import json_util MONGOCTL_CONF_FILE_NAME = \"\" __config_root__ = mongoctl_globals . DEFAULT_CONF_ROOT def set_config_root ( root_path ) : if not is_url ( root_path ) and not dir_exists ( root_path ) : raise MongoctlException ( \"\" \"\" % root_path ) global __config_root__ __config_root__ = root_path def get_mongoctl_config_val ( key , default = None ) : return get_mongoctl_config ( ) . get ( key , default ) def set_mongoctl_config_val ( key , value ) : get_mongoctl_config ( ) [ key ] = value def get_generate_key_file_conf ( default = None ) : return get_mongoctl_config_val ( '' , default = default ) def get_database_repository_conf ( ) : return get_mongoctl_config_val ( '' ) def get_file_repository_conf ( ) : return get_mongoctl_config_val ( '' ) def get_mongodb_installs_dir ( ) : installs_dir = get_mongoctl_config_val ( '' ) if installs_dir : return resolve_path ( installs_dir ) def set_mongodb_installs_dir ( installs_dir ) : set_mongoctl_config_val ( '' , installs_dir ) def get_default_users ( ) : return get_mongoctl_config_val ( '' , { } ) def get_cluster_member_alt_address_mapping ( ) : return get_mongoctl_config_val ( '' , { } ) def to_full_config_path ( path_or_url ) : global __config_root__ if os . path . isabs ( path_or_url ) : return resolve_path ( path_or_url ) elif is_url ( path_or_url ) : return path_or_url else : result = os . path . join ( __config_root__ , path_or_url ) if not is_url ( __config_root__ ) : result = resolve_path ( result ) return result __mongo_config__ = None def get_mongoctl_config ( ) : global __mongo_config__ if __mongo_config__ is None : __mongo_config__ = read_config_json ( \"\" , ", "answer": "MONGOCTL_CONF_FILE_NAME )"}, {"prompt": " \"\"\"\"\"\" import click from SoftLayer . CLI import exceptions def multi_option ( * param_decls , ** attrs ) : \"\"\"\"\"\" ", "answer": "attrhelp = attrs . get ( '' , None )"}, {"prompt": " from webob import Request , Response class SessionManager ( object ) : '''''' def __init__ ( self , application = None , days = , session_class = None ) : self . session_class = session_class self . days = days if application : self . application = application else : self . applicaion = Response ( ) def __call__ ( self , environ , start_response ) : req = Request ( environ ) environ [ '' ] = self . session_class . _before ( req ) environ . setdefault ( '' , { } ) [ '' ] = environ [ '' ] ", "answer": "resp = req . get_response ( self . application )"}, {"prompt": " from calvin . actor . actor import Actor , ActionResult , manage , condition , guard from calvin . runtime . north . calvin_token import EOSToken , ExceptionToken from copy import deepcopy class SetValue ( Actor ) : \"\"\"\"\"\" def exception_handler ( self , action , args , context ) : return ActionResult ( production = ( ExceptionToken ( ) , ) ) @ manage ( ) def init ( self ) : pass def _type_mismatch ( self , container , key ) : t_cont = type ( container ) t_key = type ( key ) ", "answer": "return ( t_cont is list and t_key is not int ) or ( t_cont is dict and not isinstance ( key , basestring ) )"}, {"prompt": " \"\"\"\"\"\" import os import stat __all__ = [ \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ] curdir = '' pardir = '' extsep = '' sep = '' altsep = '' pathsep = '' defpath = '' devnull = '' def normcase ( s ) : \"\"\"\"\"\" return s . replace ( '' , '' ) . lower ( ) def isabs ( s ) : \"\"\"\"\"\" s = splitdrive ( s ) [ ] return s != '' and s [ : ] in '' def join ( a , * p ) : \"\"\"\"\"\" path = a for b in p : if isabs ( b ) : path = b elif path == '' or path [ - : ] in '' : path = path + b else : path = path + '' + b return path def splitdrive ( p ) : \"\"\"\"\"\" if p [ : ] == '' : return p [ : ] , p [ : ] return '' , p def splitunc ( p ) : \"\"\"\"\"\" if p [ : ] == '' : return '' , p firstTwo = p [ : ] if firstTwo == '' * or firstTwo == '' * : normp = normcase ( p ) index = normp . find ( '' , ) if index == - : return ( \"\" , p ) index = normp . find ( '' , index + ) if index == - : index = len ( p ) return p [ : index ] , p [ index : ] return '' , p def split ( p ) : \"\"\"\"\"\" d , p = splitdrive ( p ) i = len ( p ) while i and p [ i - ] not in '' : i = i - head , tail = p [ : i ] , p [ i : ] head2 = head while head2 and head2 [ - ] in '' : head2 = head2 [ : - ] head = head2 or head return d + head , tail def splitext ( p ) : \"\"\"\"\"\" root , ext = '' , '' for c in p : if c in [ '' , '' ] : root , ext = root + ext + c , '' elif c == '' : if ext : root , ext = root + ext , c else : ext = c elif ext : ext = ext + c else : root = root + c return root , ext def basename ( p ) : \"\"\"\"\"\" return split ( p ) [ ] def dirname ( p ) : \"\"\"\"\"\" return split ( p ) [ ] def commonprefix ( m ) : \"\" if not m : return '' s1 = min ( m ) s2 = max ( m ) n = min ( len ( s1 ) , len ( s2 ) ) for i in xrange ( n ) : if s1 [ i ] != s2 [ i ] : return s1 [ : i ] return s1 [ : n ] def getsize ( filename ) : \"\"\"\"\"\" return os . stat ( filename ) . st_size def getmtime ( filename ) : \"\"\"\"\"\" return os . stat ( filename ) . st_mtime def getatime ( filename ) : \"\"\"\"\"\" return os . stat ( filename ) . st_atime def getctime ( filename ) : \"\"\"\"\"\" return os . stat ( filename ) . st_ctime def islink ( path ) : \"\"\"\"\"\" return False def exists ( path ) : \"\"\"\"\"\" try : st = os . stat ( path ) except os . error : return False return True lexists = exists def isdir ( path ) : \"\"\"\"\"\" try : st = os . stat ( path ) except os . error : return False return stat . S_ISDIR ( st . st_mode ) def isfile ( path ) : \"\"\"\"\"\" try : st = os . stat ( path ) except os . error : return False return stat . S_ISREG ( st . st_mode ) def ismount ( path ) : \"\"\"\"\"\" unc , rest = splitunc ( path ) if unc : return rest in ( \"\" , \"\" , \"\" ) p = splitdrive ( path ) [ ] return len ( p ) == and p [ ] in '' def walk ( top , func , arg ) : \"\"\"\"\"\" try : names = os . listdir ( top ) except os . error : return func ( arg , top , names ) exceptions = ( '' , '' ) for name in names : if name not in exceptions : name = join ( top , name ) if isdir ( name ) : walk ( name , func , arg ) def expanduser ( path ) : \"\"\"\"\"\" if path [ : ] != '' : return path i , n = , len ( path ) while i < n and path [ i ] not in '' : i = i + if i == : if '' in os . environ : userhome = os . environ [ '' ] elif not '' in os . environ : return path else : try : drive = os . environ [ '' ] except KeyError : drive = '' userhome = join ( drive , os . environ [ '' ] ) else : return path return userhome + path [ i : ] def expandvars ( path ) : \"\"\"\"\"\" if '' not in path : return path import string varchars = string . letters + string . digits + '' res = '' index = pathlen = len ( path ) ", "answer": "while index < pathlen :"}, {"prompt": " from . import element class Range ( element . Element ) : \"\"\"\"\"\" resource_name = \"\" def __init__ ( self , jsondict = None ) : \"\"\"\"\"\" ", "answer": "self . high = None"}, {"prompt": " from unittest import TestCase , mock from thorium . response import ( Response , DetailResponse , CollectionResponse , ErrorResponse ) from thorium . errors import MethodNotAllowedError , BadRequestError from thorium import Resource , fields class SimpleResource ( Resource ) : id = fields . IntField ( ) ", "answer": "name = fields . CharField ( )"}, {"prompt": " \"\"\"\"\"\" import datetime import itertools import socket import time from SoftLayer import exceptions from SoftLayer . managers import ordering from SoftLayer import utils class VSManager ( utils . IdentifierMixin , object ) : \"\"\"\"\"\" def __init__ ( self , client , ordering_manager = None ) : self . client = client self . account = client [ '' ] self . guest = client [ '' ] self . resolvers = [ self . _get_ids_from_ip , self . _get_ids_from_hostname ] if ordering_manager is None : self . ordering_manager = ordering . OrderingManager ( client ) else : self . ordering_manager = ordering_manager def list_instances ( self , hourly = True , monthly = True , tags = None , cpus = None , memory = None , hostname = None , domain = None , local_disk = None , datacenter = None , nic_speed = None , public_ip = None , private_ip = None , ** kwargs ) : \"\"\"\"\"\" if '' not in kwargs : items = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , ] kwargs [ '' ] = \"\" % '' . join ( items ) call = '' if not all ( [ hourly , monthly ] ) : if hourly : call = '' elif monthly : call = '' _filter = utils . NestedDict ( kwargs . get ( '' ) or { } ) if tags : _filter [ '' ] [ '' ] [ '' ] [ '' ] = { '' : '' , '' : [ { '' : '' , '' : tags } ] , } if cpus : _filter [ '' ] [ '' ] = utils . query_filter ( cpus ) if memory : _filter [ '' ] [ '' ] = utils . query_filter ( memory ) if hostname : _filter [ '' ] [ '' ] = utils . query_filter ( hostname ) if domain : _filter [ '' ] [ '' ] = utils . query_filter ( domain ) if local_disk is not None : _filter [ '' ] [ '' ] = ( utils . query_filter ( bool ( local_disk ) ) ) if datacenter : _filter [ '' ] [ '' ] [ '' ] = ( utils . query_filter ( datacenter ) ) if nic_speed : _filter [ '' ] [ '' ] [ '' ] = ( utils . query_filter ( nic_speed ) ) if public_ip : _filter [ '' ] [ '' ] = ( utils . query_filter ( public_ip ) ) if private_ip : _filter [ '' ] [ '' ] = ( utils . query_filter ( private_ip ) ) kwargs [ '' ] = _filter . to_dict ( ) func = getattr ( self . account , call ) return func ( ** kwargs ) def get_instance ( self , instance_id , ** kwargs ) : \"\"\"\"\"\" if '' not in kwargs : items = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '''''' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '''''' , '''''' , '' , '' , '' , '' , '' , '' ] kwargs [ '' ] = \"\" % '' . join ( items ) return self . guest . getObject ( id = instance_id , ** kwargs ) def get_create_options ( self ) : \"\"\"\"\"\" return self . guest . getCreateObjectOptions ( ) def cancel_instance ( self , instance_id ) : \"\"\"\"\"\" return self . guest . deleteObject ( id = instance_id ) def reload_instance ( self , instance_id , post_uri = None , ssh_keys = None , image_id = None ) : \"\"\"\"\"\" config = { } if post_uri : config [ '' ] = post_uri if ssh_keys : config [ '' ] = [ key_id for key_id in ssh_keys ] if image_id : config [ '' ] = image_id return self . client . call ( '' , '' , '' , config , id = instance_id ) def _generate_create_dict ( self , cpus = None , memory = None , hourly = True , hostname = None , domain = None , local_disk = True , datacenter = None , os_code = None , image_id = None , dedicated = False , public_vlan = None , private_vlan = None , userdata = None , nic_speed = None , disks = None , post_uri = None , private = False , ssh_keys = None ) : \"\"\"\"\"\" required = [ cpus , memory , hostname , domain ] mutually_exclusive = [ { '' : os_code , \"\" : image_id } , ] if not all ( required ) : raise ValueError ( \"\" ) for mu_ex in mutually_exclusive : if all ( mu_ex . values ( ) ) : raise ValueError ( '' % ( '' . join ( mu_ex . keys ( ) ) ) ) data = { \"\" : int ( cpus ) , \"\" : int ( memory ) , \"\" : hostname , \"\" : domain , \"\" : local_disk , } data [ \"\" ] = hourly if dedicated : data [ \"\" ] = dedicated if private : data [ '' ] = private if image_id : data [ \"\" ] = { \"\" : image_id } elif os_code : data [ \"\" ] = os_code if datacenter : data [ \"\" ] = { \"\" : datacenter } if public_vlan : data . update ( { '' : { \"\" : { \"\" : int ( public_vlan ) } } } ) if private_vlan : data . update ( { \"\" : { \"\" : { \"\" : int ( private_vlan ) } } } ) if userdata : data [ '' ] = [ { '' : userdata } ] if nic_speed : data [ '' ] = [ { '' : nic_speed } ] if disks : data [ '' ] = [ { \"\" : \"\" , \"\" : { \"\" : disks [ ] } } ] for dev_id , disk in enumerate ( disks [ : ] , start = ) : data [ '' ] . append ( { \"\" : str ( dev_id ) , \"\" : { \"\" : disk } } ) if post_uri : data [ '' ] = post_uri if ssh_keys : data [ '' ] = [ { '' : key_id } for key_id in ssh_keys ] return data def wait_for_transaction ( self , instance_id , limit , delay = ) : \"\"\"\"\"\" return self . wait_for_ready ( instance_id , limit , delay = delay , pending = True ) def wait_for_ready ( self , instance_id , limit , delay = , pending = False ) : \"\"\"\"\"\" until = time . time ( ) + limit for new_instance in itertools . repeat ( instance_id ) : mask = \"\"\"\"\"\" instance = self . get_instance ( new_instance , mask = mask ) last_reload = utils . lookup ( instance , '' , '' ) active_transaction = utils . lookup ( instance , '' , '' ) reloading = all ( ( active_transaction , last_reload , last_reload == active_transaction , ) ) outstanding = False if pending : outstanding = active_transaction if all ( [ instance . get ( '' ) , not reloading , not outstanding ] ) : return True now = time . time ( ) if now >= until : return False time . sleep ( min ( delay , until - now ) ) def verify_create_instance ( self , ** kwargs ) : \"\"\"\"\"\" kwargs . pop ( '' , None ) create_options = self . _generate_create_dict ( ** kwargs ) return self . guest . generateOrderTemplate ( create_options ) def create_instance ( self , ** kwargs ) : \"\"\"\"\"\" tags = kwargs . pop ( '' , None ) inst = self . guest . createObject ( self . _generate_create_dict ( ** kwargs ) ) if tags is not None : self . guest . setTags ( tags , id = inst [ '' ] ) return inst def create_instances ( self , config_list ) : \"\"\"\"\"\" tags = [ conf . pop ( '' , None ) for conf in config_list ] resp = self . guest . createObjects ( [ self . _generate_create_dict ( ** kwargs ) for kwargs in config_list ] ) for instance , tag in zip ( resp , tags ) : if tag is not None : self . guest . setTags ( tag , id = instance [ '' ] ) return resp ", "answer": "def change_port_speed ( self , instance_id , public , speed ) :"}, {"prompt": " \"\"\"\"\"\" import socket , time , sys TIMES = S = \"\" * ", "answer": "sent = len ( S ) * TIMES"}, {"prompt": " \"\"\"\"\"\" __docformat__ = '' labels = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' } \"\"\"\"\"\" bibliographic_fields = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' } \"\"\"\"\"\" ", "answer": "author_separators = [ '' , '' ]"}, {"prompt": " from SimpleCV import * from CardUtil import * from PlayingCardFactory import * import numpy as np def GetParallelSets ( line_fs , parallel_thresh = ) : result = [ ] sz = len ( line_fs ) for i in range ( , sz ) : for j in range ( , sz ) : if ( j <= i ) : result . append ( np . Inf ) else : result . append ( np . abs ( line_fs [ i ] . cross ( line_fs [ j ] ) ) ) result = np . array ( result ) result = result . reshape ( sz , sz ) l1 , l2 = np . where ( result < parallel_thresh ) idxs = zip ( l1 , l2 ) retVal = [ ] for idx in idxs : retVal . append ( ( line_fs [ idx [ ] ] , line_fs [ idx [ ] ] ) ) return retVal pcf = PlayingCardFactory ( ) data , labels = GetFullDataSet ( ) print len ( data ) datapoints = zip ( data , labels ) datapoints = datapoints [ : ] result = [ ] passing = for d in datapoints : img = d [ ] label = d [ ] img = img . edges ( ) l = img . findLines ( threshold = ) if ( l is not None ) : v = h = vl = l . filter ( np . abs ( l . angle ( ) ) > v ) vl = vl . filter ( vl . length ( ) > img . height / ) ", "answer": "hl = l . filter ( np . abs ( l . angle ( ) ) < h )"}, {"prompt": " import sys import os sys . path . insert ( , os . path . abspath ( '' ) ) extensions = [ '' , ] templates_path = [ '' ] source_suffix = '' ", "answer": "master_doc = ''"}, {"prompt": " \"\"\"\"\"\" import socket from oslo_log import log as logging import six . moves import nova . conf from nova import exception from nova . i18n import _LW from nova import utils LOG = logging . getLogger ( __name__ ) ALLOCATED_PORTS = set ( ) SERIAL_LOCK = '' CONF = nova . conf . CONF @ utils . synchronized ( SERIAL_LOCK ) def acquire_port ( host ) : \"\"\"\"\"\" start , stop = _get_port_range ( ) for port in six . moves . range ( start , stop ) : if ( host , port ) in ALLOCATED_PORTS : continue try : _verify_port ( host , port ) ALLOCATED_PORTS . add ( ( host , port ) ) return port except exception . SocketPortInUseException as e : LOG . warning ( e . format_message ( ) ) raise exception . SocketPortRangeExhaustedException ( host = host ) @ utils . synchronized ( SERIAL_LOCK ) def release_port ( host , port ) : \"\"\"\"\"\" ALLOCATED_PORTS . discard ( ( host , port ) ) def _get_port_range ( ) : config_range = CONF . serial_console . port_range try : start , stop = map ( int , config_range . split ( '' ) ) if start >= stop : raise ValueError except ValueError : default_port_range = nova . conf . serial_console . DEFAULT_PORT_RANGE LOG . warning ( _LW ( \"\" ", "answer": "\"\""}, {"prompt": " from django . utils . translation import ugettext_lazy as _ import horizon from openstack_dashboard . dashboards . project import dashboard class Stacks ( horizon . Panel ) : name = _ ( \"\" ) slug = \"\" ", "answer": "permissions = ( '' , )"}, {"prompt": " \"\"\"\"\"\" from setuptools import setup from os . path import join , dirname LONG_DESCRIPION = \"\"\"\"\"\" def long_description ( ) : \"\"\"\"\"\" ", "answer": "try :"}, {"prompt": " from . data_calc import DataCalc class GearCalc ( DataCalc ) : def __init__ ( self ) : self . initialize_data ( ) def initialize_data ( self ) : self . gears = [ '' , '' , '' , '' , '' , '' , '' ] ", "answer": "self . data = self . gears [ ]"}, {"prompt": " from PyQt4 import QtGui from PyQt4 import Qsci from zipfile import ZipFile from gzip import GzipFile from bz2 import BZ2File import codecs ", "answer": "class SQLEditor ( Qsci . QsciScintilla ) :"}, {"prompt": " import luigi ", "answer": "luigi . namespace ( \"\" )"}, {"prompt": " from agate . aggregations . base import Aggregation from agate . aggregations . has_nulls import HasNulls from agate . aggregations . mean import Mean from agate . data_types import Number from agate . exceptions import DataTypeError from agate . warns import warn_null_calculation class Variance ( Aggregation ) : \"\"\"\"\"\" def __init__ ( self , column_name ) : self . _column_name = column_name self . _mean = Mean ( column_name ) def get_aggregate_data_type ( self , table ) : return Number ( ) def validate ( self , table ) : column = table . columns [ self . _column_name ] if not isinstance ( column . data_type , Number ) : raise DataTypeError ( '' ) has_nulls = HasNulls ( self . _column_name ) . run ( table ) if has_nulls : warn_null_calculation ( self , column ) def run ( self , table ) : column = table . columns [ self . _column_name ] data = column . values_without_nulls ( ) mean = self . _mean . run ( table ) return sum ( ( n - mean ) ** for n in data ) / ( len ( data ) - ) class PopulationVariance ( Variance ) : \"\"\"\"\"\" def __init__ ( self , column_name ) : self . _column_name = column_name self . _mean = Mean ( column_name ) def get_aggregate_data_type ( self , table ) : return Number ( ) def validate ( self , table ) : column = table . columns [ self . _column_name ] if not isinstance ( column . data_type , Number ) : raise DataTypeError ( '' ) has_nulls = HasNulls ( self . _column_name ) . run ( table ) if has_nulls : warn_null_calculation ( self , column ) def run ( self , table ) : column = table . columns [ self . _column_name ] data = column . values_without_nulls ( ) ", "answer": "mean = self . _mean . run ( table )"}, {"prompt": " import sys , os docs_dir = os . path . dirname ( __file__ ) project_dir = os . path . abspath ( os . path . join ( docs_dir , '' ) ) print ( project_dir ) sys . path . insert ( , project_dir ) import textblob_de sys . path . pop ( ) sys . path . append ( os . path . abspath ( \"\" ) ) extensions = [ '' , '' , '' , '' , '' , '' , ", "answer": "]"}, {"prompt": " from . compat import basestring , numeric_types def _split_params_and_files ( params_ ) : params = { } files = { } for k , v in params_ . items ( ) : if hasattr ( v , '' ) and callable ( v . read ) : files [ k ] = v elif isinstance ( v , basestring ) or isinstance ( v , numeric_types ) : ", "answer": "params [ k ] = v"}, {"prompt": " from barbicanclient import client as barbicanclient from keystoneclient . auth import identity from keystoneclient import session from oslo_config import cfg from solum . openstack . common import importutils class BarbicanClient ( object ) : \"\"\"\"\"\" def __init__ ( self , verify = True ) : self . verify = verify self . _admin_client = None @ property def admin_client ( self ) : if not self . _admin_client : self . _admin_client = self . _barbican_admin_init ( ) return self . _admin_client def _barbican_admin_init ( self ) : importutils . import_module ( '' ) auth = identity . v2 . Password ( auth_url = cfg . CONF . keystone_authtoken . auth_uri , ", "answer": "username = cfg . CONF . keystone_authtoken . admin_user ,"}, {"prompt": " from __future__ import unicode_literals import pytest from rtv . page import Page , PageController , logged_in try : from unittest import mock except ImportError : import mock def test_page_logged_in ( terminal ) : page = mock . MagicMock ( ) page . term = terminal @ logged_in def func ( _ ) : raise RuntimeError ( ) page . reddit . is_oauth_session . return_value = True with pytest . raises ( RuntimeError ) : func ( page ) message = '' . encode ( '' ) with pytest . raises ( AssertionError ) : terminal . stdscr . subwin . addstr . assert_called_with ( , , message ) page . reddit . is_oauth_session . return_value = False func ( page ) message = '' . encode ( '' ) terminal . stdscr . subwin . addstr . assert_called_with ( , , message ) def test_page_unauthenticated ( reddit , terminal , config , oauth ) : page = Page ( reddit , terminal , config , oauth ) page . controller = PageController ( page , keymap = config . keymap ) with mock . patch . object ( page , '' ) , mock . patch . object ( page , '' ) , mock . patch . object ( page , '' ) , mock . patch . object ( page , '' ) : def func ( _ ) : page . active = False with mock . patch . object ( page , '' ) : page . controller . trigger = mock . MagicMock ( side_effect = func ) page . loop ( ) assert page . draw . called terminal . stdscr . getch . return_value = ord ( '' ) with mock . patch ( '' ) as sys_exit : page . controller . trigger ( '' ) assert sys_exit . called terminal . stdscr . getch . return_value = terminal . ESCAPE with mock . patch ( '' ) as sys_exit : page . controller . trigger ( '' ) assert not sys_exit . called terminal . stdscr . getch . return_value = terminal . ESCAPE with mock . patch ( '' ) as sys_exit : page . controller . trigger ( '' ) assert sys_exit . called page . controller . trigger ( '' ) message = '' . encode ( '' ) terminal . stdscr . subwin . addstr . assert_any_call ( , , message ) page . controller . trigger ( '' ) page . refresh_content . assert_called_with ( order = '' ) page . controller . trigger ( '' ) page . refresh_content . assert_called_with ( order = '' ) page . controller . trigger ( '' ) page . refresh_content . assert_called_with ( order = '' ) page . controller . trigger ( '' ) page . refresh_content . assert_called_with ( order = '' ) page . controller . trigger ( '' ) page . refresh_content . assert_called_with ( order = '' ) logged_in_methods = [ '' , ", "answer": "'' ,"}, {"prompt": " \"\"\"\"\"\" from __future__ import print_function import sys import collections from . utils import isclassdesc , NotSpecified from . types . matching import TypeMatcher from . plugins import Plugin if sys . version_info [ ] >= : basestring = str def modify_desc ( skips , desc ) : \"\"\"\"\"\" for at_name , at_t in desc [ '' ] . copy ( ) . items ( ) : for tm in skips : if tm . flatmatches ( at_t ) : del desc [ '' ] [ at_name ] break for m_key , m_ret in desc [ '' ] . copy ( ) . items ( ) : _deleted = False for tm in skips : if m_ret and tm . flatmatches ( m_ret [ '' ] ) : del desc [ '' ] [ m_key ] _deleted = True break if _deleted : continue m_args = m_key [ : ] for arg in m_args : t = arg [ ] for tm in skips : if tm . flatmatches ( t ) : del desc [ '' ] [ m_key ] _deleted = True break if _deleted : break class XDressPlugin ( Plugin ) : \"\"\"\"\"\" requires = ( '' , ) defaultrc = { '' : NotSpecified , '' : NotSpecified , '' : NotSpecified , '' : NotSpecified , '' : NotSpecified } rcdocs = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , } def setup ( self , rc ) : if rc . skiptypes is NotSpecified : return if isinstance ( rc . skiptypes , collections . Mapping ) : _skippers = { } for kls in rc . skiptypes . keys ( ) : _skippers [ kls ] = [ TypeMatcher ( t ) for t in rc . skiptypes [ kls ] ] rc . skiptypes = _skippers elif isinstance ( rc . skiptypes , collections . Sequence ) : rc . skiptypes = [ TypeMatcher ( t ) for t in rc . skiptypes ] if rc . verbose : print ( \"\" . format ( rc . skiptypes ) ) def skip_types ( self , rc ) : \"\"\"\"\"\" if rc . skiptypes is NotSpecified : return print ( \"\" ) if isinstance ( rc . skiptypes , collections . Mapping ) : skip_classes = rc . skiptypes . keys ( ) for mod_key , mod in rc . env . items ( ) : for kls_key , desc in mod . items ( ) : if isclassdesc ( desc ) : if desc [ '' ] [ '' ] in skip_classes : skips = rc . skips [ desc [ '' ] [ '' ] ] modify_desc ( skips , desc ) elif isinstance ( rc . skiptypes , collections . Sequence ) : for mod_key , mod in rc . env . items ( ) : for kls_key , desc in mod . items ( ) : if isclassdesc ( desc ) : skips = rc . skiptypes modify_desc ( skips , desc ) def skip_methods ( self , rc ) : \"\"\"\"\"\" if rc . skipmethods is NotSpecified : return print ( \"\" ) skip_classes = rc . skipmethods . keys ( ) for m_key , mod in rc . env . items ( ) : for k_key , kls_desc in mod . items ( ) : if isclassdesc ( kls_desc ) : if kls_desc [ '' ] [ '' ] in skip_classes : skippers = rc . skipmethods [ k_key ] m_nms = rc . env [ m_key ] [ k_key ] [ '' ] . keys ( ) for m in skippers : try : f = lambda x : x [ ] . startswith ( m ) if isinstance ( x [ ] , basestring ) else x [ ] [ ] . startswith ( m ) del_key = filter ( f , m_nms ) [ ] except IndexError : msg = '' msg += '' print ( msg . format ( m , k_key ) ) continue del rc . env [ m_key ] [ k_key ] [ '' ] [ del_key ] def skip_attrs ( self , rc ) : \"\"\"\"\"\" if rc . skipattrs is NotSpecified : return print ( \"\" ) skip_classes = rc . skipattrs . keys ( ) for m_key , mod in rc . env . items ( ) : for k_key , kls_desc in mod . items ( ) : if isclassdesc ( kls_desc ) : if kls_desc [ '' ] [ '' ] in skip_classes : skippers = rc . skipattrs [ k_key ] a_nms = rc . env [ m_key ] [ k_key ] [ '' ] for m in skippers : if m in a_nms : del rc . env [ m_key ] [ k_key ] [ '' ] [ m ] ", "answer": "else :"}, {"prompt": " \"\"\"\"\"\" from __future__ import division , absolute_import from functools import wraps class DummyLock ( object ) : \"\"\"\"\"\" def __reduce__ ( self ) : return ( unpickle_lock , ( ) ) def unpickle_lock ( ) : if threadingmodule is not None : return XLock ( ) else : return DummyLock ( ) unpickle_lock . __safe_for_unpickling__ = True def _synchPre ( self ) : if '' not in self . __dict__ : _synchLockCreator . acquire ( ) if '' not in self . __dict__ : self . __dict__ [ '' ] = XLock ( ) _synchLockCreator . release ( ) self . _threadable_lock . acquire ( ) def _synchPost ( self ) : self . _threadable_lock . release ( ) def _sync ( klass , function ) : @ wraps ( function ) def sync ( self , * args , ** kwargs ) : _synchPre ( self ) try : return function ( self , * args , ** kwargs ) finally : _synchPost ( self ) return sync def synchronize ( * klasses ) : \"\"\"\"\"\" if threadingmodule is not None : for klass in klasses : for methodName in klass . synchronized : sync = _sync ( klass , klass . __dict__ [ methodName ] ) setattr ( klass , methodName , sync ) def init ( with_threads = ) : \"\"\"\"\"\" global threaded , _synchLockCreator , XLock if with_threads : if not threaded : if threadingmodule is not None : threaded = True class XLock ( threadingmodule . _RLock , object ) : def __reduce__ ( self ) : return ( unpickle_lock , ( ) ) _synchLockCreator = XLock ( ) else : raise RuntimeError ( \"\" ) else : if threaded : raise RuntimeError ( \"\" ) else : pass _dummyID = object ( ) def getThreadID ( ) : if threadingmodule is None : return _dummyID return threadingmodule . currentThread ( ) . ident def isInIOThread ( ) : \"\"\"\"\"\" return ioThread == getThreadID ( ) def registerAsIOThread ( ) : \"\"\"\"\"\" global ioThread ioThread = getThreadID ( ) ioThread = None threaded = False ", "answer": "try :"}, {"prompt": " \"\"\"\"\"\" from django . http import HttpResponse , Http404 from django . shortcuts import render_to_response from django . template import RequestContext from django . utils . importlib import import_module from cloud_browser . app_settings import settings from cloud_browser . cloud import get_connection , get_connection_cls , errors from cloud_browser . common import get_int , path_parts , path_join , path_yield , relpath MAX_LIMIT = get_connection_cls ( ) . cont_cls . max_list def settings_view_decorator ( function ) : \"\"\"\"\"\" dec = settings . CLOUD_BROWSER_VIEW_DECORATOR if isinstance ( dec , basestring ) : mod_str , _ , dec_str = dec . rpartition ( '' ) if not ( mod_str and dec_str ) : raise ImportError ( \"\" % mod_str ) mod = import_module ( mod_str ) if not hasattr ( mod , dec_str ) : raise ImportError ( \"\" % dec ) dec = getattr ( mod , dec_str ) if dec and callable ( dec ) : return dec ( function ) return function def _breadcrumbs ( path ) : \"\"\"\"\"\" full = None crumbs = [ ] for part in path_yield ( path ) : full = path_join ( full , part ) if full else part crumbs . append ( ( full , part ) ) return crumbs @ settings_view_decorator def browser ( request , path = '' , template = \"\" ) : \"\"\"\"\"\" from itertools import ifilter , islice container_path , object_path = path_parts ( path ) incoming = request . POST or request . GET or { } marker = incoming . get ( '' , None ) marker_part = incoming . get ( '' , None ) if marker_part : marker = path_join ( object_path , marker_part ) limit_default = settings . CLOUD_BROWSER_DEFAULT_LIST_LIMIT limit_test = lambda x : x > and ( MAX_LIMIT is None or x <= MAX_LIMIT - ) limit = get_int ( incoming . get ( '' , limit_default ) , limit_default , limit_test ) conn = get_connection ( ) containers = conn . get_containers ( ) marker_part = None container = None objects = None if container_path != '' : cont_eq = lambda c : c . name == container_path cont_list = list ( islice ( ifilter ( cont_eq , containers ) , ) ) if not cont_list : raise Http404 ( \"\" % container_path ) container = cont_list [ ] objects = container . get_objects ( object_path , marker , limit + ) marker = None if len ( objects ) == limit + : objects = objects [ : limit ] marker = objects [ - ] . name marker_part = relpath ( marker , object_path ) return render_to_response ( template , { '' : path , '' : marker , '' : marker_part , '' : limit , '' : _breadcrumbs ( path ) , '' : container_path , '' : containers , '' : container , '' : object_path , '' : objects } , context_instance = RequestContext ( request ) ) ", "answer": "@ settings_view_decorator"}, {"prompt": " THREADS_PER_PAGE = ", "answer": "POSTS_PER_PAGE = "}, {"prompt": " import logging log = logging . getLogger ( __name__ ) class Middleware ( object ) : def process_request ( self , env , url , data , ** kwargs ) : raise NotImplementedError ", "answer": "def process_response ( self , env , response ) :"}, {"prompt": " from google . appengine . api import app_identity from google . appengine . api import mail import webapp2 ", "answer": "def send_approved_mail ( sender_address ) :"}, {"prompt": " import numpy as np import pandas as pd import warnings from . pycompat import builtins , reduce def _validate_axis ( data , axis ) : ndim = data . ndim if not - ndim <= axis < ndim : raise IndexError ( '' % ( axis , ndim , ndim ) ) if axis < : axis += ndim return axis def _select_along_axis ( values , idx , axis ) : other_ind = np . ix_ ( * [ np . arange ( s ) for s in idx . shape ] ) sl = other_ind [ : axis ] + ( idx , ) + other_ind [ axis : ] return values [ sl ] def nanfirst ( values , axis ) : axis = _validate_axis ( values , axis ) idx_first = np . argmax ( ~ pd . isnull ( values ) , axis = axis ) return _select_along_axis ( values , idx_first , axis ) def nanlast ( values , axis ) : axis = _validate_axis ( values , axis ) rev = ( slice ( None ) , ) * axis + ( slice ( None , None , - ) , ) idx_last = - - np . argmax ( ~ pd . isnull ( values ) [ rev ] , axis = axis ) return _select_along_axis ( values , idx_last , axis ) def _calc_concat_shape ( arrays , axis = ) : first_shape = arrays [ ] . shape length = builtins . sum ( a . shape [ axis ] for a in arrays ) result_shape = first_shape [ : axis ] + ( length , ) + first_shape [ ( axis + ) : ] return result_shape def interleaved_concat ( arrays , indices , axis = ) : arrays = [ np . asarray ( a ) for a in arrays ] axis = _validate_axis ( arrays [ ] , axis ) ", "answer": "result_shape = _calc_concat_shape ( arrays , axis = axis )"}, {"prompt": " \"\"\"\"\"\" import os gettext = lambda s : s DEBUG = True DATABASES = { '' : { '' : '' , '' : os . path . join ( os . path . dirname ( __file__ ) , '' ) } } TIME_ZONE = '' STATIC_URL = '' MEDIA_URL = '' SECRET_KEY = '' USE_TZ = True USE_I18N = True USE_L10N = True SITE_ID = LANGUAGE_CODE = '' LANGUAGES = ( ( '' , gettext ( '' ) ) , ( '' , gettext ( '' ) ) , ( '' , gettext ( '' ) ) , ( '' , gettext ( '' ) ) , ( '' , gettext ( '' ) ) , ( '' , gettext ( '' ) ) , ( '' , gettext ( '' ) ) , ( '' , gettext ( '' ) ) , ( '' , gettext ( '' ) ) , ( '' , gettext ( '' ) ) , ( '' , gettext ( '' ) ) , ( '' , gettext ( '' ) ) , ( '' , gettext ( '' ) ) , ( '' , gettext ( '' ) ) , ( '' , gettext ( '' ) ) , ( '' , gettext ( '' ) ) , ( '' , gettext ( '' ) ) , ( '' , gettext ( '' ) ) , ( '' , gettext ( '' ) ) , ( '' , gettext ( '' ) ) , ( '' , gettext ( '' ) ) , ( '' , gettext ( '' ) ) , ( '' , gettext ( '' ) ) , ( '' , gettext ( '' ) ) , ( '' , gettext ( '' ) ) , ( '' , gettext ( '' ) ) , ) MIDDLEWARE_CLASSES = ( '' , '' , '' , '' , '' , '' , '' , '' , ) ROOT_URLCONF = '' TEMPLATES = [ { '' : '' , '' : True , '' : { '' : [ '' , '' , '' , '' , '' , ] } } ] INSTALLED_APPS = ( '' , '' , '' , '' , '' , '' , ", "answer": "'' ,"}, {"prompt": " \"\"\"\"\"\" __revision__ = \"\" import SCons from SCons . Tool . install import copyFunc copyToBuilder , copyAsBuilder = None , None def copyto_emitter ( target , source , env ) : \"\"\"\"\"\" n_target = [ ] for t in target : n_target = n_target + map ( lambda s , t = t : t . File ( str ( s ) ) , source ) return ( n_target , source ) def copy_action_func ( target , source , env ) : assert ( len ( target ) == len ( source ) ) , \"\" % ( map ( str , target ) , map ( str , source ) ) for t , s in zip ( target , source ) : if copyFunc ( t . get_path ( ) , s . get_path ( ) , env ) : return return def copy_action_str ( target , source , env ) : return env . subst_target_source ( env [ '' ] , , target , source ) copy_action = SCons . Action . Action ( copy_action_func , copy_action_str ) def generate ( env ) : try : env [ '' ] [ '' ] env [ '' ] [ '' ] except KeyError , e : global copyToBuilder ", "answer": "if copyToBuilder is None :"}, {"prompt": " import os from django . template import RequestContext , Context from django . template . loader import render_to_string , select_template from oembed . constants import CONSUMER_URLIZE_ALL from oembed . utils import mock_request ", "answer": "class BaseParser ( object ) :"}, {"prompt": " \"\"\"\"\"\" import copy import os import sys import tempfile import eventlet eventlet . monkey_patch ( os = False ) import fixtures from oslo_config import cfg from oslo_config import fixture as config_fixture from oslo_log import log as logging import testtools from ironic . common import config as ironic_config from ironic . common import context as ironic_context from ironic . common import hash_ring from ironic . objects import base as objects_base from ironic . tests . unit import policy_fixture CONF = cfg . CONF CONF . import_opt ( '' , '' ) logging . register_options ( CONF ) logging . setup ( CONF , '' ) class ReplaceModule ( fixtures . Fixture ) : \"\"\"\"\"\" def __init__ ( self , name , new_value ) : self . name = name self . new_value = new_value def _restore ( self , old_value ) : sys . modules [ self . name ] = old_value def setUp ( self ) : super ( ReplaceModule , self ) . setUp ( ) old_value = sys . modules . get ( self . name ) sys . modules [ self . name ] = self . new_value self . addCleanup ( self . _restore , old_value ) class TestingException ( Exception ) : pass class TestCase ( testtools . TestCase ) : \"\"\"\"\"\" ", "answer": "def setUp ( self ) :"}, {"prompt": " import os from bs4 import BeautifulSoup from django . test import TestCase from django . conf import settings from django . core . management import call_command from django . core . exceptions import ImproperlyConfigured from django . test . utils import override_settings from pages . models import Image FAKE_PEP_REPO = os . path . join ( settings . BASE , '' ) class PEPManagementCommandTests ( TestCase ) : @ override_settings ( PEP_REPO_PATH = '' ) def test_generate_pep_pages ( self ) : with self . assertRaises ( ImproperlyConfigured ) : call_command ( '' ) @ override_settings ( PEP_REPO_PATH = FAKE_PEP_REPO ) def test_generate_pep_pages_real ( self ) : call_command ( '' ) @ override_settings ( PEP_REPO_PATH = FAKE_PEP_REPO ) def test_image_generated ( self ) : call_command ( '' ) ", "answer": "img = Image . objects . get ( page__path = '' )"}, {"prompt": " import mock from neutronclient . common import exceptions as neutron_client_exc from neutronclient . v2_0 import client from oslo_config import cfg from oslo_utils import uuidutils from ironic . common import dhcp_factory from ironic . common import exception from ironic . common import pxe_utils from ironic . conductor import task_manager from ironic . dhcp import neutron from ironic . drivers . modules import ssh from ironic . tests . unit . conductor import mgr_utils from ironic . tests . unit . db import base as db_base from ironic . tests . unit . objects import utils as object_utils class TestNeutron ( db_base . DbTestCase ) : def setUp ( self ) : super ( TestNeutron , self ) . setUp ( ) mgr_utils . mock_the_extension_manager ( driver = '' ) self . config ( cleaning_network_uuid = '' , group = '' ) self . config ( enabled_drivers = [ '' ] ) self . config ( dhcp_provider = '' , group = '' ) self . config ( url = '' , url_timeout = , retries = , group = '' ) self . config ( insecure = False , certfile = '' , admin_user = '' , admin_tenant_name = '' , admin_password = '' , auth_uri = '' , group = '' ) self . node = object_utils . create_test_node ( self . context ) self . ports = [ object_utils . create_test_port ( self . context , node_id = self . node . id , id = , uuid = '' , address = '' ) ] self . neutron_port = { '' : '' , '' : '' } dhcp_factory . DHCPFactory . _dhcp_provider = None @ mock . patch . object ( client . Client , \"\" ) def test__build_client_with_token ( self , mock_client_init ) : token = '' expected = { '' : , '' : , '' : False , '' : '' , '' : token , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' } mock_client_init . return_value = None neutron . _build_client ( token = token ) mock_client_init . assert_called_once_with ( ** expected ) @ mock . patch . object ( client . Client , \"\" ) def test__build_client_without_token ( self , mock_client_init ) : expected = { '' : , '' : , '' : False , '' : '' , '' : None , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' } mock_client_init . return_value = None neutron . _build_client ( token = None ) mock_client_init . assert_called_once_with ( ** expected ) @ mock . patch . object ( client . Client , \"\" ) def test__build_client_with_region ( self , mock_client_init ) : expected = { '' : , '' : , '' : False , '' : '' , '' : None , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' } self . config ( region_name = '' , group = '' ) mock_client_init . return_value = None neutron . _build_client ( token = None ) mock_client_init . assert_called_once_with ( ** expected ) @ mock . patch . object ( client . Client , \"\" ) def test__build_client_noauth ( self , mock_client_init ) : self . config ( auth_strategy = '' , group = '' ) expected = { '' : '' , '' : False , '' : '' , '' : , '' : , '' : '' } mock_client_init . return_value = None neutron . _build_client ( token = None ) mock_client_init . assert_called_once_with ( ** expected ) @ mock . patch . object ( client . Client , '' ) @ mock . patch . object ( client . Client , \"\" ) def test_update_port_dhcp_opts ( self , mock_client_init , mock_update_port ) : opts = [ { '' : '' , '' : '' } , { '' : '' , '' : '' } , { '' : '' , '' : '' } ] port_id = '' expected = { '' : { '' : opts } } mock_client_init . return_value = None api = dhcp_factory . DHCPFactory ( ) api . provider . update_port_dhcp_opts ( port_id , opts ) mock_update_port . assert_called_once_with ( port_id , expected ) @ mock . patch . object ( client . Client , '' ) @ mock . patch . object ( client . Client , \"\" ) def test_update_port_dhcp_opts_with_exception ( self , mock_client_init , mock_update_port ) : opts = [ { } ] port_id = '' mock_client_init . return_value = None mock_update_port . side_effect = ( neutron_client_exc . NeutronClientException ( ) ) api = dhcp_factory . DHCPFactory ( ) self . assertRaises ( exception . FailedToUpdateDHCPOptOnPort , api . provider . update_port_dhcp_opts , port_id , opts ) @ mock . patch . object ( client . Client , '' ) @ mock . patch . object ( client . Client , '' ) def test_update_port_address ( self , mock_client_init , mock_update_port ) : address = '' port_id = '' expected = { '' : { '' : address } } mock_client_init . return_value = None api = dhcp_factory . DHCPFactory ( ) api . provider . update_port_address ( port_id , address ) mock_update_port . assert_called_once_with ( port_id , expected ) @ mock . patch . object ( client . Client , '' ) @ mock . patch . object ( client . Client , '' ) def test_update_port_address_with_exception ( self , mock_client_init , mock_update_port ) : address = '' port_id = '' mock_client_init . return_value = None api = dhcp_factory . DHCPFactory ( ) mock_update_port . side_effect = ( neutron_client_exc . NeutronClientException ( ) ) self . assertRaises ( exception . FailedToUpdateMacOnPort , api . provider . update_port_address , port_id , address ) @ mock . patch ( '' ) @ mock . patch ( '' ) def test_update_dhcp ( self , mock_gnvi , mock_updo ) : mock_gnvi . return_value = { '' : { '' : '' } , '' : { } } with task_manager . acquire ( self . context , self . node . uuid ) as task : opts = pxe_utils . dhcp_options_for_instance ( task ) api = dhcp_factory . DHCPFactory ( ) api . update_dhcp ( task , opts ) mock_updo . assert_called_once_with ( '' , opts , token = self . context . auth_token ) @ mock . patch ( '' ) @ mock . patch ( '' ) def test_update_dhcp_no_vif_data ( self , mock_gnvi , mock_updo ) : mock_gnvi . return_value = { '' : { } , '' : { } } with task_manager . acquire ( self . context , self . node . uuid ) as task : api = dhcp_factory . DHCPFactory ( ) self . assertRaises ( exception . FailedToUpdateDHCPOptOnPort , api . update_dhcp , task , self . node ) self . assertFalse ( mock_updo . called ) @ mock . patch ( '' ) @ mock . patch ( '' ) def test_update_dhcp_some_failures ( self , mock_gnvi , mock_updo ) : mock_gnvi . return_value = { '' : { '' : '' , '' : '' } , '' : { } } exc = exception . FailedToUpdateDHCPOptOnPort ( '' ) mock_updo . side_effect = [ None , exc ] with task_manager . acquire ( self . context , self . node . uuid ) as task : api = dhcp_factory . DHCPFactory ( ) api . update_dhcp ( task , self . node ) mock_gnvi . assert_called_once_with ( task ) self . assertEqual ( , mock_updo . call_count ) @ mock . patch ( '' ) @ mock . patch ( '' ) def test_update_dhcp_fails ( self , mock_gnvi , mock_updo ) : mock_gnvi . return_value = { '' : { '' : '' , '' : '' } , '' : { } } exc = exception . FailedToUpdateDHCPOptOnPort ( '' ) mock_updo . side_effect = [ exc , exc ] with task_manager . acquire ( self . context , self . node . uuid ) as task : api = dhcp_factory . DHCPFactory ( ) self . assertRaises ( exception . FailedToUpdateDHCPOptOnPort , api . update_dhcp , task , self . node ) mock_gnvi . assert_called_once_with ( task ) self . assertEqual ( , mock_updo . call_count ) @ mock . patch ( '' , autospec = True ) @ mock . patch . object ( neutron . NeutronDHCPApi , '' , autospec = True ) @ mock . patch ( '' , autospec = True ) def test_update_dhcp_set_sleep_and_ssh ( self , mock_gnvi , mock_updo , mock_ts ) : mock_gnvi . return_value = { '' : { '' : '' } , '' : { } } self . config ( port_setup_delay = , group = '' ) with task_manager . acquire ( self . context , self . node . uuid ) as task : task . driver . power = ssh . SSHPower ( ) opts = pxe_utils . dhcp_options_for_instance ( task ) api = dhcp_factory . DHCPFactory ( ) api . update_dhcp ( task , opts ) mock_ts . assert_called_with ( ) mock_updo . assert_called_once_with ( mock . ANY , '' , opts , token = self . context . auth_token ) @ mock . patch . object ( neutron , '' , autospec = True ) @ mock . patch ( '' , autospec = True ) @ mock . patch . object ( neutron . NeutronDHCPApi , '' , autospec = True ) @ mock . patch ( '' , autospec = True ) def test_update_dhcp_unset_sleep_and_ssh ( self , mock_gnvi , mock_updo , mock_ts , mock_log ) : mock_gnvi . return_value = { '' : { '' : '' } , '' : { } } with task_manager . acquire ( self . context , self . node . uuid ) as task : opts = pxe_utils . dhcp_options_for_instance ( task ) task . driver . power = ssh . SSHPower ( ) api = dhcp_factory . DHCPFactory ( ) api . update_dhcp ( task , opts ) self . assertTrue ( mock_log . warning . called ) self . assertIn ( '' , mock_log . warning . call_args [ ] [ ] ) mock_ts . assert_called_with ( ) mock_updo . assert_called_once_with ( mock . ANY , '' , opts , token = self . context . auth_token ) @ mock . patch . object ( neutron , '' , autospec = True ) @ mock . patch ( '' , autospec = True ) @ mock . patch . object ( neutron . NeutronDHCPApi , '' , autospec = True ) @ mock . patch ( '' , autospec = True ) def test_update_dhcp_set_sleep_and_fake ( self , mock_gnvi , mock_updo , mock_ts , mock_log ) : mock_gnvi . return_value = { '' : { '' : '' } , '' : { } } self . config ( port_setup_delay = , group = '' ) with task_manager . acquire ( self . context , self . node . uuid ) as task : opts = pxe_utils . dhcp_options_for_instance ( task ) api = dhcp_factory . DHCPFactory ( ) api . update_dhcp ( task , opts ) mock_log . debug . assert_called_once_with ( \"\" , ) mock_log . warning . assert_not_called ( ) mock_ts . assert_called_with ( ) mock_updo . assert_called_once_with ( mock . ANY , '' , opts , token = self . context . auth_token ) @ mock . patch . object ( neutron , '' , autospec = True ) @ mock . patch . object ( neutron . NeutronDHCPApi , '' , autospec = True ) @ mock . patch ( '' , autospec = True ) def test_update_dhcp_unset_sleep_and_fake ( self , mock_gnvi , mock_updo , mock_log ) : mock_gnvi . return_value = { '' : { '' : '' } , '' : { } } with task_manager . acquire ( self . context , self . node . uuid ) as task : opts = pxe_utils . dhcp_options_for_instance ( task ) api = dhcp_factory . DHCPFactory ( ) api . update_dhcp ( task , opts ) mock_log . debug . assert_not_called ( ) mock_log . warning . assert_not_called ( ) mock_updo . assert_called_once_with ( mock . ANY , '' , opts , token = self . context . auth_token ) def test__get_fixed_ip_address ( self ) : port_id = '' expected = \"\" api = dhcp_factory . DHCPFactory ( ) . provider port_data = { \"\" : port_id , \"\" : \"\" , \"\" : True , \"\" : \"\" , \"\" : \"\" , \"\" : [ { \"\" : \"\" , \"\" : \"\" } ] , \"\" : '' , } fake_client = mock . Mock ( ) fake_client . show_port . return_value = { '' : port_data } result = api . _get_fixed_ip_address ( port_id , fake_client ) self . assertEqual ( expected , result ) fake_client . show_port . assert_called_once_with ( port_id ) def test__get_fixed_ip_address_invalid_ip ( self ) : port_id = '' api = dhcp_factory . DHCPFactory ( ) . provider port_data = { \"\" : port_id , \"\" : \"\" , \"\" : True , \"\" : \"\" , \"\" : \"\" , \"\" : [ { \"\" : \"\" , \"\" : \"\" } ] , \"\" : '' , } fake_client = mock . Mock ( ) fake_client . show_port . return_value = { '' : port_data } self . assertRaises ( exception . InvalidIPv4Address , api . _get_fixed_ip_address , port_id , fake_client ) fake_client . show_port . assert_called_once_with ( port_id ) def test__get_fixed_ip_address_with_exception ( self ) : port_id = '' api = dhcp_factory . DHCPFactory ( ) . provider fake_client = mock . Mock ( ) fake_client . show_port . side_effect = ( neutron_client_exc . NeutronClientException ( ) ) self . assertRaises ( exception . FailedToGetIPAddressOnPort , api . _get_fixed_ip_address , port_id , fake_client ) fake_client . show_port . assert_called_once_with ( port_id ) @ mock . patch ( '' ) def test__get_port_ip_address ( self , mock_gfia ) : expected = \"\" port = object_utils . create_test_port ( self . context , node_id = self . node . id , address = '' , uuid = uuidutils . generate_uuid ( ) , extra = { '' : '' } , driver = '' ) mock_gfia . return_value = expected with task_manager . acquire ( self . context , self . node . uuid ) as task : api = dhcp_factory . DHCPFactory ( ) . provider result = api . _get_port_ip_address ( task , port , mock . sentinel . client ) self . assertEqual ( expected , result ) mock_gfia . assert_called_once_with ( '' , mock . sentinel . client ) @ mock . patch ( '' ) def test__get_port_ip_address_for_portgroup ( self , mock_gfia ) : expected = \"\" pg = object_utils . create_test_portgroup ( self . context , node_id = self . node . id , address = '' , uuid = uuidutils . generate_uuid ( ) , extra = { '' : '' } , driver = '' ) mock_gfia . return_value = expected with task_manager . acquire ( self . context , self . node . uuid ) as task : api = dhcp_factory . DHCPFactory ( ) . provider result = api . _get_port_ip_address ( task , pg , mock . sentinel . client ) self . assertEqual ( expected , result ) mock_gfia . assert_called_once_with ( '' , mock . sentinel . client ) @ mock . patch ( '' ) def test__get_port_ip_address_with_exception ( self , mock_gfia ) : expected = \"\" port = object_utils . create_test_port ( self . context , node_id = self . node . id , address = '' , uuid = uuidutils . generate_uuid ( ) , driver = '' ) mock_gfia . return_value = expected with task_manager . acquire ( self . context , self . node . uuid ) as task : api = dhcp_factory . DHCPFactory ( ) . provider self . assertRaises ( exception . FailedToGetIPAddressOnPort , api . _get_port_ip_address , task , port , mock . sentinel . client ) @ mock . patch ( '' ) def test__get_port_ip_address_for_portgroup_with_exception ( self , mock_gfia ) : expected = \"\" pg = object_utils . create_test_portgroup ( self . context , node_id = self . node . id , address = '' , uuid = uuidutils . generate_uuid ( ) , driver = '' ) mock_gfia . return_value = expected with task_manager . acquire ( self . context , self . node . uuid ) as task : api = dhcp_factory . DHCPFactory ( ) . provider self . assertRaises ( exception . FailedToGetIPAddressOnPort , api . _get_port_ip_address , task , pg , mock . sentinel . client ) @ mock . patch ( '' ) def test__get_ip_addresses_ports ( self , mock_gfia ) : ip_address = '' expected = [ ip_address ] port = object_utils . create_test_port ( self . context , node_id = self . node . id , address = '' , uuid = uuidutils . generate_uuid ( ) , extra = { '' : '' } , driver = '' ) mock_gfia . return_value = ip_address with task_manager . acquire ( self . context , self . node . uuid ) as task : api = dhcp_factory . DHCPFactory ( ) . provider result = api . _get_ip_addresses ( task , [ port ] , mock . sentinel . client ) self . assertEqual ( expected , result ) @ mock . patch ( '' ) def test__get_ip_addresses_portgroup ( self , mock_gfia ) : ip_address = '' expected = [ ip_address ] pg = object_utils . create_test_portgroup ( self . context , node_id = self . node . id , address = '' , uuid = uuidutils . generate_uuid ( ) , extra = { '' : '' } , driver = '' ) mock_gfia . return_value = ip_address with task_manager . acquire ( self . context , self . node . uuid ) as task : api = dhcp_factory . DHCPFactory ( ) . provider result = api . _get_ip_addresses ( task , [ pg ] , mock . sentinel . client ) self . assertEqual ( expected , result ) @ mock . patch ( '' ) def test_get_ip_addresses ( self , get_ip_mock ) : ip_address = '' expected = [ ip_address ] get_ip_mock . return_value = ip_address with task_manager . acquire ( self . context , self . node . uuid ) as task : api = dhcp_factory . DHCPFactory ( ) . provider result = api . get_ip_addresses ( task ) get_ip_mock . assert_called_once_with ( task , task . ports [ ] , mock . ANY ) self . assertEqual ( expected , result ) @ mock . patch ( '' ) def test_get_ip_addresses_for_port_and_portgroup ( self , get_ip_mock ) : object_utils . create_test_portgroup ( self . context , node_id = self . node . id , address = '' , uuid = uuidutils . generate_uuid ( ) , extra = { '' : '' } , driver = '' ) with task_manager . acquire ( self . context , self . node . uuid ) as task : api = dhcp_factory . DHCPFactory ( ) . provider api . get_ip_addresses ( task ) get_ip_mock . assert_has_calls ( [ mock . call ( task , task . ports [ ] , mock . ANY ) , mock . call ( task , task . portgroups [ ] , mock . ANY ) ] ) @ mock . patch . object ( client . Client , '' ) def test_create_cleaning_ports ( self , create_mock ) : create_mock . return_value = { '' : self . neutron_port } expected = { self . ports [ ] . uuid : self . neutron_port [ '' ] } api = dhcp_factory . DHCPFactory ( ) . provider with task_manager . acquire ( self . context , self . node . uuid ) as task : ports = api . create_cleaning_ports ( task ) self . assertEqual ( expected , ports ) create_mock . assert_called_once_with ( { '' : { '' : '' , '' : True , '' : self . ports [ ] . address } } ) @ mock . patch . object ( neutron . NeutronDHCPApi , '' ) @ mock . patch . object ( client . Client , '' ) def test_create_cleaning_ports_fail ( self , create_mock , rollback_mock ) : create_mock . side_effect = neutron_client_exc . ConnectionFailed api = dhcp_factory . DHCPFactory ( ) . provider with task_manager . acquire ( self . context , self . node . uuid ) as task : self . assertRaises ( exception . NodeCleaningFailure , api . create_cleaning_ports , task ) create_mock . assert_called_once_with ( { '' : { '' : '' , '' : True , '' : self . ports [ ] . address } } ) rollback_mock . assert_called_once_with ( task ) @ mock . patch . object ( neutron . NeutronDHCPApi , '' ) @ mock . patch . object ( client . Client , '' ) def test_create_cleaning_ports_fail_delayed ( self , create_mock , rollback_mock ) : \"\"\"\"\"\" mockport = mock . MagicMock ( ) create_mock . return_value = mockport mockport . get . return_value = True mockitem = mock . Mock ( ) mockport . __getitem__ . return_value = mockitem mockitem . get . return_value = None api = dhcp_factory . DHCPFactory ( ) . provider with task_manager . acquire ( self . context , self . node . uuid ) as task : self . assertRaises ( exception . NodeCleaningFailure , api . create_cleaning_ports , task ) create_mock . assert_called_once_with ( { '' : { '' : '' , '' : True , '' : self . ports [ ] . address } } ) rollback_mock . assert_called_once_with ( task ) mockport . get . assert_called_once_with ( '' ) mockitem . get . assert_called_once_with ( '' ) mockport . __getitem__ . assert_called_once_with ( '' ) @ mock . patch . object ( client . Client , '' ) def test_create_cleaning_ports_bad_config ( self , create_mock ) : self . config ( cleaning_network_uuid = None , group = '' ) api = dhcp_factory . DHCPFactory ( ) . provider with task_manager . acquire ( self . context , self . node . uuid ) as task : self . assertRaises ( exception . InvalidParameterValue , api . create_cleaning_ports , task ) @ mock . patch . object ( client . Client , '' ) @ mock . patch . object ( client . Client , '' ) def test_delete_cleaning_ports ( self , list_mock , delete_mock ) : other_port = { '' : '' , '' : '' } list_mock . return_value = { '' : [ self . neutron_port , other_port ] } api = dhcp_factory . DHCPFactory ( ) . provider with task_manager . acquire ( self . context , self . node . uuid ) as task : api . delete_cleaning_ports ( task ) list_mock . assert_called_once_with ( network_id = '' ) delete_mock . assert_called_once_with ( self . neutron_port [ '' ] ) @ mock . patch . object ( client . Client , '' ) def test_delete_cleaning_ports_list_fail ( self , list_mock ) : list_mock . side_effect = neutron_client_exc . ConnectionFailed api = dhcp_factory . DHCPFactory ( ) . provider with task_manager . acquire ( self . context , self . node . uuid ) as task : self . assertRaises ( exception . NodeCleaningFailure , api . delete_cleaning_ports , task ) list_mock . assert_called_once_with ( network_id = '' ) @ mock . patch . object ( client . Client , '' ) @ mock . patch . object ( client . Client , '' ) def test_delete_cleaning_ports_delete_fail ( self , list_mock , delete_mock ) : list_mock . return_value = { '' : [ self . neutron_port ] } delete_mock . side_effect = neutron_client_exc . ConnectionFailed api = dhcp_factory . DHCPFactory ( ) . provider with task_manager . acquire ( self . context , self . node . uuid ) as task : self . assertRaises ( exception . NodeCleaningFailure , api . delete_cleaning_ports , task ) list_mock . assert_called_once_with ( network_id = '' ) delete_mock . assert_called_once_with ( self . neutron_port [ '' ] ) def test_out_range_auth_strategy ( self ) : self . assertRaises ( ValueError , cfg . CONF . set_override , '' , '' , '' , ", "answer": "enforce_type = True ) "}, {"prompt": " from django . conf . urls import patterns urlpatterns = patterns ( '' , ( r'' , '' ) , ( r'' , '' ) , ", "answer": "( r'' , '' ) ,"}, {"prompt": " from django . conf . urls import url ", "answer": "from django . contrib . auth . models import User"}, {"prompt": " import cStringIO from nova import context from nova import flags from nova import log from nova import test FLAGS = flags . FLAGS def _fake_context ( ) : return context . RequestContext ( , ) class RootLoggerTestCase ( test . TestCase ) : def setUp ( self ) : super ( RootLoggerTestCase , self ) . setUp ( ) self . log = log . logging . root def test_is_nova_instance ( self ) : self . assert_ ( isinstance ( self . log , log . NovaLogger ) ) def test_name_is_nova ( self ) : self . assertEqual ( \"\" , self . log . name ) def test_handlers_have_nova_formatter ( self ) : formatters = [ ] for h in self . log . handlers : f = h . formatter if isinstance ( f , log . NovaFormatter ) : formatters . append ( f ) self . assert_ ( formatters ) self . assertEqual ( len ( formatters ) , len ( self . log . handlers ) ) def test_handles_context_kwarg ( self ) : self . log . info ( \"\" , context = _fake_context ( ) ) self . assert_ ( True ) def test_module_level_methods_handle_context_arg ( self ) : log . info ( \"\" , context = _fake_context ( ) ) self . assert_ ( True ) def test_module_level_audit_handles_context_arg ( self ) : log . audit ( \"\" , context = _fake_context ( ) ) self . assert_ ( True ) def test_will_be_verbose_if_verbose_flag_set ( self ) : self . flags ( verbose = True ) log . reset ( ) self . assertEqual ( log . DEBUG , self . log . level ) def test_will_not_be_verbose_if_verbose_flag_not_set ( self ) : self . flags ( verbose = False ) log . reset ( ) self . assertEqual ( log . INFO , self . log . level ) class LogHandlerTestCase ( test . TestCase ) : def test_log_path_logdir ( self ) : self . flags ( logdir = '' , logfile = None ) self . assertEquals ( log . _get_log_file_path ( binary = '' ) , '' ) def test_log_path_logfile ( self ) : self . flags ( logfile = '' ) self . assertEquals ( log . _get_log_file_path ( binary = '' ) , '' ) def test_log_path_none ( self ) : self . flags ( logdir = None , logfile = None ) self . assertTrue ( log . _get_log_file_path ( binary = '' ) is None ) def test_log_path_logfile_overrides_logdir ( self ) : self . flags ( logdir = '' , logfile = '' ) self . assertEquals ( log . _get_log_file_path ( binary = '' ) , '' ) class NovaFormatterTestCase ( test . TestCase ) : ", "answer": "def setUp ( self ) :"}, {"prompt": " import mock from neutron . common import constants as q_const from neutron . common import exceptions as n_exc from neutron import context from gbpservice . neutron . services . l3_router import l3_apic from gbpservice . neutron . tests . unit . services . grouppolicy import ( test_apic_mapping ) TENANT = '' ROUTER = '' SUBNET = '' NETWORK = '' PORT = '' NETWORK_NAME = '' TEST_SEGMENT1 = '' FLOATINGIP = '' class TestCiscoApicL3Plugin ( test_apic_mapping . ApicMappingTestCase ) : '''''' def setUp ( self ) : super ( TestCiscoApicL3Plugin , self ) . setUp ( ) self . subnet = { '' : NETWORK , '' : TENANT } self . port = { '' : TENANT , '' : NETWORK , '' : [ { '' : SUBNET } ] , '' : '' } self . interface_info = { '' : { '' : SUBNET } , '' : { '' : self . port [ '' ] } } self . floatingip = { '' : FLOATINGIP , '' : NETWORK_NAME , '' : PORT } self . context = context . get_admin_context ( ) self . context . tenant_id = TENANT self . plugin = l3_apic . ApicGBPL3ServicePlugin ( ) self . plugin . apic_gbp . _notify_port_update = mock . Mock ( ) self . plugin . _core_plugin . get_ports = mock . Mock ( return_value = [ self . port ] ) self . plugin . _core_plugin . get_port = mock . Mock ( return_value = self . port ) self . plugin . _core_plugin . get_subnet = mock . Mock ( return_value = self . subnet ) self . plugin . _core_plugin . update_port_status = mock . Mock ( ) self . plugin . update_floatingip_status = mock . Mock ( ) self . plugin . get_floatingip = mock . Mock ( return_value = self . floatingip ) def test_reverse_on_delete ( self ) : pass def _check_call_list ( self , expected , observed ) : for call in expected : self . assertTrue ( call in observed , msg = '' '' % ( str ( call ) , str ( observed ) ) ) observed . remove ( call ) self . assertFalse ( len ( observed ) , msg = '' % str ( observed ) ) def _test_add_router_interface ( self , interface_info ) : with mock . patch ( '' '' ) as if_mock : if_mock . return_value = self . port port = self . plugin . add_router_interface ( self . context , ROUTER , interface_info ) self . assertEqual ( port , self . port ) test_assert = self . plugin . _core_plugin . update_port_status test_assert . assert_called_once_with ( self . context , self . port [ '' ] , q_const . PORT_STATUS_ACTIVE ) def _test_remove_router_interface ( self , interface_info ) : with mock . patch ( '' '' ) as if_mock : self . plugin . remove_router_interface ( self . context , ROUTER , interface_info ) self . assertEqual ( , if_mock . call_count ) def test_add_router_interface_subnet ( self ) : self . _test_add_router_interface ( self . interface_info [ '' ] ) def test_add_router_interface_port ( self ) : self . _test_add_router_interface ( self . interface_info [ '' ] ) def test_remove_router_interface_subnet ( self ) : self . _test_remove_router_interface ( self . interface_info [ '' ] ) def test_remove_router_interface_port ( self ) : self . _test_remove_router_interface ( self . interface_info [ '' ] ) def test_create_router_gateway_fails ( self ) : with mock . patch ( '' '' , side_effect = n_exc . NeutronException ) : data = { '' : { '' : '' , '' : '' , '' : True , '' : { '' : '' } } } self . assertRaises ( n_exc . NeutronException , self . plugin . create_router , self . context , data ) routers = self . plugin . get_routers ( self . context ) self . assertEqual ( , len ( routers ) ) def test_floatingip_port_notify_on_create ( self ) : with mock . patch ( '' '' , new = mock . Mock ( return_value = self . floatingip ) ) : self . plugin . create_floatingip ( self . context , { '' : self . floatingip } ) self . plugin . apic_gbp . _notify_port_update . assert_called_once_with ( mock . ANY , PORT ) def test_floatingip_port_notify_on_reassociate ( self ) : with mock . patch ( '' '' , new = mock . Mock ( return_value = self . floatingip ) ) : new_fip = { '' : '' } self . plugin . update_floatingip ( self . context , FLOATINGIP , { '' : new_fip } ) self . _check_call_list ( [ mock . call ( mock . ANY , PORT ) , mock . call ( mock . ANY , '' ) ] , self . plugin . apic_gbp . _notify_port_update . call_args_list ) def test_floatingip_port_notify_on_disassociate ( self ) : with mock . patch ( '' '' , new = mock . Mock ( return_value = self . floatingip ) ) : self . plugin . update_floatingip ( self . context , FLOATINGIP , { '' : { } } ) self . plugin . apic_gbp . _notify_port_update . assert_called_once_with ( mock . ANY , PORT ) def test_floatingip_port_notify_on_delete ( self ) : with mock . patch ( '' ) : self . plugin . delete_floatingip ( self . context , FLOATINGIP ) self . plugin . apic_gbp . _notify_port_update . assert_called_once_with ( mock . ANY , PORT ) def test_floatingip_status ( self ) : with mock . patch ( '' '' , new = mock . Mock ( return_value = self . floatingip ) ) : fip = self . plugin . create_floatingip ( self . context , { '' : self . floatingip } ) self . plugin . update_floatingip_status . assert_called_once_with ( mock . ANY , FLOATINGIP , q_const . FLOATINGIP_STATUS_ACTIVE ) self . assertEqual ( q_const . FLOATINGIP_STATUS_ACTIVE , fip [ '' ] ) with mock . patch ( '' '' , new = mock . Mock ( return_value = self . floatingip ) ) : self . plugin . update_floatingip_status . reset_mock ( ) self . floatingip . pop ( '' ) fip = self . plugin . update_floatingip ( self . context , FLOATINGIP , { '' : self . floatingip } ) self . plugin . update_floatingip_status . assert_called_once_with ( mock . ANY , FLOATINGIP , q_const . FLOATINGIP_STATUS_DOWN ) self . assertEqual ( q_const . FLOATINGIP_STATUS_DOWN , fip [ '' ] ) with mock . patch ( '' '' , new = mock . Mock ( return_value = self . floatingip ) ) : self . plugin . update_floatingip_status . reset_mock ( ) self . floatingip [ '' ] = PORT fip = self . plugin . update_floatingip ( self . context , FLOATINGIP , { '' : self . floatingip } ) self . plugin . update_floatingip_status . assert_called_once_with ( mock . ANY , FLOATINGIP , q_const . FLOATINGIP_STATUS_ACTIVE ) ", "answer": "self . assertEqual ( q_const . FLOATINGIP_STATUS_ACTIVE , fip [ '' ] ) "}, {"prompt": " from . platform import Platform from . keywords . postgresql_keywords import PostgreSQLKeywords from . . table import Table from . . column import Column from . . identifier import Identifier class PostgresPlatform ( Platform ) : INTERNAL_TYPE_MAPPING = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , ", "answer": "'' : '' ,"}, {"prompt": " from py . xml import html paras = \"\" , \"\" ", "answer": "doc = html . html ("}, {"prompt": " from nose . plugins . skip import SkipTest import numpy try : import scipy . sparse as sp import scipy . sparse except ImportError : pass import theano from theano import sparse , config , tensor from theano . sparse import enable_sparse if not enable_sparse : raise SkipTest ( '' ) from theano . sparse . tests . test_basic import random_lil def test_local_csm_properties_csm ( ) : data = tensor . vector ( ) indices , indptr , shape = ( tensor . ivector ( ) , tensor . ivector ( ) , tensor . ivector ( ) ) mode = theano . compile . mode . get_default_mode ( ) mode = mode . including ( \"\" , \"\" ) for CS , cast in [ ( sparse . CSC , sp . csc_matrix ) , ( sparse . CSR , sp . csr_matrix ) ] : f = theano . function ( [ data , indices , indptr , shape ] , sparse . csm_properties ( CS ( data , indices , indptr , shape ) ) , mode = mode ) assert not any ( isinstance ( node . op , ( sparse . CSM , sparse . CSMProperties ) ) for node in f . maker . fgraph . toposort ( ) ) v = cast ( random_lil ( ( , ) , config . floatX , ) ) f ( v . data , v . indices , v . indptr , v . shape ) def test_local_csm_grad_c ( ) : raise SkipTest ( \"\" ) if not theano . config . cxx : raise SkipTest ( \"\" ) data = tensor . vector ( ) indices , indptr , shape = ( tensor . ivector ( ) , tensor . ivector ( ) , tensor . ivector ( ) ) mode = theano . compile . mode . get_default_mode ( ) if theano . config . mode == '' : mode = theano . compile . Mode ( linker = '' , optimizer = '' ) mode = mode . including ( \"\" , \"\" ) for CS , cast in [ ( sparse . CSC , sp . csc_matrix ) , ( sparse . CSR , sp . csr_matrix ) ] : cost = tensor . sum ( sparse . DenseFromSparse ( ) ( CS ( data , indices , indptr , shape ) ) ) f = theano . function ( [ data , indices , indptr , shape ] , tensor . grad ( cost , data ) , mode = mode ) assert not any ( isinstance ( node . op , sparse . CSMGrad ) for node in f . maker . fgraph . toposort ( ) ) v = cast ( random_lil ( ( , ) , config . floatX , ) ) f ( v . data , v . indices , v . indptr , v . shape ) def test_local_mul_s_d ( ) : if not theano . config . cxx : raise SkipTest ( \"\" ) mode = theano . compile . mode . get_default_mode ( ) mode = mode . including ( \"\" , \"\" ) for sp_format in sparse . sparse_formats : inputs = [ getattr ( theano . sparse , sp_format + '' ) ( ) , tensor . matrix ( ) ] f = theano . function ( inputs , sparse . mul_s_d ( * inputs ) , mode = mode ) assert not any ( isinstance ( node . op , sparse . MulSD ) for node in f . maker . fgraph . toposort ( ) ) def test_local_mul_s_v ( ) : if not theano . config . cxx : raise SkipTest ( \"\" ) mode = theano . compile . mode . get_default_mode ( ) mode = mode . including ( \"\" , \"\" ) for sp_format in [ '' ] : inputs = [ getattr ( theano . sparse , sp_format + '' ) ( ) , tensor . vector ( ) ] f = theano . function ( inputs , sparse . mul_s_v ( * inputs ) , mode = mode ) assert not any ( isinstance ( node . op , sparse . MulSV ) for node in f . maker . fgraph . toposort ( ) ) def test_local_structured_add_s_v ( ) : if not theano . config . cxx : raise SkipTest ( \"\" ) mode = theano . compile . mode . get_default_mode ( ) mode = mode . including ( \"\" , \"\" ) for sp_format in [ '' ] : inputs = [ getattr ( theano . sparse , sp_format + '' ) ( ) , tensor . vector ( ) ] f = theano . function ( inputs , sparse . structured_add_s_v ( * inputs ) , mode = mode ) assert not any ( isinstance ( node . op , sparse . StructuredAddSV ) for node in f . maker . fgraph . toposort ( ) ) def test_local_sampling_dot_csr ( ) : if not theano . config . cxx : raise SkipTest ( \"\" ) mode = theano . compile . mode . get_default_mode ( ) mode = mode . including ( \"\" , \"\" ) for sp_format in [ '' ] : ", "answer": "inputs = [ tensor . matrix ( ) ,"}, {"prompt": " import pytest from schematics . datastructures import OrderedDict from schematics . models import Model from schematics . types import IntType , StringType from schematics . types . compound import ModelType , ListType from schematics . exceptions import ( ConversionError , ValidationError , StopValidationError , DataError , MockCreationError ) def test_list_field ( ) : class User ( Model ) : ids = ListType ( StringType , required = True ) c = User ( { \"\" : [ ] } ) c . validate ( { '' : [ ] } ) assert c . ids == [ ] def test_list_with_default_type ( ) : class CategoryStatsInfo ( Model ) : slug = StringType ( ) class PlayerInfo ( Model ) : categories = ListType ( ModelType ( CategoryStatsInfo ) ) math_stats = CategoryStatsInfo ( dict ( slug = \"\" ) ) twilight_stats = CategoryStatsInfo ( dict ( slug = \"\" ) ) info = PlayerInfo ( { \"\" : [ { \"\" : \"\" } , { \"\" : \"\" } ] } ) assert info . categories == [ math_stats , twilight_stats ] d = info . serialize ( ) assert d == { \"\" : [ { \"\" : \"\" } , { \"\" : \"\" } ] , } def test_set_default ( ) : class CategoryStatsInfo ( Model ) : slug = StringType ( ) class PlayerInfo ( Model ) : categories = ListType ( ModelType ( CategoryStatsInfo ) , default = lambda : [ ] , serialize_when_none = True ) info = PlayerInfo ( ) assert info . categories == [ ] d = info . serialize ( ) assert d == { \"\" : [ ] , } ", "answer": "def test_list_defaults_to_none ( ) :"}, {"prompt": " from __future__ import absolute_import from django . conf . urls import patterns from . views import empty_view urlpatterns = patterns ( '' ) ", "answer": "handler404 = empty_view"}, {"prompt": " def validate_cluster_config ( ) : ", "answer": "pass "}, {"prompt": " from testtools import testcase from functionaltests import utils from functionaltests . client import base from functionaltests . common import cleanup order_create_key_data = { \"\" : \"\" , ", "answer": "\"\" : \"\" ,"}, {"prompt": " from msrest . serialization import Model class AddStorageAccountParameters ( Model ) : \"\"\"\"\"\" ", "answer": "_validation = {"}, {"prompt": " import numpy as np ", "answer": "import tensorprob as tp"}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import , division , print_function , unicode_literals import re from collections import namedtuple from pies . overrides import * BY_CODE = { } _ERROR_INDEX = AbstractMessageType = namedtuple ( '' , ( '' , '' , '' , '' , '' ) ) class MessageType ( AbstractMessageType ) : class Message ( namedtuple ( '' , ( '' , '' , '' , '' ) ) ) : def __str__ ( self ) : return self . message def __new__ ( cls , error_code , name , template , keyword = '' ) : global _ERROR_INDEX new_instance = AbstractMessageType . __new__ ( cls , error_code , name , template , keyword , _ERROR_INDEX ) _ERROR_INDEX += BY_CODE [ error_code ] = new_instance return new_instance def __call__ ( self , filename , loc = None , * kargs , ** kwargs ) : values = { '' : filename , '' : , '' : } if loc : values [ '' ] = loc . lineno values [ '' ] = getattr ( loc , '' , ) values . update ( kwargs ) message = self . template . format ( * kargs , ** values ) if kwargs . get ( '' , False ) : keyword = self . keyword . format ( * kargs , ** values ) return self . Message ( '' . format ( filename , values [ '' ] , values [ '' ] , self . error_code , keyword , message ) , self , values [ '' ] , values [ '' ] ) return self . Message ( '' . format ( filename , values [ '' ] , message ) , self , values [ '' ] , values [ '' ] ) class OffsetMessageType ( MessageType ) : def __call__ ( self , filename , loc , position = None , * kargs , ** kwargs ) : if position : kwargs . update ( { '' : position [ ] , '' : position [ ] } ) return MessageType . __call__ ( self , filename , loc , * kargs , ** kwargs ) class SyntaxErrorType ( MessageType ) : def __call__ ( self , filename , msg , lineno , offset , text , * kargs , ** kwargs ) : kwargs [ '' ] = lineno line = text . splitlines ( ) [ - ] msg += \"\" + str ( line ) if offset is not None : offset = offset - ( len ( text ) - len ( line ) ) kwargs [ '' ] = offset msg += \"\" + re . sub ( r'' , '' , line [ : offset ] ) + \"\" return MessageType . __call__ ( self , filename , None , msg , * kargs , ** kwargs ) Message = MessageType ( '' , '' , '' , '' ) UnusedImport = MessageType ( '' , '' , '' ) ", "answer": "RedefinedWhileUnused = MessageType ( '' , '' ,"}, {"prompt": " import itertools import mock import six from openstack import exceptions from openstack import format from openstack import resource2 from openstack import session from openstack . tests . unit import base class TestComponent ( base . TestCase ) : class ExampleComponent ( resource2 . _BaseComponent ) : key = \"\" def test_implementations ( self ) : self . assertEqual ( \"\" , resource2 . Body . key ) self . assertEqual ( \"\" , resource2 . Header . key ) self . assertEqual ( \"\" , resource2 . URI . key ) def test_creation ( self ) : sot = resource2 . _BaseComponent ( \"\" , type = int , default = , alternate_id = True ) self . assertEqual ( \"\" , sot . name ) self . assertEqual ( int , sot . type ) self . assertEqual ( , sot . default ) self . assertTrue ( sot . alternate_id ) def test_get_no_instance ( self ) : sot = resource2 . _BaseComponent ( \"\" ) result = sot . __get__ ( None , None ) self . assertIsNone ( result ) def test_get_name_None ( self ) : name = \"\" class Parent ( object ) : _example = { name : None } instance = Parent ( ) sot = TestComponent . ExampleComponent ( name , default = ) result = sot . __get__ ( instance , None ) self . assertIsNone ( result ) def test_get_default ( self ) : expected_result = class Parent ( object ) : _example = { } instance = Parent ( ) sot = TestComponent . ExampleComponent ( \"\" , type = dict , default = expected_result ) result = sot . __get__ ( instance , None ) self . assertEqual ( expected_result , result ) def test_get_name_untyped ( self ) : name = \"\" expected_result = class Parent ( object ) : _example = { name : expected_result } instance = Parent ( ) sot = TestComponent . ExampleComponent ( \"\" ) result = sot . __get__ ( instance , None ) self . assertEqual ( expected_result , result ) def test_get_name_typed ( self ) : name = \"\" value = \"\" class Parent ( object ) : _example = { name : value } instance = Parent ( ) sot = TestComponent . ExampleComponent ( \"\" , type = int ) result = sot . __get__ ( instance , None ) self . assertEqual ( int ( value ) , result ) def test_get_name_formatter ( self ) : name = \"\" value = \"\" expected_result = \"\" class Parent ( object ) : _example = { name : value } class FakeFormatter ( object ) : @ classmethod def deserialize ( cls , value ) : return expected_result instance = Parent ( ) sot = TestComponent . ExampleComponent ( \"\" , type = FakeFormatter ) mock_issubclass = mock . Mock ( return_value = True ) module = six . moves . builtins . __name__ with mock . patch ( \"\" % module , mock_issubclass ) : result = sot . __get__ ( instance , None ) self . assertEqual ( expected_result , result ) def test_set_name_untyped ( self ) : name = \"\" expected_value = \"\" class Parent ( object ) : _example = { } instance = Parent ( ) sot = TestComponent . ExampleComponent ( \"\" ) sot . __set__ ( instance , expected_value ) self . assertEqual ( expected_value , instance . _example [ name ] ) def test_set_name_typed ( self ) : expected_value = \"\" class Parent ( object ) : _example = { } instance = Parent ( ) class FakeType ( object ) : calls = [ ] def __init__ ( self , arg ) : FakeType . calls . append ( arg ) sot = TestComponent . ExampleComponent ( \"\" , type = FakeType ) sot . __set__ ( instance , expected_value ) self . assertEqual ( [ expected_value ] , FakeType . calls ) def test_set_name_formatter ( self ) : expected_value = \"\" class Parent ( object ) : _example = { } instance = Parent ( ) class FakeFormatter ( format . Formatter ) : calls = [ ] @ classmethod def serialize ( cls , arg ) : FakeFormatter . calls . append ( arg ) sot = TestComponent . ExampleComponent ( \"\" , type = FakeFormatter ) sot . __set__ ( instance , expected_value ) self . assertEqual ( [ expected_value ] , FakeFormatter . calls ) def test_delete_name ( self ) : name = \"\" expected_value = \"\" class Parent ( object ) : _example = { name : expected_value } instance = Parent ( ) sot = TestComponent . ExampleComponent ( \"\" ) sot . __delete__ ( instance ) self . assertNotIn ( name , instance . _example ) def test_delete_name_doesnt_exist ( self ) : name = \"\" expected_value = \"\" class Parent ( object ) : _example = { \"\" : expected_value } instance = Parent ( ) sot = TestComponent . ExampleComponent ( name ) sot . __delete__ ( instance ) self . assertNotIn ( name , instance . _example ) class TestComponentManager ( base . TestCase ) : def test_create_basic ( self ) : sot = resource2 . _ComponentManager ( ) self . assertEqual ( dict ( ) , sot . attributes ) self . assertEqual ( set ( ) , sot . _dirty ) def test_create_unsynced ( self ) : attrs = { \"\" : , \"\" : , \"\" : } sync = False sot = resource2 . _ComponentManager ( attributes = attrs , synchronized = sync ) self . assertEqual ( attrs , sot . attributes ) self . assertEqual ( set ( attrs . keys ( ) ) , sot . _dirty ) def test_create_synced ( self ) : attrs = { \"\" : , \"\" : , \"\" : } sync = True sot = resource2 . _ComponentManager ( attributes = attrs , synchronized = sync ) self . assertEqual ( attrs , sot . attributes ) self . assertEqual ( set ( ) , sot . _dirty ) def test_getitem ( self ) : key = \"\" value = \"\" attrs = { key : value } sot = resource2 . _ComponentManager ( attributes = attrs ) self . assertEqual ( value , sot . __getitem__ ( key ) ) def test_setitem_new ( self ) : key = \"\" value = \"\" sot = resource2 . _ComponentManager ( ) sot . __setitem__ ( key , value ) self . assertIn ( key , sot . attributes ) self . assertIn ( key , sot . dirty ) def test_setitem_unchanged ( self ) : key = \"\" value = \"\" attrs = { key : value } sot = resource2 . _ComponentManager ( attributes = attrs , synchronized = True ) sot . __setitem__ ( key , value ) self . assertEqual ( value , sot . attributes [ key ] ) self . assertNotIn ( key , sot . dirty ) def test_delitem ( self ) : key = \"\" value = \"\" attrs = { key : value } sot = resource2 . _ComponentManager ( attributes = attrs , synchronized = True ) sot . __delitem__ ( key ) self . assertIsNone ( sot . dirty [ key ] ) def test_iter ( self ) : attrs = { \"\" : \"\" } sot = resource2 . _ComponentManager ( attributes = attrs ) self . assertItemsEqual ( iter ( attrs ) , sot . __iter__ ( ) ) def test_len ( self ) : attrs = { \"\" : \"\" } sot = resource2 . _ComponentManager ( attributes = attrs ) self . assertEqual ( len ( attrs ) , sot . __len__ ( ) ) def test_dirty ( self ) : key = \"\" key2 = \"\" value = \"\" attrs = { key : value } sot = resource2 . _ComponentManager ( attributes = attrs , synchronized = False ) self . assertEqual ( { key : value } , sot . dirty ) sot . __setitem__ ( key2 , value ) self . assertEqual ( { key : value , key2 : value } , sot . dirty ) def test_clean ( self ) : key = \"\" value = \"\" attrs = { key : value } sot = resource2 . _ComponentManager ( attributes = attrs , synchronized = False ) self . assertEqual ( attrs , sot . dirty ) sot . clean ( ) self . assertEqual ( dict ( ) , sot . dirty ) class Test_Request ( base . TestCase ) : def test_create ( self ) : uri = body = headers = sot = resource2 . _Request ( uri , body , headers ) self . assertEqual ( uri , sot . uri ) self . assertEqual ( body , sot . body ) self . assertEqual ( headers , sot . headers ) class TestQueryParameters ( base . TestCase ) : def test_create ( self ) : location = \"\" mapping = { \"\" : \"\" } sot = resource2 . QueryParameters ( location , ** mapping ) self . assertEqual ( { \"\" : \"\" , \"\" : \"\" } , sot . _mapping ) def test_transpose_unmapped ( self ) : location = \"\" mapping = { \"\" : \"\" } sot = resource2 . QueryParameters ( location , ** mapping ) result = sot . _transpose ( { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" } ) self . assertEqual ( { \"\" : \"\" , \"\" : \"\" } , result ) def test_transpose_not_in_query ( self ) : location = \"\" mapping = { \"\" : \"\" } sot = resource2 . QueryParameters ( location , ** mapping ) result = sot . _transpose ( { \"\" : \"\" } ) self . assertEqual ( { \"\" : \"\" } , result ) class TestResource ( base . TestCase ) : def test_initialize_basic ( self ) : body = { \"\" : } header = { \"\" : } uri = { \"\" : } everything = dict ( itertools . chain ( body . items ( ) , header . items ( ) , uri . items ( ) ) ) mock_collect = mock . Mock ( ) mock_collect . return_value = body , header , uri with mock . patch . object ( resource2 . Resource , \"\" , mock_collect ) : sot = resource2 . Resource ( synchronized = False , ** everything ) mock_collect . assert_called_once_with ( everything ) self . assertIsInstance ( sot . _body , resource2 . _ComponentManager ) self . assertEqual ( body , sot . _body . dirty ) self . assertIsInstance ( sot . _header , resource2 . _ComponentManager ) self . assertEqual ( header , sot . _header . dirty ) self . assertIsInstance ( sot . _uri , resource2 . _ComponentManager ) self . assertEqual ( uri , sot . _uri . dirty ) self . assertFalse ( sot . allow_create ) self . assertFalse ( sot . allow_get ) self . assertFalse ( sot . allow_update ) self . assertFalse ( sot . allow_delete ) self . assertFalse ( sot . allow_list ) self . assertFalse ( sot . allow_head ) self . assertFalse ( sot . patch_update ) def test_repr ( self ) : a = { \"\" : } b = { \"\" : } c = { \"\" : } class Test ( resource2 . Resource ) : def __init__ ( self ) : self . _body = mock . Mock ( ) self . _body . attributes . items = mock . Mock ( return_value = a . items ( ) ) self . _header = mock . Mock ( ) self . _header . attributes . items = mock . Mock ( return_value = b . items ( ) ) self . _uri = mock . Mock ( ) self . _uri . attributes . items = mock . Mock ( return_value = c . items ( ) ) the_repr = repr ( Test ( ) ) self . assertIn ( \"\" , the_repr ) self . assertIn ( \"\" , the_repr ) self . assertIn ( \"\" , the_repr ) self . assertIn ( \"\" , the_repr ) def test__update ( self ) : sot = resource2 . Resource ( ) body = \"\" header = \"\" uri = \"\" sot . _collect_attrs = mock . Mock ( return_value = ( body , header , uri ) ) sot . _body . update = mock . Mock ( ) sot . _header . update = mock . Mock ( ) sot . _uri . update = mock . Mock ( ) args = { \"\" : } sot . _update ( ** args ) sot . _collect_attrs . assert_called_once_with ( args ) sot . _body . update . assert_called_once_with ( body ) sot . _header . update . assert_called_once_with ( header ) sot . _uri . update . assert_called_once_with ( uri ) def test__collect_attrs ( self ) : sot = resource2 . Resource ( ) expected_attrs = [ \"\" , \"\" , \"\" ] sot . _consume_attrs = mock . Mock ( ) sot . _consume_attrs . side_effect = expected_attrs actual_attrs = sot . _collect_attrs ( dict ( ) ) self . assertItemsEqual ( expected_attrs , actual_attrs ) def test__consume_attrs ( self ) : serverside_key1 = \"\" clientside_key1 = \"\" serverside_key2 = \"\" clientside_key2 = \"\" value1 = \"\" value2 = \"\" mapping = { clientside_key1 : serverside_key1 , clientside_key2 : serverside_key2 } other_key = \"\" other_value = \"\" attrs = { clientside_key1 : value1 , serverside_key2 : value2 , other_key : other_value } sot = resource2 . Resource ( ) result = sot . _consume_attrs ( mapping , attrs ) self . assertDictEqual ( { other_key : other_value } , attrs ) self . assertDictEqual ( { serverside_key1 : value1 , serverside_key2 : value2 } , result ) def test__mapping_defaults ( self ) : self . assertIn ( \"\" , resource2 . Resource . _header_mapping ( ) ) self . assertIn ( \"\" , resource2 . Resource . _body_mapping ( ) ) self . assertIn ( \"\" , resource2 . Resource . _body_mapping ( ) ) def test__mapping_overrides ( self ) : new_name = \"\" new_id = \"\" class Test ( resource2 . Resource ) : name = resource2 . Body ( new_name ) id = resource2 . Body ( new_id ) mapping = Test . _body_mapping ( ) self . assertEqual ( new_name , mapping [ \"\" ] ) self . assertEqual ( new_id , mapping [ \"\" ] ) def test__body_mapping ( self ) : class Test ( resource2 . Resource ) : x = resource2 . Body ( \"\" ) y = resource2 . Body ( \"\" ) z = resource2 . Body ( \"\" ) self . assertIn ( \"\" , Test . _body_mapping ( ) ) self . assertIn ( \"\" , Test . _body_mapping ( ) ) self . assertIn ( \"\" , Test . _body_mapping ( ) ) def test__header_mapping ( self ) : class Test ( resource2 . Resource ) : x = resource2 . Header ( \"\" ) y = resource2 . Header ( \"\" ) z = resource2 . Header ( \"\" ) self . assertIn ( \"\" , Test . _header_mapping ( ) ) self . assertIn ( \"\" , Test . _header_mapping ( ) ) self . assertIn ( \"\" , Test . _header_mapping ( ) ) def test__uri_mapping ( self ) : class Test ( resource2 . Resource ) : x = resource2 . URI ( \"\" ) y = resource2 . URI ( \"\" ) z = resource2 . URI ( \"\" ) self . assertIn ( \"\" , Test . _uri_mapping ( ) ) self . assertIn ( \"\" , Test . _uri_mapping ( ) ) self . assertIn ( \"\" , Test . _uri_mapping ( ) ) def test__alternate_id_None ( self ) : self . assertEqual ( \"\" , resource2 . Resource . _alternate_id ( ) ) def test__alternate_id ( self ) : class Test ( resource2 . Resource ) : alt = resource2 . Body ( \"\" , alternate_id = True ) self . assertTrue ( \"\" , Test . _alternate_id ( ) ) def test__get_id_instance ( self ) : class Test ( resource2 . Resource ) : id = resource2 . Body ( \"\" ) value = \"\" sot = Test ( id = value ) self . assertEqual ( value , sot . _get_id ( sot ) ) def test__get_id_instance_alternate ( self ) : class Test ( resource2 . Resource ) : attr = resource2 . Body ( \"\" , alternate_id = True ) value = \"\" sot = Test ( attr = value ) self . assertEqual ( value , sot . _get_id ( sot ) ) def test__get_id_value ( self ) : value = \"\" self . assertEqual ( value , resource2 . Resource . _get_id ( value ) ) def test_new ( self ) : class Test ( resource2 . Resource ) : attr = resource2 . Body ( \"\" ) value = \"\" sot = Test . new ( attr = value ) self . assertIn ( \"\" , sot . _body . dirty ) self . assertEqual ( value , sot . attr ) def test_existing ( self ) : class Test ( resource2 . Resource ) : attr = resource2 . Body ( \"\" ) value = \"\" sot = Test . existing ( attr = value ) self . assertNotIn ( \"\" , sot . _body . dirty ) self . assertEqual ( value , sot . attr ) def test__prepare_request_with_id ( self ) : class Test ( resource2 . Resource ) : base_path = \"\" body_attr = resource2 . Body ( \"\" ) header_attr = resource2 . Header ( \"\" ) the_id = \"\" body_value = \"\" header_value = \"\" sot = Test ( id = the_id , body_attr = body_value , header_attr = header_value , synchronized = False ) result = sot . _prepare_request ( requires_id = True ) self . assertEqual ( \"\" , result . uri ) self . assertEqual ( { \"\" : body_value , \"\" : the_id } , result . body ) self . assertEqual ( { \"\" : header_value } , result . headers ) def test__prepare_request_missing_id ( self ) : sot = resource2 . Resource ( id = None ) self . assertRaises ( exceptions . InvalidRequest , sot . _prepare_request , requires_id = True ) def test__prepare_request_with_key ( self ) : key = \"\" class Test ( resource2 . Resource ) : base_path = \"\" resource_key = key body_attr = resource2 . Body ( \"\" ) header_attr = resource2 . Header ( \"\" ) body_value = \"\" header_value = \"\" sot = Test ( body_attr = body_value , header_attr = header_value , synchronized = False ) result = sot . _prepare_request ( requires_id = False , prepend_key = True ) self . assertEqual ( \"\" , result . uri ) self . assertEqual ( { key : { \"\" : body_value } } , result . body ) self . assertEqual ( { \"\" : header_value } , result . headers ) def test__transpose_component ( self ) : client_name = \"\" server_name = \"\" value = \"\" mapping = { client_name : server_name , \"\" : \"\" } component = { server_name : value } sot = resource2 . Resource ( ) result = sot . _transpose_component ( component , mapping ) self . assertEqual ( { client_name : value } , result ) def test__translate_response_no_body ( self ) : class Test ( resource2 . Resource ) : attr = resource2 . Header ( \"\" ) response = mock . Mock ( ) response . headers = dict ( ) sot = Test ( ) sot . _transpose_component = mock . Mock ( return_value = { \"\" : \"\" } ) sot . _translate_response ( response , has_body = False ) self . assertEqual ( dict ( ) , sot . _header . dirty ) self . assertEqual ( \"\" , sot . attr ) def test__translate_response_with_body_no_resource_key ( self ) : class Test ( resource2 . Resource ) : attr = resource2 . Body ( \"\" ) body = { \"\" : \"\" } response = mock . Mock ( ) response . headers = dict ( ) response . json . return_value = body sot = Test ( ) sot . _transpose_component = mock . Mock ( side_effect = [ body , dict ( ) ] ) sot . _translate_response ( response , has_body = True ) self . assertEqual ( \"\" , sot . attr ) self . assertEqual ( dict ( ) , sot . _body . dirty ) self . assertEqual ( dict ( ) , sot . _header . dirty ) def test__translate_response_with_body_with_resource_key ( self ) : key = \"\" class Test ( resource2 . Resource ) : resource_key = key attr = resource2 . Body ( \"\" ) body = { \"\" : \"\" } response = mock . Mock ( ) response . headers = dict ( ) response . json . return_value = { key : body } sot = Test ( ) sot . _transpose_component = mock . Mock ( side_effect = [ body , dict ( ) ] ) sot . _translate_response ( response , has_body = True ) self . assertEqual ( \"\" , sot . attr ) self . assertEqual ( dict ( ) , sot . _body . dirty ) self . assertEqual ( dict ( ) , sot . _header . dirty ) def test_cant_do_anything ( self ) : class Test ( resource2 . Resource ) : allow_create = False allow_get = False allow_update = False allow_delete = False allow_head = False allow_list = False sot = Test ( ) self . assertRaises ( exceptions . MethodNotSupported , sot . create , \"\" ) self . assertRaises ( exceptions . MethodNotSupported , sot . get , \"\" ) self . assertRaises ( exceptions . MethodNotSupported , sot . delete , \"\" ) self . assertRaises ( exceptions . MethodNotSupported , sot . head , \"\" ) the_list = sot . list ( \"\" ) self . assertRaises ( exceptions . MethodNotSupported , next , the_list ) sot . _body = mock . Mock ( ) sot . _body . dirty = mock . Mock ( return_value = { \"\" : \"\" } ) self . assertRaises ( exceptions . MethodNotSupported , sot . update , \"\" ) class TestResourceActions ( base . TestCase ) : def setUp ( self ) : super ( TestResourceActions , self ) . setUp ( ) self . service_name = \"\" self . base_path = \"\" class Test ( resource2 . Resource ) : service = self . service_name base_path = self . base_path allow_create = True allow_get = True allow_head = True allow_update = True allow_delete = True allow_list = True self . test_class = Test self . request = mock . Mock ( spec = resource2 . _Request ) self . request . uri = \"\" self . request . body = \"\" self . request . headers = \"\" self . response = mock . Mock ( ) self . sot = Test ( id = \"\" ) self . sot . _prepare_request = mock . Mock ( return_value = self . request ) self . sot . _translate_response = mock . Mock ( ) self . session = mock . Mock ( spec = session . Session ) self . session . create = mock . Mock ( return_value = self . response ) self . session . get = mock . Mock ( return_value = self . response ) self . session . put = mock . Mock ( return_value = self . response ) self . session . patch = mock . Mock ( return_value = self . response ) self . session . post = mock . Mock ( return_value = self . response ) self . session . delete = mock . Mock ( return_value = self . response ) self . session . head = mock . Mock ( return_value = self . response ) def _test_create ( self , requires_id = False , prepend_key = False ) : if not requires_id : self . sot . id = None result = self . sot . create ( self . session ) self . sot . _prepare_request . assert_called_once_with ( requires_id = requires_id , prepend_key = prepend_key ) if requires_id : self . session . put . assert_called_once_with ( self . request . uri , endpoint_filter = self . service_name , json = self . request . body , headers = self . request . headers ) else : self . session . post . assert_called_once_with ( self . request . uri , endpoint_filter = self . service_name , json = self . request . body , headers = self . request . headers ) self . sot . _translate_response . assert_called_once_with ( self . response ) self . assertEqual ( result , self . sot ) def test_create_with_id ( self ) : self . _test_create ( requires_id = True , prepend_key = True ) def test_create_without_id ( self ) : self . _test_create ( requires_id = False , prepend_key = True ) def test_get ( self ) : result = self . sot . get ( self . session ) self . sot . _prepare_request . assert_called_once_with ( ) self . session . get . assert_called_once_with ( self . request . uri , endpoint_filter = self . service_name ) self . sot . _translate_response . assert_called_once_with ( self . response ) self . assertEqual ( result , self . sot ) def test_head ( self ) : result = self . sot . head ( self . session ) self . sot . _prepare_request . assert_called_once_with ( ) self . session . head . assert_called_once_with ( self . request . uri , endpoint_filter = self . service_name , headers = { \"\" : \"\" } ) self . sot . _translate_response . assert_called_once_with ( self . response ) self . assertEqual ( result , self . sot ) def _test_update ( self , patch_update = False ) : self . sot . patch_update = patch_update self . sot . _body = mock . Mock ( ) self . sot . _body . dirty = mock . Mock ( return_value = { \"\" : \"\" } ) result = self . sot . update ( self . session ) self . sot . _prepare_request . assert_called_once_with ( prepend_key = True ) if patch_update : self . session . patch . assert_called_once_with ( self . request . uri , endpoint_filter = self . service_name , json = self . request . body , headers = self . request . headers ) else : self . session . put . assert_called_once_with ( self . request . uri , endpoint_filter = self . service_name , json = self . request . body , headers = self . request . headers ) self . sot . _translate_response . assert_called_once_with ( self . response ) self . assertEqual ( result , self . sot ) def test_update_put ( self ) : self . _test_update ( patch_update = False ) def test_update_patch ( self ) : self . _test_update ( patch_update = True ) def test_update_not_dirty ( self ) : self . sot . _body = mock . Mock ( ) self . sot . _body . dirty = dict ( ) self . sot . _header = mock . Mock ( ) self . sot . _header . dirty = dict ( ) result = self . sot . update ( self . session ) self . assertEqual ( result , self . sot ) self . session . put . assert_not_called ( ) def test_delete ( self ) : result = self . sot . delete ( self . session ) self . sot . _prepare_request . assert_called_once_with ( ) self . session . delete . assert_called_once_with ( self . request . uri , endpoint_filter = self . service_name , headers = { \"\" : \"\" } ) self . sot . _translate_response . assert_called_once_with ( self . response , has_body = False ) self . assertEqual ( result , self . sot ) def test_list_empty_response ( self ) : mock_response = mock . Mock ( ) mock_response . json . return_value = [ ] self . session . get . return_value = mock_response result = list ( self . sot . list ( self . session ) ) self . session . get . assert_called_once_with ( self . base_path , ", "answer": "endpoint_filter = self . service_name ,"}, {"prompt": " '''''' __all__ = [ '' , '' , '' , '' , '' , '' ] from . service import OAuth1Service , OAuth2Service , OflyService from . session import OAuth1Session , OAuth2Session , OflySession from . __about__ import ( __title__ , __version_info__ , __version__ , __author__ , __license__ , __copyright__ ) ", "answer": "( __title__ , __version_info__ , __version__ , __author__ , __license__ ,"}, {"prompt": " VERSION = ( , , , \"\" , ) def get_version ( ) : if VERSION [ ] == \"\" : return \"\" % ( VERSION [ ] , VERSION [ ] , VERSION [ ] ) elif VERSION [ ] == \"\" : if VERSION [ ] == : return \"\" % ( VERSION [ ] , VERSION [ ] , VERSION [ ] , VERSION [ ] ) ", "answer": "return \"\" % ( VERSION [ ] , VERSION [ ] , VERSION [ ] , VERSION [ ] , VERSION [ ] )"}, {"prompt": " \"\"\"\"\"\" import os . path as op import sys import logging from collections import defaultdict from jcvi . formats . base import BaseFile , must_open from jcvi . formats . fasta import gaps from jcvi . formats . sizes import Sizes from jcvi . formats . posmap import query , bed from jcvi . formats . bed import BedLine , sort from jcvi . apps . base import OptionParser , ActionDispatcher , sh , need_update class Coverage ( BaseFile ) : \"\"\"\"\"\" def __init__ ( self , bedfile , sizesfile ) : bedfile = sort ( [ bedfile ] ) coveragefile = bedfile + \"\" if need_update ( bedfile , coveragefile ) : cmd = \"\" cmd += \"\" . format ( bedfile , sizesfile ) sh ( cmd , outfile = coveragefile ) self . sizes = Sizes ( sizesfile ) . mapping filename = coveragefile assert filename . endswith ( \"\" ) super ( Coverage , self ) . __init__ ( filename ) def get_plot_data ( self , ctg , bins = None ) : import numpy as np from jcvi . algorithms . matrix import chunk_average fp = open ( self . filename ) size = self . sizes [ ctg ] data = np . zeros ( ( size , ) , dtype = np . int ) for row in fp : seqid , start , end , cov = row . split ( ) if seqid != ctg : continue start , end = int ( start ) , int ( end ) cov = int ( cov ) data [ start : end ] = cov bases = np . arange ( , size + ) if bins : window = size / bins bases = bases [ : : window ] data = chunk_average ( data , window ) return bases , data def main ( ) : actions = ( ( '' , '' ) , ) p = ActionDispatcher ( actions ) p . dispatch ( globals ( ) ) def clone_name ( s , ca = False ) : \"\"\"\"\"\" if not ca : return s [ : - ] if s [ ] == '' : ", "answer": "return s [ : ]"}, {"prompt": " from . chemparser import chemparse from . physical_constants import ( R_ELECTRON_CM , AVOGADRO , BARN , PLANCK_HC , RAD2DEG ) from . xraydb import xrayDB from . xraydb_plugin import ( atomic_mass , atomic_number , atomic_symbol , atomic_density , ", "answer": "xray_line , xray_lines , xray_edge ,"}, {"prompt": " \"\"\"\"\"\" from __future__ import division , absolute_import from twisted . names import dns , common from twisted . python import failure , log from twisted . internet import defer class CacheResolver ( common . ResolverBase ) : \"\"\"\"\"\" cache = None def __init__ ( self , cache = None , verbose = , reactor = None ) : common . ResolverBase . __init__ ( self ) self . cache = { } self . verbose = verbose self . cancel = { } if reactor is None : from twisted . internet import reactor self . _reactor = reactor if cache : for query , ( seconds , payload ) in cache . items ( ) : self . cacheResult ( query , payload , seconds ) def __setstate__ ( self , state ) : self . __dict__ = state now = self . _reactor . seconds ( ) for ( k , ( when , ( ans , add , ns ) ) ) in self . cache . items ( ) : diff = now - when for rec in ans + add + ns : if rec . ttl < diff : del self . cache [ k ] break def __getstate__ ( self ) : for c in self . cancel . values ( ) : c . cancel ( ) self . cancel . clear ( ) return self . __dict__ def _lookup ( self , name , cls , type , timeout ) : now = self . _reactor . seconds ( ) q = dns . Query ( name , type , cls ) try : when , ( ans , auth , add ) = self . cache [ q ] except KeyError : if self . verbose > : log . msg ( '' + repr ( name ) ) return defer . fail ( failure . Failure ( dns . DomainError ( name ) ) ) else : if self . verbose : log . msg ( '' + repr ( name ) ) diff = now - when try : result = ( [ dns . RRHeader ( r . name . name , r . type , r . cls , r . ttl - diff , r . payload ) for r in ans ] , [ dns . RRHeader ( r . name . name , r . type , r . cls , r . ttl - diff , r . payload ) for r in auth ] , [ dns . RRHeader ( r . name . name , r . type , r . cls , r . ttl - diff , r . payload ) for r in add ] ) except ValueError : return defer . fail ( failure . Failure ( dns . DomainError ( name ) ) ) else : return defer . succeed ( result ) def lookupAllRecords ( self , name , timeout = None ) : return defer . fail ( failure . Failure ( dns . DomainError ( name ) ) ) ", "answer": "def cacheResult ( self , query , payload , cacheTime = None ) :"}, {"prompt": " from pypy . rpython . ootypesystem . ootype import Signed , Record , new from pypy . rpython . rrange import AbstractRangeRepr , AbstractRangeIteratorRepr RANGE = Record ( { \"\" : Signed , \"\" : Signed } ) RANGEITER = Record ( { \"\" : Signed , \"\" : Signed } ) RANGEST = Record ( { \"\" : Signed , \"\" : Signed , \"\" : Signed } ) RANGESTITER = Record ( { \"\" : Signed , \"\" : Signed , \"\" : Signed } ) class RangeRepr ( AbstractRangeRepr ) : RANGE = RANGE RANGEITER = RANGEITER ", "answer": "RANGEST = RANGEST"}, {"prompt": " import os from os . path import join as pjoin , normpath , exists as pexists , dirname import subprocess from shutil import rmtree , move as shmove import re from zipfile import ZipFile from lib import get_svn_version , get_scipy_version BUILD_MSI = False SRC_ROOT = normpath ( pjoin ( os . getcwd ( ) , os . pardir , os . pardir , os . pardir ) ) BUILD_ROOT = os . getcwd ( ) PYVER = '' ARCH = '' PYEXECS = { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" } _SSE3_CFG = r\"\"\"\"\"\" _SSE2_CFG = r\"\"\"\"\"\" _NOSSE_CFG = r\"\"\"\"\"\" SITECFG = { \"\" : _SSE2_CFG , \"\" : _SSE3_CFG , \"\" : _NOSSE_CFG } options ( clean = Bunch ( src_dir = SRC_ROOT , pyver = PYVER ) , clean_bootstrap = Bunch ( src_dir = SRC_ROOT , pyver = PYVER ) , build_sdist = Bunch ( src_dir = SRC_ROOT ) , build_binary = Bunch ( pyver = PYVER , arch = ARCH , src_root = SRC_ROOT ) , bootstrap = Bunch ( pyver = PYVER , src_root = SRC_ROOT ) , bootstrap_arch = Bunch ( pyver = PYVER , arch = ARCH ) , bootstrap_nsis = Bunch ( pyver = PYVER , src_root = SRC_ROOT ) ) @ task def clean ( ) : raw_clean ( options . src_dir , options . pyver ) @ task def clean_bootstrap ( ) : raw_clean_bootstrap ( options . pyver ) @ task def build_sdist ( ) : raw_build_sdist ( options . src_dir ) @ task @ needs ( '' ) def bootstrap ( ) : raw_bootstrap ( options . pyver , options . src_dir ) @ task def bootstrap_arch ( ) : pyver = options . pyver arch = options . arch set_bootstrap_sources ( arch , pyver ) @ task def bootstrap_nsis ( ) : pyver = options . pyver bdir = bootstrap_dir ( options . pyver ) prepare_nsis_script ( bdir , pyver , get_scipy_version ( options . src_root ) ) @ task def build_binary ( ) : pyver = options . pyver arch = options . arch raw_build_arch ( pyver , arch , options . src_root ) @ task @ needs ( '' ) @ needs ( '' ) def build_nsis ( ) : scipy_verstr = get_scipy_version ( options . src_root ) bdir = bootstrap_dir ( options . pyver ) prepare_nsis_script ( bdir , options . pyver , scipy_verstr ) for arch in [ '' , '' , '' ] : raw_clean_bootstrap ( options . pyver ) set_bootstrap_sources ( arch , options . pyver ) raw_build_arch ( options . pyver , arch , options . src_root ) raw_build_nsis ( options . pyver ) def set_bootstrap_sources ( arch , pyver ) : bdir = bootstrap_dir ( pyver ) write_site_cfg ( arch , cwd = bdir ) def get_sdist_tarball ( src_root ) : \"\"\"\"\"\" name = \"\" % get_scipy_version ( src_root ) return name def prepare_scipy_sources ( src_root , bootstrap ) : zid = ZipFile ( pjoin ( src_root , '' , get_sdist_tarball ( src_root ) ) ) root = '' % get_scipy_version ( src_root ) for name in zid . namelist ( ) : cnt = zid . read ( name ) if name . startswith ( root ) : name = name . split ( '' , ) [ ] newname = pjoin ( bootstrap , name ) if not pexists ( dirname ( newname ) ) : os . makedirs ( dirname ( newname ) ) fid = open ( newname , '' ) fid . write ( cnt ) def prepare_nsis_script ( bdir , pyver , numver ) : tpl = pjoin ( '' , '' ) source = open ( tpl , '' ) target = open ( pjoin ( bdir , '' ) , '' ) installer_name = '' % ( numver , pyver ) cnt = \"\" . join ( source . readlines ( ) ) cnt = cnt . replace ( '' , installer_name ) for arch in [ '' , '' , '' ] : cnt = cnt . replace ( '' % arch . upper ( ) , get_binary_name ( arch , numver ) ) target . write ( cnt ) def bootstrap_dir ( pyver ) : return pjoin ( BUILD_ROOT , \"\" % pyver ) def get_python_exec ( ver ) : \"\"\"\"\"\" try : return PYEXECS [ ver ] except KeyError : raise ValueError ( \"\" % ver ) def write_site_cfg ( arch , cwd = None ) : if not cwd : ", "answer": "cwd = os . getcwd ( )"}, {"prompt": " from __future__ import absolute_import __author__ = '' from enum import IntEnum from . base import PebblePacket from . base . types import * __all__ = [ \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ] class AppMessageTuple ( PebblePacket ) : \"\"\"\"\"\" class Type ( IntEnum ) : ByteArray = CString = Uint = Int = key = Uint32 ( ) type = Uint8 ( ) length = Uint16 ( ) data = BinaryArray ( length = length ) class AppMessagePush ( PebblePacket ) : ", "answer": "uuid = UUID ( )"}, {"prompt": " from xml . etree import ElementTree from xml . parsers . expat import ExpatError from django . utils import six from allauth . socialaccount import providers from allauth . socialaccount . providers . oauth . client import OAuth from allauth . socialaccount . providers . oauth . views import ( OAuthAdapter , OAuthLoginView , OAuthCallbackView ) from . provider import LinkedInProvider class LinkedInAPI ( OAuth ) : url = '' def get_user_info ( self ) : fields = providers . registry . by_id ( LinkedInProvider . id ) . get_profile_fields ( ) url = self . url + '' % '' . join ( fields ) raw_xml = self . query ( url ) if not six . PY3 : raw_xml = raw_xml . encode ( '' ) try : return self . to_dict ( ElementTree . fromstring ( raw_xml ) ) except ( ExpatError , KeyError , IndexError ) : return None def to_dict ( self , xml ) : \"\"\"\"\"\" children = list ( xml ) if not children : return xml . text else : out = { } for node in list ( xml ) : if node . tag in out : if not isinstance ( out [ node . tag ] , list ) : out [ node . tag ] = [ out [ node . tag ] ] ", "answer": "out [ node . tag ] . append ( self . to_dict ( node ) )"}, {"prompt": " from pypy . rpython . lltypesystem . llmemory import * from pypy . rpython . lltypesystem import lltype from pypy . rpython . test . test_llinterp import interpret import py def test_simple ( ) : S = lltype . GcStruct ( \"\" , ( \"\" , lltype . Signed ) , ( \"\" , lltype . Signed ) ) s = lltype . malloc ( S ) s . x = s . y = a = fakeaddress ( s ) assert a . ref ( ) == s b = a + FieldOffset ( S , '' ) assert b . signed [ ] == b . signed [ ] = assert s . x == def test_simple_float ( ) : S = lltype . GcStruct ( \"\" , ( \"\" , lltype . Float ) , ( \"\" , lltype . Float ) ) s = lltype . malloc ( S ) s . x = s . y = a = fakeaddress ( s ) assert a . ref ( ) == s b = a + FieldOffset ( S , '' ) assert b . float [ ] == b . float [ ] = assert s . x == def test_composite ( ) : S1 = lltype . GcStruct ( \"\" , ( \"\" , lltype . Signed ) , ( \"\" , lltype . Signed ) ) S2 = lltype . GcStruct ( \"\" , ( \"\" , S1 ) ) s2 = lltype . malloc ( S2 ) s2 . s . x = s2 . s . y = a = fakeaddress ( s2 ) assert a . ref ( ) == s2 b = a + FieldOffset ( S2 , '' ) + FieldOffset ( S1 , '' ) assert b . signed [ ] == b . signed [ ] = assert s2 . s . x == def test_array ( ) : A = lltype . GcArray ( lltype . Signed ) x = lltype . malloc ( A , ) x [ ] = a = fakeaddress ( x ) b = a + ArrayItemsOffset ( A ) b += ItemOffset ( lltype . Signed ) * b += ItemOffset ( lltype . Signed ) assert b . signed [ ] == b . signed [ ] = assert x [ ] == def test_array_endaddress ( ) : A = lltype . GcArray ( lltype . Signed ) x = lltype . malloc ( A , ) x [ ] = a = fakeaddress ( x ) b = a + ArrayItemsOffset ( A ) b += ItemOffset ( lltype . Signed ) * assert b == a + ArrayItemsOffset ( A ) + ItemOffset ( lltype . Signed ) * py . test . raises ( IndexError , \"\" ) b -= ItemOffset ( lltype . Signed ) assert b . signed [ ] == def test_structarray_endaddress ( ) : S = lltype . Struct ( '' , ( '' , lltype . Signed ) ) A = lltype . GcArray ( S ) x = lltype . malloc ( A , ) x [ ] . foo = a = fakeaddress ( x ) b = a + ArrayItemsOffset ( A ) b += ItemOffset ( S ) * assert b == a + ArrayItemsOffset ( A ) + ItemOffset ( S ) * p = cast_adr_to_ptr ( b , lltype . Ptr ( S ) ) py . test . raises ( AttributeError , \"\" ) py . test . raises ( AttributeError , \"\" ) b -= ItemOffset ( S ) p = cast_adr_to_ptr ( b , lltype . Ptr ( S ) ) assert p . foo == def test_dont_mix_offsets_and_ints ( ) : o = AddressOffset ( ) py . test . raises ( TypeError , \"\" ) py . test . raises ( TypeError , \"\" ) def test_sizeof ( ) : array = lltype . Array ( lltype . Signed ) struct = lltype . Struct ( \"\" , ( '' , lltype . Signed ) ) varstruct = lltype . Struct ( \"\" , ( '' , lltype . Signed ) , ( '' , array ) ) sizeof ( struct ) sizeof ( lltype . Signed ) py . test . raises ( AssertionError , \"\" ) py . test . raises ( AssertionError , \"\" ) sizeof ( array , ) sizeof ( varstruct , ) def test_confusion_with_fixedarray_item_0 ( ) : A = lltype . FixedSizeArray ( lltype . Signed , ) B = lltype . FixedSizeArray ( A , ) myoffset = itemoffsetof ( A , ) global_b = lltype . malloc ( B , immortal = True ) global_b [ ] [ ] = global_b [ ] [ ] = global_b [ ] [ ] = def f ( n ) : a = global_b [ n ] adr_a = cast_ptr_to_adr ( a ) return ( adr_a + myoffset ) . signed [ ] assert f ( ) == assert f ( ) == assert f ( ) == res = interpret ( f , [ ] ) assert res == def test_structarray_add ( ) : S = lltype . Struct ( \"\" , ( \"\" , lltype . Signed ) ) for a in [ lltype . malloc ( lltype . GcArray ( S ) , ) , lltype . malloc ( lltype . FixedSizeArray ( S , ) , immortal = True ) ] : a [ ] . x = adr_s = cast_ptr_to_adr ( a ) adr_s += itemoffsetof ( lltype . typeOf ( a ) . TO , ) adr_s += sizeof ( S ) * s = cast_adr_to_ptr ( adr_s , lltype . Ptr ( S ) ) assert s . x == def test_fakeaddress_equality ( ) : S = lltype . GcStruct ( '' , ( '' , lltype . Signed ) ) T = lltype . GcStruct ( '' , ( '' , lltype . Signed ) ) s1 = lltype . malloc ( S ) s1 . x = s2 = lltype . malloc ( S ) s2 . x = t = lltype . malloc ( T ) t . y = a1s1 , a2s1 , as2 , at = map ( cast_ptr_to_adr , [ s1 , s1 , s2 , t ] ) assert a1s1 == a2s1 assert a1s1 != as2 assert a1s1 != at assert as2 != at def test_more_fakeaddress_equality ( ) : S = lltype . GcStruct ( '' , ( '' , lltype . Signed ) ) T = lltype . GcStruct ( '' , ( '' , S ) ) t = lltype . malloc ( T ) t . s . x = s = lltype . cast_pointer ( lltype . Ptr ( S ) , t ) a_t , a_s = map ( cast_ptr_to_adr , [ s , t ] ) assert a_t == a_s def test_fakeaccessor ( ) : S = lltype . GcStruct ( \"\" , ( \"\" , lltype . Signed ) , ( \"\" , lltype . Signed ) ) s = lltype . malloc ( S ) s . x = s . y = adr = cast_ptr_to_adr ( s ) adr += FieldOffset ( S , \"\" ) assert adr . signed [ ] == adr . signed [ ] = assert s . y == A = lltype . GcArray ( lltype . Signed ) a = lltype . malloc ( A , ) a [ ] = adr = cast_ptr_to_adr ( a ) assert ( adr + ArrayLengthOffset ( A ) ) . signed [ ] == assert ( adr + ArrayItemsOffset ( A ) ) . signed [ ] == ( adr + ArrayItemsOffset ( A ) ) . signed [ ] = assert a [ ] == adr1000 = ( adr + ArrayItemsOffset ( A ) + ItemOffset ( lltype . Signed , ) ) assert adr1000 . signed [ - ] == A = lltype . GcArray ( lltype . Char ) a = lltype . malloc ( A , ) a [ ] = '' adr = cast_ptr_to_adr ( a ) assert ( adr + ArrayLengthOffset ( A ) ) . signed [ ] == assert ( adr + ArrayItemsOffset ( A ) ) . char [ ] == '' ( adr + ArrayItemsOffset ( A ) ) . char [ ] = '' assert a [ ] == '' adr1000 = ( adr + ArrayItemsOffset ( A ) + ItemOffset ( lltype . Char , ) ) assert adr1000 . char [ - ] == '' T = lltype . FixedSizeArray ( lltype . Char , ) S = lltype . GcStruct ( '' , ( '' , lltype . Ptr ( T ) ) ) s = lltype . malloc ( S ) s . z = lltype . malloc ( T , immortal = True ) adr = cast_ptr_to_adr ( s ) assert ( adr + offsetof ( S , '' ) ) . address [ ] == cast_ptr_to_adr ( s . z ) ( adr + offsetof ( S , '' ) ) . address [ ] = NULL assert s . z == lltype . nullptr ( T ) t = lltype . malloc ( T , immortal = True ) ( adr + offsetof ( S , '' ) ) . address [ ] = cast_ptr_to_adr ( t ) assert s . z == t ", "answer": "def test_fakeadr_eq ( ) :"}, {"prompt": " import os import py from pypy . lang . gameboy import constants from pypy . lang . gameboy . gameboy import GameBoy ROM_PATH = str ( py . magic . autopath ( ) . dirpath ( ) . dirpath ( ) . dirpath ( ) ) + \"\" EMULATION_CYCLES = << def entry_point ( argv = None ) : if len ( argv ) > : filename = argv [ ] else : filename = ROM_PATH + \"\" ", "answer": "gameBoy = GameBoy ( )"}, {"prompt": " \"\"\"\"\"\" print ( __doc__ ) import numpy as np import matplotlib . pyplot as plt from matplotlib . colors import ListedColormap from sklearn . model_selection import train_test_split from sklearn . preprocessing import StandardScaler from sklearn . datasets import make_moons , make_circles , make_classification from sklearn . neural_network import MLPClassifier from sklearn . neighbors import KNeighborsClassifier from sklearn . svm import SVC from sklearn . gaussian_process import GaussianProcessClassifier from sklearn . gaussian_process . kernels import RBF from sklearn . tree import DecisionTreeClassifier from sklearn . ensemble import RandomForestClassifier , AdaBoostClassifier from sklearn . naive_bayes import GaussianNB from sklearn . discriminant_analysis import QuadraticDiscriminantAnalysis h = names = [ \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ] classifiers = [ KNeighborsClassifier ( ) , SVC ( kernel = \"\" , C = ) , SVC ( gamma = , C = ) , GaussianProcessClassifier ( * RBF ( ) , warm_start = True ) , DecisionTreeClassifier ( max_depth = ) , RandomForestClassifier ( max_depth = , n_estimators = , max_features = ) , MLPClassifier ( alpha = ) , AdaBoostClassifier ( ) , GaussianNB ( ) , QuadraticDiscriminantAnalysis ( ) ] X , y = make_classification ( n_features = , n_redundant = , n_informative = , random_state = , n_clusters_per_class = ) rng = np . random . RandomState ( ) X += * rng . uniform ( size = X . shape ) linearly_separable = ( X , y ) datasets = [ make_moons ( noise = , random_state = ) , ", "answer": "make_circles ( noise = , factor = , random_state = ) ,"}, {"prompt": " from xml . dom import pulldom from cStringIO import StringIO from twisted . python import usage import nevow class LineBasedStream ( object ) : \"\"\"\"\"\" def __init__ ( self , stream ) : self . stream = stream ", "answer": "self . buffer = ''"}, {"prompt": " from memsql_loader . util import apsw_helpers class TableDefinition ( object ) : def __init__ ( self , table_name , sql , index_columns = None ) : self . table_name = table_name self . sql = sql self . index_columns = index_columns or [ ] class APSWSQLUtility ( object ) : def __init__ ( self , storage ) : self . storage = storage self . _tables = { } def setup ( self ) : \"\"\"\"\"\" with self . storage . transaction ( ) as cursor : for table_defn in self . _tables . values ( ) : cursor . execute ( table_defn . sql ) for index_column in table_defn . index_columns : index_name = table_defn . table_name + '' + index_column + '' cursor . execute ( '' % ( index_name , table_defn . table_name , index_column ) ) return self def ready ( self ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " \"\"\"\"\"\" import functools import platform import sys from nova import exception from nova import image from nova . virt import driver from os_win import exceptions as os_win_exc from os_win import utilsfactory from oslo_log import log as logging from oslo_utils import excutils import six from hyperv . i18n import _ , _LE from hyperv . nova import eventhandler from hyperv . nova import hostops from hyperv . nova import imagecache from hyperv . nova import livemigrationops from hyperv . nova import migrationops from hyperv . nova import rdpconsoleops from hyperv . nova import serialconsoleops from hyperv . nova import snapshotops from hyperv . nova import vmops from hyperv . nova import volumeops LOG = logging . getLogger ( __name__ ) def convert_exceptions ( function , exception_map ) : expected_exceptions = tuple ( exception_map . keys ( ) ) @ functools . wraps ( function ) def wrapper ( * args , ** kwargs ) : try : return function ( * args , ** kwargs ) except expected_exceptions as ex : raised_exception = exception_map . get ( type ( ex ) ) if not raised_exception : for expected in expected_exceptions : if isinstance ( ex , expected ) : raised_exception = exception_map [ expected ] break exc_info = sys . exc_info ( ) exc = raised_exception ( six . text_type ( exc_info [ ] ) ) six . reraise ( raised_exception , exc , exc_info [ ] ) return wrapper def decorate_all_methods ( decorator , * args , ** kwargs ) : def decorate ( cls ) : for attr in cls . __dict__ : class_member = getattr ( cls , attr ) if callable ( class_member ) : setattr ( cls , attr , decorator ( class_member , * args , ** kwargs ) ) return cls return decorate exception_conversion_map = { os_win_exc . OSWinException : exception . NovaException , os_win_exc . HyperVVMNotFoundException : exception . InstanceNotFound , } @ decorate_all_methods ( convert_exceptions , exception_conversion_map ) class HyperVDriver ( driver . ComputeDriver ) : capabilities = { \"\" : True , \"\" : False , \"\" : True } def __init__ ( self , virtapi ) : self . _check_minimum_windows_version ( ) super ( HyperVDriver , self ) . __init__ ( virtapi ) self . _hostops = hostops . HostOps ( ) self . _volumeops = volumeops . VolumeOps ( ) self . _vmops = vmops . VMOps ( virtapi ) self . _snapshotops = snapshotops . SnapshotOps ( ) self . _livemigrationops = livemigrationops . LiveMigrationOps ( ) self . _migrationops = migrationops . MigrationOps ( ) self . _rdpconsoleops = rdpconsoleops . RDPConsoleOps ( ) self . _serialconsoleops = serialconsoleops . SerialConsoleOps ( ) self . _imagecache = imagecache . ImageCache ( ) self . _image_api = image . API ( ) def _check_minimum_windows_version ( self ) : if not utilsfactory . get_hostutils ( ) . check_min_windows_version ( , ) : LOG . error ( _LE ( '' '' '' '' ) ) raise exception . HypervisorTooOld ( version = '' ) @ property def need_legacy_block_device_info ( self ) : return False def init_host ( self , host ) : self . _serialconsoleops . start_console_handlers ( ) event_handler = eventhandler . InstanceEventHandler ( state_change_callback = self . emit_event ) event_handler . start_listener ( ) def list_instance_uuids ( self ) : return self . _vmops . list_instance_uuids ( ) def list_instances ( self ) : return self . _vmops . list_instances ( ) def spawn ( self , context , instance , image_meta , injected_files , admin_password , network_info = None , block_device_info = None ) : image_meta = self . _recreate_image_meta ( context , instance , image_meta ) self . _vmops . spawn ( context , instance , image_meta , injected_files , admin_password , network_info , block_device_info ) def reboot ( self , context , instance , network_info , reboot_type , block_device_info = None , bad_volumes_callback = None ) : self . _vmops . reboot ( instance , network_info , reboot_type ) def destroy ( self , context , instance , network_info , block_device_info = None , destroy_disks = True , migrate_data = None ) : self . _vmops . destroy ( instance , network_info , block_device_info , destroy_disks ) def cleanup ( self , context , instance , network_info , block_device_info = None , destroy_disks = True , migrate_data = None , destroy_vifs = True ) : \"\"\"\"\"\" pass def get_info ( self , instance ) : return self . _vmops . get_info ( instance ) def attach_volume ( self , context , connection_info , instance , mountpoint , disk_bus = None , device_type = None , encryption = None ) : return self . _volumeops . attach_volume ( connection_info , instance . name ) def detach_volume ( self , connection_info , instance , mountpoint , encryption = None ) : return self . _volumeops . detach_volume ( connection_info , instance . name ) def get_volume_connector ( self , instance ) : return self . _volumeops . get_volume_connector ( ) def get_available_resource ( self , nodename ) : return self . _hostops . get_available_resource ( ) def get_available_nodes ( self , refresh = False ) : return [ platform . node ( ) ] def host_power_action ( self , action ) : return self . _hostops . host_power_action ( action ) def snapshot ( self , context , instance , image_id , update_task_state ) : self . _snapshotops . snapshot ( context , instance , image_id , update_task_state ) def pause ( self , instance ) : self . _vmops . pause ( instance ) def unpause ( self , instance ) : self . _vmops . unpause ( instance ) def suspend ( self , context , instance ) : self . _vmops . suspend ( instance ) def resume ( self , context , instance , network_info , block_device_info = None ) : self . _vmops . resume ( instance ) def power_off ( self , instance , timeout = , retry_interval = ) : self . _vmops . power_off ( instance , timeout , retry_interval ) def power_on ( self , context , instance , network_info , block_device_info = None ) : self . _vmops . power_on ( instance , block_device_info , network_info ) def resume_state_on_host_boot ( self , context , instance , network_info , block_device_info = None ) : \"\"\"\"\"\" self . _vmops . resume_state_on_host_boot ( context , instance , network_info , block_device_info ) def live_migration ( self , context , instance , dest , post_method , recover_method , block_migration = False , migrate_data = None ) : self . _livemigrationops . live_migration ( context , instance , dest , post_method , recover_method , block_migration , migrate_data ) def rollback_live_migration_at_destination ( self , context , instance , network_info , block_device_info , destroy_disks = True , migrate_data = None ) : self . destroy ( context , instance , network_info , block_device_info ) def pre_live_migration ( self , context , instance , block_device_info , network_info , disk_info , migrate_data = None ) : self . _livemigrationops . pre_live_migration ( context , instance , block_device_info , network_info ) def post_live_migration ( self , context , instance , block_device_info , migrate_data = None ) : self . _livemigrationops . post_live_migration ( context , instance , block_device_info ) def post_live_migration_at_source ( self , context , instance , network_info ) : \"\"\"\"\"\" self . _vmops . unplug_vifs ( instance , network_info ) def post_live_migration_at_destination ( self , context , instance , network_info , block_migration = False , block_device_info = None ) : self . _livemigrationops . post_live_migration_at_destination ( context , instance , network_info , block_migration ) def check_can_live_migrate_destination ( self , context , instance , src_compute_info , dst_compute_info , block_migration = False , disk_over_commit = False ) : return self . _livemigrationops . check_can_live_migrate_destination ( context , instance , src_compute_info , dst_compute_info , block_migration , disk_over_commit ) def check_can_live_migrate_destination_cleanup ( self , context , dest_check_data ) : self . _livemigrationops . check_can_live_migrate_destination_cleanup ( context , dest_check_data ) ", "answer": "def check_can_live_migrate_source ( self , context , instance ,"}, {"prompt": " \"\"\"\"\"\" import abc import contextlib import hashlib ", "answer": "import os"}, {"prompt": " import copy from django import http from horizon import exceptions from horizon import tabs as horizon_tabs from horizon . test import helpers as test from horizon . test . tests . tables import MyTable from horizon . test . tests . tables import TEST_DATA class BaseTestTab ( horizon_tabs . Tab ) : def get_context_data ( self , request ) : return { \"\" : self } class TabOne ( BaseTestTab ) : slug = \"\" name = \"\" template_name = \"\" class TabDelayed ( BaseTestTab ) : slug = \"\" name = \"\" template_name = \"\" preload = False class TabDisabled ( BaseTestTab ) : slug = \"\" name = \"\" template_name = \"\" def enabled ( self , request ) : ", "answer": "return False"}, {"prompt": " __author__ = '' import logging import time import json from threading import Thread import requests import websocket log = logging . getLogger ( '' ) WEBSOCKET_URL = '' class Listener ( Thread , websocket . WebSocketApp ) : def __init__ ( self , account , on_push = None , http_proxy_host = None , http_proxy_port = None ) : \"\"\"\"\"\" self . _account = account self . _api_key = self . _account . api_key Thread . __init__ ( self ) websocket . WebSocketApp . __init__ ( self , WEBSOCKET_URL + self . _api_key , on_open = self . on_open , on_message = self . on_message , on_close = self . on_close ) self . connected = False self . last_update = time . time ( ) self . on_push = on_push self . history = None self . clean_history ( ) self . http_proxy_host = http_proxy_host self . http_proxy_port = http_proxy_port self . proxies = None if http_proxy_port is not None and http_proxy_port is not None : self . proxies = { \"\" : \"\" + http_proxy_host + \"\" + str ( http_proxy_port ) , \"\" : \"\" + http_proxy_host + \"\" + str ( http_proxy_port ) , } def clean_history ( self ) : self . history = [ ] def on_open ( self , ws ) : self . connected = True self . last_update = time . time ( ) def on_close ( self , ws ) : log . debug ( '' ) self . connected = False def on_message ( self , ws , message ) : log . debug ( '' + message ) try : ", "answer": "json_message = json . loads ( message )"}, {"prompt": " import py from pypy . translator . cli . test . runtest import CliTest from pypy . rlib . test . test_streamio import BaseTestBufferingInputStreamTests , BaseTestBufferingOutputStream , BaseTestLineBufferingOutputStream , BaseTestCRLFFilter , BaseTestBufferingInputOutputStreamTests , BaseTestTextInputFilter , BaseTestTextOutputFilter ", "answer": "class TestBufferingInputStreamTests ( CliTest , BaseTestBufferingInputStreamTests ) :"}, {"prompt": " import asterisk . manager import threading import datetime import settings from models import Call def handle_shutdown ( event , manager ) : manager . close ( ) def handle_event ( event , manager , call ) : if event . name == '' : call . disposition = event . get_header ( '' ) call . cause = event . get_header ( '' ) call . duration = ( datetime . datetime . now ( ) - call . start ) . seconds call . save ( ) with manager . lock : manager . lock . notifyAll ( ) def make_call ( call ) : manager = asterisk . manager . Manager ( ) manager . lock = threading . Condition ( ) ", "answer": "try :"}, {"prompt": " filters = ( '' , ( '' , ", "answer": "'' ) )"}, {"prompt": " import collections from pycoin import ecdsa from . . script import der , opcodes , tools bytes_from_int = chr if bytes == str else lambda x : bytes ( [ x ] ) def generate_default_placeholder_signature ( ) : order = ecdsa . generator_secp256k1 . order ( ) r , s = order - , order // return der . sigencode_der ( r , s ) + bytes_from_int ( ) DEFAULT_PLACEHOLDER_SIGNATURE = generate_default_placeholder_signature ( ) class ScriptType ( object ) : def __init__ ( self ) : raise NotImplemented ( ) @ classmethod def subclasses ( cls , skip_self = True ) : for c in cls . __subclasses__ ( ) : for c1 in c . subclasses ( skip_self = False ) : yield c1 if not skip_self : yield cls @ classmethod def from_address ( cls , text , netcodes = None ) : for sc in cls . subclasses ( ) : try : st = sc . from_address ( text , netcodes = netcodes ) return st ", "answer": "except Exception :"}, {"prompt": " extensions = [ ] class ResponseExtensionType ( type ) : \"\"\"\"\"\" global extensions def __new__ ( cls , class_name , bases , attrs ) : extension = super ( ResponseExtensionType , cls ) . __new__ ( cls , class_name , bases , attrs ) if extension . __extends__ : extensions . append ( extension ) return extension class SimpleResponseExtension ( object ) : \"\"\"\"\"\" __metaclass__ = ResponseExtensionType __extends__ = [ ] _sub_attr_map = { } @ classmethod def extend ( cls , obj , ** kwargs ) : if obj . __class__ . __name__ not in cls . __extends__ : return obj for kw_name , attr_name in cls . _sub_attr_map . items ( ) : ", "answer": "setattr ( obj , attr_name , kwargs . get ( kw_name , None ) )"}, {"prompt": " from esri2open import toOpen , writeFile , closeUp , closeJSON ", "answer": "from prepare import prepareFile , prepareGeoJSON "}, {"prompt": " \"\"\"\"\"\" import os import sys import re from vex import exceptions try : FileNotFoundError except NameError : FileNotFoundError = IOError NOT_SCARY = re . compile ( br'' ) def scary_path ( path ) : \"\"\"\"\"\" if not path : return True assert isinstance ( path , bytes ) return not NOT_SCARY . match ( path ) def shell_config_for ( shell , vexrc , environ ) : \"\"\"\"\"\" here = os . path . dirname ( os . path . abspath ( __file__ ) ) path = os . path . join ( here , '' , shell ) try : with open ( path , '' ) as inp : data = inp . read ( ) except FileNotFoundError as error : if error . errno != : raise return b'' ve_base = vexrc . get_ve_base ( environ ) . encode ( '' ) if ve_base and not scary_path ( ve_base ) and os . path . exists ( ve_base ) : data = data . replace ( b'' , ve_base ) return data def handle_shell_config ( shell , vexrc , environ ) : \"\"\"\"\"\" from vex import shell_config ", "answer": "data = shell_config . shell_config_for ( shell , vexrc , environ )"}, {"prompt": " import sys import telepot from telepot . delegate import per_chat_id , create_open \"\"\"\"\"\" class MessageCounter ( telepot . helper . ChatHandler ) : def __init__ ( self , seed_tuple , timeout ) : ", "answer": "super ( MessageCounter , self ) . __init__ ( seed_tuple , timeout )"}, {"prompt": " \"\"\"\"\"\" from nova import exception BAREMETAL = \"\" BHYVE = \"\" DOCKER = \"\" FAKE = \"\" HYPERV = \"\" IRONIC = \"\" KQEMU = \"\" KVM = \"\" LXC = \"\" LXD = \"\" OPENVZ = \"\" PARALLELS = \"\" VIRTUOZZO = \"\" PHYP = \"\" QEMU = \"\" TEST = \"\" UML = \"\" VBOX = \"\" VMWARE = \"\" XEN = \"\" ZVM = \"\" ALL = ( BAREMETAL , BHYVE , DOCKER , FAKE , HYPERV , IRONIC , ", "answer": "KQEMU ,"}, {"prompt": " import pcd8544 . lcd as lcd def demo ( ) : lcd . locate ( , ) lcd . text ( map ( chr , range ( , ) ) ) if __name__ == \"\" : ", "answer": "lcd . init ( )"}, {"prompt": " from pulsar . utils . httpurl import iri_to_uri class Pagination : def first_link ( self , request , total , limit , offset ) : n = self . _count_part ( offset , limit , ) if n : offset -= n * limit if offset > : return self . link ( request , , min ( limit , offset ) ) def prev_link ( self , request , total , limit , offset ) : if offset : olimit = min ( limit , offset ) prev_offset = offset - olimit return self . link ( request , prev_offset , olimit ) def next_link ( self , request , total , limit , offset ) : next_offset = offset + limit if total > next_offset : return self . link ( request , next_offset , limit ) def last_link ( self , request , total , limit , offset ) : n = self . _count_part ( total , limit , offset ) if n > : return self . link ( request , offset + n * limit , limit ) def link ( self , request , offset , limit ) : params = request . url_data . copy ( ) cfg = request . config params . update ( { cfg [ '' ] : offset , cfg [ '' ] : limit } ) location = iri_to_uri ( request . path , params ) return request . absolute_uri ( location ) def __call__ ( self , request , result , total , limit , offset ) : data = { '' : total , '' : result } first = self . first_link ( request , total , limit , offset ) if first : data [ '' ] = first prev = self . prev_link ( request , total , limit , offset ) if prev != first : data [ '' ] = prev next = self . next_link ( request , total , limit , offset ) if next : last = self . last_link ( request , total , limit , offset ) if last != next : data [ '' ] = next data [ '' ] = last return data def _count_part ( self , total , limit , offset ) : n = ( total - offset ) // limit if n * limit + offset == total : n -= return max ( , n ) class GithubPagination ( Pagination ) : '''''' def __call__ ( self , request , result , total , limit , offset ) : links = [ ] first = self . first_link ( request , total , limit , offset ) if first : links . append ( first ) prev = self . prev_link ( request , total , limit , offset ) if prev != first : links . append ( prev ) ", "answer": "next = self . next_link ( request , total , limit , offset )"}, {"prompt": " \"\"\"\"\"\" import re import sys import logging import os import os . path as op from jcvi . apps . base import OptionParser , OptionGroup , ActionDispatcher , sh def main ( ) : actions = ( ( '' , '' ) , ( '' , '' ) ) p = ActionDispatcher ( actions ) p . dispatch ( globals ( ) ) def prepare ( args ) : \"\"\"\"\"\" from operator import itemgetter from jcvi . formats . fasta import Fasta , SeqIO p = OptionParser ( prepare . __doc__ ) p . add_option ( \"\" , default = None , help = \"\" ) p . add_option ( \"\" , help = \"\" ) g = OptionGroup ( p , \"\" ) g . add_option ( \"\" , default = \"\" , help = \"\" ) p . add_option_group ( g ) opts , args = p . parse_args ( args ) if not opts . rearray_lib or not opts . orig_lib_file : logging . error ( \"\" ) sys . exit ( not p . print_help ( ) ) rearraylib , origlibfile = opts . rearray_lib , opts . orig_lib_file if not op . isfile ( origlibfile ) : logging . error ( \"\" . format ( origlibfile ) ) sys . exit ( ) lookuptblfile = rearraylib + '' logging . debug ( lookuptblfile ) if not op . isfile ( lookuptblfile ) : logging . error ( \"\" . format ( lookuptblfile ) ) sys . exit ( ) rearraylibfile = rearraylib + '' logging . debug ( rearraylibfile ) if not op . isfile ( rearraylibfile ) : logging . error ( \"\" . format ( rearraylibfile ) ) sys . exit ( ) origlibFasta = Fasta ( origlibfile ) rearraylibFasta = Fasta ( rearraylibfile ) origlibids = [ o for o in origlibFasta . iterkeys_ordered ( ) ] rearraylibids = [ r for r in rearraylibFasta . iterkeys_ordered ( ) ] if not op . isdir ( opts . output_folder ) : logging . warning ( \"\" . format ( opts . output_folder ) ) os . makedirs ( opts . output_folder ) logfile = rearraylib + '' log = open ( logfile , '' ) fp = open ( lookuptblfile , '' ) for row in fp : origprefix , rearrayprefix = itemgetter ( , ) ( row . split ( '' ) ) libpair = origprefix + '' + rearrayprefix outfile = opts . output_folder + '' + libpair + '' ofp = open ( outfile , '' ) for o in origlibids : if re . match ( origprefix , o ) : SeqIO . write ( origlibFasta [ o ] , ofp , '' ) for r in rearraylibids : if re . match ( rearrayprefix , r ) : SeqIO . write ( rearraylibFasta [ r ] , ofp , '' ) ofp . close ( ) print >> log , outfile log . close ( ) logging . debug ( '' . format ( logfile ) ) def assemble ( args ) : \"\"\"\"\"\" p = OptionParser ( assemble . __doc__ ) g1 = OptionGroup ( p , \"\" , \"\" ) g1 . add_option ( \"\" , default = None , help = \"\" ) g1 . add_option ( \"\" , default = None , help = \"\" ) g1 . add_option ( \"\" , default = None , help = \"\" ) p . add_option_group ( g1 ) g2 = OptionGroup ( p , \"\" , \"\" ) g2 . add_option ( \"\" , \"\" , default = , type = \"\" , help = \"\" + \"\" ) g2 . add_option ( \"\" , \"\" , default = , type = \"\" , help = \"\" + \"\" ) g2 . add_option ( \"\" , \"\" , default = , type = \"\" , help = \"\" + \"\" ) g2 . add_option ( \"\" , \"\" , dest = \"\" , default = \"\" , help = \"\" ) p . add_option_group ( g2 ) p . set_params ( ) opts , args = p . parse_args ( args ) if opts . max_gap_len and opts . max_gap_len <= : logging . error ( \"\" ) sys . exit ( ) ", "answer": "elif opts . ovl_pct_id and opts . ovl_pct_id <= :"}, {"prompt": " from __future__ import absolute_import , unicode_literals import datetime import re from datetime import date from decimal import Decimal from django import forms from django . db import models from django . forms . models import ( _get_foreign_key , inlineformset_factory , modelformset_factory ) from django . test import TestCase , skipUnlessDBFeature from django . utils import six from . models import ( Author , BetterAuthor , Book , BookWithCustomPK , BookWithOptionalAltEditor , AlternateBook , AuthorMeeting , CustomPrimaryKey , Place , Owner , Location , OwnerProfile , Restaurant , Product , Price , MexicanRestaurant , ClassyMexicanRestaurant , Repository , Revision , Person , Membership , Team , Player , Poet , Poem , Post ) class DeletionTests ( TestCase ) : def test_deletion ( self ) : PoetFormSet = modelformset_factory ( Poet , can_delete = True ) poet = Poet . objects . create ( name = '' ) data = { '' : '' , '' : '' , '' : '' , '' : str ( poet . pk ) , '' : '' , '' : '' , } formset = PoetFormSet ( data , queryset = Poet . objects . all ( ) ) formset . save ( ) self . assertTrue ( formset . is_valid ( ) ) self . assertEqual ( Poet . objects . count ( ) , ) def test_add_form_deletion_when_invalid ( self ) : \"\"\"\"\"\" PoetFormSet = modelformset_factory ( Poet , can_delete = True ) data = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' * , } formset = PoetFormSet ( data , queryset = Poet . objects . all ( ) ) self . assertEqual ( formset . is_valid ( ) , False ) self . assertEqual ( Poet . objects . count ( ) , ) data [ '' ] = '' formset = PoetFormSet ( data , queryset = Poet . objects . all ( ) ) self . assertEqual ( formset . is_valid ( ) , True ) formset . save ( ) self . assertEqual ( Poet . objects . count ( ) , ) def test_change_form_deletion_when_invalid ( self ) : \"\"\"\"\"\" PoetFormSet = modelformset_factory ( Poet , can_delete = True ) poet = Poet . objects . create ( name = '' ) data = { '' : '' , '' : '' , '' : '' , '' : six . text_type ( poet . id ) , '' : '' * , } formset = PoetFormSet ( data , queryset = Poet . objects . all ( ) ) self . assertEqual ( formset . is_valid ( ) , False ) self . assertEqual ( Poet . objects . count ( ) , ) data [ '' ] = '' formset = PoetFormSet ( data , queryset = Poet . objects . all ( ) ) self . assertEqual ( formset . is_valid ( ) , True ) formset . save ( ) self . assertEqual ( Poet . objects . count ( ) , ) class ModelFormsetTest ( TestCase ) : def test_simple_save ( self ) : qs = Author . objects . all ( ) AuthorFormSet = modelformset_factory ( Author , extra = ) formset = AuthorFormSet ( queryset = qs ) self . assertEqual ( len ( formset . forms ) , ) self . assertHTMLEqual ( formset . forms [ ] . as_p ( ) , '' ) self . assertHTMLEqual ( formset . forms [ ] . as_p ( ) , '' ) self . assertHTMLEqual ( formset . forms [ ] . as_p ( ) , '' ) data = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , } formset = AuthorFormSet ( data = data , queryset = qs ) self . assertTrue ( formset . is_valid ( ) ) saved = formset . save ( ) self . assertEqual ( len ( saved ) , ) author1 , author2 = saved self . assertEqual ( author1 , Author . objects . get ( name = '' ) ) self . assertEqual ( author2 , Author . objects . get ( name = '' ) ) authors = list ( Author . objects . order_by ( '' ) ) self . assertEqual ( authors , [ author2 , author1 ] ) qs = Author . objects . order_by ( '' ) AuthorFormSet = modelformset_factory ( Author , extra = , can_delete = False ) formset = AuthorFormSet ( queryset = qs ) self . assertEqual ( len ( formset . forms ) , ) self . assertHTMLEqual ( formset . forms [ ] . as_p ( ) , '' % author2 . id ) self . assertHTMLEqual ( formset . forms [ ] . as_p ( ) , '' % author1 . id ) self . assertHTMLEqual ( formset . forms [ ] . as_p ( ) , '' ) data = { '' : '' , '' : '' , '' : '' , '' : str ( author2 . id ) , '' : '' , '' : str ( author1 . id ) , '' : '' , '' : '' , } formset = AuthorFormSet ( data = data , queryset = qs ) self . assertTrue ( formset . is_valid ( ) ) saved = formset . save ( ) self . assertEqual ( len ( saved ) , ) author3 = saved [ ] self . assertEqual ( author3 , Author . objects . get ( name = '' ) ) authors = list ( Author . objects . order_by ( '' ) ) self . assertEqual ( authors , [ author2 , author1 , author3 ] ) qs = Author . objects . order_by ( '' ) AuthorFormSet = modelformset_factory ( Author , extra = , can_delete = True ) formset = AuthorFormSet ( queryset = qs ) self . assertEqual ( len ( formset . forms ) , ) self . assertHTMLEqual ( formset . forms [ ] . as_p ( ) , '' '' % author2 . id ) self . assertHTMLEqual ( formset . forms [ ] . as_p ( ) , '' '' % author1 . id ) self . assertHTMLEqual ( formset . forms [ ] . as_p ( ) , '' '' % author3 . id ) self . assertHTMLEqual ( formset . forms [ ] . as_p ( ) , '' '' ) data = { '' : '' , '' : '' , '' : '' , '' : str ( author2 . id ) , '' : '' , '' : str ( author1 . id ) , '' : '' , '' : str ( author3 . id ) , '' : '' , '' : '' , '' : '' , } formset = AuthorFormSet ( data = data , queryset = qs ) self . assertTrue ( formset . is_valid ( ) ) self . assertEqual ( formset . save ( ) , [ ] ) authors = list ( Author . objects . order_by ( '' ) ) self . assertEqual ( authors , [ author2 , author1 , author3 ] ) data = { '' : '' , '' : '' , '' : '' , '' : str ( author2 . id ) , '' : '' , '' : str ( author1 . id ) , '' : '' , '' : str ( author3 . id ) , '' : '' , '' : '' , '' : '' , } formset = AuthorFormSet ( data = data , queryset = qs ) self . assertTrue ( formset . is_valid ( ) ) saved = formset . save ( ) self . assertEqual ( len ( saved ) , ) self . assertEqual ( saved [ ] , Author . objects . get ( name = '' ) ) def test_commit_false ( self ) : author1 = Author . objects . create ( name = '' ) author2 = Author . objects . create ( name = '' ) author3 = Author . objects . create ( name = '' ) meeting = AuthorMeeting . objects . create ( created = date . today ( ) ) meeting . authors = Author . objects . all ( ) author4 = Author . objects . create ( name = '' ) AuthorMeetingFormSet = modelformset_factory ( AuthorMeeting , extra = , can_delete = True ) data = { '' : '' , '' : '' , '' : '' , '' : str ( meeting . id ) , '' : '' , '' : [ author2 . id , author1 . id , author3 . id , author4 . id ] , '' : '' , '' : '' , '' : '' , } formset = AuthorMeetingFormSet ( data = data , queryset = AuthorMeeting . objects . all ( ) ) self . assertTrue ( formset . is_valid ( ) ) instances = formset . save ( commit = False ) for instance in instances : instance . created = date . today ( ) instance . save ( ) formset . save_m2m ( ) self . assertQuerysetEqual ( instances [ ] . authors . all ( ) , [ '' , '' , '' , '' , ] ) def test_max_num ( self ) : author1 = Author . objects . create ( name = '' ) author2 = Author . objects . create ( name = '' ) author3 = Author . objects . create ( name = '' ) qs = Author . objects . order_by ( '' ) AuthorFormSet = modelformset_factory ( Author , max_num = None , extra = ) formset = AuthorFormSet ( queryset = qs ) self . assertEqual ( len ( formset . forms ) , ) self . assertEqual ( len ( formset . extra_forms ) , ) AuthorFormSet = modelformset_factory ( Author , max_num = , extra = ) formset = AuthorFormSet ( queryset = qs ) self . assertEqual ( len ( formset . forms ) , ) self . assertEqual ( len ( formset . extra_forms ) , ) AuthorFormSet = modelformset_factory ( Author , max_num = , extra = ) formset = AuthorFormSet ( queryset = qs ) self . assertEqual ( len ( formset . forms ) , ) self . assertEqual ( len ( formset . extra_forms ) , ) AuthorFormSet = modelformset_factory ( Author , max_num = None ) formset = AuthorFormSet ( queryset = qs ) self . assertQuerysetEqual ( formset . get_queryset ( ) , [ '' , '' , '' , ] ) AuthorFormSet = modelformset_factory ( Author , max_num = ) formset = AuthorFormSet ( queryset = qs ) self . assertQuerysetEqual ( formset . get_queryset ( ) , [ '' , '' , '' , ] ) AuthorFormSet = modelformset_factory ( Author , max_num = ) formset = AuthorFormSet ( queryset = qs ) self . assertQuerysetEqual ( formset . get_queryset ( ) , [ '' , '' , '' , ] ) def test_custom_save_method ( self ) : class PoetForm ( forms . ModelForm ) : def save ( self , commit = True ) : author = super ( PoetForm , self ) . save ( commit = False ) author . name = \"\" if commit : author . save ( ) return author PoetFormSet = modelformset_factory ( Poet , form = PoetForm ) data = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , } qs = Poet . objects . all ( ) formset = PoetFormSet ( data = data , queryset = qs ) self . assertTrue ( formset . is_valid ( ) ) poets = formset . save ( ) self . assertEqual ( len ( poets ) , ) poet1 , poet2 = poets self . assertEqual ( poet1 . name , '' ) self . assertEqual ( poet2 . name , '' ) def test_custom_form ( self ) : \"\"\"\"\"\" class PostForm1 ( forms . ModelForm ) : class Meta : model = Post fields = ( '' , '' ) class PostForm2 ( forms . ModelForm ) : class Meta : model = Post exclude = ( '' , ) PostFormSet = modelformset_factory ( Post , form = PostForm1 ) formset = PostFormSet ( ) self . assertFalse ( \"\" in formset . forms [ ] . fields ) PostFormSet = modelformset_factory ( Post , form = PostForm2 ) formset = PostFormSet ( ) self . assertFalse ( \"\" in formset . forms [ ] . fields ) def test_model_inheritance ( self ) : BetterAuthorFormSet = modelformset_factory ( BetterAuthor ) formset = BetterAuthorFormSet ( ) self . assertEqual ( len ( formset . forms ) , ) self . assertHTMLEqual ( formset . forms [ ] . as_p ( ) , '' '' ) data = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , } formset = BetterAuthorFormSet ( data ) self . assertTrue ( formset . is_valid ( ) ) saved = formset . save ( ) self . assertEqual ( len ( saved ) , ) author1 , = saved self . assertEqual ( author1 , BetterAuthor . objects . get ( name = '' ) ) hemingway_id = BetterAuthor . objects . get ( name = \"\" ) . pk formset = BetterAuthorFormSet ( ) self . assertEqual ( len ( formset . forms ) , ) self . assertHTMLEqual ( formset . forms [ ] . as_p ( ) , '' '' % hemingway_id ) self . assertHTMLEqual ( formset . forms [ ] . as_p ( ) , '' '' ) data = { '' : '' , '' : '' , '' : '' , '' : hemingway_id , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , } formset = BetterAuthorFormSet ( data ) self . assertTrue ( formset . is_valid ( ) ) self . assertEqual ( formset . save ( ) , [ ] ) def test_inline_formsets ( self ) : AuthorBooksFormSet = inlineformset_factory ( Author , Book , can_delete = False , extra = ) author = Author . objects . create ( name = '' ) formset = AuthorBooksFormSet ( instance = author ) self . assertEqual ( len ( formset . forms ) , ) self . assertHTMLEqual ( formset . forms [ ] . as_p ( ) , '' % author . id ) self . assertHTMLEqual ( formset . forms [ ] . as_p ( ) , '' % author . id ) self . assertHTMLEqual ( formset . forms [ ] . as_p ( ) , '' % author . id ) data = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , } formset = AuthorBooksFormSet ( data , instance = author ) self . assertTrue ( formset . is_valid ( ) ) saved = formset . save ( ) self . assertEqual ( len ( saved ) , ) book1 , = saved self . assertEqual ( book1 , Book . objects . get ( title = '' ) ) self . assertQuerysetEqual ( author . book_set . all ( ) , [ '' ] ) AuthorBooksFormSet = inlineformset_factory ( Author , Book , can_delete = False , extra = ) author = Author . objects . get ( name = '' ) formset = AuthorBooksFormSet ( instance = author ) self . assertEqual ( len ( formset . forms ) , ) self . assertHTMLEqual ( formset . forms [ ] . as_p ( ) , '' % ( author . id , book1 . id ) ) self . assertHTMLEqual ( formset . forms [ ] . as_p ( ) , '' % author . id ) self . assertHTMLEqual ( formset . forms [ ] . as_p ( ) , '' % author . id ) data = { '' : '' , '' : '' , '' : '' , '' : str ( book1 . id ) , '' : '' , '' : '' , '' : '' , } formset = AuthorBooksFormSet ( data , instance = author ) self . assertTrue ( formset . is_valid ( ) ) saved = formset . save ( ) self . assertEqual ( len ( saved ) , ) book2 , = saved self . assertEqual ( book2 , Book . objects . get ( title = '' ) ) self . assertQuerysetEqual ( author . book_set . order_by ( '' ) , [ '' , '' , ] ) def test_inline_formsets_save_as_new ( self ) : AuthorBooksFormSet = inlineformset_factory ( Author , Book , can_delete = False , extra = ) author = Author . objects . create ( name = '' ) data = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , } formset = AuthorBooksFormSet ( data , instance = Author ( ) , save_as_new = True ) self . assertTrue ( formset . is_valid ( ) ) new_author = Author . objects . create ( name = '' ) formset = AuthorBooksFormSet ( data , instance = new_author , save_as_new = True ) saved = formset . save ( ) self . assertEqual ( len ( saved ) , ) book1 , book2 = saved self . assertEqual ( book1 . title , '' ) self . assertEqual ( book2 . title , '' ) formset = AuthorBooksFormSet ( prefix = \"\" ) self . assertEqual ( len ( formset . forms ) , ) self . assertHTMLEqual ( formset . forms [ ] . as_p ( ) , '' ) self . assertHTMLEqual ( formset . forms [ ] . as_p ( ) , '' ) def test_inline_formsets_with_custom_pk ( self ) : AuthorBooksFormSet2 = inlineformset_factory ( Author , BookWithCustomPK , can_delete = False , extra = ) author = Author . objects . create ( pk = , name = '' ) formset = AuthorBooksFormSet2 ( instance = author ) self . assertEqual ( len ( formset . forms ) , ) self . assertHTMLEqual ( formset . forms [ ] . as_p ( ) , '' '' ) data = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , } formset = AuthorBooksFormSet2 ( data , instance = author ) self . assertTrue ( formset . is_valid ( ) ) saved = formset . save ( ) self . assertEqual ( len ( saved ) , ) book1 , = saved self . assertEqual ( book1 . pk , ) book1 = author . bookwithcustompk_set . get ( ) self . assertEqual ( book1 . title , '' ) def test_inline_formsets_with_multi_table_inheritance ( self ) : AuthorBooksFormSet3 = inlineformset_factory ( Author , AlternateBook , can_delete = False , extra = ) author = Author . objects . create ( pk = , name = '' ) formset = AuthorBooksFormSet3 ( instance = author ) self . assertEqual ( len ( formset . forms ) , ) self . assertHTMLEqual ( formset . forms [ ] . as_p ( ) , '' '' ) data = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' } formset = AuthorBooksFormSet3 ( data , instance = author ) self . assertTrue ( formset . is_valid ( ) ) saved = formset . save ( ) self . assertEqual ( len ( saved ) , ) book1 , = saved self . assertEqual ( book1 . title , '' ) self . assertEqual ( book1 . notes , '' ) @ skipUnlessDBFeature ( '' ) def test_inline_formsets_with_nullable_unique_together ( self ) : AuthorBooksFormSet4 = inlineformset_factory ( Author , BookWithOptionalAltEditor , can_delete = False , extra = ) author = Author . objects . create ( pk = , name = '' ) data = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , } formset = AuthorBooksFormSet4 ( data , instance = author ) self . assertTrue ( formset . is_valid ( ) ) saved = formset . save ( ) self . assertEqual ( len ( saved ) , ) book1 , book2 = saved self . assertEqual ( book1 . author_id , ) self . assertEqual ( book1 . title , '' ) self . assertEqual ( book2 . author_id , ) self . assertEqual ( book2 . title , '' ) def test_inline_formsets_with_custom_save_method ( self ) : AuthorBooksFormSet = inlineformset_factory ( Author , Book , can_delete = False , extra = ) author = Author . objects . create ( pk = , name = '' ) book1 = Book . objects . create ( pk = , author = author , title = '' ) book2 = Book . objects . create ( pk = , author = author , title = '' ) book3 = Book . objects . create ( pk = , author = author , title = '' ) class PoemForm ( forms . ModelForm ) : def save ( self , commit = True ) : poem = super ( PoemForm , self ) . save ( commit = False ) poem . name = \"\" if commit : poem . save ( ) return poem PoemFormSet = inlineformset_factory ( Poet , Poem , form = PoemForm ) data = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , } poet = Poet . objects . create ( name = '' ) formset = PoemFormSet ( data = data , instance = poet ) self . assertTrue ( formset . is_valid ( ) ) saved = formset . save ( ) self . assertEqual ( len ( saved ) , ) poem1 , poem2 = saved self . assertEqual ( poem1 . name , '' ) self . assertEqual ( poem2 . name , '' ) custom_qs = Book . objects . order_by ( '' ) formset = AuthorBooksFormSet ( instance = author , queryset = custom_qs ) self . assertEqual ( len ( formset . forms ) , ) self . assertHTMLEqual ( formset . forms [ ] . as_p ( ) , '' ) self . assertHTMLEqual ( formset . forms [ ] . as_p ( ) , '' ) self . assertHTMLEqual ( formset . forms [ ] . as_p ( ) , '' ) self . assertHTMLEqual ( formset . forms [ ] . as_p ( ) , '' ) self . assertHTMLEqual ( formset . forms [ ] . as_p ( ) , '' ) data = { '' : '' , '' : '' , '' : '' , '' : str ( book1 . id ) , '' : '' , '' : str ( book2 . id ) , '' : '' , '' : str ( book3 . id ) , '' : '' , '' : '' , '' : '' , } formset = AuthorBooksFormSet ( data , instance = author , queryset = custom_qs ) self . assertTrue ( formset . is_valid ( ) ) custom_qs = Book . objects . filter ( title__startswith = '' ) formset = AuthorBooksFormSet ( instance = author , queryset = custom_qs ) self . assertHTMLEqual ( formset . forms [ ] . as_p ( ) , '' ) self . assertHTMLEqual ( formset . forms [ ] . as_p ( ) , '' ) self . assertHTMLEqual ( formset . forms [ ] . as_p ( ) , '' ) data = { '' : '' , '' : '' , '' : '' , '' : str ( book3 . id ) , '' : '' , '' : '' , '' : '' , } formset = AuthorBooksFormSet ( data , instance = author , queryset = custom_qs ) self . assertTrue ( formset . is_valid ( ) ) def test_custom_pk ( self ) : CustomPrimaryKeyFormSet = modelformset_factory ( CustomPrimaryKey ) formset = CustomPrimaryKeyFormSet ( ) self . assertEqual ( len ( formset . forms ) , ) self . assertHTMLEqual ( formset . forms [ ] . as_p ( ) , '' '' ) place = Place . objects . create ( pk = , name = '' , city = '' ) FormSet = inlineformset_factory ( Place , Owner , extra = , can_delete = False ) formset = FormSet ( instance = place ) self . assertEqual ( len ( formset . forms ) , ) self . assertHTMLEqual ( formset . forms [ ] . as_p ( ) , '' ) self . assertHTMLEqual ( formset . forms [ ] . as_p ( ) , '' ) data = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , } formset = FormSet ( data , instance = place ) self . assertTrue ( formset . is_valid ( ) ) saved = formset . save ( ) self . assertEqual ( len ( saved ) , ) owner1 , = saved self . assertEqual ( owner1 . name , '' ) self . assertEqual ( owner1 . place . name , '' ) formset = FormSet ( instance = place ) self . assertEqual ( len ( formset . forms ) , ) self . assertHTMLEqual ( formset . forms [ ] . as_p ( ) , '' % owner1 . auto_id ) self . assertHTMLEqual ( formset . forms [ ] . as_p ( ) , '' ) self . assertHTMLEqual ( formset . forms [ ] . as_p ( ) , '' ) data = { '' : '' , '' : '' , '' : '' , '' : six . text_type ( owner1 . auto_id ) , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , } formset = FormSet ( data , instance = place ) self . assertTrue ( formset . is_valid ( ) ) saved = formset . save ( ) self . assertEqual ( len ( saved ) , ) owner2 , = saved self . assertEqual ( owner2 . name , '' ) self . assertEqual ( owner2 . place . name , '' ) FormSet = modelformset_factory ( OwnerProfile ) formset = FormSet ( ) self . assertHTMLEqual ( formset . forms [ ] . as_p ( ) , '' '' '' '' '' '' % ( owner1 . auto_id , owner2 . auto_id ) ) owner1 = Owner . objects . get ( name = '' ) FormSet = inlineformset_factory ( Owner , OwnerProfile , max_num = , can_delete = False ) self . assertEqual ( FormSet . max_num , ) formset = FormSet ( instance = owner1 ) self . assertEqual ( len ( formset . forms ) , ) self . assertHTMLEqual ( formset . forms [ ] . as_p ( ) , '' % owner1 . auto_id ) data = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , } formset = FormSet ( data , instance = owner1 ) self . assertTrue ( formset . is_valid ( ) ) saved = formset . save ( ) self . assertEqual ( len ( saved ) , ) profile1 , = saved self . assertEqual ( profile1 . owner , owner1 ) self . assertEqual ( profile1 . age , ) formset = FormSet ( instance = owner1 ) self . assertEqual ( len ( formset . forms ) , ) self . assertHTMLEqual ( formset . forms [ ] . as_p ( ) , '' % owner1 . auto_id ) data = { '' : '' , '' : '' , '' : '' , '' : six . text_type ( owner1 . auto_id ) , '' : '' , } formset = FormSet ( data , instance = owner1 ) self . assertTrue ( formset . is_valid ( ) ) saved = formset . save ( ) self . assertEqual ( len ( saved ) , ) profile1 , = saved self . assertEqual ( profile1 . owner , owner1 ) self . assertEqual ( profile1 . age , ) def test_unique_true_enforces_max_num_one ( self ) : place = Place . objects . create ( pk = , name = '' , city = '' ) FormSet = inlineformset_factory ( Place , Location , can_delete = False ) self . assertEqual ( FormSet . max_num , ) formset = FormSet ( instance = place ) self . assertEqual ( len ( formset . forms ) , ) self . assertHTMLEqual ( formset . forms [ ] . as_p ( ) , '' '' ) def test_foreign_keys_in_parents ( self ) : self . assertEqual ( type ( _get_foreign_key ( Restaurant , Owner ) ) , models . ForeignKey ) self . assertEqual ( type ( _get_foreign_key ( MexicanRestaurant , Owner ) ) , models . ForeignKey ) def test_unique_validation ( self ) : FormSet = modelformset_factory ( Product , extra = ) data = { '' : '' , '' : '' , '' : '' , '' : '' , } formset = FormSet ( data ) self . assertTrue ( formset . is_valid ( ) ) saved = formset . save ( ) self . assertEqual ( len ( saved ) , ) product1 , = saved self . assertEqual ( product1 . slug , '' ) data = { '' : '' , '' : '' , '' : '' , '' : '' , } formset = FormSet ( data ) self . assertFalse ( formset . is_valid ( ) ) self . assertEqual ( formset . errors , [ { '' : [ '' ] } ] ) def test_unique_together_validation ( self ) : FormSet = modelformset_factory ( Price , extra = ) data = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , } formset = FormSet ( data ) self . assertTrue ( formset . is_valid ( ) ) saved = formset . save ( ) self . assertEqual ( len ( saved ) , ) price1 , = saved self . assertEqual ( price1 . price , Decimal ( '' ) ) self . assertEqual ( price1 . quantity , ) data = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , } formset = FormSet ( data ) self . assertFalse ( formset . is_valid ( ) ) self . assertEqual ( formset . errors , [ { '' : [ '' ] } ] ) def test_unique_together_with_inlineformset_factory ( self ) : repository = Repository . objects . create ( name = '' ) FormSet = inlineformset_factory ( Repository , Revision , extra = ) data = { '' : '' , '' : '' , '' : '' , '' : repository . pk , '' : '' , '' : '' , } formset = FormSet ( data , instance = repository ) self . assertTrue ( formset . is_valid ( ) ) saved = formset . save ( ) self . assertEqual ( len ( saved ) , ) revision1 , = saved self . assertEqual ( revision1 . repository , repository ) self . assertEqual ( revision1 . revision , '' ) data = { '' : '' , '' : '' , '' : '' , '' : repository . pk , '' : '' , '' : '' , } formset = FormSet ( data , instance = repository ) self . assertFalse ( formset . is_valid ( ) ) self . assertEqual ( formset . errors , [ { '' : [ '' ] } ] ) FormSet = inlineformset_factory ( Repository , Revision , fields = ( '' , ) , extra = ) data = { '' : '' , '' : '' , '' : '' , '' : repository . pk , '' : '' , '' : '' , } formset = FormSet ( data , instance = repository ) self . assertFalse ( formset . is_valid ( ) ) def test_callable_defaults ( self ) : person = Person . objects . create ( name = '' ) FormSet = inlineformset_factory ( Person , Membership , can_delete = False , extra = ) formset = FormSet ( instance = person ) self . assertEqual ( len ( formset . forms ) , ) form = formset . forms [ ] now = form . fields [ '' ] . initial ( ) result = form . as_p ( ) result = re . sub ( r'' , '' , result ) self . assertHTMLEqual ( result , '' '' % person . id ) data = { '' : '' , '' : '' , '' : '' , '' : six . text_type ( now . strftime ( '' ) ) , '' : six . text_type ( now . strftime ( '' ) ) , '' : '' , } formset = FormSet ( data , instance = person ) self . assertTrue ( formset . is_valid ( ) ) one_day_later = now + datetime . timedelta ( days = ) filled_data = { '' : '' , '' : '' , '' : '' , '' : six . text_type ( one_day_later . strftime ( '' ) ) , '' : six . text_type ( now . strftime ( '' ) ) , '' : '' , } formset = FormSet ( filled_data , instance = person ) self . assertFalse ( formset . is_valid ( ) ) class MembershipForm ( forms . ModelForm ) : date_joined = forms . SplitDateTimeField ( initial = now ) class Meta : model = Membership def __init__ ( self , ** kwargs ) : super ( MembershipForm , self ) . __init__ ( ** kwargs ) self . fields [ '' ] . widget = forms . SplitDateTimeWidget ( ) FormSet = inlineformset_factory ( Person , Membership , form = MembershipForm , can_delete = False , extra = ) data = { '' : '' , '' : '' , '' : '' , '' : six . text_type ( now . strftime ( '' ) ) , '' : six . text_type ( now . strftime ( '' ) ) , '' : six . text_type ( now . strftime ( '' ) ) , '' : '' , } formset = FormSet ( data , instance = person ) self . assertTrue ( formset . is_valid ( ) ) def test_inlineformset_factory_with_null_fk ( self ) : team = Team . objects . create ( name = \"\" ) Player ( name = \"\" ) . save ( ) Player ( name = \"\" , team = team ) . save ( ) PlayerInlineFormSet = inlineformset_factory ( Team , Player ) formset = PlayerInlineFormSet ( ) self . assertQuerysetEqual ( formset . get_queryset ( ) , [ ] ) formset = PlayerInlineFormSet ( instance = team ) players = formset . get_queryset ( ) self . assertEqual ( len ( players ) , ) player1 , = players self . assertEqual ( player1 . team , team ) self . assertEqual ( player1 . name , '' ) def test_model_formset_with_custom_pk ( self ) : FormSet = modelformset_factory ( ClassyMexicanRestaurant , fields = [ \"\" ] ) self . assertEqual ( sorted ( FormSet ( ) . forms [ ] . fields . keys ( ) ) , [ '' , '' ] ) def test_prevent_duplicates_from_with_the_same_formset ( self ) : FormSet = modelformset_factory ( Product , extra = ) data = { '' : , '' : , '' : '' , '' : '' , '' : '' , } formset = FormSet ( data ) self . assertFalse ( formset . is_valid ( ) ) self . assertEqual ( formset . _non_form_errors , [ '' ] ) FormSet = modelformset_factory ( Price , extra = ) data = { '' : , '' : , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , } formset = FormSet ( data ) self . assertFalse ( formset . is_valid ( ) ) self . assertEqual ( formset . _non_form_errors , [ '' ] ) FormSet = modelformset_factory ( Price , fields = ( \"\" , ) , extra = ) ", "answer": "data = {"}, {"prompt": " \"\"\"\"\"\" import os import re import time import diamond . collector import diamond . convertor try : import psutil psutil except ImportError : psutil = None def match_process ( pid , name , cmdline , exe , cfg ) : \"\"\"\"\"\" if cfg [ '' ] and pid == os . getpid ( ) : return True for exe_re in cfg [ '' ] : if exe_re . search ( exe ) : return True for name_re in cfg [ '' ] : if name_re . search ( name ) : return True for cmdline_re in cfg [ '' ] : if cmdline_re . search ( '' . join ( cmdline ) ) : return True return False def process_info ( process , info_keys ) : results = { } process_info = process . as_dict ( ) metrics = ( ( key , process_info . get ( key , None ) ) for key in info_keys ) for key , value in metrics : if type ( value ) in [ float , int ] : results . update ( { key : value } ) elif hasattr ( value , '' ) : for subkey , subvalue in value . _asdict ( ) . iteritems ( ) : results . update ( { \"\" % ( key , subkey ) : subvalue } ) return results def get_value ( process , name ) : result = getattr ( process , name ) try : return result ( ) except TypeError : return result class ProcessResourcesCollector ( diamond . collector . Collector ) : def process_config ( self ) : super ( ProcessResourcesCollector , self ) . process_config ( ) \"\"\"\"\"\" self . processes = { } self . processes_info = { } for pg_name , cfg in self . config [ '' ] . items ( ) : pg_cfg = { } for key in ( '' , '' , '' ) : pg_cfg [ key ] = cfg . get ( key , [ ] ) if not isinstance ( pg_cfg [ key ] , list ) : pg_cfg [ key ] = [ pg_cfg [ key ] ] pg_cfg [ key ] = [ re . compile ( e ) for e in pg_cfg [ key ] ] pg_cfg [ '' ] = cfg . get ( '' , '' ) . lower ( ) == '' pg_cfg [ '' ] = cfg . get ( '' , '' ) . lower ( ) == '' self . processes [ pg_name ] = pg_cfg self . processes_info [ pg_name ] = { } def get_default_config_help ( self ) : config_help = super ( ProcessResourcesCollector , self ) . get_default_config_help ( ) config_help . update ( { '' : '' , '' : ( \"\" \"\" ) , } ) return config_help def get_default_config ( self ) : \"\"\"\"\"\" config = super ( ProcessResourcesCollector , self ) . get_default_config ( ) config . update ( { '' : '' , '' : '' , '' : { } , } ) return config default_info_keys = [ '' , '' , '' , '' , '' , '' , '' , '' , ] def save_process_info ( self , pg_name , process_info ) : for key , value in process_info . iteritems ( ) : if key in self . processes_info [ pg_name ] : self . processes_info [ pg_name ] [ key ] += value else : self . processes_info [ pg_name ] [ key ] = value def collect_process_info ( self , process ) : try : pid = get_value ( process , '' ) name = get_value ( process , '' ) cmdline = get_value ( process , '' ) try : exe = get_value ( process , '' ) except psutil . AccessDenied : ", "answer": "exe = \"\""}, {"prompt": " import datetime from south . db import db from south . v2 import DataMigration from django . db import models class Migration ( DataMigration ) : def forwards ( self , orm ) : \"\" orm . Knesset . objects . get_or_create ( number = , defaults = { '' : datetime . date ( , , ) , '' : datetime . date ( , , ) } ) def backwards ( self , orm ) : \"\" orm . Knesset . objects . filter ( number = ) . delete ( ) models = { '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) } , '' : { '' : { '' : \"\" , '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) } , '' : { '' : { '' : \"\" , '' : \"\" , '' : '' , '' : \"\" } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : \"\" } ) , '' : ( '' , [ ] , { '' : \"\" , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) } , '' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : \"\" , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , ", "answer": "'' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) ,"}, {"prompt": " from framework . dependency_management . dependency_resolver import ServiceLocator \"\"\"\"\"\" import string , re import cgi DESCRIPTION = \"\" def run ( PluginInfo ) : plugin_helper = ServiceLocator . get_component ( \"\" ) Content = plugin_helper . VulnerabilitySearchBox ( '' ) ", "answer": "Content += plugin_helper . ResourceLinkList ( '' , ServiceLocator . get_component ( \"\" ) . GetResources ( '' ) )"}, {"prompt": " \"\"\"\"\"\" from nose . tools import * from networkx import * class TestGeneratorNonIsomorphicTrees ( ) : def test_tree_structure ( self ) : f = lambda x : list ( nx . nonisomorphic_trees ( x ) ) for i in f ( ) : assert_true ( nx . is_tree ( i ) ) for i in f ( ) : assert_true ( nx . is_tree ( i ) ) def test_nonisomorphism ( self ) : f = lambda x : list ( nx . nonisomorphic_trees ( x ) ) trees = f ( ) for i in range ( len ( trees ) ) : for j in range ( i + , len ( trees ) ) : assert_false ( nx . is_isomorphic ( trees [ i ] , trees [ j ] ) ) trees = f ( ) for i in range ( len ( trees ) ) : for j in range ( i + , len ( trees ) ) : assert_false ( nx . is_isomorphic ( trees [ i ] , trees [ j ] ) ) def test_number_of_nonisomorphic_trees ( self ) : assert_equal ( nx . number_of_nonisomorphic_trees ( ) , ) ", "answer": "assert_equal ( nx . number_of_nonisomorphic_trees ( ) , )"}, {"prompt": " \"\"\"\"\"\" import uuid import os from random import Random from copy import copy from IPython . parallel import interactive from sklearn . base import clone from sklearn . externals import joblib from pyrallel . common import TaskManager from pyrallel . mmap_utils import host_dump try : basestring except NameError : basestring = ( str , bytes ) def combine ( all_ensembles ) : \"\"\"\"\"\" final_ensemble = copy ( all_ensembles [ ] ) final_ensemble . estimators_ = [ ] for ensemble in all_ensembles : final_ensemble . estimators_ += ensemble . estimators_ final_ensemble . n_estimators = len ( final_ensemble . estimators_ ) return final_ensemble def sub_ensemble ( ensemble , n_estimators , seed = None ) : \"\"\"\"\"\" rng = Random ( seed ) final_ensemble = copy ( ensemble ) if n_estimators > len ( ensemble . estimators_ ) : raise ValueError ( \"\" % ( n_estimators , len ( ensemble . estimators_ ) ) ) final_ensemble . estimators_ = rng . sample ( ensemble . estimators_ , n_estimators ) final_ensemble . n_estimators = len ( final_ensemble . estimators_ ) return final_ensemble @ interactive def train_model ( model , data_filename , model_filename = None , random_state = None ) : from sklearn . externals import joblib X , y , sample_weight = joblib . load ( data_filename , mmap_mode = '' ) model . set_params ( random_state = random_state ) if sample_weight is not None : model . fit ( X , y , sample_weight = sample_weight ) else : model . fit ( X , y ) for estimator in model . estimators_ : if ( hasattr ( estimator , '' ) and hasattr ( estimator . tree_ , '' ) ) : estimator . tree_ . random_state = if model_filename is not None : joblib . dump ( model , model_filename ) return model_filename return model class EnsembleGrower ( TaskManager ) : \"\"\"\"\"\" def __init__ ( self , load_balanced_view , base_model ) : self . tasks = [ ] self . base_model = base_model self . lb_view = load_balanced_view self . _temp_files = [ ] def reset ( self ) : self . abort ( ) self . tasks [ : ] = [ ] for filename in self . _temp_files : os . unlink ( filename ) del self . _temp_files [ : ] def launch ( self , X , y , sample_weight = None , n_estimators = , pre_warm = True , folder = \"\" , name = None , dump_models = False ) : self . reset ( ) if name is None : name = uuid . uuid4 ( ) . get_hex ( ) if not os . path . exists ( folder ) : os . makedirs ( folder ) data_filename = os . path . join ( folder , name + '' ) data_filename = os . path . abspath ( data_filename ) host_dump ( self . lb_view . client , ( X , y , sample_weight ) , data_filename , pre_warm = pre_warm ) for i in range ( n_estimators ) : base_model = clone ( self . base_model ) if dump_models : model_filename = os . path . join ( folder , name + '' % i ) model_filename = os . path . abspath ( model_filename ) else : model_filename = None self . tasks . append ( self . lb_view . apply ( train_model , base_model , data_filename , model_filename , random_state = i ) ) return self def report ( self , n_top = ) : output = ( \"\" ", "answer": "\"\" ) . format ("}, {"prompt": " '''''' import requests import simplejson as json USERDATA = '' def retrieveUserData ( url ) : '''''' req = requests . get ( url ) content = json . loads ( req . content ) filteredData = [ ] data = { } data [ '' ] = content [ '' ] data [ '' ] = content [ '' ] . upper ( ) ", "answer": "data [ '' ] = content [ '' ]"}, {"prompt": " from __future__ import print_function from __future__ import unicode_literals try : from unittest import mock except ImportError : import mock import pytest from tdclient import cursor from tdclient import errors from tdclient . test . test_helper import * def setup_function ( function ) : unset_environ ( ) def test_cursor ( ) : td = cursor . Cursor ( mock . MagicMock ( ) ) assert td . _rows is None assert td . _rownumber == assert td . rowcount == - assert td . description == [ ] def test_cursor_close ( ) : td = cursor . Cursor ( mock . MagicMock ( ) ) td . close ( ) assert td . api . close . called def test_cursor_execute ( ) : td = cursor . Cursor ( mock . MagicMock ( ) , db = \"\" ) td . api . query = mock . MagicMock ( return_value = ) td . _do_execute = mock . MagicMock ( ) assert td . execute ( \"\" ) == td . api . query . assert_called_with ( \"\" , db = \"\" ) assert td . _do_execute . called assert td . _rows is None assert td . _rownumber == assert td . _rowcount == - assert td . _description == [ ] def test_cursor_execute_format_dict ( ) : td = cursor . Cursor ( mock . MagicMock ( ) , db = \"\" ) td . api . query = mock . MagicMock ( return_value = ) td . _do_execute = mock . MagicMock ( ) assert td . execute ( \"\" , args = { \"\" : , \"\" : \"\" } ) == td . api . query . assert_called_with ( \"\" , db = \"\" ) assert td . _do_execute . called assert td . _rows is None assert td . _rownumber == assert td . _rowcount == - assert td . _description == [ ] def test_cursor_execute_format_tuple ( ) : td = cursor . Cursor ( mock . MagicMock ( ) , db = \"\" ) with pytest . raises ( errors . NotSupportedError ) as error : td . execute ( \"\" , args = ( , \"\" ) ) def test_cursor_executemany ( ) : td = cursor . Cursor ( mock . MagicMock ( ) , db = \"\" ) td . api . query = mock . MagicMock ( side_effect = [ , , ] ) td . _do_execute = mock . MagicMock ( ) assert td . executemany ( \"\" , [ { \"\" : } , { \"\" : } , { \"\" : } ] ) == [ , , ] td . api . query . assert_called_with ( \"\" , db = \"\" ) assert td . _do_execute . called assert td . _rows is None assert td . _rownumber == assert td . _rowcount == - assert td . _description == [ ] def test_check_executed ( ) : td = cursor . Cursor ( mock . MagicMock ( ) , db = \"\" ) assert td . _executed is None with pytest . raises ( errors . ProgrammingError ) as error : td . _check_executed ( ) td . _executed = \"\" td . _check_executed ( ) def test_do_execute_success ( ) : td = cursor . Cursor ( mock . MagicMock ( ) , db = \"\" ) td . _executed = \"\" td . _check_executed = mock . MagicMock ( return_value = True ) td . api . job_status = mock . MagicMock ( return_value = \"\" ) td . api . job_result = mock . MagicMock ( return_value = [ [ \"\" , ] , [ \"\" , ] , [ \"\" , ] ] ) td . api . show_job = mock . MagicMock ( return_value = { \"\" : [ [ \"\" , \"\" ] , [ \"\" , \"\" ] ] } ) td . _do_execute ( ) assert td . _check_executed . called td . api . job_status . assert_called_with ( \"\" ) td . api . job_result . assert_called_with ( \"\" ) td . api . show_job . assert_called_with ( \"\" ) assert td . _rownumber == assert td . _rowcount == assert td . _description == [ ( \"\" , None , None , None , None , None , None ) , ( \"\" , None , None , None , None , None , None ) ] def test_do_execute_error ( ) : td = cursor . Cursor ( mock . MagicMock ( ) , db = \"\" ) td . _executed = \"\" td . api . job_status = mock . MagicMock ( side_effect = [ \"\" ] ) with pytest . raises ( errors . InternalError ) as error : td . _do_execute ( ) def test_do_execute_wait ( ) : td = cursor . Cursor ( mock . MagicMock ( ) , db = \"\" , wait_interval = , wait_callback = mock . MagicMock ( ) ) td . _executed = \"\" td . _check_executed = mock . MagicMock ( return_value = True ) td . api . job_status = mock . MagicMock ( side_effect = [ \"\" , \"\" , \"\" ] ) td . api . job_result = mock . MagicMock ( return_value = [ [ \"\" , ] , [ \"\" , ] , [ \"\" , ] ] ) td . api . show_job = mock . MagicMock ( return_value = { \"\" : [ [ \"\" , \"\" ] , [ \"\" , \"\" ] ] } ) with mock . patch ( \"\" ) as t_sleep : td . _do_execute ( ) t_sleep . assert_called_with ( ) assert td . wait_callback . called assert td . _check_executed . called td . api . job_status . assert_called_with ( \"\" ) td . api . job_result . assert_called_with ( \"\" ) td . api . show_job . assert_called_with ( \"\" ) assert td . _rownumber == assert td . _rowcount == assert td . _description == [ ( \"\" , None , None , None , None , None , None ) , ( \"\" , None , None , None , None , None , None ) ] def test_result_description ( ) : td = cursor . Cursor ( mock . MagicMock ( ) ) assert td . _result_description ( None ) == [ ] assert td . _result_description ( [ [ \"\" , \"\" ] ] ) == [ ( \"\" , None , None , None , None , None , None ) ] def test_fetchone ( ) : td = cursor . Cursor ( mock . MagicMock ( ) ) td . _executed = \"\" td . _rows = [ [ \"\" , ] , [ \"\" , ] , [ \"\" , ] ] td . _rownumber = td . _rowcount = len ( td . _rows ) assert td . fetchone ( ) == [ \"\" , ] assert td . fetchone ( ) == [ \"\" , ] assert td . fetchone ( ) == [ \"\" , ] with pytest . raises ( errors . InternalError ) as error : td . fetchone ( ) def test_fetchmany ( ) : td = cursor . Cursor ( mock . MagicMock ( ) ) td . _executed = \"\" td . _rows = [ [ \"\" , ] , [ \"\" , ] , [ \"\" , ] ] td . _rownumber = td . _rowcount = len ( td . _rows ) assert td . fetchmany ( ) == [ [ \"\" , ] , [ \"\" , ] ] assert td . fetchmany ( ) == [ [ \"\" , ] ] with pytest . raises ( errors . InternalError ) as error : td . fetchmany ( ) def test_fetchall ( ) : td = cursor . Cursor ( mock . MagicMock ( ) ) td . _executed = \"\" td . _rows = [ [ \"\" , ] , [ \"\" , ] , [ \"\" , ] ] td . _rownumber = td . _rowcount = len ( td . _rows ) assert td . fetchall ( ) == [ [ \"\" , ] , [ \"\" , ] , [ \"\" , ] ] with pytest . raises ( errors . InternalError ) as error : td . fetchall ( ) def test_show_job ( ) : td = cursor . Cursor ( mock . MagicMock ( ) ) td . _executed = \"\" td . show_job ( ) td . api . show_job . assert_called_with ( \"\" ) def test_job_status ( ) : td = cursor . Cursor ( mock . MagicMock ( ) ) td . _executed = \"\" td . job_status ( ) td . api . job_status . assert_called_with ( \"\" ) def test_job_result ( ) : ", "answer": "td = cursor . Cursor ( mock . MagicMock ( ) )"}, {"prompt": " import os import webbrowser from invoke import task , run docs_dir = '' build_dir = os . path . join ( docs_dir , '' ) @ task def test ( ) : run ( '' , pty = True ) @ task def clean ( ) : run ( \"\" ) run ( \"\" ) run ( \"\" ) clean_docs ( ) print ( \"\" ) @ task def clean_docs ( ) : run ( \"\" % build_dir ) @ task def browse_docs ( ) : path = os . path . join ( build_dir , '' ) webbrowser . open_new_tab ( path ) @ task ", "answer": "def docs ( clean = False , browse = False ) :"}, {"prompt": " from social . utils import module_member _current_strategy_getter = None def get_strategy ( strategy , storage , * args , ** kwargs ) : Strategy = module_member ( strategy ) Storage = module_member ( storage ) return Strategy ( Storage , * args , ** kwargs ) def set_current_strategy_getter ( func ) : global _current_strategy_getter _current_strategy_getter = func def get_current_strategy ( ) : ", "answer": "global _current_strategy_getter"}, {"prompt": " assert_has_feature ( ", "answer": " , , , \"\" ,"}, {"prompt": " '''''' from treemodel import PROJECT , Project , Node , Task , Context , Folder , Note , sort import sqlite3 from os import environ , path from datetime import datetime from typeof import TypeOf from xml . dom . minidom import parseString import logging logger = logging . getLogger ( __name__ ) '''''' THIRTY_ONE_YEARS = * * * * + * * * class OFNote ( Note ) : def __init__ ( self , item , noteXMLData ) : self . noteXMLData = noteXMLData self . item = item self . text = None self . lines = None def get_note_lines ( self ) : if self . lines == None : logger . debug ( '' , self . item . id ) dom = parseString ( self . noteXMLData ) logger . debug ( '' , self . item . id ) self . lines = [ ] for para in dom . getElementsByTagName ( \"\" ) : line = [ ] for lit in para . getElementsByTagName ( \"\" ) : if lit . firstChild != None : nodeValue = lit . firstChild . nodeValue if nodeValue != None : text = self . fix_dodgy_chars ( nodeValue ) line . append ( text ) self . lines . append ( u'' . join ( line ) ) logger . debug ( '' , self . item . id ) return self . lines def get_note ( self ) : if self . text == None : self . text = '' . join ( self . get_note_lines ( ) ) return self . text def fix_dodgy_chars ( self , text ) : try : return unicode ( text ) except : buf = [ ] for c in text : try : buf . append ( unicode ( c ) ) except : buf . append ( '' ) return u'' . join ( buf ) def datetimeFromAttrib ( ofattribs , name ) : val = ofattribs [ name ] if val == None : return None return datetime . fromtimestamp ( THIRTY_ONE_YEARS + val ) def intFromAttrib ( ofattribs , name ) : val = ofattribs [ name ] if val == None : return None return val class OFContext ( Context ) : TABLE = '' COLUMNS = [ '' , '' , '' , '' , '' , '' ] ofattribs = TypeOf ( '' , dict ) def __init__ ( self , ofattribs ) : Context . __init__ ( self , name = ofattribs [ '' ] ) self . ofattribs = ofattribs self . order = ofattribs [ '' ] if '' in ofattribs : self . id = ofattribs [ '' ] self . link = '' + ofattribs [ '' ] self . status = u'' if '' in ofattribs and ofattribs [ '' ] == else u'' logger . debug ( '' , self . id , self . name ) class OFTask ( Task ) : TABLE = '' COLUMNS = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ] ofattribs = TypeOf ( '' , dict ) def __init__ ( self , ofattribs ) : Task . __init__ ( self , name = ofattribs [ '' ] , date_completed = datetimeFromAttrib ( ofattribs , '' ) , date_to_start = datetimeFromAttrib ( ofattribs , '' ) , date_due = datetimeFromAttrib ( ofattribs , '' ) , date_added = datetimeFromAttrib ( ofattribs , '' ) , estimated_minutes = intFromAttrib ( ofattribs , '' ) , flagged = bool ( ofattribs [ '' ] ) , context = None ) self . ofattribs = ofattribs self . order = ofattribs [ '' ] if '' in ofattribs : self . id = ofattribs [ '' ] self . link = '' + ofattribs [ '' ] noteXMLData = ofattribs [ '' ] if noteXMLData != None : self . note = OFNote ( self , noteXMLData ) logger . debug ( '' , self . id , self . name ) class OFFolder ( Folder ) : TABLE = '' COLUMNS = [ '' , '' , '' , '' , '' , '' ] ofattribs = TypeOf ( '' , dict ) def __init__ ( self , ofattribs ) : Folder . __init__ ( self , name = ofattribs [ '' ] ) self . ofattribs = ofattribs self . order = ofattribs [ '' ] if '' in ofattribs : self . id = ofattribs [ '' ] self . link = '' + ofattribs [ '' ] logger . debug ( '' , self . id , self . name ) class ProjectInfo ( Node ) : TABLE = '' COLUMNS = [ '' , '' , '' , '' ] status = TypeOf ( '' , unicode ) nextTask = TypeOf ( '' , str ) def __init__ ( self , ofattribs ) : Node . __init__ ( self , \"\" ) self . ofattribs = ofattribs self . status = ofattribs [ '' ] self . next_task = None if ofattribs [ '' ] == None else str ( ofattribs [ '' ] ) class OFProject ( Project ) : ofattribs = TypeOf ( '' , dict ) folder = TypeOf ( '' , Folder ) project_info = TypeOf ( '' , ProjectInfo ) def __init__ ( self ) : pass def query ( conn , clazz ) : c = conn . cursor ( ) columns = clazz . COLUMNS results = { } for row in c . execute ( '' + ( '' . join ( columns ) ) + '' + clazz . TABLE ) : rowData = { } for i in range ( , len ( columns ) ) : key = columns [ i ] val = row [ i ] rowData [ key ] = val node = clazz ( rowData ) results [ rowData [ columns [ ] ] ] = node c . close ( ) return results def transmute_projects ( project_infos , tasks ) : '''''' logger . debug ( '' ) projects = { } for project in tasks . values ( ) : if project . ofattribs [ '' ] != None : logger . debug ( '' , project . id , project . name ) projects [ project . ofattribs [ '' ] ] = project project_info = project_infos [ project . ofattribs [ '' ] ] project . __class__ = OFProject project . __init__ ( ) project_info . project = project project . type = PROJECT project . project_info = project_info project . status = project_info . status return projects def wire_projects_and_folders ( projects , folders , tasks ) : logger . debug ( '' ) for project in projects . values ( ) : project_info = project . project_info if project . project_info != None : folder_ref = project_info . ofattribs [ '' ] if folder_ref != None : logger . debug ( '' , project . id , project . name ) folder = folders [ folder_ref ] project . folder = folder folder . add_child ( project ) if project_info . next_task != None : task = tasks [ project_info . next_task ] task . next = True def wire_task_hierarchy ( tasks ) : logger . debug ( '' ) for task in tasks . values ( ) : if task . ofattribs [ '' ] != None : logger . debug ( '' , task . id , task . name ) parent = tasks [ task . ofattribs [ '' ] ] parent . add_child ( task ) def wire_tasks_to_enclosing_projects ( project_infos , tasks , inbox ) : logger . debug ( '' ) for task in tasks . values ( ) : if task . ofattribs [ '' ] != None : logger . debug ( '' , task . id , task . name ) project_info = project_infos [ task . ofattribs [ '' ] ] project = project_info . project task . project = project elif task . ofattribs [ '' ] : inbox . add_child ( task ) def wire_tasks_and_contexts ( contexts , tasks , no_context ) : logger . debug ( '' ) for task in tasks . values ( ) : logger . debug ( '' , task . id , task . name ) if task . ofattribs [ '' ] != None : context = contexts [ task . ofattribs [ '' ] ] task . context = context context . children . append ( task ) else : task . context = no_context no_context . children . append ( task ) def wire_folder_hierarchy ( folders ) : logger . debug ( '' ) for folder in folders . values ( ) : if folder . ofattribs [ '' ] != None : logger . debug ( '' , folder . id , folder . name ) parent = folders [ folder . ofattribs [ '' ] ] parent . add_child ( folder ) def wire_context_hierarchy ( contexts ) : logger . debug ( '' ) for context in contexts . values ( ) : if context . ofattribs [ '' ] != None : logger . debug ( '' , context . id , context . name ) parent = contexts [ context . ofattribs [ '' ] ] parent . add_child ( context ) def only_roots ( items ) : roots = [ ] for item in items : if item . parent == None : roots . append ( item ) return roots def build_model ( db ) : conn = sqlite3 . connect ( db ) contexts = query ( conn , clazz = OFContext ) no_context = Context ( name = '' ) inbox = Project ( name = '' ) project_infos = query ( conn , clazz = ProjectInfo ) folders = query ( conn , clazz = OFFolder ) tasks = query ( conn , clazz = OFTask ) projects = transmute_projects ( project_infos , tasks ) wire_projects_and_folders ( projects , folders , tasks ) wire_task_hierarchy ( tasks ) wire_tasks_to_enclosing_projects ( project_infos , tasks , inbox ) wire_tasks_and_contexts ( contexts , tasks , no_context ) wire_folder_hierarchy ( folders ) wire_context_hierarchy ( contexts ) conn . close ( ) project_roots = only_roots ( projects . values ( ) ) folder_roots = only_roots ( folders . values ( ) ) ", "answer": "root_projects_and_folders = project_roots + folder_roots"}, {"prompt": " \"\"\"\"\"\" ", "answer": "from gcloud . bigtable . client import Client "}, {"prompt": " import datetime from south . db import db from south . v2 import SchemaMigration from django . db import models class Migration ( SchemaMigration ) : def forwards ( self , orm ) : db . alter_column ( '' , '' , self . gf ( '' ) ( null = True , to = orm [ '' ] ) ) def backwards ( self , orm ) : raise RuntimeError ( \"\" ) models = { '' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) } , '' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : \"\" , '' : '' , '' : [ '' ] } , '' : ( '' , [ ] , { } ) , '' : ( '' , [ ] , { } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { } ) , '' : ( '' , [ ] , { } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) } , '' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : \"\" , '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , ", "answer": "'' : ( '' , [ ] , { '' : \"\" , '' : '' } ) ,"}, {"prompt": " from __future__ import unicode_literals from argparse import Namespace try : from io import StringIO except : from StringIO import StringIO import sys import unittest try : from unittest . mock import MagicMock , patch except : from mock import MagicMock , patch from green import djangorunner from green . config import mergeConfig class TestDjangoMissing ( unittest . TestCase ) : def test_importError ( self ) : self . assertRaises ( ImportError , djangorunner . django_missing ) class TestDjangoRunner ( unittest . TestCase ) : def setUp ( self ) : try : djangorunner . DjangoRunner ( ) except ImportError : raise unittest . SkipTest ( \"\" ) saved_stdout = sys . stdout self . stream = StringIO ( ) sys . stdout = self . stream self . addCleanup ( setattr , sys , '' , saved_stdout ) def test_run_testsWithLabel ( self ) : dr = djangorunner . DjangoRunner ( ) dr . setup_test_environment = MagicMock ( ) dr . setup_databases = MagicMock ( ) dr . teardown_databases = MagicMock ( ) dr . teardown_test_environment = MagicMock ( ) dr . run_tests ( ( '' , ) , testing = True ) self . assertIn ( '' , self . stream . getvalue ( ) ) def test_run_testsWithoutLabel ( self ) : \"\"\"\"\"\" dr = djangorunner . DjangoRunner ( ) dr . setup_test_environment = MagicMock ( ) dr . setup_databases = MagicMock ( ) dr . teardown_databases = MagicMock ( ) dr . teardown_test_environment = MagicMock ( ) saved_loadTargets = djangorunner . loadTargets djangorunner . loadTargets = MagicMock ( ) self . addCleanup ( setattr , djangorunner , '' , saved_loadTargets ) dr . run_tests ( ( ) , testing = True ) djangorunner . loadTargets . assert_called_with ( [ '' ] ) self . assertIn ( '' , self . stream . getvalue ( ) ) def test_run_testsWithBadInput ( self ) : \"\"\"\"\"\" dr = djangorunner . DjangoRunner ( ) dr . setup_test_environment = MagicMock ( ) dr . setup_databases = MagicMock ( ) self . assertRaises ( ValueError , dr . run_tests , None , True ) @ patch ( '' ) @ patch ( '' ) ", "answer": "@ patch ( '' )"}, {"prompt": " from . . import queue __all__ = [ '' , '' , '' , '' , '' ] __patched__ = [ '' , '' , '' ] class Queue ( queue . Queue ) : def __init__ ( self , maxsize = ) : if maxsize == : maxsize = None super ( Queue , self ) . __init__ ( maxsize ) class PriorityQueue ( queue . PriorityQueue ) : def __init__ ( self , maxsize = ) : if maxsize == : maxsize = None super ( PriorityQueue , self ) . __init__ ( maxsize ) class LifoQueue ( queue . LifoQueue ) : def __init__ ( self , maxsize = ) : if maxsize == : ", "answer": "maxsize = None"}, {"prompt": " from muntjac . demo . sampler . APIResource import APIResource from muntjac . demo . sampler . Feature import Feature , Version from muntjac . ui . menu_bar import MenuBar class BasicMenuBar ( Feature ) : def getSinceVersion ( self ) : return Version . V62 def getName ( self ) : return '' def getDescription ( self ) : return ( '' '' ) def getRelatedAPI ( self ) : ", "answer": "return [ APIResource ( MenuBar ) ]"}, {"prompt": " \"\"\"\"\"\" from twisted . trial . unittest import TestCase from twisted . python . constants import ( NamedConstant , Names , ValueConstant , Values , FlagConstant , Flags ) class NamedConstantTests ( TestCase ) : \"\"\"\"\"\" def setUp ( self ) : \"\"\"\"\"\" class foo ( Names ) : pass self . container = foo def test_name ( self ) : \"\"\"\"\"\" name = NamedConstant ( ) name . _realize ( self . container , \"\" , None ) self . assertEqual ( \"\" , name . name ) def test_representation ( self ) : \"\"\"\"\"\" name = NamedConstant ( ) name . _realize ( self . container , \"\" , None ) self . assertEqual ( \"\" , repr ( name ) ) def test_equality ( self ) : \"\"\"\"\"\" name = NamedConstant ( ) name . _realize ( self . container , \"\" , None ) self . assertTrue ( name == name ) self . assertFalse ( name != name ) def test_nonequality ( self ) : \"\"\"\"\"\" first = NamedConstant ( ) first . _realize ( self . container , \"\" , None ) second = NamedConstant ( ) second . _realize ( self . container , \"\" , None ) self . assertFalse ( first == second ) self . assertTrue ( first != second ) def test_hash ( self ) : \"\"\"\"\"\" first = NamedConstant ( ) first . _realize ( self . container , \"\" , None ) second = NamedConstant ( ) second . _realize ( self . container , \"\" , None ) self . assertNotEqual ( hash ( first ) , hash ( second ) ) class _ConstantsTestsMixin ( object ) : \"\"\"\"\"\" def _notInstantiableTest ( self , name , cls ) : \"\"\"\"\"\" exc = self . assertRaises ( TypeError , cls ) self . assertEqual ( name + \"\" , str ( exc ) ) class NamesTests ( TestCase , _ConstantsTestsMixin ) : \"\"\"\"\"\" def setUp ( self ) : \"\"\"\"\"\" class METHOD ( Names ) : \"\"\"\"\"\" GET = NamedConstant ( ) PUT = NamedConstant ( ) POST = NamedConstant ( ) DELETE = NamedConstant ( ) self . METHOD = METHOD def test_notInstantiable ( self ) : \"\"\"\"\"\" self . _notInstantiableTest ( \"\" , self . METHOD ) def test_symbolicAttributes ( self ) : \"\"\"\"\"\" self . assertTrue ( hasattr ( self . METHOD , \"\" ) ) self . assertTrue ( hasattr ( self . METHOD , \"\" ) ) self . assertTrue ( hasattr ( self . METHOD , \"\" ) ) self . assertTrue ( hasattr ( self . METHOD , \"\" ) ) def test_withoutOtherAttributes ( self ) : \"\"\"\"\"\" self . assertFalse ( hasattr ( self . METHOD , \"\" ) ) def test_representation ( self ) : \"\"\"\"\"\" self . assertEqual ( \"\" , repr ( self . METHOD . GET ) ) def test_lookupByName ( self ) : \"\"\"\"\"\" method = self . METHOD . lookupByName ( \"\" ) self . assertIdentical ( self . METHOD . GET , method ) def test_notLookupMissingByName ( self ) : \"\"\"\"\"\" self . assertRaises ( ValueError , self . METHOD . lookupByName , \"\" ) self . assertRaises ( ValueError , self . METHOD . lookupByName , \"\" ) self . assertRaises ( ValueError , self . METHOD . lookupByName , \"\" ) def test_name ( self ) : \"\"\"\"\"\" self . assertEqual ( \"\" , self . METHOD . GET . name ) def test_attributeIdentity ( self ) : \"\"\"\"\"\" self . assertIdentical ( self . METHOD . GET , self . METHOD . GET ) def test_iterconstants ( self ) : \"\"\"\"\"\" constants = list ( self . METHOD . iterconstants ( ) ) self . assertEqual ( [ self . METHOD . GET , self . METHOD . PUT , self . METHOD . POST , self . METHOD . DELETE ] , constants ) def test_attributeIterconstantsIdentity ( self ) : \"\"\"\"\"\" constants = list ( self . METHOD . iterconstants ( ) ) self . assertIdentical ( self . METHOD . GET , constants [ ] ) self . assertIdentical ( self . METHOD . PUT , constants [ ] ) self . assertIdentical ( self . METHOD . POST , constants [ ] ) self . assertIdentical ( self . METHOD . DELETE , constants [ ] ) def test_iterconstantsIdentity ( self ) : \"\"\"\"\"\" constants = list ( self . METHOD . iterconstants ( ) ) again = list ( self . METHOD . iterconstants ( ) ) self . assertIdentical ( again [ ] , constants [ ] ) self . assertIdentical ( again [ ] , constants [ ] ) self . assertIdentical ( again [ ] , constants [ ] ) self . assertIdentical ( again [ ] , constants [ ] ) def test_initializedOnce ( self ) : \"\"\"\"\"\" first = self . METHOD . _enumerants self . METHOD . GET second = self . METHOD . _enumerants self . assertIdentical ( first , second ) class ValuesTests ( TestCase , _ConstantsTestsMixin ) : \"\"\"\"\"\" def setUp ( self ) : \"\"\"\"\"\" class STATUS ( Values ) : OK = ValueConstant ( \"\" ) NOT_FOUND = ValueConstant ( \"\" ) self . STATUS = STATUS def test_notInstantiable ( self ) : \"\"\"\"\"\" self . _notInstantiableTest ( \"\" , self . STATUS ) def test_symbolicAttributes ( self ) : \"\"\"\"\"\" self . assertTrue ( hasattr ( self . STATUS , \"\" ) ) self . assertTrue ( hasattr ( self . STATUS , \"\" ) ) def test_withoutOtherAttributes ( self ) : \"\"\"\"\"\" self . assertFalse ( hasattr ( self . STATUS , \"\" ) ) def test_representation ( self ) : \"\"\"\"\"\" self . assertEqual ( \"\" , repr ( self . STATUS . OK ) ) def test_lookupByName ( self ) : \"\"\"\"\"\" method = self . STATUS . lookupByName ( \"\" ) self . assertIdentical ( self . STATUS . OK , method ) def test_notLookupMissingByName ( self ) : \"\"\"\"\"\" self . assertRaises ( ValueError , self . STATUS . lookupByName , \"\" ) self . assertRaises ( ValueError , self . STATUS . lookupByName , \"\" ) self . assertRaises ( ValueError , self . STATUS . lookupByName , \"\" ) def test_lookupByValue ( self ) : \"\"\"\"\"\" status = self . STATUS . lookupByValue ( \"\" ) self . assertIdentical ( self . STATUS . OK , status ) def test_lookupDuplicateByValue ( self ) : \"\"\"\"\"\" class TRANSPORT_MESSAGE ( Values ) : \"\"\"\"\"\" KEX_DH_GEX_REQUEST_OLD = ValueConstant ( ) KEXDH_INIT = ValueConstant ( ) self . assertIdentical ( TRANSPORT_MESSAGE . lookupByValue ( ) , TRANSPORT_MESSAGE . KEX_DH_GEX_REQUEST_OLD ) def test_notLookupMissingByValue ( self ) : \"\"\"\"\"\" self . assertRaises ( ValueError , self . STATUS . lookupByValue , \"\" ) self . assertRaises ( ValueError , self . STATUS . lookupByValue , ) self . assertRaises ( ValueError , self . STATUS . lookupByValue , \"\" ) def test_name ( self ) : \"\"\"\"\"\" self . assertEqual ( \"\" , self . STATUS . OK . name ) def test_attributeIdentity ( self ) : \"\"\"\"\"\" self . assertIdentical ( self . STATUS . OK , self . STATUS . OK ) def test_iterconstants ( self ) : \"\"\"\"\"\" constants = list ( self . STATUS . iterconstants ( ) ) self . assertEqual ( [ self . STATUS . OK , self . STATUS . NOT_FOUND ] , constants ) def test_attributeIterconstantsIdentity ( self ) : \"\"\"\"\"\" constants = list ( self . STATUS . iterconstants ( ) ) self . assertIdentical ( self . STATUS . OK , constants [ ] ) self . assertIdentical ( self . STATUS . NOT_FOUND , constants [ ] ) def test_iterconstantsIdentity ( self ) : \"\"\"\"\"\" constants = list ( self . STATUS . iterconstants ( ) ) again = list ( self . STATUS . iterconstants ( ) ) self . assertIdentical ( again [ ] , constants [ ] ) self . assertIdentical ( again [ ] , constants [ ] ) def test_initializedOnce ( self ) : \"\"\"\"\"\" first = self . STATUS . _enumerants self . STATUS . OK second = self . STATUS . _enumerants self . assertIdentical ( first , second ) class _FlagsTestsMixin ( object ) : \"\"\"\"\"\" def setUp ( self ) : \"\"\"\"\"\" class FXF ( Flags ) : READ = FlagConstant ( ) WRITE = FlagConstant ( ) APPEND = FlagConstant ( ) EXCLUSIVE = FlagConstant ( ) TEXT = FlagConstant ( ) self . FXF = FXF class FlagsTests ( _FlagsTestsMixin , TestCase , _ConstantsTestsMixin ) : \"\"\"\"\"\" def test_notInstantiable ( self ) : \"\"\"\"\"\" self . _notInstantiableTest ( \"\" , self . FXF ) def test_symbolicAttributes ( self ) : \"\"\"\"\"\" self . assertTrue ( hasattr ( self . FXF , \"\" ) ) self . assertTrue ( hasattr ( self . FXF , \"\" ) ) self . assertTrue ( hasattr ( self . FXF , \"\" ) ) self . assertTrue ( hasattr ( self . FXF , \"\" ) ) self . assertTrue ( hasattr ( self . FXF , \"\" ) ) def test_withoutOtherAttributes ( self ) : \"\"\"\"\"\" ", "answer": "self . assertFalse ( hasattr ( self . FXF , \"\" ) )"}, {"prompt": " import os os . environ [ '' ] = '' from rllab . algos . vpg import VPG from rllab . envs . box2d . cartpole_env import CartpoleEnv from rllab . baselines . zero_baseline import ZeroBaseline from rllab . baselines . linear_feature_baseline import LinearFeatureBaseline from rllab . baselines . gaussian_mlp_baseline import GaussianMLPBaseline from rllab . policies . gaussian_mlp_policy import GaussianMLPPolicy from nose2 import tools baselines = [ ZeroBaseline , LinearFeatureBaseline , GaussianMLPBaseline ] @ tools . params ( * baselines ) def test_baseline ( baseline_cls ) : env = CartpoleEnv ( ) policy = GaussianMLPPolicy ( env_spec = env . spec , hidden_sizes = ( , ) ) baseline = baseline_cls ( env_spec = env . spec ) algo = VPG ( env = env , policy = policy , baseline = baseline , ", "answer": "n_itr = , batch_size = , max_path_length = "}, {"prompt": " from shaker . engine . executors import flent from shaker . engine . executors import iperf from shaker . engine . executors import netperf from shaker . engine . executors import shell EXECUTORS = { '' : shell . ShellExecutor , ", "answer": "'' : netperf . NetperfExecutor ,"}, {"prompt": " import time from tempest . lib . common . utils import data_utils import testtools from ec2api . tests . functional import base from ec2api . tests . functional import config CONF = config . CONF class TagTest ( base . EC2TestCase ) : @ classmethod @ base . safe_setup def setUpClass ( cls ) : super ( TagTest , cls ) . setUpClass ( ) cls . zone = CONF . aws . aws_zone data = cls . client . create_volume ( Size = , AvailabilityZone = cls . zone ) cls . volume_id = data [ '' ] cls . addResourceCleanUpStatic ( cls . client . delete_volume , VolumeId = cls . volume_id ) cls . get_volume_waiter ( ) . wait_available ( cls . volume_id ) def test_create_get_delete_tag ( self ) : tag_key = data_utils . rand_name ( '' ) self . client . create_tags ( Resources = [ self . volume_id ] , Tags = [ { '' : tag_key , '' : '' } ] ) self . addResourceCleanUp ( self . client . delete_tags , Resources = [ self . volume_id ] , Tags = [ { '' : tag_key } ] ) data = self . client . describe_tags ( Filters = [ { '' : '' , '' : [ self . volume_id ] } ] ) self . assertEqual ( , len ( data [ '' ] ) ) self . client . delete_tags ( Resources = [ self . volume_id ] , Tags = [ { '' : tag_key } ] ) data = self . client . describe_tags ( Filters = [ { '' : '' , '' : [ self . volume_id ] } ] ) self . assertEqual ( , len ( data [ '' ] ) ) def test_describe_tags ( self ) : tag_key = data_utils . rand_name ( '' ) self . client . create_tags ( Resources = [ self . volume_id ] , Tags = [ { '' : tag_key , '' : '' } ] ) self . addResourceCleanUp ( self . client . delete_tags , Resources = [ self . volume_id ] , Tags = [ { '' : tag_key } ] ) data = self . client . describe_tags ( Filters = [ { '' : '' , '' : [ self . volume_id ] } ] ) self . assertEqual ( , len ( data [ '' ] ) ) tag = data [ '' ] [ ] self . assertEqual ( '' , tag . get ( '' ) ) self . assertEqual ( self . volume_id , tag . get ( '' ) ) self . assertEqual ( tag_key , tag . get ( '' ) ) self . assertEqual ( '' , tag . get ( '' ) ) data = self . client . describe_tags ( Filters = [ { '' : '' , '' : [ self . volume_id ] } , { '' : '' , '' : [ tag_key ] } ] ) self . assertEqual ( , len ( data [ '' ] ) ) data = self . client . describe_tags ( Filters = [ { '' : '' , '' : [ tag_key ] } ] ) self . assertIn ( tag_key , [ k . get ( '' ) for k in data [ '' ] ] ) data = self . client . describe_tags ( Filters = [ { '' : '' , '' : [ '' ] } ] ) self . assertIn ( '' , [ k . get ( '' ) for k in data [ '' ] ] ) data = self . client . describe_tags ( Filters = [ { '' : '' , '' : [ '' ] } ] ) items = [ k . get ( '' ) for k in data [ '' ] ] self . assertNotIn ( tag_key , items ) self . assertNotIn ( '' , items ) data = self . client . describe_tags ( Filters = [ { '' : '' , '' : [ '' ] } ] ) self . assertIn ( tag_key , [ k . get ( '' ) for k in data [ '' ] ] ) self . client . delete_tags ( Resources = [ self . volume_id ] , Tags = [ { '' : tag_key } ] ) data = self . client . describe_tags ( Filters = [ { '' : '' , '' : [ self . volume_id ] } ] ) self . assertEqual ( , len ( data [ '' ] ) ) def _test_tag_resource ( self , resource_id , res_type , describe_func ) : data = self . client . describe_tags ( Filters = [ { '' : '' , '' : [ resource_id ] } ] ) origin_count = len ( data [ '' ] ) tag_key = data_utils . rand_name ( '' ) data = self . client . create_tags ( Resources = [ resource_id ] , Tags = [ { '' : tag_key , '' : '' } ] ) self . addResourceCleanUp ( self . client . delete_tags , Resources = [ resource_id ] , Tags = [ { '' : tag_key } ] ) data = self . client . describe_tags ( Filters = [ { '' : '' , '' : [ resource_id ] } ] ) self . assertEqual ( origin_count + , len ( data [ '' ] ) ) data = self . client . describe_tags ( Filters = [ { '' : '' , '' : [ res_type ] } ] ) self . assertIn ( tag_key , [ k . get ( '' ) for k in data [ '' ] ] ) describe_func ( Filters = [ { '' : '' , '' : [ tag_key ] } ] ) self . client . delete_tags ( Resources = [ resource_id ] , Tags = [ { '' : tag_key } ] ) data = self . client . describe_tags ( Filters = [ { '' : '' , '' : [ resource_id ] } ] ) self . assertEqual ( origin_count , len ( data [ '' ] ) ) def _test_tag_resource_negative ( self , resource_id ) : data = self . client . describe_tags ( Filters = [ { '' : '' , '' : [ resource_id ] } ] ) self . assertEmpty ( data [ '' ] ) def _rollback ( fn_data ) : self . client . delete_tags ( Resources = [ resource_id ] , Tags = [ { '' : tag_key } ] ) tag_key = data_utils . rand_name ( '' ) self . assertRaises ( '' , self . client . create_tags , rollback_fn = _rollback , Resources = [ resource_id ] , Tags = [ { '' : tag_key , '' : '' } ] ) def test_tag_image ( self ) : image_id = CONF . aws . ebs_image_id if not image_id : image_id = CONF . aws . image_id if not image_id : raise self . skipException ( '' ) def describe_func ( * args , ** kwargs ) : data = self . client . describe_images ( * args , ** kwargs ) self . assertEqual ( , len ( data [ '' ] ) ) self . assertEqual ( image_id , data [ '' ] [ ] [ '' ] ) self . _test_tag_resource ( image_id , '' , describe_func ) data = self . client . describe_images ( ImageIds = [ image_id ] ) ", "answer": "image = data [ '' ] [ ]"}, {"prompt": " import mock from rally . plugins . openstack . scenarios . nova import flavors from tests . unit import test class NovaFlavorsTestCase ( test . TestCase ) : ", "answer": "def test_list_flavors ( self ) :"}, {"prompt": " \"\"\"\"\"\" import os . path as op import sys import fnmatch import boto3 from jcvi . formats . base import SetFile from jcvi . apps . base import OptionParser , ActionDispatcher , popen , sh def main ( ) : actions = ( ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ) p = ActionDispatcher ( actions ) p . dispatch ( globals ( ) ) def glob_s3 ( store , keys = None ) : store , cards = store . rsplit ( \"\" , ) contents = ls_s3 ( store ) if keys : filtered = [ x for x in contents if op . basename ( x ) . split ( \"\" ) [ ] in keys ] else : filtered = fnmatch . filter ( contents , cards ) filtered = [ \"\" . join ( ( store , x ) ) for x in filtered ] return filtered def rm_s3 ( store ) : cmd = \"\" . format ( store ) sh ( cmd ) def rm ( args ) : \"\"\"\"\"\" p = OptionParser ( rm . __doc__ ) opts , args = p . parse_args ( args ) if len ( args ) != : sys . exit ( not p . print_help ( ) ) store , = args contents = glob_s3 ( store ) for c in contents : rm_s3 ( c ) def cp ( args ) : \"\"\"\"\"\" p = OptionParser ( cp . __doc__ ) p . add_option ( \"\" , default = False , action = \"\" , help = \"\" ) opts , args = p . parse_args ( args ) if len ( args ) != : sys . exit ( not p . print_help ( ) ) store , folder = args contents = glob_s3 ( store ) for c in contents : oc = op . basename ( c ) tc = op . join ( folder , oc ) if opts . force or not op . exists ( tc ) : pull_from_s3 ( c ) def ls ( args ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " from oslo_serialization import jsonutils from oslo_utils import versionutils from nova import db from nova . objects import base from nova . objects import fields @ base . NovaObjectRegistry . register class InstancePCIRequest ( base . NovaObject , base . NovaObjectDictCompat ) : VERSION = '' fields = { '' : fields . IntegerField ( ) , '' : fields . ListOfDictOfNullableStringsField ( ) , '' : fields . StringField ( nullable = True ) , '' : fields . BooleanField ( default = False ) , '' : fields . UUIDField ( nullable = True ) , } def obj_load_attr ( self , attr ) : setattr ( self , attr , None ) @ property def new ( self ) : return self . is_new def obj_make_compatible ( self , primitive , target_version ) : target_version = versionutils . convert_version_to_tuple ( target_version ) if target_version < ( , ) and '' in primitive : del primitive [ '' ] ", "answer": "@ base . NovaObjectRegistry . register"}, {"prompt": " import sct_utils as sct import commands def test ( path_data ) : folder_data = '' file_data = [ '' , '' ] cmd = '' + path_data + folder_data + file_data [ ] + '' + path_data + folder_data + file_data [ ] + '' + '' + '' + '' return commands . getstatusoutput ( cmd ) ", "answer": "if __name__ == \"\" :"}, {"prompt": " import autocomplete_light . shortcuts as al from models import * class AuthorityAutocomplete ( al . AutocompleteModelBase ) : \"\"\"\"\"\" choice_html_format = u'''''' def choice_html ( self , choice ) : return self . choice_html_format % ( self . choice_value ( choice ) , self . choice_label ( choice ) , choice . description ) search_fields = [ '' , ] autocomplete_js_attributes = { '' : , } widget_js_attributes = { '' : , } al . register ( Authority , AuthorityAutocomplete ) al . register ( Language , search_fields = [ '' , '' ] , attrs = { '' : '' , '' : , } , widget_attrs = { '' : , } , ) al . register ( Citation , ", "answer": "search_fields = [ '' , ] ,"}, {"prompt": " \"\"\"\"\"\" import os import hmac import posixpath from itertools import izip from random import SystemRandom try : from hashlib import sha1 , md5 _hash_funcs = _hash_mods = { '' : sha1 , '' : md5 } _sha1_mod = sha1 _md5_mod = md5 except ImportError : import sha as _sha1_mod , md5 as _md5_mod _hash_mods = { '' : _sha1_mod , '' : _md5_mod } _hash_funcs = { '' : _sha1_mod . new , '' : _md5_mod . new } SALT_CHARS = '' _sys_rng = SystemRandom ( ) _os_alt_seps = list ( sep for sep in [ os . path . sep , os . path . altsep ] if sep not in ( None , '' ) ) def safe_str_cmp ( a , b ) : \"\"\"\"\"\" if len ( a ) != len ( b ) : ", "answer": "return False"}, {"prompt": " from __future__ import with_statement import os import re import warnings from . context import StreamPositionRestore RE_KEY = re . compile ( \"\" \"\" , re . S ) RE_CERTS = re . compile ( \"\" \"\" , re . S ) ", "answer": "__all__ = [ \"\" , \"\" , \"\" ]"}, {"prompt": " import cStringIO from xml . dom import minidom import zipfile from django . test import TestCase from models import City , Country class GeoSitemapTest ( TestCase ) : urls = '' def assertChildNodes ( self , elem , expected ) : \"\" actual = set ( [ n . nodeName for n in elem . childNodes ] ) expected = set ( expected ) self . assertEqual ( actual , expected ) def test_geositemap_index ( self ) : \"\" doc = minidom . parseString ( self . client . get ( '' ) . content ) index = doc . firstChild self . assertEqual ( index . getAttribute ( u'' ) , u'' ) self . assertEqual ( , len ( index . getElementsByTagName ( '' ) ) ) def test_geositemap_kml ( self ) : \"\" for kml_type in ( '' , '' ) : doc = minidom . parseString ( self . client . get ( '' % kml_type ) . content ) urlset = doc . firstChild self . assertEqual ( urlset . getAttribute ( u'' ) , u'' ) self . assertEqual ( urlset . getAttribute ( u'' ) , u'' ) urls = urlset . getElementsByTagName ( '' ) self . assertEqual ( , len ( urls ) ) for url in urls : self . assertChildNodes ( url , [ '' , '' ] ) geo_elem = url . getElementsByTagName ( '' ) [ ] geo_format = geo_elem . getElementsByTagName ( '' ) [ ] self . assertEqual ( kml_type , geo_format . childNodes [ ] . data ) kml_url = url . getElementsByTagName ( '' ) [ ] . childNodes [ ] . data . split ( '' ) [ ] if kml_type == '' : kml_doc = minidom . parseString ( self . client . get ( kml_url ) . content ) elif kml_type == '' : buf = cStringIO . StringIO ( self . client . get ( kml_url ) . content ) zf = zipfile . ZipFile ( buf ) self . assertEqual ( , len ( zf . filelist ) ) self . assertEqual ( '' , zf . filelist [ ] . filename ) kml_doc = minidom . parseString ( zf . read ( '' ) ) if '' in kml_url : model = City elif '' in kml_url : model = Country self . assertEqual ( model . objects . count ( ) , len ( kml_doc . getElementsByTagName ( '' ) ) ) def test_geositemap_georss ( self ) : \"\" from feeds import feed_dict doc = minidom . parseString ( self . client . get ( '' ) . content ) urlset = doc . firstChild self . assertEqual ( urlset . getAttribute ( u'' ) , u'' ) ", "answer": "self . assertEqual ( urlset . getAttribute ( u'' ) , u'' )"}, {"prompt": " def deserialize ( d , ** kw ) : vert_section , edge_section = d . split ( '' , ) verts = [ line . split ( None , ) for line in vert_section . split ( '' ) if line ] counts = { } ", "answer": "edges = [ ]"}, {"prompt": " \"\"\"\"\"\" ", "answer": "from social . backends . oauth import BaseOAuth2"}, {"prompt": " from __future__ import unicode_literals import os , sys import re import pythoncom import win32com . client from win32com . adsi import adsi , adsicon from winsys import constants , core , exc , utils \"\"\"\"\"\" class x_active_directory ( exc . x_winsys ) : \"\" SEARCHPREF = constants . Constants . from_pattern ( \"\" , namespace = adsicon ) SEARCHPREF . doc ( \"\" ) SCOPE = constants . Constants . from_pattern ( \"\" , namespace = adsicon ) SCOPE . doc ( \"\" ) WINERROR_MAP = { adsicon . E_ADS_COLUMN_NOT_SET : exc . x_not_found , : AttributeError } wrapped = exc . wrapper ( WINERROR_MAP , x_active_directory ) SEARCH_PREFERENCES = { SEARCHPREF . PAGESIZE : , SEARCHPREF . SEARCH_SCOPE : SCOPE . SUBTREE , } class Result ( dict ) : def __getattr__ ( self , attr ) : return self [ attr ] ESCAPED_CHARACTERS = dict ( ( special , r\"\" % ord ( special ) ) for special in \"\" ) def escaped ( s ) : for original , escape in ESCAPED_CHARACTERS . items ( ) : s = s . replace ( original , escape ) return s class IADs ( core . _WinSysObject ) : def __init__ ( self , obj , interface = adsi . IID_IADs ) : self . _obj = wrapped ( obj . QueryInterface , interface ) def __getattr__ ( self , attr ) : try : return getattr ( self . _obj , attr ) except AttributeError : return wrapped ( self . _obj . Get , attr ) def __getitem__ ( self , item ) : return self . __class__ . from_object ( self . _obj . QueryInterface ( adsi . IID_IADsContainer ) . GetObject ( None , item ) ) def pyobject ( self ) : return self . _obj def as_string ( self ) : return self . _obj . ADsPath @ classmethod def from_string ( cls , moniker , username = None , password = None , interface = adsi . IID_IADs ) : return cls . from_object ( adsi . ADsOpenObject ( moniker , username , password , adsicon . ADS_SECURE_AUTHENTICATION | adsicon . ADS_SERVER_BIND | adsicon . ADS_FAST_BIND , interface ) ) @ classmethod def from_object ( cls , obj ) : klass = CLASS_MAP . get ( obj . QueryInterface ( adsi . IID_IADs ) . Class . lower ( ) , cls ) return klass ( obj ) def __iter__ ( self ) : try : enumerator = adsi . ADsBuildEnumerator ( self . _obj . QueryInterface ( adsi . IID_IADsContainer ) ) except : raise TypeError ( \"\" % self ) while True : item = adsi . ADsEnumerateNext ( enumerator , ) if item : yield IADs . from_object ( item [ ] ) else : break def walk ( self , depthfirst = False ) : \"\"\"\"\"\" top = self containers , items = [ ] , [ ] for item in self : if isinstance ( f , Dir ) : dirs . append ( f ) else : nondirs . append ( f ) if not depthfirst : yield top , dirs , nondirs for d in dirs : for x in d . walk ( depthfirst = depthfirst , ignore_access_errors = ignore_access_errors ) : yield x if depthfirst : yield top , dirs , nondirs class IADsOU ( IADs ) : def __init__ ( self , obj ) : IADs . __init__ ( self , obj ) class IADsUser ( IADs ) : def __init__ ( self , obj ) : IADs . __init__ ( self , obj ) class IADsGroup ( IADs ) : def __init__ ( self , obj ) : IADs . __init__ ( self , obj ) class GC ( IADs ) : def __iter__ ( self ) : for domain in IADs . __iter__ ( self ) : yield ad ( \"\" + domain . Name ) def ad ( obj = core . UNSET , username = None , password = None , interface = adsi . IID_IADs ) : if obj is core . UNSET : return IADs . from_string ( ldap_moniker ( username = username , password = password ) , username , password ) elif obj is None : return None elif isinstance ( obj , IADs ) : return obj elif isinstance ( obj , basestring ) : moniker = obj if not moniker . upper ( ) . startswith ( \"\" ) : moniker = \"\" + moniker return IADs . from_string ( moniker , username , password , interface ) else : return IADs . from_object ( obj ) def ldap_moniker ( root = None , server = None , username = None , password = None ) : if root is None : ", "answer": "root = adsi . ADsOpenObject ("}, {"prompt": " from django . contrib import admin from django . contrib . auth . admin import UserAdmin from django . contrib . auth . models import User from longerusername . forms import UserCreationForm , UserChangeForm class LongerUserNameUserAdmin ( UserAdmin ) : add_form = UserCreationForm form = UserChangeForm ", "answer": "admin . site . unregister ( User )"}, {"prompt": " from commando import management BaseSQLSequenceResetCommand = management . get_command_class ( \"\" , exclude_packages = ( \"\" , ) ) if BaseSQLSequenceResetCommand is not None : base = BaseSQLSequenceResetCommand ( ) class SQLSequenceResetCommandOptions ( management . CommandOptions ) : \"\"\"\"\"\" args = base . args help = base . help option_list = base . option_list [ len ( management . BaseCommandOptions . option_list ) : ] option_groups = ( ( \"\" , \"\" , option_list , ) , ) if option_list else ( ) actions = ( \"\" , ) def handle_sqlsequencereset ( self , * args , ** options ) : return self . call_command ( \"\" , * args , ** options ) class SQLSequenceResetCommand ( SQLSequenceResetCommandOptions , management . StandardCommand ) : \"\"\"\"\"\" option_list = management . StandardCommand . option_list option_groups = SQLSequenceResetCommandOptions . option_groups + management . StandardCommand . option_groups else : ", "answer": "SQLSequenceResetCommand = management . StandardCommand "}, {"prompt": " import rospy from nav_msgs . msg import Odometry import sys import time def close ( p1 , p2 ) : diff = abs ( p1 . x - p2 . x ) + abs ( p1 . y - p2 . y ) + abs ( p1 . z - p2 . z ) return diff < def grid_pt_for_pos ( pos ) : gx , gy = int ( pos . x / ) , int ( pos . y / ) return gx + * gy class MovingOdomReward ( object ) : def __init__ ( self , robot_id ) : self . robot_id = robot_id self . reset ( ) rospy . Subscriber ( \"\" % self . robot_id , Odometry , self . odom_callback ) def reset ( self ) : self . last_pos = None self . latest_pos = None def odom_callback ( self , msg ) : self . latest_pos = msg . pose . pose . position def reward ( self , last_action ) : if self . latest_pos == None : return if self . last_pos == None : self . last_pos = self . latest_pos ", "answer": "return "}, {"prompt": " from calvin . utilities . calvinlogger import get_logger _log = get_logger ( __name__ ) class PublicAttribute ( object ) : \"\"\"\"\"\" def __init__ ( self , node , actor ) : self . _node = node self . _actor = actor def exists ( self , index ) : \"\"\"\"\"\" return self . _node . attributes . has_public_attribute ( index ) def get ( self , index ) : \"\"\"\"\"\" return self . _node . attributes . get_public ( index ) ", "answer": "def register ( node , actor ) :"}, {"prompt": " from . version import get_version ", "answer": "__version__ = get_version ( ) "}, {"prompt": " from jumpgate . common import error_handling EXTENSIONS = { '' : { '' : '' , '' : '''''' , '' : [ ] , '' : '' , '' : '' '' , '' : '' , ", "answer": "'' : { '' : None } ,"}, {"prompt": " \"\"\"\"\"\" __author__ = \"\" __email__ = \"\" __copyright__ = \"\" __contributors__ = [ ] __maintainer__ = \"\" __license__ = \"\" __url__ = \"\" __status__ = \"\" import os import sys import time import stat import socket import multiprocessing import threading import subprocess import traceback import logging import marshal import tempfile import shutil import glob import functools import inspect import pickle import io try : import psutil except ImportError : psutil = None from dispy import _JobReply , DispyJob , DispyNodeAvailInfo , _Function , _Compute , _XferFile , _node_ipaddr , _dispy_version , auth_code , num_min , _same_file , MsgTimeout import asyncoro from asyncoro import Coro , AsynCoro , AsyncSocket , serialize , unserialize __version__ = _dispy_version __all__ = [ ] MaxFileSize = def dispy_provisional_result ( result , timeout = MsgTimeout ) : \"\"\"\"\"\" dispy_job_reply = __dispy_job_info . job_reply dispy_job_reply . status = DispyJob . ProvisionalResult dispy_job_reply . result = result dispy_job_reply . end_time = time . time ( ) sock = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) sock = AsyncSocket ( sock , blocking = True , keyfile = __dispy_job_keyfile , certfile = __dispy_job_certfile ) sock . settimeout ( timeout ) try : sock . connect ( __dispy_job_info . reply_addr ) sock . send_msg ( b'' + serialize ( dispy_job_reply ) ) ack = sock . recv_msg ( ) assert ack == b'' except : print ( \"\" % ( str ( result ) , traceback . format_exc ( ) ) ) return - else : return finally : sock . close ( ) def dispy_send_file ( path , timeout = MsgTimeout ) : \"\"\"\"\"\" path = os . path . expanduser ( path ) xf = _XferFile ( path , os . stat ( path ) ) if MaxFileSize and xf . stat_buf . st_size > MaxFileSize : return - xf . name = os . path . splitdrive ( path ) [ ] if xf . name . startswith ( os . sep ) : xf . name = xf . name [ len ( os . sep ) : ] dispy_job_reply = __dispy_job_info . job_reply sock = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) sock = AsyncSocket ( sock , blocking = True , keyfile = __dispy_job_keyfile , certfile = __dispy_job_certfile ) sock . settimeout ( timeout ) try : sock . connect ( __dispy_job_info . reply_addr ) sock . send_msg ( '' . encode ( ) + serialize ( xf ) ) sock . send_msg ( serialize ( dispy_job_reply ) ) recvd = sock . recv_msg ( ) recvd = unserialize ( recvd ) fd = open ( path , '' ) sent = while sent == recvd : data = fd . read ( ) if not data : break sock . sendall ( data ) sent += len ( data ) recvd = sock . recv_msg ( ) recvd = unserialize ( recvd ) fd . close ( ) assert recvd == xf . stat_buf . st_size except : print ( '' % ( path , traceback . format_exc ( ) ) ) return - else : return finally : sock . close ( ) class _DispyJobInfo ( object ) : \"\"\"\"\"\" def __init__ ( self , job_reply , reply_addr , compute , xfer_files ) : self . job_reply = job_reply self . reply_addr = reply_addr self . compute_id = compute . id self . compute_dest_path = compute . dest_path self . xfer_files = xfer_files self . compute_auth = compute . auth self . proc = None def _dispy_job_func ( __dispy_job_info , __dispy_job_certfile , __dispy_job_keyfile , __dispy_job_name , __dispy_job_args , __dispy_job_kwargs , __dispy_job_code , __dispy_job_globals , __dispy_path , __dispy_reply_Q ) : \"\"\"\"\"\" os . chdir ( __dispy_path ) sys . stdout = io . StringIO ( ) sys . stderr = io . StringIO ( ) __dispy_job_reply = __dispy_job_info . job_reply globals ( ) . update ( __dispy_job_globals ) try : exec ( marshal . loads ( __dispy_job_code [ ] ) , globals ( ) ) if __dispy_job_code [ ] : exec ( __dispy_job_code [ ] , globals ( ) ) if __name__ == '' : sys . modules [ '' ] . __dict__ . update ( globals ( ) ) __dispy_job_args = unserialize ( __dispy_job_args ) __dispy_job_kwargs = unserialize ( __dispy_job_kwargs ) globals ( ) . update ( locals ( ) ) exec ( '' % __dispy_job_name , globals ( ) ) __dispy_job_reply . status = DispyJob . Finished except : __dispy_job_reply . exception = traceback . format_exc ( ) __dispy_job_reply . status = DispyJob . Terminated __dispy_job_reply . stdout = sys . stdout . getvalue ( ) __dispy_job_reply . stderr = sys . stderr . getvalue ( ) __dispy_job_reply . end_time = time . time ( ) __dispy_job_info . proc = None __dispy_reply_Q . put ( __dispy_job_reply ) class _DispyNode ( object ) : \"\"\"\"\"\" def __init__ ( self , cpus , ip_addr = None , ext_ip_addr = None , node_port = None , name = '' , scheduler_node = None , scheduler_port = None , dest_path_prefix = '' , clean = False , secret = '' , keyfile = None , certfile = None , zombie_interval = , service_start = None , service_stop = None , service_end = None , serve = - , daemon = False ) : assert < cpus <= multiprocessing . cpu_count ( ) self . num_cpus = cpus if name : self . name = name else : self . name = socket . gethostname ( ) if ip_addr : ip_addr = _node_ipaddr ( ip_addr ) if not ip_addr : raise Exception ( '' ) else : ip_addr = socket . gethostbyname ( socket . gethostname ( ) ) if ip_addr . startswith ( '' ) : _dispy_logger . warning ( '' '' '' , ip_addr ) if ext_ip_addr : ext_ip_addr = _node_ipaddr ( ext_ip_addr ) if not ext_ip_addr : raise Exception ( '' ) else : ext_ip_addr = ip_addr if not self . name : try : self . name = socket . gethostbyaddr ( ext_ip_addr ) [ ] except : self . name = '' if node_port is None : node_port = self . ext_ip_addr = ext_ip_addr self . pulse_interval = None self . keyfile = keyfile self . certfile = certfile if self . keyfile : self . keyfile = os . path . abspath ( self . keyfile ) if self . certfile : self . certfile = os . path . abspath ( self . certfile ) self . asyncoro = AsynCoro ( ) self . tcp_sock = AsyncSocket ( socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) , keyfile = keyfile , certfile = certfile ) self . tcp_sock . setsockopt ( socket . SOL_SOCKET , socket . SO_REUSEADDR , ) self . tcp_sock . bind ( ( ip_addr , node_port ) ) self . address = self . tcp_sock . getsockname ( ) self . port = self . address [ ] self . tcp_sock . listen ( ) if not dest_path_prefix : dest_path_prefix = os . path . join ( tempfile . gettempdir ( ) , '' , '' ) self . dest_path_prefix = os . path . abspath ( dest_path_prefix . strip ( ) ) . rstrip ( os . sep ) if clean : shutil . rmtree ( self . dest_path_prefix , ignore_errors = True ) if not os . path . isdir ( self . dest_path_prefix ) : os . makedirs ( self . dest_path_prefix ) os . chmod ( self . dest_path_prefix , stat . S_IRUSR | stat . S_IWUSR | stat . S_IXUSR ) self . avail_cpus = self . num_cpus self . computations = { } self . job_infos = { } self . terminate = False self . sign = '' . join ( hex ( x ) [ : ] for x in os . urandom ( ) ) self . secret = secret self . auth = auth_code ( self . secret , self . sign ) self . zombie_interval = * zombie_interval if not scheduler_port : scheduler_port = self . scheduler = { '' : None , '' : scheduler_port , '' : set ( ) } self . cpu_time = self . num_jobs = self . num_computations = fd = open ( os . path . join ( self . dest_path_prefix , '' ) , '' ) config = { '' : self . ext_ip_addr , '' : self . port , '' : self . avail_cpus , '' : self . sign , '' : self . secret , '' : self . auth } pickle . dump ( config , fd ) fd . close ( ) sys . path . insert ( , '' ) proc = multiprocessing . Process ( target = functools . partial ( int ) , args = ( , ) ) proc . start ( ) proc . join ( ) self . thread_lock = threading . Lock ( ) self . udp_sock = socket . socket ( socket . AF_INET , socket . SOCK_DGRAM ) self . udp_sock . setsockopt ( socket . SOL_SOCKET , socket . SO_REUSEADDR , ) self . udp_sock . bind ( ( '' , self . port ) ) _dispy_logger . info ( '' , self . num_cpus , self . ext_ip_addr , self . port ) _dispy_logger . debug ( '' , self . address [ ] , self . address [ ] ) self . udp_sock = AsyncSocket ( self . udp_sock ) self . reply_Q = multiprocessing . Queue ( ) self . reply_Q_thread = threading . Thread ( target = self . __reply_Q ) self . reply_Q_thread . start ( ) self . serve = serve self . timer_coro = Coro ( self . timer_task ) self . service_start = self . service_stop = self . service_end = None if isinstance ( service_start , time . struct_time ) and ( isinstance ( service_stop , time . struct_time ) or isinstance ( service_end , time . struct_time ) ) : self . service_start = ( service_start . tm_hour , service_start . tm_min ) if isinstance ( service_stop , time . struct_time ) : self . service_stop = ( service_stop . tm_hour , service_stop . tm_min ) if isinstance ( service_end , time . struct_time ) : self . service_end = ( service_end . tm_hour , service_end . tm_min ) Coro ( self . service_schedule ) self . __init_code = '' . join ( inspect . getsource ( dispy_provisional_result ) ) self . __init_code += '' . join ( inspect . getsource ( dispy_send_file ) ) self . __init_modules = dict ( sys . modules ) if os . name == '' : self . __init_globals = dict ( globals ( ) ) self . tcp_coro = Coro ( self . tcp_server ) self . udp_coro = Coro ( self . udp_server , _node_ipaddr ( scheduler_node ) , scheduler_port ) if not daemon : Coro ( self . read_stdin ) def broadcast_ping_msg ( self , coro = None ) : if ( self . scheduler [ '' ] or self . job_infos or not self . avail_cpus or not self . service_available ( ) ) : raise StopIteration sock = socket . socket ( socket . AF_INET , socket . SOCK_DGRAM ) sock . setsockopt ( socket . SOL_SOCKET , socket . SO_BROADCAST , ) sock = AsyncSocket ( sock ) sock . settimeout ( MsgTimeout ) ping_msg = { '' : self . ext_ip_addr , '' : self . port , '' : self . sign , '' : _dispy_version , '' : None } try : yield sock . sendto ( '' . encode ( ) + serialize ( ping_msg ) , ( '' , self . scheduler [ '' ] ) ) except : _dispy_logger . debug ( traceback . format_exc ( ) ) pass sock . close ( ) def send_pong_msg ( self , info , addr , coro = None ) : if ( self . scheduler [ '' ] or self . job_infos or not self . num_cpus or not self . service_available ( ) ) : _dispy_logger . debug ( '' , self . avail_cpus , self . num_cpus , addr [ ] ) raise StopIteration try : scheduler_ip_addrs = info [ '' ] if not info . get ( '' , None ) : scheduler_ip_addrs . append ( addr [ ] ) scheduler_port = info [ '' ] except : _dispy_logger . debug ( traceback . format_exc ( ) ) raise StopIteration if info . get ( '' , None ) : pong_msg = { '' : self . ext_ip_addr , '' : self . port , '' : self . sign , '' : _dispy_version , '' : self . name , '' : self . avail_cpus , '' : auth_code ( self . secret , info [ '' ] ) } if psutil : pong_msg [ '' ] = DispyNodeAvailInfo ( - psutil . cpu_percent ( ) , psutil . virtual_memory ( ) . available , psutil . disk_usage ( self . dest_path_prefix ) . free , - psutil . swap_memory ( ) . percent ) else : pong_msg [ '' ] = None for scheduler_ip_addr in scheduler_ip_addrs : addr = ( scheduler_ip_addr , scheduler_port ) pong_msg [ '' ] = scheduler_ip_addr sock = AsyncSocket ( socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) , keyfile = self . keyfile , certfile = self . certfile ) sock . settimeout ( MsgTimeout ) try : yield sock . connect ( addr ) yield sock . send_msg ( '' . encode ( ) + serialize ( pong_msg ) ) except : _dispy_logger . debug ( '' , addr [ ] , addr [ ] ) finally : sock . close ( ) else : sock = AsyncSocket ( socket . socket ( socket . AF_INET , socket . SOCK_DGRAM ) ) sock . settimeout ( MsgTimeout ) ping_msg = { '' : self . ext_ip_addr , '' : self . port , '' : self . sign , '' : _dispy_version } for scheduler_ip_addr in scheduler_ip_addrs : addr = ( scheduler_ip_addr , scheduler_port ) ping_msg [ '' ] = scheduler_ip_addr try : yield sock . sendto ( '' . encode ( ) + serialize ( ping_msg ) , addr ) except : _dispy_logger . debug ( traceback . format_exc ( ) ) pass sock . close ( ) def udp_server ( self , scheduler_ip , scheduler_port , coro = None ) : coro . set_daemon ( ) yield self . broadcast_ping_msg ( coro = coro ) ping_msg = { '' : self . ext_ip_addr , '' : self . port , '' : self . sign , '' : _dispy_version } def send_ping_msg ( self , info , coro = None ) : sock = AsyncSocket ( socket . socket ( socket . AF_INET , socket . SOCK_DGRAM ) ) sock . settimeout ( MsgTimeout ) addr = ( info [ '' ] , info [ '' ] ) info . update ( ping_msg ) info [ '' ] = addr [ ] try : yield sock . sendto ( '' . encode ( ) + serialize ( info ) , addr ) except : pass finally : sock . close ( ) sock = AsyncSocket ( socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) , keyfile = self . keyfile , certfile = self . certfile ) sock . settimeout ( MsgTimeout ) try : yield sock . connect ( addr ) yield sock . send_msg ( '' . encode ( ) + serialize ( info ) ) except : pass finally : sock . close ( ) if scheduler_ip : Coro ( send_ping_msg , self , { '' : scheduler_ip , '' : scheduler_port } ) while True : msg , addr = yield self . udp_sock . recvfrom ( ) if msg . startswith ( b'' ) : try : info = unserialize ( msg [ len ( b'' ) : ] ) if info [ '' ] != _dispy_version : _dispy_logger . warning ( '' , addr [ ] ) continue except : _dispy_logger . debug ( '' , addr [ ] , addr [ ] ) continue Coro ( self . send_pong_msg , info , addr ) elif msg . startswith ( b'' ) : try : info = unserialize ( msg [ len ( b'' ) : ] ) except : _dispy_logger . warning ( '' , addr [ ] ) else : if info [ '' ] == self . scheduler [ '' ] : now = time . time ( ) for compute in self . computations . values ( ) : compute . last_pulse = now else : _dispy_logger . warning ( '' , addr [ ] ) def tcp_server ( self ) : while : try : conn , addr = yield self . tcp_sock . accept ( ) except GeneratorExit : break except : _dispy_logger . debug ( traceback . format_exc ( ) ) continue Coro ( self . tcp_serve_task , conn , addr ) def tcp_serve_task ( self , conn , addr , coro = None ) : def job_request_task ( msg ) : try : _job = unserialize ( msg ) except : _dispy_logger . debug ( '' , addr [ ] ) raise StopIteration compute = self . computations . get ( _job . compute_id , None ) if compute is not None : if compute . scheduler_ip_addr != self . scheduler [ '' ] or compute . scheduler_port != self . scheduler [ '' ] or compute . auth not in self . scheduler [ '' ] : _dispy_logger . debug ( '' , compute . scheduler_ip_addr , compute . scheduler_port , self . scheduler [ '' ] , self . scheduler [ '' ] ) compute = None if self . avail_cpus == : try : yield conn . send_msg ( '' . encode ( ) ) except : pass raise StopIteration elif compute is None : _dispy_logger . warning ( '' , _job . compute_id ) try : yield conn . send_msg ( ( '' % _job . compute_id ) . encode ( ) ) except : pass raise StopIteration for xf in _job . xfer_files : if MaxFileSize and xf . stat_buf . st_size > MaxFileSize : try : yield conn . send_msg ( '' . encode ( ) ) except : pass raise StopIteration reply_addr = ( compute . scheduler_ip_addr , compute . job_result_port ) _dispy_logger . debug ( '' , _job . uid , addr [ ] , compute . scheduler_ip_addr ) if compute . type == _Compute . func_type : reply = _JobReply ( _job , self . ext_ip_addr ) reply . start_time = time . time ( ) job_info = _DispyJobInfo ( reply , reply_addr , compute , _job . xfer_files ) args = ( job_info , self . certfile , self . keyfile , compute . name , _job . args , _job . kwargs , ( compute . code , _job . code ) , compute . globals , compute . dest_path , self . reply_Q ) try : yield conn . send_msg ( b'' ) except : _dispy_logger . warning ( '' , str ( addr ) ) raise StopIteration proc = multiprocessing . Process ( target = _dispy_job_func , args = args ) self . avail_cpus -= compute . pending_jobs += self . thread_lock . acquire ( ) self . job_infos [ _job . uid ] = job_info self . thread_lock . release ( ) try : proc . start ( ) except : job_info . job_reply . status = DispyJob . Terminated job_info . job_reply . exception = traceback . format_exc ( ) job_info . job_reply . end_time = time . time ( ) job_info . proc = None self . reply_Q . put ( job_info . job_reply ) else : job_info . proc = proc job_info . job_reply . status = DispyJob . Running raise StopIteration elif compute . type == _Compute . prog_type : try : yield conn . send_msg ( b'' ) except : _dispy_logger . warning ( '' , str ( addr ) ) raise StopIteration reply = _JobReply ( _job , self . ext_ip_addr ) reply . start_time = time . time ( ) job_info = _DispyJobInfo ( reply , reply_addr , compute , _job . xfer_files ) job_info . job_reply . status = DispyJob . Running self . thread_lock . acquire ( ) self . job_infos [ _job . uid ] = job_info self . thread_lock . release ( ) self . avail_cpus -= compute . pending_jobs += prog_thread = threading . Thread ( target = self . __job_program , args = ( _job , job_info ) ) prog_thread . start ( ) raise StopIteration else : try : yield conn . send_msg ( ( '' % compute . type ) . encode ( ) ) except : _dispy_logger . warning ( '' , str ( addr ) ) def add_computation_task ( msg ) : try : compute = unserialize ( msg ) except : try : yield conn . send_msg ( ( '' ) . encode ( ) ) except : pass raise StopIteration if not ( ( self . scheduler [ '' ] is None and not self . scheduler [ '' ] ) or ( self . scheduler [ '' ] == compute . scheduler_ip_addr and self . scheduler [ '' ] == compute . scheduler_port and self . service_available ( ) ) ) : _dispy_logger . debug ( '' , compute . scheduler_ip_addr , self . scheduler [ '' ] , self . avail_cpus , self . num_cpus ) try : yield conn . send_msg ( ( '' ) . encode ( ) ) except : pass raise StopIteration if MaxFileSize : for xf in compute . xfer_files : if xf . stat_buf . st_size > MaxFileSize : try : yield conn . send_msg ( ( '' % ( xf . name , MaxFileSize ) ) . encode ( ) ) except : pass raise StopIteration compute . xfer_files = set ( ) dest = os . path . join ( self . dest_path_prefix , compute . scheduler_ip_addr ) if not os . path . isdir ( dest ) : try : os . mkdir ( dest ) except : yield conn . send_msg ( ( '' ) . encode ( ) ) raise StopIteration if compute . dest_path and isinstance ( compute . dest_path , str ) : if not compute . dest_path . startswith ( os . sep ) : compute . dest_path = os . path . join ( dest , compute . dest_path ) if not os . path . isdir ( compute . dest_path ) : try : os . makedirs ( compute . dest_path ) except : try : yield conn . send_msg ( ( '' ) . encode ( ) ) except : pass raise StopIteration else : compute . dest_path = tempfile . mkdtemp ( prefix = compute . name + '' , dir = dest ) os . chmod ( compute . dest_path , stat . S_IRUSR | stat . S_IWUSR | stat . S_IXUSR ) if compute . id in self . computations : _dispy_logger . warning ( '' , compute . name , compute . id ) setattr ( compute , '' , time . time ( ) ) setattr ( compute , '' , ) setattr ( compute , '' , ) setattr ( compute , '' , False ) setattr ( compute , '' , { } ) setattr ( compute , '' , set ( sys . modules . keys ( ) ) ) setattr ( compute , '' , { } ) if compute . code : try : code = compute . code code += self . __init_code code = compile ( code , '' , '' ) except : if os . path . isdir ( compute . dest_path ) : os . rmdir ( compute . dest_path ) try : yield conn . send_msg ( ( '' % ( self . ext_ip_addr , compute . name ) ) . encode ( ) ) except : pass raise StopIteration compute . code = marshal . dumps ( code ) if compute . type == _Compute . prog_type : compute . name = os . path . join ( compute . dest_path , os . path . basename ( compute . name ) ) if not ( ( self . scheduler [ '' ] is None ) or ( self . scheduler [ '' ] == compute . scheduler_ip_addr and self . scheduler [ '' ] == compute . scheduler_port ) ) : if os . path . isdir ( compute . dest_path ) : try : os . rmdir ( compute . dest_path ) yield conn . send_msg ( serialize ( - ) ) except : pass raise StopIteration self . computations [ compute . id ] = compute self . scheduler [ '' ] = compute . scheduler_ip_addr self . scheduler [ '' ] = compute . scheduler_port self . scheduler [ '' ] . add ( compute . auth ) compute_save = os . path . join ( self . dest_path_prefix , '' % ( compute . id , compute . auth ) ) fd = open ( compute_save , '' ) pickle . dump ( compute , fd ) fd . close ( ) if os . name == '' : compute . globals = { } else : for var in ( '' , '' , '' , '' , '' , '' , '' ) : compute . globals [ var ] = globals ( ) [ var ] compute . globals . update ( self . __init_modules ) compute . globals [ '' ] = None try : yield conn . send_msg ( serialize ( self . avail_cpus ) ) except : del self . computations [ compute . id ] compute . globals = { } self . scheduler [ '' ] = None self . scheduler [ '' ] . discard ( compute . auth ) os . remove ( compute_save ) if os . path . isdir ( compute . dest_path ) : try : os . rmdir ( compute . dest_path ) except : pass else : self . pulse_interval = num_min ( self . pulse_interval , compute . pulse_interval ) if not self . pulse_interval : self . pulse_interval = * if self . zombie_interval : self . pulse_interval = num_min ( self . pulse_interval , self . zombie_interval / ) self . timer_coro . resume ( True ) def xfer_file_task ( msg ) : try : xf = unserialize ( msg ) except : _dispy_logger . debug ( '' , addr [ ] ) raise StopIteration compute = self . computations . get ( xf . compute_id , None ) if not compute or ( MaxFileSize and xf . stat_buf . st_size > MaxFileSize ) : _dispy_logger . error ( '' , xf . name ) yield conn . send_msg ( serialize ( - ) ) raise StopIteration tgt = os . path . join ( compute . dest_path , os . path . basename ( xf . name ) ) if os . path . isfile ( tgt ) and _same_file ( tgt , xf ) : if tgt in compute . file_uses : compute . file_uses [ tgt ] += else : compute . file_uses [ tgt ] = yield conn . send_msg ( serialize ( xf . stat_buf . st_size ) ) else : try : fd = open ( tgt , '' ) recvd = _dispy_logger . debug ( '' , xf . name , tgt , xf . stat_buf . st_size ) while recvd < xf . stat_buf . st_size : yield conn . send_msg ( serialize ( recvd ) ) data = yield conn . recvall ( min ( xf . stat_buf . st_size - recvd , ) ) if not data : break fd . write ( data ) recvd += len ( data ) yield conn . send_msg ( serialize ( recvd ) ) fd . close ( ) _dispy_logger . debug ( '' , tgt , recvd , xf . stat_buf . st_size ) assert recvd == xf . stat_buf . st_size os . utime ( tgt , ( xf . stat_buf . st_atime , xf . stat_buf . st_mtime ) ) os . chmod ( tgt , stat . S_IMODE ( xf . stat_buf . st_mode ) ) except : _dispy_logger . warning ( '' , xf . name , traceback . format_exc ( ) ) os . remove ( tgt ) else : if tgt in compute . file_uses : compute . file_uses [ tgt ] += else : compute . file_uses [ tgt ] = raise StopIteration def setup_computation ( msg ) : try : compute_id = unserialize ( msg ) compute = self . computations [ compute_id ] assert isinstance ( compute . setup , _Function ) os . chdir ( compute . dest_path ) localvars = { '' : compute . setup . args , '' : compute . setup . kwargs } if os . name == '' : globalvars = globals ( ) else : globalvars = compute . globals exec ( marshal . loads ( compute . code ) , globalvars , localvars ) exec ( '' % compute . setup . name , globalvars , localvars ) if os . name == '' : compute . globals . update ( { var : globals ( ) [ var ] for var in globals ( ) if var not in self . __init_globals } ) except : _dispy_logger . debug ( '' ) resp = traceback . format_exc ( ) . encode ( ) else : resp = b'' if resp != b'' : if not compute . cleanup : compute . cleanup = True compute . zombie = True self . cleanup_computation ( compute ) yield conn . send_msg ( resp ) def terminate_job_task ( compute , job_info ) : if not job_info . proc : raise StopIteration _dispy_logger . debug ( '' , job_info . job_reply . uid , compute . name ) job_info . proc . terminate ( ) if isinstance ( job_info . proc , multiprocessing . Process ) : for x in range ( ) : if job_info . proc . is_alive ( ) : yield coro . sleep ( ) else : _dispy_logger . debug ( '' , compute . name , job_info . job_reply . uid ) break else : _dispy_logger . warning ( '' , compute . name ) raise StopIteration else : assert isinstance ( job_info . proc , subprocess . Popen ) for x in range ( ) : rc = job_info . proc . poll ( ) _dispy_logger . debug ( '' , compute . name , job_info . job_reply . uid , rc ) if rc is not None : break if x == : _dispy_logger . debug ( '' , job_info . job_reply . uid ) job_info . proc . kill ( ) yield coro . sleep ( ) else : _dispy_logger . warning ( '' , compute . name ) raise StopIteration job_info . job_reply . end_time = time . time ( ) job_info . proc = None self . thread_lock . acquire ( ) if self . job_infos . get ( job_info . job_reply . uid , None ) == job_info : job_info . job_reply . status = DispyJob . Terminated self . reply_Q . put ( job_info . job_reply ) self . thread_lock . release ( ) def retrieve_job_task ( msg ) : def send_reply ( reply ) : try : yield conn . send_msg ( serialize ( reply ) ) except : raise StopIteration ( - ) raise StopIteration ( ) try : req = unserialize ( msg ) uid = req [ '' ] compute_id = req [ '' ] auth = req [ '' ] job_hash = req [ '' ] except : yield send_reply ( None ) raise StopIteration pkl_path = os . path . join ( self . dest_path_prefix , '' % ( compute_id , auth ) ) compute = self . computations . get ( compute_id , None ) if not compute : fd = open ( pkl_path , '' ) compute = pickle . load ( fd ) fd . close ( ) if not compute or compute . auth != auth : yield send_reply ( None ) raise StopIteration info_file = os . path . join ( compute . dest_path , '' % uid ) if not os . path . isfile ( info_file ) : yield send_reply ( None ) raise StopIteration try : fd = open ( info_file , '' ) job_reply = pickle . load ( fd ) fd . close ( ) assert job_reply . hash == job_hash except : yield send_reply ( None ) raise StopIteration try : yield conn . send_msg ( serialize ( job_reply ) ) ack = yield conn . recv_msg ( ) assert ack == b'' compute . pending_results -= fd = open ( pkl_path , '' ) pickle . dump ( compute , fd ) fd . close ( ) except : pass else : try : os . remove ( info_file ) except : pass if compute . pending_results == : self . cleanup_computation ( compute ) try : req = yield conn . recvall ( len ( self . auth ) ) except : _dispy_logger . warning ( '' ) conn . close ( ) raise StopIteration msg = yield conn . recv_msg ( ) if req != self . auth : if msg . startswith ( b'' ) : pass else : _dispy_logger . warning ( '' ) conn . close ( ) raise StopIteration if not msg : conn . close ( ) raise StopIteration if msg . startswith ( b'' ) : msg = msg [ len ( b'' ) : ] yield job_request_task ( msg ) conn . close ( ) elif msg . startswith ( b'' ) : msg = msg [ len ( b'' ) : ] yield add_computation_task ( msg ) conn . close ( ) elif msg . startswith ( b'' ) : msg = msg [ len ( b'' ) : ] yield xfer_file_task ( msg ) conn . close ( ) elif msg . startswith ( b'' ) : msg = msg [ len ( b'' ) : ] yield setup_computation ( msg ) conn . close ( ) elif msg . startswith ( b'' ) : msg = msg [ len ( b'' ) : ] try : info = unserialize ( msg ) compute_id = info [ '' ] auth = info [ '' ] terminate_pending = info . get ( '' , False ) except : _dispy_logger . debug ( '' , traceback . format_exc ( ) ) else : compute = self . computations . get ( compute_id , None ) if compute is None or compute . auth != auth : _dispy_logger . warning ( '' , compute_id ) else : compute . zombie = True if terminate_pending : self . thread_lock . acquire ( ) job_infos = [ job_info for job_info in self . job_infos . values ( ) if job_info . compute_id == compute_id ] self . thread_lock . release ( ) for job_info in job_infos : yield terminate_job_task ( compute , job_info ) self . cleanup_computation ( compute ) yield conn . send_msg ( b'' ) conn . close ( ) elif msg . startswith ( b'' ) : msg = msg [ len ( b'' ) : ] try : _job = unserialize ( msg ) compute = self . computations [ _job . compute_id ] self . thread_lock . acquire ( ) job_info = self . job_infos . get ( _job . uid , None ) self . thread_lock . release ( ) assert job_info is not None except : _dispy_logger . debug ( '' , addr [ ] , compute . scheduler_ip_addr ) else : yield terminate_job_task ( compute , job_info ) conn . close ( ) elif msg . startswith ( b'' ) : msg = msg [ len ( b'' ) : ] try : info = unserialize ( msg ) compute_id = info [ '' ] auth = info [ '' ] except : reply = else : compute = self . computations . get ( compute_id , None ) if compute is None or compute . auth != auth : try : fd = open ( os . path . join ( self . dest_path_prefix , '' % ( compute_id , auth ) ) , '' ) compute = pickle . load ( fd ) fd . close ( ) except : pass if compute is None : reply = else : reply = compute . pending_results + compute . pending_jobs yield conn . send_msg ( serialize ( reply ) ) conn . close ( ) if reply > : yield self . resend_job_results ( compute , coro = coro ) elif msg . startswith ( b'' ) : try : info = unserialize ( msg [ len ( b'' ) : ] ) if ( info [ '' ] == _dispy_version and not self . scheduler [ '' ] and not self . job_infos ) : Coro ( self . send_pong_msg , info , addr ) except : _dispy_logger . debug ( traceback . format_exc ( ) ) conn . close ( ) elif msg . startswith ( b'' ) : msg = msg [ len ( b'' ) : ] reply = { '' : [ ] , '' : } try : info = unserialize ( msg ) compute_id = info [ '' ] auth = info [ '' ] except : pass else : compute = self . computations . get ( compute_id , None ) if compute is None or compute . auth != auth : fd = open ( os . path . join ( self . dest_path_prefix , '' % ( compute_id , auth ) ) , '' ) compute = pickle . load ( fd ) fd . close ( ) if compute is not None : done = [ ] if compute . pending_results : for result_file in glob . glob ( os . path . join ( compute . dest_path , '' ) ) : result_file = os . path . basename ( result_file ) try : uid = int ( result_file [ len ( '' ) : ] ) except : pass else : done . append ( uid ) if len ( done ) > : break reply [ '' ] = done reply [ '' ] = compute . pending_jobs yield conn . send_msg ( serialize ( reply ) ) conn . close ( ) elif msg . startswith ( b'' ) : msg = msg [ len ( b'' ) : ] yield retrieve_job_task ( msg ) conn . close ( ) else : _dispy_logger . warning ( '' , msg [ : min ( , len ( msg ) ) ] , addr [ ] ) resp = ( '' % ( msg [ : min ( , len ( msg ) ) ] ) ) . encode ( ) try : yield conn . send_msg ( resp ) except : _dispy_logger . warning ( '' , str ( addr ) ) conn . close ( ) def resend_job_results ( self , compute , coro = None ) : if not os . path . isdir ( compute . dest_path ) : raise StopIteration result_files = [ f for f in os . listdir ( compute . dest_path ) if f . startswith ( '' ) ] result_files = result_files [ : min ( len ( result_files ) , ) ] for result_file in result_files : result_file = os . path . join ( compute . dest_path , result_file ) try : fd = open ( result_file , '' ) job_result = pickle . load ( fd ) fd . close ( ) except : _dispy_logger . debug ( '' , result_file ) continue job_info = _DispyJobInfo ( job_result , ( compute . scheduler_ip_addr , compute . job_result_port ) , compute , [ ] ) status = yield self . _send_job_reply ( job_info , resending = True ) if status : break def timer_task ( self , coro = None ) : coro . set_daemon ( ) last_pulse_time = last_zombie_time = time . time ( ) while True : reset = yield coro . suspend ( self . pulse_interval ) if reset : continue now = time . time ( ) if self . pulse_interval and ( now - last_pulse_time ) >= self . pulse_interval : if self . scheduler [ '' ] : last_pulse_time = now sock = AsyncSocket ( socket . socket ( socket . AF_INET , socket . SOCK_DGRAM ) ) sock . settimeout ( MsgTimeout ) info = { '' : self . ext_ip_addr , '' : self . port , '' : self . num_cpus - self . avail_cpus , '' : self . scheduler [ '' ] } if psutil : info [ '' ] = DispyNodeAvailInfo ( - psutil . cpu_percent ( ) , psutil . virtual_memory ( ) . available , psutil . disk_usage ( self . dest_path_prefix ) . free , - psutil . swap_memory ( ) . percent ) else : info [ '' ] = None yield sock . sendto ( b'' + serialize ( info ) , ( self . scheduler [ '' ] , self . scheduler [ '' ] ) ) sock . close ( ) resend = [ compute for compute in self . computations . values ( ) if compute . pending_results and not compute . zombie ] for compute in resend : Coro ( self . resend_job_results , compute ) if self . zombie_interval and ( now - last_zombie_time ) >= self . zombie_interval : last_zombie_time = now for compute in self . computations . values ( ) : if ( now - compute . last_pulse ) > self . zombie_interval : _dispy_logger . warning ( '' , compute . name ) compute . zombie = True zombies = [ compute for compute in self . computations . values ( ) if compute . zombie and compute . pending_jobs == ] for compute in zombies : _dispy_logger . warning ( '' , compute . name ) self . cleanup_computation ( compute ) for compute in zombies : sock = AsyncSocket ( socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) , keyfile = self . keyfile , certfile = self . certfile ) sock . settimeout ( MsgTimeout ) _dispy_logger . debug ( '' , compute . scheduler_ip_addr ) info = { '' : self . ext_ip_addr , '' : self . port , '' : self . sign } try : yield sock . connect ( ( compute . scheduler_ip_addr , compute . scheduler_port ) ) yield sock . send_msg ( '' . encode ( ) + serialize ( info ) ) except : pass finally : sock . close ( ) if ( not self . scheduler [ '' ] and not self . job_infos and self . avail_cpus > ) : self . pulse_interval = None yield self . broadcast_ping_msg ( coro = coro ) def service_available ( self ) : if self . serve == : return False if not self . service_start or not self . service_end : return True now = time . localtime ( ) if self . service_stop : end = self . service_stop else : end = self . service_end if self . service_start < end : if self . service_start <= ( now . tm_hour , now . tm_min ) < end : return True else : if ( now . tm_hour , now . tm_min ) >= self . service_start or ( now . tm_hour , now . tm_min ) < end : return True return False def service_schedule ( self , coro = None ) : coro . set_daemon ( ) while True : yield coro . sleep ( ) if self . service_available ( ) : yield self . broadcast_ping_msg ( coro = coro ) else : if self . scheduler [ '' ] : now = time . localtime ( ) if self . service_end and ( now . tm_hour , now . tm_min ) > self . service_end : _dispy_logger . debug ( '' ) self . shutdown ( quit = False ) else : _dispy_logger . debug ( '' ) sock = AsyncSocket ( socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) , keyfile = self . keyfile , certfile = self . certfile ) sock . settimeout ( MsgTimeout ) try : yield sock . connect ( ( self . scheduler [ '' ] , self . scheduler [ '' ] ) ) info = { '' : self . ext_ip_addr , '' : self . sign , '' : } yield sock . send_msg ( '' . encode ( ) + serialize ( info ) ) except : pass finally : sock . close ( ) def __job_program ( self , _job , job_info ) : compute = self . computations [ _job . compute_id ] if compute . name . endswith ( '' ) : program = [ sys . executable , compute . name ] else : program = [ compute . name ] args = unserialize ( _job . args ) program . extend ( args ) reply = job_info . job_reply try : os . chdir ( compute . dest_path ) env = { } env . update ( os . environ ) env [ '' ] = compute . dest_path + os . pathsep + env [ '' ] job_info . proc = subprocess . Popen ( program , stdout = subprocess . PIPE , stderr = subprocess . PIPE , env = env ) assert isinstance ( job_info . proc , subprocess . Popen ) reply . stdout , reply . stderr = job_info . proc . communicate ( ) reply . result = job_info . proc . returncode reply . status = DispyJob . Finished except : reply . exception = traceback . format_exc ( ) reply . status = DispyJob . Terminated reply . end_time = time . time ( ) job_info . proc = None self . reply_Q . put ( reply ) def __reply_Q ( self ) : while True : job_reply = self . reply_Q . get ( ) if job_reply is None : break self . thread_lock . acquire ( ) job_info = self . job_infos . get ( job_reply . uid , None ) if job_info is not None : job_info . job_reply = job_reply self . thread_lock . release ( ) if job_info is not None : self . num_jobs += self . cpu_time += ( job_reply . end_time - job_reply . start_time ) if job_info . proc is not None : if isinstance ( job_info . proc , multiprocessing . Process ) : job_info . proc . join ( ) else : job_info . proc . wait ( ) Coro ( self . _send_job_reply , job_info , resending = False ) compute = self . computations . get ( job_info . compute_id , None ) if not compute : continue for xf in job_info . xfer_files : path = os . path . join ( compute . dest_path , os . path . basename ( xf . name ) ) try : compute . file_uses [ path ] -= if compute . file_uses [ path ] == : compute . file_uses . pop ( path ) os . remove ( path ) except : _dispy_logger . warning ( '' , path ) continue def _send_job_reply ( self , job_info , resending = False , coro = None ) : \"\"\"\"\"\" job_reply = job_info . job_reply _dispy_logger . debug ( '' , job_reply . uid , job_reply . status , str ( job_info . reply_addr ) ) compute = self . computations . get ( job_info . compute_id , None ) if not resending : self . thread_lock . acquire ( ) assert self . job_infos . pop ( job_reply . uid , None ) is not None self . thread_lock . release ( ) self . avail_cpus += assert self . avail_cpus <= self . num_cpus if compute : compute . pending_jobs -= sock = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) sock = AsyncSocket ( sock , keyfile = self . keyfile , certfile = self . certfile ) sock . settimeout ( MsgTimeout ) try : yield sock . connect ( job_info . reply_addr ) yield sock . send_msg ( b'' + serialize ( job_reply ) ) ack = yield sock . recv_msg ( ) assert ack == b'' except : status = - if not resending : f = os . path . join ( job_info . compute_dest_path , '' % job_reply . uid ) _dispy_logger . error ( '' , job_reply . uid , str ( job_info . reply_addr ) , f ) try : fd = open ( f , '' ) pickle . dump ( job_reply , fd ) fd . close ( ) except : _dispy_logger . debug ( '' , job_reply . uid ) else : if compute is not None : compute . pending_results += else : status = if compute : compute . last_pulse = time . time ( ) if resending : compute . pending_results -= elif compute . pending_results : Coro ( self . resend_job_results , compute ) if resending : f = os . path . join ( job_info . compute_dest_path , '' % job_reply . uid ) if os . path . isfile ( f ) : try : os . remove ( f ) except : _dispy_logger . warning ( '' , f ) if compute is None : fd = open ( os . path . join ( self . dest_path_prefix , '' % ( job_info . compute_id , job_info . compute_auth ) ) , '' ) compute = pickle . load ( fd ) fd . close ( ) if compute : compute . pending_results -= finally : sock . close ( ) if compute and compute . pending_jobs == and compute . zombie : self . cleanup_computation ( compute ) raise StopIteration ( status ) def cleanup_computation ( self , compute ) : if not compute . zombie or compute . pending_jobs > : return if compute . pending_jobs != : _dispy_logger . debug ( '' , compute . name , compute . id , compute . pending_jobs ) if self . computations . pop ( compute . id , None ) is None : _dispy_logger . warning ( '' , compute . id ) return self . num_computations += file_uses , compute . file_uses = compute . file_uses , { } globalvars , compute . globals = compute . globals , { } pkl_path = os . path . join ( self . dest_path_prefix , '' % ( compute . id , compute . auth ) ) if compute . pending_results == : try : os . remove ( pkl_path ) except : _dispy_logger . warning ( '' , pkl_path ) else : fd = open ( pkl_path , '' ) pickle . dump ( compute , fd ) fd . close ( ) self . scheduler [ '' ] . discard ( compute . auth ) if ( ( not self . computations ) and ( not self . scheduler [ '' ] ) and compute . scheduler_ip_addr == self . scheduler [ '' ] and compute . scheduler_port == self . scheduler [ '' ] ) : self . scheduler [ '' ] = None self . pulse_interval = None self . timer_coro . resume ( None ) if self . serve > : self . serve -= Coro ( self . broadcast_ping_msg ) if compute . cleanup is False : if self . serve == : self . shutdown ( quit = True ) return os . chdir ( self . dest_path_prefix ) if isinstance ( compute . cleanup , _Function ) : try : localvars = { '' : compute . cleanup . args , '' : compute . cleanup . kwargs } if os . name == '' : globalvars = globals ( ) exec ( marshal . loads ( compute . code ) , globalvars , localvars ) exec ( '' % compute . cleanup . name , globalvars , localvars ) except : _dispy_logger . debug ( '' , compute . cleanup . name ) _dispy_logger . debug ( traceback . format_exc ( ) ) if os . name == '' : for var in list ( globals ( ) . keys ( ) ) : if var not in self . __init_globals : _dispy_logger . debug ( '' , var , compute . name , compute . scheduler_ip_addr ) globals ( ) . pop ( var , None ) for var , value in self . __init_globals . items ( ) : if var in ( '' , '' , '' , '' ) : continue if value != globals ( ) . get ( var , None ) : _dispy_logger . warning ( '' , var , compute . name , compute . scheduler_ip_addr ) globals ( ) [ var ] = value for module in list ( sys . modules . keys ( ) ) : if module not in compute . ante_modules : sys . modules . pop ( module , None ) sys . modules . update ( self . __init_modules ) for path in os . listdir ( compute . dest_path ) : path = os . path . join ( compute . dest_path , path ) if file_uses . get ( path , ) == : try : if os . path . isfile ( path ) or os . path . islink ( path ) : os . remove ( path ) elif os . path . isdir ( path ) : shutil . rmtree ( path , ignore_errors = True ) else : os . remove ( path ) except : _dispy_logger . warning ( '' , path ) if os . path . isdir ( compute . dest_path ) and compute . dest_path . startswith ( self . dest_path_prefix ) and len ( os . listdir ( compute . dest_path ) ) == : try : os . rmdir ( compute . dest_path ) except : _dispy_logger . warning ( '' , compute . dest_path ) else : _dispy_logger . debug ( '' , compute . dest_path ) if self . serve == : self . shutdown ( quit = True ) def shutdown ( self , quit = True ) : def _shutdown ( self , quit , coro = None ) : self . thread_lock . acquire ( ) job_infos , self . job_infos = self . job_infos , { } if quit and self . reply_Q : self . reply_Q . put ( None ) self . scheduler [ '' ] = None ", "answer": "self . scheduler [ '' ] = set ( )"}, {"prompt": " \"\"\"\"\"\" from . . phonemetadata import NumberFormat , PhoneNumberDesc , PhoneMetadata PHONE_METADATA_SD = PhoneMetadata ( id = '' , country_code = , international_prefix = '' , general_desc = PhoneNumberDesc ( national_number_pattern = '' , possible_number_pattern = '' ) , fixed_line = PhoneNumberDesc ( national_number_pattern = '' , possible_number_pattern = '' , example_number = '' ) , mobile = PhoneNumberDesc ( national_number_pattern = '' , possible_number_pattern = '' , example_number = '' ) , toll_free = PhoneNumberDesc ( national_number_pattern = '' , possible_number_pattern = '' ) , premium_rate = PhoneNumberDesc ( national_number_pattern = '' , possible_number_pattern = '' ) , shared_cost = PhoneNumberDesc ( national_number_pattern = '' , possible_number_pattern = '' ) , personal_number = PhoneNumberDesc ( national_number_pattern = '' , possible_number_pattern = '' ) , ", "answer": "voip = PhoneNumberDesc ( national_number_pattern = '' , possible_number_pattern = '' ) ,"}, {"prompt": " from __future__ import division from ... util import keys from . . node import Node from ... visuals . transforms import ( STTransform , MatrixTransform , NullTransform , TransformCache ) class BaseCamera ( Node ) : \"\"\"\"\"\" _state_props = ( ) zoom_factor = def __init__ ( self , interactive = True , flip = None , up = '' , parent = None , name = None ) : super ( BaseCamera , self ) . __init__ ( parent , name ) self . _viewbox = None self . _linked_cameras = [ ] self . _linked_cameras_no_update = None self . transform = NullTransform ( ) self . _pre_transform = None self . _viewbox_tr = STTransform ( ) self . _projection = MatrixTransform ( ) self . _transform_cache = TransformCache ( ) self . _event_value = None self . _resetting = False self . _key_events_bound = False self . _set_range_args = None self . _xlim = None self . _ylim = None self . _zlim = None self . _default_state = None self . _fov = self . _center = None self . _depth_value = self . interactive = bool ( interactive ) self . flip = flip if ( flip is not None ) else ( False , False , False ) self . up = up @ property def depth_value ( self ) : \"\"\"\"\"\" return self . _depth_value @ depth_value . setter def depth_value ( self , value ) : value = float ( value ) if value <= : raise ValueError ( '' ) self . _depth_value = value self . view_changed ( ) def _depth_to_z ( self , depth ) : \"\"\"\"\"\" val = self . depth_value return val - depth * * val def _viewbox_set ( self , viewbox ) : \"\"\"\"\"\" self . _viewbox = viewbox viewbox . events . mouse_press . connect ( self . viewbox_mouse_event ) viewbox . events . mouse_release . connect ( self . viewbox_mouse_event ) viewbox . events . mouse_move . connect ( self . viewbox_mouse_event ) viewbox . events . mouse_wheel . connect ( self . viewbox_mouse_event ) viewbox . events . resize . connect ( self . viewbox_resize_event ) def _viewbox_unset ( self , viewbox ) : \"\"\"\"\"\" self . _viewbox = None viewbox . events . mouse_press . disconnect ( self . viewbox_mouse_event ) viewbox . events . mouse_release . disconnect ( self . viewbox_mouse_event ) viewbox . events . mouse_move . disconnect ( self . viewbox_mouse_event ) viewbox . events . mouse_wheel . disconnect ( self . viewbox_mouse_event ) viewbox . events . resize . disconnect ( self . viewbox_resize_event ) @ property def viewbox ( self ) : \"\"\"\"\"\" return self . _viewbox @ property def interactive ( self ) : \"\"\"\"\"\" return self . _interactive @ interactive . setter def interactive ( self , value ) : self . _interactive = bool ( value ) @ property def flip ( self ) : return self . _flip @ flip . setter def flip ( self , value ) : if not isinstance ( value , ( list , tuple ) ) : raise ValueError ( '' ) if len ( value ) == : self . _flip = bool ( value [ ] ) , bool ( value [ ] ) , False elif len ( value ) == : self . _flip = bool ( value [ ] ) , bool ( value [ ] ) , bool ( value [ ] ) else : raise ValueError ( '' ) self . _flip_factors = tuple ( [ ( - x * ) for x in self . _flip ] ) self . view_changed ( ) @ property def up ( self ) : \"\"\"\"\"\" return self . _up @ up . setter def up ( self , value ) : value = value . lower ( ) value = ( '' + value ) if value in '' else value if value not in ( '' , '' , '' , '' , '' , '' ) : raise ValueError ( '' ) self . _up = value self . view_changed ( ) @ property def center ( self ) : \"\"\"\"\"\" return self . _center or ( , , ) @ center . setter def center ( self , val ) : if len ( val ) == : self . _center = float ( val [ ] ) , float ( val [ ] ) , elif len ( val ) == : self . _center = float ( val [ ] ) , float ( val [ ] ) , float ( val [ ] ) else : raise ValueError ( '' ) self . view_changed ( ) @ property def fov ( self ) : \"\"\"\"\"\" return self . _fov @ fov . setter def fov ( self , fov ) : fov = float ( fov ) if fov < or fov >= : raise ValueError ( \"\" ) self . _fov = fov self . view_changed ( ) def set_range ( self , x = None , y = None , z = None , margin = ) : \"\"\"\"\"\" init = self . _xlim is None bounds = [ None , None , None ] if x is not None : bounds [ ] = float ( x [ ] ) , float ( x [ ] ) if y is not None : bounds [ ] = float ( y [ ] ) , float ( y [ ] ) if z is not None : bounds [ ] = float ( z [ ] ) , float ( z [ ] ) if self . _viewbox is None : self . _set_range_args = bounds [ ] , bounds [ ] , bounds [ ] , margin return self . _resetting = True if all ( [ ( b is None ) for b in bounds ] ) : bounds = self . _viewbox . get_scene_bounds ( ) else : for i in range ( ) : if bounds [ i ] is None : bounds [ i ] = self . _viewbox . get_scene_bounds ( i ) ranges = [ b [ ] - b [ ] for b in bounds ] margins = [ ( r * margin or ) for r in ranges ] bounds_margins = [ ( b [ ] - m , b [ ] + m ) for b , m in zip ( bounds , margins ) ] self . _xlim , self . _ylim , self . _zlim = bounds_margins if ( not init ) or ( self . _center is None ) : self . _center = [ ( b [ ] + r / ) for b , r in zip ( bounds , ranges ) ] self . _set_range ( init ) self . _resetting = False self . view_changed ( ) def _set_range ( self , init ) : pass def reset ( self ) : \"\"\"\"\"\" self . set_state ( self . _default_state ) def set_default_state ( self ) : \"\"\"\"\"\" self . _default_state = self . get_state ( ) def get_state ( self ) : \"\"\"\"\"\" D = { } for key in self . _state_props : D [ key ] = getattr ( self , key ) return D def set_state ( self , state = None , ** kwargs ) : \"\"\"\"\"\" D = state or { } D . update ( kwargs ) for key , val in D . items ( ) : if key not in self . _state_props : raise KeyError ( '' % key ) setattr ( self , key , val ) def link ( self , camera ) : \"\"\"\"\"\" cam1 , cam2 = self , camera while cam1 in cam2 . _linked_cameras : cam2 . _linked_cameras . remove ( cam1 ) while cam2 in cam1 . _linked_cameras : cam1 . _linked_cameras . remove ( cam2 ) cam1 . _linked_cameras . append ( cam2 ) cam2 . _linked_cameras . append ( cam1 ) def view_changed ( self ) : \"\"\"\"\"\" if self . _resetting : return if self . _viewbox : if self . _xlim is None : args = self . _set_range_args or ( ) self . set_range ( * args ) if self . _default_state is None : self . set_default_state ( ) self . _update_transform ( ) @ property def pre_transform ( self ) : \"\"\"\"\"\" return self . _pre_transform @ pre_transform . setter def pre_transform ( self , tr ) : self . _pre_transform = tr self . view_changed ( ) def viewbox_mouse_event ( self , event ) : \"\"\"\"\"\" pass def on_canvas_change ( self , event ) : \"\"\"\"\"\" if event . old is not None : event . old . events . key_press . disconnect ( self . viewbox_key_event ) event . old . events . key_release . disconnect ( self . viewbox_key_event ) if event . new is not None : event . new . events . key_press . connect ( self . viewbox_key_event ) event . new . events . key_release . connect ( self . viewbox_key_event ) def viewbox_key_event ( self , event ) : \"\"\"\"\"\" ", "answer": "if event . key == keys . BACKSPACE :"}, {"prompt": " \"\"\"\"\"\" from facebook import Facebook __docformat__ = \"\" try : from paste . registry import StackedObjectProxy from webob . exc import _HTTPMove from paste . util . quoting import strip_html , html_quote , no_quote except ImportError : pass else : facebook = StackedObjectProxy ( name = \"\" ) class CanvasRedirect ( _HTTPMove ) : \"\"\"\"\"\" title = \"\" code = template = '' def html ( self , environ ) : \"\"\"\"\"\" body = self . make_body ( environ , self . template , html_quote , no_quote ) return body class FacebookWSGIMiddleware ( object ) : \"\"\"\"\"\" def __init__ ( self , app , config , facebook_class = Facebook ) : \"\"\"\"\"\" self . app = app self . config = config self . facebook_class = facebook_class def __call__ ( self , environ , start_response ) : config = self . config real_facebook = self . facebook_class ( config [ \"\" ] , config [ \"\" ] ) registry = environ . get ( '' ) if registry : registry . register ( facebook , real_facebook ) environ [ '' ] = real_facebook return self . app ( environ , start_response ) try : ", "answer": "import pylons"}, {"prompt": " \"\"\"\"\"\" from . code_edit import CodeEdit from . decoration import TextDecoration from . encodings import ENCODINGS_MAP , convert_to_codec_key from . manager import Manager from . mode import Mode from . panel import Panel from . syntax_highlighter import ColorScheme from . syntax_highlighter import PYGMENTS_STYLES from . syntax_highlighter import SyntaxHighlighter from . syntax_highlighter import TextBlockUserData from . utils import TextHelper , TextBlockHelper from . utils import get_block_symbol_data from . utils import DelayJobRunner from . folding import FoldDetector from . folding import IndentFoldDetector from . folding import CharBasedFoldDetector from . folding import FoldScope __all__ = [ '' , ", "answer": "'' ,"}, {"prompt": " \"\"\"\"\"\" from operator import attrgetter from shutil import move from tempfile import mkstemp from wsgiref . simple_server import make_server from six . moves . urllib import parse from itertools import cycle from common import * from config import * from lrucache import * from utils import * import argparse import json import logging import os import os . path import stat import re import requests import shlex import subprocess import sys import time import dateutil . parser import threading import traceback import random import hashlib logger = logging . getLogger ( '' ) SERVICE_PORT_ASSIGNER = ServicePortAssigner ( ) class MarathonBackend ( object ) : def __init__ ( self , host , ip , port , draining ) : self . host = host \"\"\"\"\"\" self . ip = ip \"\"\"\"\"\" self . port = port \"\"\"\"\"\" self . draining = draining \"\"\"\"\"\" def __hash__ ( self ) : return hash ( ( self . host , self . port ) ) def __repr__ ( self ) : return \"\" % ( self . host , self . ip , self . port ) class MarathonService ( object ) : def __init__ ( self , appId , servicePort , healthCheck ) : self . appId = appId self . servicePort = servicePort self . backends = set ( ) self . hostname = None self . proxypath = None self . revproxypath = None self . redirpath = None self . haproxy_groups = frozenset ( ) self . path = None self . authRealm = None self . authUser = None self . authPasswd = None self . sticky = False self . redirectHttpToHttps = False self . useHsts = False self . sslCert = None self . bindOptions = None self . bindAddr = '' self . groups = frozenset ( ) self . mode = '' self . balance = '' self . healthCheck = healthCheck self . labels = { } self . backend_weight = if healthCheck : if healthCheck [ '' ] == '' : self . mode = '' def add_backend ( self , host , ip , port , draining ) : self . backends . add ( MarathonBackend ( host , ip , port , draining ) ) def __hash__ ( self ) : return hash ( self . servicePort ) def __eq__ ( self , other ) : return self . servicePort == other . servicePort def __repr__ ( self ) : return \"\" % ( self . appId , self . servicePort ) class MarathonApp ( object ) : def __init__ ( self , marathon , appId , app ) : self . app = app self . groups = frozenset ( ) self . appId = appId self . services = dict ( ) def __hash__ ( self ) : return hash ( self . appId ) def __eq__ ( self , other ) : return self . appId == other . appId class Marathon ( object ) : def __init__ ( self , hosts , health_check , auth ) : self . __hosts = hosts self . __health_check = health_check self . __auth = auth self . __cycle_hosts = cycle ( self . __hosts ) def api_req_raw ( self , method , path , auth , body = None , ** kwargs ) : for host in self . __hosts : path_str = os . path . join ( host , '' ) for path_elem in path : path_str = path_str + \"\" + path_elem response = requests . request ( method , path_str , auth = auth , headers = { '' : '' , '' : '' } , ** kwargs ) logger . debug ( \"\" , method , response . url ) if response . status_code == : break if '' in response . json ( ) : response . reason = \"\" % ( response . reason , response . json ( ) [ '' ] ) response . raise_for_status ( ) return response def api_req ( self , method , path , ** kwargs ) : return self . api_req_raw ( method , path , self . __auth , ** kwargs ) . json ( ) def create ( self , app_json ) : return self . api_req ( '' , [ '' ] , app_json ) def get_app ( self , appid ) : logger . info ( '' , appid ) return self . api_req ( '' , [ '' , appid ] ) [ \"\" ] def list ( self ) : logger . info ( '' ) return self . api_req ( '' , [ '' ] , params = { '' : '' } ) [ \"\" ] def health_check ( self ) : return self . __health_check def tasks ( self ) : logger . info ( '' ) return self . api_req ( '' , [ '' ] ) [ \"\" ] def add_subscriber ( self , callbackUrl ) : return self . api_req ( '' , [ '' ] , params = { '' : callbackUrl } ) def remove_subscriber ( self , callbackUrl ) : return self . api_req ( '' , [ '' ] , params = { '' : callbackUrl } ) def get_event_stream ( self ) : url = self . host + \"\" logger . info ( \"\" . format ( url ) ) headers = { '' : '' , '' : '' } resp = requests . get ( url , stream = True , headers = headers , auth = self . __auth ) class Event ( object ) : def __init__ ( self , data ) : self . data = data for line in resp . iter_lines ( ) : if line . strip ( ) != '' : for real_event_data in re . split ( r'' , line . decode ( '' ) ) : if real_event_data [ : ] == \"\" : event = Event ( data = real_event_data [ : ] ) yield event @ property def host ( self ) : return next ( self . __cycle_hosts ) def has_group ( groups , app_groups ) : if '' in groups : return True if len ( groups ) == and len ( app_groups ) == : raise Exception ( \"\" ) if ( len ( frozenset ( app_groups ) & groups ) ) : return True return False def config ( apps , groups , bind_http_https , ssl_certs , templater ) : logger . info ( \"\" ) config = templater . haproxy_head groups = frozenset ( groups ) _ssl_certs = ssl_certs or \"\" _ssl_certs = _ssl_certs . split ( \"\" ) if bind_http_https : http_frontends = templater . haproxy_http_frontend_head https_frontends = templater . haproxy_https_frontend_head . format ( sslCerts = \"\" . join ( map ( lambda cert : \"\" + cert , _ssl_certs ) ) ) userlists = str ( ) frontends = str ( ) backends = str ( ) http_appid_frontends = templater . haproxy_http_frontend_appid_head apps_with_http_appid_backend = [ ] http_frontend_list = [ ] https_frontend_list = [ ] for app in sorted ( apps , key = attrgetter ( '' , '' ) ) : if app . haproxy_groups : if not has_group ( groups , app . haproxy_groups ) : continue else : if not has_group ( groups , app . groups ) : continue logger . debug ( \"\" , app . appId ) backend = app . appId [ : ] . replace ( '' , '' ) + '' + str ( app . servicePort ) logger . debug ( \"\" , app . bindAddr , app . servicePort , backend ) if app . hostname : app . mode = '' if app . authUser : userlist_head = templater . haproxy_userlist_head ( app ) userlists += userlist_head . format ( backend = backend , user = app . authUser , passwd = app . authPasswd ) frontend_head = templater . haproxy_frontend_head ( app ) frontends += frontend_head . format ( bindAddr = app . bindAddr , backend = backend , servicePort = app . servicePort , mode = app . mode , sslCert = '' + app . sslCert if app . sslCert else '' , bindOptions = '' + app . bindOptions if app . bindOptions else '' ) backend_head = templater . haproxy_backend_head ( app ) backends += backend_head . format ( backend = backend , balance = app . balance , mode = app . mode ) if bind_http_https and app . hostname : backend_weight , p_fe , s_fe = generateHttpVhostAcl ( templater , app , backend ) http_frontend_list . append ( ( backend_weight , p_fe ) ) https_frontend_list . append ( ( backend_weight , s_fe ) ) if app . mode == '' and app . appId not in apps_with_http_appid_backend : logger . debug ( \"\" , app . appId ) apps_with_http_appid_backend += [ app . appId ] cleanedUpAppId = re . sub ( r'' , '' , app . appId ) http_appid_frontend_acl = templater . haproxy_http_frontend_appid_acl ( app ) http_appid_frontends += http_appid_frontend_acl . format ( cleanedUpAppId = cleanedUpAppId , hostname = app . hostname , appId = app . appId , backend = backend ) if app . mode == '' : if app . useHsts : backends += templater . haproxy_backend_hsts_options ( app ) backends += templater . haproxy_backend_http_options ( app ) backend_http_backend_proxypass = templater . haproxy_http_backend_proxypass ( app ) if app . proxypath : backends += backend_http_backend_proxypass . format ( hostname = app . hostname , proxypath = app . proxypath ) backend_http_backend_revproxy = templater . haproxy_http_backend_revproxy ( app ) if app . revproxypath : backends += backend_http_backend_revproxy . format ( hostname = app . hostname , rootpath = app . revproxypath ) backend_http_backend_redir = templater . haproxy_http_backend_redir ( app ) if app . redirpath : backends += backend_http_backend_redir . format ( hostname = app . hostname , redirpath = app . redirpath ) if app . healthCheck : health_check_options = None if app . mode == '' or app . healthCheck [ '' ] == '' : health_check_options = templater . haproxy_backend_tcp_healthcheck_options ( app ) elif app . mode == '' : health_check_options = templater . haproxy_backend_http_healthcheck_options ( app ) if health_check_options : healthCheckPort = app . healthCheck . get ( '' ) backends += health_check_options . format ( healthCheck = app . healthCheck , healthCheckPortIndex = app . healthCheck . get ( '' ) , healthCheckPort = healthCheckPort , healthCheckProtocol = app . healthCheck [ '' ] , healthCheckPath = app . healthCheck . get ( '' , '' ) , healthCheckTimeoutSeconds = app . healthCheck [ '' ] , healthCheckIntervalSeconds = app . healthCheck [ '' ] , healthCheckIgnoreHttp1xx = app . healthCheck [ '' ] , healthCheckGracePeriodSeconds = app . healthCheck [ '' ] , healthCheckMaxConsecutiveFailures = app . healthCheck [ '' ] , healthCheckFalls = app . healthCheck [ '' ] + , healthCheckPortOptions = '' + str ( healthCheckPort ) if healthCheckPort else '' ) if app . sticky : logger . debug ( \"\" ) backends += templater . haproxy_backend_sticky_options ( app ) frontend_backend_glue = templater . haproxy_frontend_backend_glue ( app ) frontends += frontend_backend_glue . format ( backend = backend ) key_func = attrgetter ( '' , '' ) for backendServer in sorted ( app . backends , key = key_func ) : logger . debug ( \"\" , backendServer . ip , backendServer . port , backendServer . host ) if backendServer . host != backendServer . ip : serverName = re . sub ( r'' , '' , ( backendServer . host + '' + backendServer . ip + '' + str ( backendServer . port ) ) ) else : serverName = re . sub ( r'' , '' , ( backendServer . ip + '' + str ( backendServer . port ) ) ) shortHashedServerName = hashlib . sha1 ( serverName . encode ( ) ) . hexdigest ( ) [ : ] healthCheckOptions = None if app . healthCheck : server_health_check_options = None if app . mode == '' or app . healthCheck [ '' ] == '' : server_health_check_options = templater . haproxy_backend_server_tcp_healthcheck_options ( app ) elif app . mode == '' : server_health_check_options = templater . haproxy_backend_server_http_healthcheck_options ( app ) if server_health_check_options : healthCheckPort = app . healthCheck . get ( '' ) healthCheckOptions = server_health_check_options . format ( healthCheck = app . healthCheck , healthCheckPortIndex = app . healthCheck . get ( '' ) , healthCheckPort = healthCheckPort , healthCheckProtocol = app . healthCheck [ '' ] , healthCheckPath = app . healthCheck . get ( '' , '' ) , healthCheckTimeoutSeconds = app . healthCheck [ '' ] , healthCheckIntervalSeconds = app . healthCheck [ '' ] , healthCheckIgnoreHttp1xx = app . healthCheck [ '' ] , healthCheckGracePeriodSeconds = app . healthCheck [ '' ] , healthCheckMaxConsecutiveFailures = app . healthCheck [ '' ] , healthCheckFalls = app . healthCheck [ '' ] + , healthCheckPortOptions = '' + str ( healthCheckPort ) if healthCheckPort else '' ) backend_server_options = templater . haproxy_backend_server_options ( app ) backends += backend_server_options . format ( host = backendServer . host , host_ipv4 = backendServer . ip , port = backendServer . port , serverName = serverName , cookieOptions = '' + shortHashedServerName if app . sticky else '' , healthCheckOptions = healthCheckOptions if healthCheckOptions else '' , otherOptions = '' if backendServer . draining else '' ) http_frontend_list . sort ( key = lambda x : x [ ] , reverse = True ) https_frontend_list . sort ( key = lambda x : x [ ] , reverse = True ) for backend in http_frontend_list : http_frontends += backend [ ] for backend in https_frontend_list : https_frontends += backend [ ] config += userlists if bind_http_https : config += http_frontends config += http_appid_frontends if bind_http_https : config += https_frontends config += frontends config += backends return config def get_haproxy_pids ( ) : try : return subprocess . check_output ( \"\" , stderr = subprocess . STDOUT , shell = True ) except subprocess . CalledProcessError as ex : return '' def reloadConfig ( ) : reloadCommand = [ ] if args . command : reloadCommand = shlex . split ( args . command ) else : logger . debug ( \"\" + \"\" ) if os . path . isfile ( '' ) : logger . debug ( \"\" ) reloadCommand = [ '' , '' ] elif ( os . path . isfile ( '' ) or os . path . isfile ( '' ) ) : logger . debug ( \"\" ) reloadCommand = [ '' , '' , '' ] elif os . path . isfile ( '' ) : logger . debug ( \"\" ) reloadCommand = [ '' , '' ] else : logger . debug ( \"\" ) reloadCommand = None if reloadCommand : logger . info ( \"\" , \"\" . join ( reloadCommand ) ) try : start_time = time . time ( ) pids = get_haproxy_pids ( ) subprocess . check_call ( reloadCommand , close_fds = True ) while pids == get_haproxy_pids ( ) : time . sleep ( ) logger . debug ( \"\" , time . time ( ) - start_time ) except OSError as ex : logger . error ( \"\" , \"\" . join ( reloadCommand ) ) logger . error ( \"\" , ex ) except subprocess . CalledProcessError as ex : logger . error ( \"\" , \"\" . join ( reloadCommand ) ) logger . error ( \"\" , ex ) def generateHttpVhostAcl ( templater , app , backend ) : staging_http_frontends = \"\" staging_https_frontends = \"\" if \"\" in app . hostname : logger . debug ( \"\" , app . hostname ) vhosts = app . hostname . split ( '' ) acl_name = re . sub ( r'' , '' , vhosts [ ] ) + '' + app . appId [ : ] . replace ( '' , '' ) if app . path : if app . authRealm : logger . debug ( \"\" , app . path ) http_frontend_acl = templater . haproxy_http_frontend_acl_only_with_path_and_auth ( app ) staging_http_frontends += http_frontend_acl . format ( path = app . path , cleanedUpHostname = acl_name , hostname = vhosts [ ] , realm = app . authRealm , backend = backend ) https_frontend_acl = templater . haproxy_https_frontend_acl_only_with_path ( app ) staging_https_frontends += https_frontend_acl . format ( path = app . path , cleanedUpHostname = acl_name , hostname = vhosts [ ] , realm = app . authRealm , backend = backend ) else : logger . debug ( \"\" , app . path ) http_frontend_acl = templater . haproxy_http_frontend_acl_only_with_path ( app ) staging_http_frontends += http_frontend_acl . format ( path = app . path , backend = backend ) https_frontend_acl = templater . haproxy_https_frontend_acl_only_with_path ( app ) staging_https_frontends += https_frontend_acl . format ( path = app . path , backend = backend ) for vhost_hostname in vhosts : logger . debug ( \"\" , vhost_hostname ) http_frontend_acl = templater . haproxy_http_frontend_acl_only ( app ) staging_http_frontends += http_frontend_acl . format ( cleanedUpHostname = acl_name , hostname = vhost_hostname ) if app . path : if app . authRealm : https_frontend_acl = templater . haproxy_https_frontend_acl_with_auth_and_path ( app ) staging_https_frontends += https_frontend_acl . format ( cleanedUpHostname = acl_name , hostname = vhost_hostname , appId = app . appId , realm = app . authRealm , backend = backend ) else : https_frontend_acl = templater . haproxy_https_frontend_acl_with_path ( app ) staging_https_frontends += https_frontend_acl . format ( cleanedUpHostname = acl_name , hostname = vhost_hostname , appId = app . appId , backend = backend ) else : if app . authRealm : https_frontend_acl = templater . haproxy_https_frontend_acl_with_auth ( app ) staging_https_frontends += https_frontend_acl . format ( cleanedUpHostname = acl_name , hostname = vhost_hostname , appId = app . appId , realm = app . authRealm , backend = backend ) else : https_frontend_acl = templater . haproxy_https_frontend_acl ( app ) staging_https_frontends += https_frontend_acl . format ( cleanedUpHostname = acl_name , hostname = vhost_hostname , appId = app . appId , backend = backend ) if app . redirectHttpToHttps : logger . debug ( \"\" ) if app . path : haproxy_backend_redirect_http_to_https = templater . haproxy_backend_redirect_http_to_https_with_path ( app ) frontend = haproxy_backend_redirect_http_to_https . format ( bindAddr = app . bindAddr , cleanedUpHostname = acl_name , backend = backend ) staging_http_frontends += frontend else : haproxy_backend_redirect_http_to_https = templater . haproxy_backend_redirect_http_to_https ( app ) frontend = haproxy_backend_redirect_http_to_https . format ( bindAddr = app . bindAddr , cleanedUpHostname = acl_name ) staging_http_frontends += frontend elif app . path : if app . authRealm : http_frontend_route = templater . haproxy_http_frontend_routing_only_with_path_and_auth ( app ) staging_http_frontends += http_frontend_route . format ( cleanedUpHostname = acl_name , realm = app . authRealm , backend = backend ) else : http_frontend_route = templater . haproxy_http_frontend_routing_only_with_path ( app ) staging_http_frontends += http_frontend_route . format ( cleanedUpHostname = acl_name , backend = backend ) else : if app . authRealm : http_frontend_route = templater . haproxy_http_frontend_routing_only_with_auth ( app ) staging_http_frontends += http_frontend_route . format ( cleanedUpHostname = acl_name , realm = app . authRealm , backend = backend ) else : http_frontend_route = templater . haproxy_http_frontend_routing_only ( app ) staging_http_frontends += http_frontend_route . format ( cleanedUpHostname = acl_name , backend = backend ) else : logger . debug ( \"\" , app . hostname ) acl_name = re . sub ( r'' , '' , app . hostname ) + '' + app . appId [ : ] . replace ( '' , '' ) if app . path : if app . redirectHttpToHttps : http_frontend_acl = templater . haproxy_http_frontend_acl_only ( app ) staging_http_frontends += http_frontend_acl . format ( cleanedUpHostname = acl_name , hostname = app . hostname ) http_frontend_acl = templater . haproxy_http_frontend_acl_only_with_path ( app ) staging_http_frontends += http_frontend_acl . format ( cleanedUpHostname = acl_name , hostname = app . hostname , path = app . path , backend = backend ) haproxy_backend_redirect_http_to_https = templater . haproxy_backend_redirect_http_to_https_with_path ( app ) frontend = haproxy_backend_redirect_http_to_https . format ( bindAddr = app . bindAddr , cleanedUpHostname = acl_name , backend = backend ) staging_http_frontends += frontend else : if app . authRealm : http_frontend_acl = templater . haproxy_http_frontend_acl_with_auth_and_path ( app ) staging_http_frontends += http_frontend_acl . format ( cleanedUpHostname = acl_name , hostname = app . hostname , path = app . path , appId = app . appId , realm = app . authRealm , backend = backend ) else : http_frontend_acl = templater . haproxy_http_frontend_acl_with_path ( app ) staging_http_frontends += http_frontend_acl . format ( cleanedUpHostname = acl_name , hostname = app . hostname , path = app . path , appId = app . appId , backend = backend ) https_frontend_acl = templater . haproxy_https_frontend_acl_only_with_path ( app ) staging_https_frontends += https_frontend_acl . format ( path = app . path , backend = backend ) if app . authRealm : https_frontend_acl = templater . haproxy_https_frontend_acl_with_auth_and_path ( app ) staging_https_frontends += https_frontend_acl . format ( cleanedUpHostname = acl_name , hostname = app . hostname , path = app . path , appId = app . appId , realm = app . authRealm , backend = backend ) else : https_frontend_acl = templater . haproxy_https_frontend_acl_with_path ( app ) staging_https_frontends += https_frontend_acl . format ( cleanedUpHostname = acl_name , hostname = app . hostname , appId = app . appId , backend = backend ) else : if app . redirectHttpToHttps : http_frontend_acl = templater . haproxy_http_frontend_acl_only ( app ) staging_http_frontends += http_frontend_acl . format ( cleanedUpHostname = acl_name , hostname = app . hostname ) haproxy_backend_redirect_http_to_https = templater . haproxy_backend_redirect_http_to_https ( app ) frontend = haproxy_backend_redirect_http_to_https . format ( bindAddr = app . bindAddr , cleanedUpHostname = acl_name ) staging_http_frontends += frontend else : if app . authRealm : http_frontend_acl = templater . haproxy_http_frontend_acl_with_auth ( app ) staging_http_frontends += http_frontend_acl . format ( cleanedUpHostname = acl_name , hostname = app . hostname , appId = app . appId , realm = app . authRealm , backend = backend ) else : http_frontend_acl = templater . haproxy_http_frontend_acl ( app ) staging_http_frontends += http_frontend_acl . format ( cleanedUpHostname = acl_name , hostname = app . hostname , appId = app . appId , backend = backend ) if app . authRealm : https_frontend_acl = templater . haproxy_https_frontend_acl_with_auth ( app ) staging_https_frontends += https_frontend_acl . format ( cleanedUpHostname = acl_name , hostname = app . hostname , appId = app . appId , realm = app . authRealm , backend = backend ) else : https_frontend_acl = templater . haproxy_https_frontend_acl ( app ) staging_https_frontends += https_frontend_acl . format ( cleanedUpHostname = acl_name , hostname = app . hostname , appId = app . appId , backend = backend ) return ( app . backend_weight , staging_http_frontends , staging_https_frontends ) def writeConfigAndValidate ( config , config_file ) : if args . dry : print ( config ) sys . exit ( ) fd , haproxyTempConfigFile = mkstemp ( ) logger . debug ( \"\" , haproxyTempConfigFile ) with os . fdopen ( fd , '' ) as haproxyTempConfig : haproxyTempConfig . write ( config ) perms = if os . path . isfile ( config_file ) : perms = stat . S_IMODE ( os . lstat ( config_file ) . st_mode ) os . chmod ( haproxyTempConfigFile , perms ) if args . skip_validation : logger . debug ( \"\" , haproxyTempConfigFile , config_file ) move ( haproxyTempConfigFile , config_file ) return True cmd = [ '' , '' , haproxyTempConfigFile , '' ] logger . debug ( \"\" + str ( cmd ) ) returncode = subprocess . call ( args = cmd ) if returncode == : logger . debug ( \"\" , haproxyTempConfigFile , config_file ) move ( haproxyTempConfigFile , config_file ) return True else : logger . error ( \"\" ) return False def compareWriteAndReloadConfig ( config , config_file ) : runningConfig = str ( ) try : logger . debug ( \"\" , config_file ) with open ( config_file , \"\" ) as f : runningConfig = f . read ( ) except IOError : logger . warning ( \"\" ) if runningConfig != config : logger . info ( \"\" ) if writeConfigAndValidate ( config , config_file ) : reloadConfig ( ) else : logger . warning ( \"\" ) def get_health_check ( app , portIndex ) : for check in app [ '' ] : if check . get ( '' ) : return check if check . get ( '' ) == portIndex : return check return None healthCheckResultCache = LRUCache ( ) def get_apps ( marathon ) : apps = marathon . list ( ) logger . debug ( \"\" , [ app [ \"\" ] for app in apps ] ) marathon_apps = [ ] processed_apps = [ ] deployment_groups = { } for app in apps : deployment_group = None if '' in app [ '' ] : deployment_group = app [ '' ] [ '' ] if deployment_group [ ] != '' : deployment_group = '' + deployment_group app [ '' ] = deployment_group else : processed_apps . append ( app ) continue if deployment_group in deployment_groups : prev = deployment_groups [ deployment_group ] cur = app if '' in prev [ '' ] : prev_date = dateutil . parser . parse ( prev [ '' ] [ '' ] ) else : prev_date = '' if '' in cur [ '' ] : cur_date = dateutil . parser . parse ( cur [ '' ] [ '' ] ) else : cur_date = '' old = new = None if prev_date < cur_date : old = prev new = cur else : new = prev old = cur target_instances = int ( new [ '' ] [ '' ] ) old_tasks = sorted ( old [ '' ] , key = lambda task : task [ '' ] ) healthy_new_instances = if len ( app [ '' ] ) > : for task in new [ '' ] : if '' not in task : continue alive = True for result in task [ '' ] : if not result [ '' ] : alive = False if alive : healthy_new_instances += else : healthy_new_instances = new [ '' ] maximum_drainable = max ( , ( healthy_new_instances + old [ '' ] ) - target_instances ) for i in range ( , min ( len ( old_tasks ) , healthy_new_instances , maximum_drainable ) ) : old_tasks [ i ] [ '' ] = True merged = old old_tasks . extend ( new [ '' ] ) merged [ '' ] = old_tasks deployment_groups [ deployment_group ] = merged else : deployment_groups [ deployment_group ] = app processed_apps . extend ( deployment_groups . values ( ) ) SERVICE_PORT_ASSIGNER . reset ( ) for app in processed_apps : appId = app [ '' ] if appId [ : ] == os . environ . get ( \"\" ) : continue marathon_app = MarathonApp ( marathon , appId , app ) if '' in marathon_app . app [ '' ] : marathon_app . groups = marathon_app . app [ '' ] [ '' ] . split ( '' ) marathon_apps . append ( marathon_app ) service_ports = SERVICE_PORT_ASSIGNER . get_service_ports ( app ) for i , servicePort in enumerate ( service_ports ) : if servicePort is None : logger . warning ( \"\" ) continue service = MarathonService ( appId , servicePort , get_health_check ( app , i ) ) for key_unformatted in label_keys : key = key_unformatted . format ( i ) if key in marathon_app . app [ '' ] : func = label_keys [ key_unformatted ] func ( service , key_unformatted , marathon_app . app [ '' ] [ key ] ) marathon_app . services [ servicePort ] = service for task in app [ '' ] : if not task [ '' ] : logger . warning ( \"\" + task [ '' ] ) continue if marathon . health_check ( ) and '' in app and len ( app [ '' ] ) > : alive = True if '' not in task : if not healthCheckResultCache . get ( task [ '' ] , False ) : continue else : for result in task [ '' ] : if not result [ '' ] : alive = False healthCheckResultCache . set ( task [ '' ] , alive ) if not alive : continue task_ip , task_ports = get_task_ip_and_ports ( app , task ) if not task_ip : logger . warning ( \"\" ) continue draining = task . get ( '' , False ) for task_port , service_port in zip ( task_ports , service_ports ) : service = marathon_app . services . get ( service_port , None ) if service : service . groups = marathon_app . groups service . add_backend ( task [ '' ] , task_ip , task_port , draining ) apps_list = [ ] for marathon_app in marathon_apps : for service in list ( marathon_app . services . values ( ) ) : if service . backends : apps_list . append ( service ) return apps_list def regenerate_config ( apps , config_file , groups , bind_http_https , ssl_certs , templater ) : compareWriteAndReloadConfig ( config ( apps , groups , bind_http_https , ssl_certs , templater ) , config_file ) class MarathonEventProcessor ( object ) : def __init__ ( self , marathon , config_file , groups , bind_http_https , ssl_certs ) : self . __marathon = marathon self . __apps = dict ( ) self . __config_file = config_file self . __groups = groups self . __templater = ConfigTemplater ( ) self . __bind_http_https = bind_http_https self . __ssl_certs = ssl_certs self . __condition = threading . Condition ( ) self . __thread = threading . Thread ( target = self . do_reset ) self . __pending_reset = False self . __stop = False self . __thread . start ( ) self . reset_from_tasks ( ) def do_reset ( self ) : with self . __condition : logger . info ( '' ) while True : self . __condition . acquire ( ) if self . __stop : logger . info ( '' ) return if not self . __pending_reset : if not self . __condition . wait ( ) : logger . info ( '' ) self . __pending_reset = False self . __condition . release ( ) try : ", "answer": "start_time = time . time ( )"}, {"prompt": " from __future__ import absolute_import from django . conf . urls import patterns , include from . import views , customadmin , admin urlpatterns = patterns ( '' , ( r'' , include ( '' ) ) , ( r'' , views . secure_view ) , ( r'' , include ( admin . site . urls ) ) , ( r'' , include ( customadmin . site . urls ) ) , ", "answer": "( r'' , include ( admin . site . urls ) , dict ( form_url = '' ) ) ,"}, {"prompt": " from __future__ import print_function , unicode_literals import io import logging import os import shutil import unittest import mock import yaml from chalmers import config , errors from chalmers . scripts import chalmers_main class ChalmersCli ( object ) : def __init__ ( self ) : self . script = chalmers_main . __file__ if self . script . endswith ( '' ) or self . script . endswith ( '' ) : self . script = self . script [ : - ] self . env = os . environ . copy ( ) self . root = '' self . env [ '' ] = self . root config . set_relative_dirs ( self . root ) logging . getLogger ( '' ) . addHandler ( logging . NullHandler ( ) ) def __getattr__ ( self , subcommand ) : def run_subcommand ( * args ) : cmd = [ '' , '' , subcommand ] cmd . extend ( args ) out = io . StringIO ( ) ", "answer": "log = logging . getLogger ( '' )"}, {"prompt": " \"\"\"\"\"\" from muntjac . event . dd . acceptcriteria . accept_criterion import IAcceptCriterion class ServerSideCriterion ( IAcceptCriterion ) : \"\"\"\"\"\" ", "answer": "def isClientSideVerifiable ( self ) :"}, {"prompt": " import datetime import json import webob import nova from nova import context from nova import test from nova . api . openstack . contrib . volumes import BootFromVolumeController from nova . compute import instance_types from nova . tests . api . openstack import fakes from nova . tests . api . openstack . test_servers import fake_gen_uuid def fake_compute_api_create ( cls , context , instance_type , image_href , ** kwargs ) : inst_type = instance_types . get_instance_type_by_flavor_id ( ) return [ { '' : , '' : '' , '' : fake_gen_uuid ( ) , '' : dict ( inst_type ) , '' : '' , '' : '' , '' : , '' : '' , '' : '' , '' : datetime . datetime ( , , , , , ) , '' : datetime . datetime ( , , , , , ) , } ] class BootFromVolumeTest ( test . TestCase ) : def setUp ( self ) : super ( BootFromVolumeTest , self ) . setUp ( ) self . stubs . Set ( nova . compute . API , '' , fake_compute_api_create ) def test_create_root_volume ( self ) : body = dict ( server = dict ( name = '' , imageRef = , flavorRef = , min_count = , max_count = , block_device_mapping = [ dict ( volume_id = , device_name = '' , virtual = '' , delete_on_termination = False , ) ] ) ) req = webob . Request . blank ( '' ) ", "answer": "req . method = ''"}, {"prompt": " import os . path import platform import sys import webbrowser import argparse import simplejson as json from datadog import api from datadog . util . format import pretty_json from datadog . dogshell . common import report_errors , report_warnings , print_err from datetime import datetime class TimeboardClient ( object ) : @ classmethod def setup_parser ( cls , subparsers ) : parser = subparsers . add_parser ( '' , help = \"\" ) parser . add_argument ( '' , action = '' , dest = '' , help = \"\" ) verb_parsers = parser . add_subparsers ( title = '' , dest = '' ) verb_parsers . required = True post_parser = verb_parsers . add_parser ( '' , help = \"\" ) post_parser . add_argument ( '' , help = \"\" ) post_parser . add_argument ( '' , help = \"\" ) post_parser . add_argument ( '' , help = \"\" ", "answer": "\"\" , nargs = \"\" )"}, {"prompt": " \"\"\"\"\"\" from collections import deque as _deque import sys , operator , itertools from utilitytypes import ProxyUnicode def isIterable ( obj ) : \"\"\"\"\"\" if isinstance ( obj , basestring ) : return False elif isinstance ( obj , ProxyUnicode ) : return False try : iter ( obj ) except TypeError : return False else : return True def isScalar ( obj ) : \"\"\"\"\"\" return operator . isNumberType ( obj ) and not isinstance ( obj , complex ) def isNumeric ( obj ) : \"\"\"\"\"\" return operator . isNumberType ( obj ) def isSequence ( obj ) : \"\"\"\"\"\" return operator . isSequenceType ( obj ) def isMapping ( obj ) : \"\"\"\"\"\" return operator . isMappingType ( obj ) clsname = lambda x : type ( x ) . __name__ def convertListArgs ( args ) : if len ( args ) == and isIterable ( args [ ] ) : return tuple ( args [ ] ) return args def expandArgs ( * args , ** kwargs ) : \"\"\"\"\"\" tpe = kwargs . get ( '' , '' ) limit = kwargs . get ( '' , sys . getrecursionlimit ( ) ) postorder = kwargs . get ( '' , False ) breadth = kwargs . get ( '' , False ) if tpe == '' or tpe == list : def _expandArgsTest ( arg ) : return type ( arg ) == list elif tpe == '' : def _expandArgsTest ( arg ) : return isIterable ( arg ) else : raise ValueError , \"\" % str ( tpe ) if postorder : return postorderArgs ( limit , _expandArgsTest , * args ) elif breadth : return breadthArgs ( limit , _expandArgsTest , * args ) else : return preorderArgs ( limit , _expandArgsTest , * args ) def preorderArgs ( limit = sys . getrecursionlimit ( ) , testFn = isIterable , * args ) : \"\"\"\"\"\" stack = [ ( x , ) for x in args ] result = _deque ( ) while stack : arg , level = stack . pop ( ) if testFn ( arg ) and level < limit : stack += [ ( x , level + ) for x in arg ] else : result . appendleft ( arg ) return tuple ( result ) def postorderArgs ( limit = sys . getrecursionlimit ( ) , testFn = isIterable , * args ) : \"\"\"\"\"\" if len ( args ) == : return ( args [ ] , ) else : deq = _deque ( ( x , ) for x in args ) stack = [ ] result = [ ] while deq : arg , level = deq . popleft ( ) if testFn ( arg ) and level < limit : deq = _deque ( [ ( x , level + ) for x in arg ] + list ( deq ) ) else : if stack : while stack and level <= stack [ - ] [ ] : result . append ( stack . pop ( ) [ ] ) stack . append ( ( arg , level ) ) else : stack . append ( ( arg , level ) ) while stack : result . append ( stack . pop ( ) [ ] ) return tuple ( result ) def breadthArgs ( limit = sys . getrecursionlimit ( ) , testFn = isIterable , * args ) : \"\"\"\"\"\" deq = _deque ( ( x , ) for x in args ) result = [ ] while deq : arg , level = deq . popleft ( ) if testFn ( arg ) and level < limit : for a in arg : deq . append ( ( a , level + ) ) else : result . append ( arg ) return tuple ( result ) def iterateArgs ( * args , ** kwargs ) : \"\"\"\"\"\" tpe = kwargs . get ( '' , '' ) limit = kwargs . get ( '' , sys . getrecursionlimit ( ) ) postorder = kwargs . get ( '' , False ) breadth = kwargs . get ( '' , False ) if tpe == '' or tpe == list : def _iterateArgsTest ( arg ) : return type ( arg ) == list elif tpe == '' : def _iterateArgsTest ( arg ) : return isIterable ( arg ) else : raise ValueError , \"\" % str ( tpe ) if postorder : for arg in postorderIterArgs ( limit , _iterateArgsTest , * args ) : yield arg elif breadth : for arg in breadthIterArgs ( limit , _iterateArgsTest , * args ) : ", "answer": "yield arg"}, {"prompt": " from model_test import * from view_test import * from templatetag_test import * ", "answer": "__test__ = {"}, {"prompt": " \"\"\"\"\"\" from xmlloader import * ", "answer": "from xmldumper import * "}, {"prompt": " from django . conf . urls import patterns , include , url from django . views . generic import TemplateView from django . contrib import admin admin . autodiscover ( ) ", "answer": "urlpatterns = patterns ( '' ,"}, {"prompt": " import os import datetime from opencanary . modules import CanaryService from base64 import b64decode import urlparse from urllib import quote as urlquote from twisted . application import internet from twisted . internet . protocol import ServerFactory from twisted . application . internet import TCPServer from twisted . internet . protocol import ClientFactory from twisted . internet import protocol from twisted . web . http import HTTPClient , Request , HTTPChannel from twisted . web import http from twisted . internet import reactor from jinja2 import Template PROFILES = { \"\" : { \"\" : True , \"\" : [ ( \"\" , \"\" ) , ( \"\" , \"\" ) , ( \"\" , \"\" ) , ( \"\" , \"\" ) , ] , \"\" : \"\" } , \"\" : { \"\" : '' , \"\" : [ ( \"\" , \"\" ) , ( \"\" , \"\" ) , ( \"\" , \"\" ) , ( \"\" , \"\" ) , ( \"\" , \"\" ) , ( \"\" , \"\" ) , ( \"\" , \"\" ) ] , \"\" : \"\" } } class AlertProxyRequest ( Request ) : \"\"\"\"\"\" FACTORY = None def __init__ ( self , channel , queued ) : Request . __init__ ( self , channel , queued ) def logAuth ( self ) : auth = self . getHeader ( \"\" ) if auth is None : return factory = AlertProxyRequest . FACTORY username , password = \"\" , \"\" atype , token = auth . split ( \"\" ) if atype == \"\" : try : username , password = b64decode ( token ) . split ( \"\" ) except : pass elif atype == \"\" : print b64decode ( token ) . split ( \"\" ) exit ( ) print \"\" return logdata = { '' : username , '' : password } factory . log ( logdata , transport = self . transport ) def process ( self ) : self . logAuth ( ) factory = AlertProxyRequest . FACTORY profile = PROFILES [ factory . skin ] content = factory . auth_template . render ( url = self . uri , date = datetime . datetime . utcnow ( ) . strftime ( \"\" ) , clientip = self . transport . getPeer ( ) . host ) if factory . banner : prompt = factory . banner else : prompt = profile . get ( \"\" , \"\" ) if profile . get ( \"\" , False ) : self . clientproto = \"\" self . setResponseCode ( , profile [ \"\" ] ) for ( name , value ) in profile [ \"\" ] : self . responseHeaders . addRawHeader ( name , value ) self . responseHeaders . addRawHeader ( \"\" , \"\" ) self . responseHeaders . addRawHeader ( \"\" , '' % prompt ) self . responseHeaders . addRawHeader ( \"\" , len ( content ) ) self . write ( content . encode ( \"\" ) ) self . finish ( ) class AlertProxy ( HTTPChannel ) : requestFactory = AlertProxyRequest class HTTPProxyFactory ( http . HTTPFactory ) : def buildProtocol ( self , addr ) : return AlertProxy ( ) class HTTPProxy ( CanaryService ) : NAME = '' def __init__ ( self , config = None , logger = None ) : CanaryService . __init__ ( self , config = config , logger = logger ) self . port = int ( config . getVal ( '' , default = ) ) self . banner = config . getVal ( '' , '' ) . encode ( '' ) ", "answer": "self . skin = config . getVal ( '' , default = '' )"}, {"prompt": " from __future__ import absolute_import , unicode_literals from tests . mpd import protocol class ChannelsHandlerTest ( protocol . BaseTestCase ) : def test_subscribe ( self ) : self . send_request ( '' ) self . assertEqualResponse ( '' ) def test_unsubscribe ( self ) : self . send_request ( '' ) self . assertEqualResponse ( '' ) def test_channels ( self ) : ", "answer": "self . send_request ( '' )"}, {"prompt": " \"\"\"\"\"\" import importlib import click import pkg_resources import SoftLayer from SoftLayer . CLI import formatting from SoftLayer . CLI import routes class Environment ( object ) : \"\"\"\"\"\" def __init__ ( self ) : self . commands = { } self . aliases = { } self . vars = { } self . client = None self . format = '' self . skip_confirmations = False self . config_file = None self . _modules_loaded = False def out ( self , output , newline = True ) : \"\"\"\"\"\" click . echo ( output , nl = newline ) def err ( self , output , newline = True ) : \"\"\"\"\"\" click . echo ( output , nl = newline , err = True ) def fmt ( self , output ) : \"\"\"\"\"\" return formatting . format_output ( output , fmt = self . format ) def fout ( self , output , newline = True ) : \"\"\"\"\"\" if output is not None : self . out ( self . fmt ( output ) , newline = newline ) def input ( self , prompt , default = None , show_default = True ) : \"\"\"\"\"\" return click . prompt ( prompt , default = default , show_default = show_default ) def getpass ( self , prompt , default = None ) : \"\"\"\"\"\" return click . prompt ( prompt , hide_input = True , default = default ) def list_commands ( self , * path ) : \"\"\"\"\"\" path_str = '' . join ( path ) commands = [ ] for command in self . commands . keys ( ) : if all ( [ command . startswith ( path_str ) , len ( path ) == command . count ( \"\" ) ] ) : offset = len ( path_str ) + if path_str else commands . append ( command [ offset : ] ) return sorted ( commands ) def get_command ( self , * path ) : \"\"\"\"\"\" path_str = '' . join ( path ) if path_str in self . commands : return self . commands [ path_str ] . load ( ) return None def resolve_alias ( self , path_str ) : \"\"\"\"\"\" if path_str in self . aliases : return self . aliases [ path_str ] return path_str def load ( self ) : \"\"\"\"\"\" if self . _modules_loaded is True : return self . load_modules_from_python ( routes . ALL_ROUTES ) self . aliases . update ( routes . ALL_ALIASES ) self . _load_modules_from_entry_points ( '' ) self . _modules_loaded = True def load_modules_from_python ( self , route_list ) : \"\"\"\"\"\" for name , modpath in route_list : if '' in modpath : path , attr = modpath . split ( '' , ) else : path , attr = modpath , None self . commands [ name ] = ModuleLoader ( path , attr = attr ) def _load_modules_from_entry_points ( self , entry_point_group ) : \"\"\"\"\"\" for obj in pkg_resources . iter_entry_points ( group = entry_point_group , name = None ) : self . commands [ obj . name ] = obj def ensure_client ( self , config_file = None , is_demo = False , proxy = None ) : \"\"\"\"\"\" if self . client is not None : return ", "answer": "if is_demo :"}, {"prompt": " from sympy . crypto . crypto import ( cycle_list , encipher_shift , encipher_affine , encipher_substitution , check_and_join , encipher_vigenere , decipher_vigenere , bifid5_square , bifid6_square , encipher_hill , decipher_hill , ", "answer": "encipher_bifid5 , encipher_bifid6 , decipher_bifid5 ,"}, {"prompt": " \"\"\"\"\"\" from eventlet import event from eventlet import greenthread from eventlet . queue import LightQueue from glance import client from nova import exception from nova import log as logging LOG = logging . getLogger ( \"\" ) IO_THREAD_SLEEP_TIME = GLANCE_POLL_INTERVAL = class ThreadSafePipe ( LightQueue ) : \"\"\"\"\"\" def __init__ ( self , maxsize , transfer_size ) : LightQueue . __init__ ( self , maxsize ) self . transfer_size = transfer_size self . transferred = def read ( self , chunk_size ) : \"\"\"\"\"\" if self . transferred < self . transfer_size : data_item = self . get ( ) self . transferred += len ( data_item ) return data_item else : return \"\" def write ( self , data ) : \"\"\"\"\"\" self . put ( data ) def close ( self ) : \"\"\"\"\"\" pass class GlanceWriteThread ( object ) : \"\"\"\"\"\" def __init__ ( self , input , glance_client , image_id , image_meta = None ) : if not image_meta : image_meta = { } self . input = input self . glance_client = glance_client self . image_id = image_id self . image_meta = image_meta self . _running = False def start ( self ) : self . done = event . Event ( ) def _inner ( ) : \"\"\"\"\"\" self . glance_client . update_image ( self . image_id , image_meta = self . image_meta , image_data = self . input ) self . _running = True while self . _running : try : image_status = self . glance_client . get_image_meta ( self . image_id ) . get ( ", "answer": "\"\" )"}, {"prompt": " import mimetypes from django import template from django . conf import settings from django . contrib import messages from django . contrib . admin import helpers from django . http import HttpResponse from django . shortcuts import render_to_response from django . utils . translation import ugettext as _ import object_tools from export import forms , tasks , utils class Export ( object_tools . ObjectTool ) : name = '' label = '' help_text = '' form_class = forms . Export def serialize ( self , format , queryset , fields = [ ] ) : return utils . serialize ( format , queryset , fields ) def gen_filename ( self , format ) : app_label = self . model . _meta . app_label object_name = self . model . _meta . object_name . lower ( ) if format == '' : format = '' return '' % ( self . name , app_label , object_name , format ) def order ( self , queryset , by , direction ) : return utils . order_queryset ( queryset , by , direction ) def has_celery ( self ) : return '' in getattr ( settings , '' , [ ] ) def get_queryset ( self , form ) : return utils . get_queryset ( form , self . model ) def get_data ( self , form ) : queryset = self . get_queryset ( form ) format = form . cleaned_data [ '' ] fields = form . cleaned_data [ '' ] data = self . serialize ( format , queryset , fields ) return format , data def export_response ( self , form ) : format , data = self . get_data ( form ) filename = self . gen_filename ( format ) response = HttpResponse ( data , content_type = mimetypes . guess_type ( filename ) [ ] ) response [ '' ] = '' % filename return response def mail_response ( self , request , extra_context = None ) : form = extra_context [ '' ] format = form . cleaned_data [ '' ] filename = self . gen_filename ( format ) serializer_kwargs = { '' : form . cleaned_data [ '' ] , '' : format } query_kwargs = { '' : form , '' : self . model ", "answer": "}"}, {"prompt": " \"\"\"\"\"\" import logging import numpy from argparse import ArgumentParser from theano import tensor from blocks . algorithms import GradientDescent , Scale from blocks . bricks import ( MLP , Rectifier , Initializable , FeedforwardSequence , Softmax , Activation ) from blocks . bricks . conv import ( Convolutional , ConvolutionalSequence , Flattener , MaxPooling ) from blocks . bricks . cost import CategoricalCrossEntropy , MisclassificationRate from blocks . extensions import FinishAfter , Timing , Printing , ProgressBar from blocks . extensions . monitoring import ( DataStreamMonitoring , TrainingDataMonitoring ) from blocks . extensions . saveload import Checkpoint from blocks . graph import ComputationGraph from blocks . initialization import Constant , Uniform from blocks . main_loop import MainLoop from blocks . model import Model from blocks . monitoring import aggregation from fuel . datasets import MNIST from fuel . schemes import ShuffledScheme from fuel . streams import DataStream from toolz . itertoolz import interleave class LeNet ( FeedforwardSequence , Initializable ) : \"\"\"\"\"\" def __init__ ( self , conv_activations , num_channels , image_shape , filter_sizes , feature_maps , pooling_sizes , top_mlp_activations , top_mlp_dims , conv_step = None , border_mode = '' , ** kwargs ) : if conv_step is None : self . conv_step = ( , ) else : self . conv_step = conv_step self . num_channels = num_channels self . image_shape = image_shape self . top_mlp_activations = top_mlp_activations ", "answer": "self . top_mlp_dims = top_mlp_dims"}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import from . tag import SWFTimelineContainer from . stream import SWFStream from . export import SVGExporter from six . moves import cStringIO from io import BytesIO class SWFHeaderException ( Exception ) : \"\"\"\"\"\" def __init__ ( self , message ) : super ( SWFHeaderException , self ) . __init__ ( message ) class SWFHeader ( object ) : \"\"\"\"\"\" def __init__ ( self , stream ) : a = stream . readUI8 ( ) b = stream . readUI8 ( ) c = stream . readUI8 ( ) if not a in [ , , ] or b != or c != : raise SWFHeaderException ( \"\" ) self . _compressed_zlib = ( a == ) self . _compressed_lzma = ( a == ) self . _version = stream . readUI8 ( ) ", "answer": "self . _file_length = stream . readUI32 ( )"}, {"prompt": " import datetime from south . db import db from south . v2 import SchemaMigration from django . db import models from django . contrib . auth import get_user_model User = get_user_model ( ) class Migration ( SchemaMigration ) : def forwards ( self , orm ) : db . create_table ( u'' , ( ( u'' , self . gf ( '' ) ( primary_key = True ) ) , ( '' , self . gf ( '' ) ( auto_now_add = True , blank = True ) ) , ( '' , self . gf ( '' ) ( auto_now = True , blank = True ) ) , ( '' , self . gf ( '' ) ( to = orm [ '' % ( User . _meta . app_label , User . _meta . object_name ) ] ) ) , ( '' , self . gf ( '' ) ( default = , to = orm [ '' ] ) ) , ( '' , self . gf ( '' ) ( db_index = True , max_length = , null = True , blank = True ) ) , ( '' , self . gf ( '' ) ( db_index = True , max_length = , null = True , blank = True ) ) , ", "answer": "( '' , self . gf ( '' ) ( default = datetime . datetime . now , null = True , db_index = True ) ) ,"}, {"prompt": " from setuptools import setup from wakatime . __about__ import ( __author__ , __author_email__ , __description__ , __license__ , __title__ , __url__ , __version__ , ) packages = [ __title__ , ] setup ( name = __title__ , version = __version__ , license = __license__ , description = __description__ , long_description = open ( '' ) . read ( ) , author = __author__ , author_email = __author_email__ , url = __url__ , packages = packages , package_dir = { __title__ : __title__ } , include_package_data = True , zip_safe = False , platforms = '' , entry_points = { '' : [ '' ] , } , classifiers = ( '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , ", "answer": ") ,"}, {"prompt": " from oslo_serialization import jsonutils as json from sahara . plugins . cdh . v5_4_0 import config_helper from sahara . tests . unit import base from sahara . tests . unit . plugins . cdh import utils as ctu from sahara . utils import files as f c_h = config_helper . ConfigHelperV540 ( ) path_to_config = '' json_files = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ] class ConfigHelperTestCase ( base . SaharaTestCase ) : def test_get_ng_plugin_configs ( self ) : actual_configs = c_h . _get_ng_plugin_configs ( ) expected_configs = [ ] for json_file in json_files : expected_configs += json . loads ( f . get_file_text ( path_to_config + json_file ) ) expected_names = set ( i [ '' ] for i in expected_configs ) actual_names = set ( i . to_dict ( ) [ '' ] for i in actual_configs ) self . assertEqual ( expected_names , actual_names ) def test_get_cdh5_repo_url ( self ) : cluster = ctu . get_fake_cluster ( cluster_configs = { } ) self . assertEqual ( c_h . CDH5_REPO_URL . default_value , c_h . get_cdh5_repo_url ( cluster ) ) cluster = ctu . get_fake_cluster ( cluster_configs = { '' : { c_h . CDH5_REPO_URL . name : '' } } ) self . assertEqual ( '' , c_h . get_cdh5_repo_url ( cluster ) ) def test_get_cdh5_key_url ( self ) : cluster = ctu . get_fake_cluster ( cluster_configs = { } ) self . assertEqual ( c_h . CDH5_REPO_KEY_URL . default_value , c_h . get_cdh5_key_url ( cluster ) ) cluster = ctu . get_fake_cluster ( cluster_configs = { '' : { c_h . CDH5_REPO_KEY_URL . name : '' } } ) self . assertEqual ( '' , c_h . get_cdh5_key_url ( cluster ) ) def test_get_cm5_repo_url ( self ) : cluster = ctu . get_fake_cluster ( cluster_configs = { } ) self . assertEqual ( c_h . CM5_REPO_URL . default_value , c_h . get_cm5_repo_url ( cluster ) ) cluster = ctu . get_fake_cluster ( cluster_configs = { '' : { c_h . CM5_REPO_URL . name : '' } } ) self . assertEqual ( '' , c_h . get_cm5_repo_url ( cluster ) ) def test_get_cm5_key_url ( self ) : cluster = ctu . get_fake_cluster ( cluster_configs = { } ) self . assertEqual ( c_h . CM5_REPO_KEY_URL . default_value , c_h . get_cm5_key_url ( cluster ) ) cluster = ctu . get_fake_cluster ( cluster_configs = { '' : { c_h . CM5_REPO_KEY_URL . name : '' } } ) self . assertEqual ( '' , c_h . get_cm5_key_url ( cluster ) ) def test_is_swift_enabled ( self ) : ", "answer": "cluster = ctu . get_fake_cluster ( cluster_configs = { } )"}, {"prompt": " from datetime import datetime from django . conf import settings from rosetta . conf import settings as rosetta_settings import django import os import inspect from django . apps import AppConfig from django . apps import apps from django . utils import timezone try : from django . core . cache import caches cache = caches [ rosetta_settings . ROSETTA_CACHE_NAME ] ", "answer": "except ImportError :"}, {"prompt": " from gevent import monkey monkey . patch_all ( ) import json import logging from pyinfra . api import Inventory , Config , State from pyinfra . api . operation import add_op from pyinfra . api . operations import run_ops from pyinfra . api . ssh import connect_all from pyinfra . api . facts import get_facts from pyinfra . modules import server , files logging . basicConfig ( level = logging . WARNING ) logging . getLogger ( '' ) . setLevel ( logging . INFO ) inventory = Inventory ( ( [ '' , ( '' , { '' : True } ) , '' , '' , '' ] , { } ) , bsd = ( [ '' ] , { '' : '' } ) , centos = ( [ '' , '' ] , { } ) , ssh_user = '' , ssh_key = '' ) config = Config ( FAIL_PERCENT = , TIMEOUT = ) state = State ( inventory , config ) connect_all ( state ) add_op ( state , server . user , '' , home = '' , shell = '' , sudo = True ) add_op ( state , files . file , '' , user = '' , group = '' , mode = '' , sudo = True ) add_op ( ", "answer": "state , files . directory ,"}, {"prompt": " from socket import socket as _socket class socket ( object ) : '' def __init__ ( self , * args , ** kwargs ) : self . _ss = _socket ( * args , ** kwargs ) self . records = [ ] self . recording = False self . replaying = False def start_record ( self ) : self . recording = True self . replaying = False self . records = [ ] def start_replay ( self ) : self . recording = False self . replaying = True self . replay_records = self . records [ : ] def settimeout ( self , n ) : return self . _ss . settimeout ( n ) def connect ( self , * args , ** kwargs ) : return self . _ss . connect ( * args , ** kwargs ) def setsockopt ( self , * args ) : if not self . replaying : return self . _ss . setsockopt ( * args ) def shutdown ( self , * args ) : if not self . replaying : ", "answer": "return self . _ss . shutdown ( * args )"}, {"prompt": " import os from setuptools import setup , find_packages from tree import __version__ CURRENT_PATH = os . path . abspath ( os . path . dirname ( __file__ ) ) with open ( os . path . join ( CURRENT_PATH , '' ) ) as f : required = f . read ( ) . splitlines ( ) setup ( name = '' , version = __version__ , author = '' , author_email = '' , url = '' , ", "answer": "description = '' ,"}, {"prompt": " import warnings from scrapy . exceptions import ScrapyDeprecationWarning ", "answer": "warnings . warn ( \"\""}, {"prompt": " \"\"\"\"\"\" from __future__ import print_function import sys import os import subprocess as sp import copy import numpy as np from flopy import utils iconst = iprn = - def is_exe ( fpath ) : return os . path . isfile ( fpath ) and os . access ( fpath , os . X_OK ) def which ( program ) : fpath , fname = os . path . split ( program ) if fpath : if is_exe ( program ) : return program else : if is_exe ( program ) : return program for path in os . environ [ \"\" ] . split ( os . pathsep ) : path = path . strip ( '' ) exe_file = os . path . join ( path , program ) if is_exe ( exe_file ) : return exe_file return None class BaseModel ( object ) : \"\"\"\"\"\" def __init__ ( self , modelname = '' , namefile_ext = '' , exe_name = '' , model_ws = None , structured = True , ** kwargs ) : \"\"\"\"\"\" self . __name = modelname self . namefile_ext = namefile_ext self . namefile = self . __name + '' + self . namefile_ext self . packagelist = [ ] self . heading = '' self . exe_name = exe_name self . external_extension = '' if model_ws is None : model_ws = os . getcwd ( ) if not os . path . exists ( model_ws ) : try : os . makedirs ( model_ws ) except : print ( '' . format ( model_ws , os . getcwd ( ) ) ) model_ws = os . getcwd ( ) self . _model_ws = model_ws self . structured = structured self . pop_key_list = [ ] self . cl_params = '' xul = kwargs . pop ( \"\" , None ) yul = kwargs . pop ( \"\" , None ) rotation = kwargs . pop ( \"\" , ) proj4_str = kwargs . pop ( \"\" , \"\" ) self . start_datetime = kwargs . pop ( \"\" , \"\" ) self . _sr = utils . SpatialReference ( xul = xul , yul = yul , rotation = rotation , proj4_str = proj4_str ) self . array_free_format = True self . array_format = None ", "answer": "self . external_fnames = [ ]"}, {"prompt": " \"\"\"\"\"\" from __future__ import print_function , division , absolute_import class TargetOptions ( object ) : OPTIONS = { } def __init__ ( self ) : self . values = { } def from_dict ( self , dic ) : for k , v in dic . items ( ) : ", "answer": "try :"}, {"prompt": " \"\"\"\"\"\" module = request . controller resourcename = request . function if not settings . has_module ( module ) : raise HTTP ( , body = \"\" % module ) def s3_menu_postp ( ) : menu_selected = [ ] body_id = s3base . s3_get_last_record_id ( \"\" ) if body_id : body = s3db . dvi_body query = ( body . id == body_id ) record = db ( query ) . select ( body . id , body . pe_label , limitby = ( , ) ) . first ( ) if record : label = record . pe_label response . menu_options [ - ] [ - ] . append ( [ T ( \"\" ) % dict ( label = label ) , False , URL ( f = \"\" , vars = dict ( match = record . id ) ) ] ) menu_selected . append ( [ \"\" % ( T ( \"\" ) , label ) , False , URL ( f = \"\" , args = [ record . id ] ) ] ) person_id = s3base . s3_get_last_record_id ( \"\" ) if person_id : person = s3db . pr_person query = ( person . id == person_id ) record = db ( query ) . select ( person . id , limitby = ( , ) ) . first ( ) if record : name = s3db . pr_person_id ( ) . represent ( record . id ) menu_selected . append ( [ \"\" % ( T ( \"\" ) , name ) , False , URL ( f = \"\" , args = [ record . id ] ) ] ) if menu_selected : menu_selected = [ T ( \"\" ) , True , None , menu_selected ] response . menu_options . append ( menu_selected ) def index ( ) : \"\"\"\"\"\" try : module_name = settings . modules [ module ] . name_nice except : module_name = T ( \"\" ) btable = s3db . dvi_body itable = s3db . dvi_identification query = ( btable . deleted == False ) left = itable . on ( itable . pe_id == btable . pe_id ) body_count = btable . id . count ( ) rows = db ( query ) . select ( body_count , itable . status , left = left , groupby = itable . status ) numbers = { None : } for row in rows : numbers [ row [ itable . status ] ] = row [ body_count ] total = sum ( numbers . values ( ) ) dvi_id_status = dict ( s3db . dvi_id_status ) dvi_id_status [ None ] = T ( \"\" ) statistics = [ ] for status in dvi_id_status : count = numbers . get ( status ) or statistics . append ( ( str ( dvi_id_status [ status ] ) , count ) ) response . title = module_name return dict ( module_name = module_name , total = total , status = json . dumps ( statistics ) ) def recreq ( ) : \"\"\"\"\"\" table = s3db . dvi_recreq table . person_id . default = s3_logged_in_person ( ) def prep ( r ) : if r . interactive and not r . record : table . status . readable = False ", "answer": "table . status . writable = False"}, {"prompt": " from __future__ import ( absolute_import , division , generators , nested_scopes , print_function , unicode_literals , with_statement ) ", "answer": "from pants . base . exceptions import TaskError"}, {"prompt": " \"\"\"\"\"\" __title__ = '' __author__ = '' __license__ = '' ", "answer": "__copyright__ = '' "}, {"prompt": " import re import os from Queue import Queue try : import cPickle as pickle except ImportError : import pickle from zope . interface import implements from twisted . persisted import sob from twisted . persisted . sob import Persistent from pymon import exceptions from pymon import utils from pymon . config import cfg from pymon . interfaces import IState from pymon . utils . logger import log from pymon . utils . registry import Registry from pymon . workflow . base import Workflow from pymon . workflow . service import ServiceState , stateWorkflow initialCheckData = { '' : '' , '' : '' , '' : '' , '' : '' , '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : - , '' : - , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , } class InitialCheckData ( dict ) : '''''' def __init__ ( self ) : self . update ( initialCheckData ) class BaseState ( Persistent ) : '''''' def __init__ ( self , data = { } ) : Persistent . __init__ ( self , self , '' ) self . data = data self . filename = None def __getstate__ ( self ) : return self . __dict__ def set ( self , key , value ) : self . data [ key ] = value self . __dict__ [ key ] = value def get ( self , key ) : return self . data [ key ] def setFilename ( self , filename ) : self . filename = filename def getFilename ( self ) : return self . filename def save ( self , filename = None ) : if not filename : filename = self . filename else : self . filename = filename def restore ( self ) : if not self . filename : raise exceptions . StateRestoreError , \"\" if os . path . exists ( self . filename ) : s = sob . load ( self . filename , '' ) for key , val in s . __dict__ . items ( ) : setattr ( self , key , val ) def items ( self ) : return self . data . items ( ) class MonitorState ( BaseState ) : '''''' implements ( IState ) ", "answer": "def __init__ ( self , monitor ) :"}, {"prompt": " import logging import click from sqlalchemy . exc import IntegrityError from chanjo . load import link as link_mod from chanjo import load from chanjo . parse import bed from chanjo . store import Store from chanjo . utils import validate_stdin from chanjo . store . models import BASE from chanjo . store . txmodels import BASE as TXBASE logger = logging . getLogger ( __name__ ) @ click . command ( ) @ click . option ( '' , '' , is_flag = True , help = '' ) @ click . argument ( '' , callback = validate_stdin , type = click . File ( encoding = '' ) , default = '' , required = False ) @ click . pass_context def link ( context , transcripts , bed_stream ) : \"\"\"\"\"\" only_tx = transcripts or context . obj . get ( '' ) or False base = TXBASE if only_tx else BASE chanjo_db = Store ( uri = context . obj [ '' ] , base = base ) try : if only_tx : result = load . link_transcripts ( bed_stream ) with click . progressbar ( result . models , length = result . count , ", "answer": "label = '' ) as bar :"}, {"prompt": " from django . conf . urls . defaults import * ", "answer": "urlpatterns = patterns ( '' ,"}, {"prompt": " \"\"\"\"\"\" import logging import sys import threading import time from google . appengine . api import memcache from google . appengine . ext import webapp from ndb import context , model , tasklets @ tasklets . tasklet def fibonacci ( n ) : \"\"\"\"\"\" if n <= : raise tasklets . Return ( n ) a , b = yield fibonacci ( n - ) , fibonacci ( n - ) raise tasklets . Return ( a + b ) class FibonacciMemo ( model . Model ) : arg = model . IntegerProperty ( ) value = model . IntegerProperty ( ) @ tasklets . tasklet def memoizing_fibonacci ( n ) : \"\"\"\"\"\" if n <= : raise tasklets . Return ( n ) key = model . Key ( FibonacciMemo , str ( n ) ) memo = yield key . get_async ( ndb_should_cache = False ) if memo is not None : assert memo . arg == n logging . info ( '' , n , memo . value ) raise tasklets . Return ( memo . value ) logging . info ( '' , n ) a = yield memoizing_fibonacci ( n - ) b = yield memoizing_fibonacci ( n - ) ans = a + b memo = FibonacciMemo ( key = key , arg = n , value = ans ) logging . info ( '' , n , memo . value ) yield memo . put_async ( ndb_should_cache = False ) raise tasklets . Return ( ans ) TRUE_VALUES = frozenset ( [ '' , '' , '' , '' , '' , '' ] ) class FiboHandler ( webapp . RequestHandler ) : @ context . toplevel def get ( self ) : num = try : num = int ( self . request . get ( '' ) ) except Exception : pass if self . request . get ( '' ) in TRUE_VALUES : logging . info ( '' ) yield model . delete_multi_async ( x . key for x in FibonacciMemo . query ( ) ) t0 = time . time ( ) if self . request . get ( '' ) in TRUE_VALUES : memo_type = '' ans = yield memoizing_fibonacci ( num ) else : memo_type = '' ans = yield fibonacci ( num ) t1 = time . time ( ) self . response . out . write ( '' % ( memo_type , num , ans , t1 - t0 ) ) urls = [ ( '' , FiboHandler ) , ] ", "answer": "app = webapp . WSGIApplication ( urls ) "}, {"prompt": " \"\"\"\"\"\" from django . contrib . gis . db import models from django . contrib . gis . db . models . fields import GeometryField from django . contrib . gis . db . backends . base import SpatialRefSysMixin class GeometryColumns ( models . Model ) : \"\" table_name = models . CharField ( max_length = ) column_name = models . CharField ( max_length = ) srid = models . IntegerField ( primary_key = True ) class Meta : db_table = '' managed = False @ classmethod def table_name_col ( cls ) : \"\"\"\"\"\" ", "answer": "return ''"}, {"prompt": " import unittest import JustReleaseNotes . artifacters from JustReleaseNotes . artifacters import factory class factory_Test ( unittest . TestCase ) : def test_factoryRetrievesArtifactory ( self ) : self . assertIsNotNone ( JustReleaseNotes . artifacters . factory . create ( { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : { \"\" : { \"\" : \"\" } } } ) ) def test_factoryRetrievesGitHubReleases ( self ) : self . assertIsNotNone ( JustReleaseNotes . artifacters . factory . create ( { \"\" : \"\" , \"\" : \"\" , ", "answer": "\"\" : \"\" ,"}, {"prompt": " from __future__ import unicode_literals import re from django . core . validators import MaxValueValidator , RegexValidator from django . db import models from django . test import TestCase from rest_framework import generics , serializers , status from rest_framework . test import APIRequestFactory factory = APIRequestFactory ( ) class ValidationModel ( models . Model ) : blank_validated_field = models . CharField ( max_length = ) class ValidationModelSerializer ( serializers . ModelSerializer ) : class Meta : model = ValidationModel fields = ( '' , ) read_only_fields = ( '' , ) class UpdateValidationModel ( generics . RetrieveUpdateDestroyAPIView ) : queryset = ValidationModel . objects . all ( ) serializer_class = ValidationModelSerializer class ShouldValidateModel ( models . Model ) : should_validate_field = models . CharField ( max_length = ) class ShouldValidateModelSerializer ( serializers . ModelSerializer ) : renamed = serializers . CharField ( source = '' , required = False ) def validate_renamed ( self , value ) : if len ( value ) < : raise serializers . ValidationError ( '' ) return value class Meta : model = ShouldValidateModel fields = ( '' , ) class TestNestedValidationError ( TestCase ) : def test_nested_validation_error_detail ( self ) : \"\"\"\"\"\" e = serializers . ValidationError ( { '' : { '' : [ '' ] , } } ) self . assertEqual ( serializers . get_validation_error_detail ( e ) , { '' : { '' : [ '' ] , } } ) class TestPreSaveValidationExclusionsSerializer ( TestCase ) : def test_renamed_fields_are_model_validated ( self ) : \"\"\"\"\"\" serializer = ShouldValidateModelSerializer ( data = { '' : '' } ) self . assertEqual ( serializer . is_valid ( ) , False ) self . assertIn ( '' , serializer . errors ) self . assertNotIn ( '' , serializer . errors ) class TestCustomValidationMethods ( TestCase ) : def test_custom_validation_method_is_executed ( self ) : serializer = ShouldValidateModelSerializer ( data = { '' : '' } ) self . assertFalse ( serializer . is_valid ( ) ) self . assertIn ( '' , serializer . errors ) def test_custom_validation_method_passing ( self ) : serializer = ShouldValidateModelSerializer ( data = { '' : '' } ) self . assertTrue ( serializer . is_valid ( ) ) class ValidationSerializer ( serializers . Serializer ) : foo = serializers . CharField ( ) def validate_foo ( self , attrs , source ) : raise serializers . ValidationError ( \"\" ) def validate ( self , attrs ) : raise serializers . ValidationError ( \"\" ) class TestAvoidValidation ( TestCase ) : \"\"\"\"\"\" def test_serializer_errors_has_only_invalid_data_error ( self ) : serializer = ValidationSerializer ( data = '' ) self . assertFalse ( serializer . is_valid ( ) ) self . assertDictEqual ( serializer . errors , { '' : [ '' % type ( '' ) . __name__ ] } ) class ValidationMaxValueValidatorModel ( models . Model ) : number_value = models . PositiveIntegerField ( validators = [ MaxValueValidator ( ) ] ) class ValidationMaxValueValidatorModelSerializer ( serializers . ModelSerializer ) : class Meta : model = ValidationMaxValueValidatorModel class UpdateMaxValueValidationModel ( generics . RetrieveUpdateDestroyAPIView ) : queryset = ValidationMaxValueValidatorModel . objects . all ( ) serializer_class = ValidationMaxValueValidatorModelSerializer class TestMaxValueValidatorValidation ( TestCase ) : def test_max_value_validation_serializer_success ( self ) : serializer = ValidationMaxValueValidatorModelSerializer ( data = { '' : } ) self . assertTrue ( serializer . is_valid ( ) ) def test_max_value_validation_serializer_fails ( self ) : serializer = ValidationMaxValueValidatorModelSerializer ( data = { '' : } ) self . assertFalse ( serializer . is_valid ( ) ) self . assertDictEqual ( { '' : [ '' ] } , serializer . errors ) def test_max_value_validation_success ( self ) : obj = ValidationMaxValueValidatorModel . objects . create ( number_value = ) request = factory . patch ( '' . format ( obj . pk ) , { '' : } , format = '' ) view = UpdateMaxValueValidationModel ( ) . as_view ( ) response = view ( request , pk = obj . pk ) . render ( ) self . assertEqual ( response . status_code , status . HTTP_200_OK ) def test_max_value_validation_fail ( self ) : obj = ValidationMaxValueValidatorModel . objects . create ( number_value = ) request = factory . patch ( '' . format ( obj . pk ) , { '' : } , format = '' ) view = UpdateMaxValueValidationModel ( ) . as_view ( ) response = view ( request , pk = obj . pk ) . render ( ) self . assertEqual ( response . content , b'' ) self . assertEqual ( response . status_code , status . HTTP_400_BAD_REQUEST ) class TestChoiceFieldChoicesValidate ( TestCase ) : CHOICES = [ ( , '' ) , ( , '' ) , ( , '' ) , ] SINGLE_CHOICES = [ , , ] CHOICES_NESTED = [ ( '' , ( ( , '' ) , ( , '' ) , ( , '' ) , ) ) , ( , '' ) , ] MIXED_CHOICES = [ ( '' , ( ( , '' ) , ( , '' ) , ) ) , , ( , '' ) , ] def test_choices ( self ) : \"\"\"\"\"\" f = serializers . ChoiceField ( choices = self . CHOICES ) value = self . CHOICES [ ] [ ] try : f . to_internal_value ( value ) except serializers . ValidationError : self . fail ( \"\" % str ( value ) ) def test_single_choices ( self ) : \"\"\"\"\"\" f = serializers . ChoiceField ( choices = self . SINGLE_CHOICES ) value = self . SINGLE_CHOICES [ ] try : f . to_internal_value ( value ) except serializers . ValidationError : self . fail ( \"\" % str ( value ) ) def test_nested_choices ( self ) : \"\"\"\"\"\" f = serializers . ChoiceField ( choices = self . CHOICES_NESTED ) value = self . CHOICES_NESTED [ ] [ ] [ ] [ ] try : f . to_internal_value ( value ) except serializers . ValidationError : self . fail ( \"\" % str ( value ) ) def test_mixed_choices ( self ) : \"\"\"\"\"\" f = serializers . ChoiceField ( choices = self . MIXED_CHOICES ) value = self . MIXED_CHOICES [ ] try : f . to_internal_value ( value ) except serializers . ValidationError : self . fail ( \"\" % str ( value ) ) class RegexSerializer ( serializers . Serializer ) : pin = serializers . CharField ( validators = [ RegexValidator ( regex = re . compile ( '' ) , message = '' ) ] ) expected_repr = \"\"\"\"\"\" . strip ( ) class TestRegexSerializer ( TestCase ) : def test_regex_repr ( self ) : serializer_repr = repr ( RegexSerializer ( ) ) ", "answer": "assert serializer_repr == expected_repr "}, {"prompt": " import difflib import os from oslo_utils import encodeutils import rally ", "answer": "from rally . cli import cliutils"}, {"prompt": " \"\"\"\"\"\" from __future__ import unicode_literals from scrapi . base import OAIHarvester class ArxivHarvester ( OAIHarvester ) : short_name = '' long_name = '' url = '' timeout = base_url = '' property_list = [ '' , '' , '' , ", "answer": "'' , '' , ''"}, {"prompt": " '''''' from webilder import AboutDialog from webilder import config_dialog from webilder import DownloadDialog from webilder import infofile from webilder import wbz_handler from webilder import WebilderFullscreen from webilder . thumbs import ThumbLoader from webilder . uitricks import UITricks , open_browser import sys , os , time , glob , gc import optparse import gtk , gobject import pkg_resources try : import gnomevfs except ImportError : gnomevfs = None from webilder . config import config , set_wallpaper , reload_config IV_TEXT_COLUMN = IV_PIXBUF_COLUMN = IV_DATA_COLUMN = TV_TEXT_COLUMN = TV_PATH_COLUMN = TV_KIND_COLUMN = TV_KIND_DIR = \"\" TV_KIND_RECENT = \"\" EMPTY_PICTURE = gtk . gdk . pixbuf_new_from_file_at_size ( pkg_resources . resource_filename ( __name__ , '' ) , , ) def connect_to_menu ( wtree , item , callback ) : \"\"\"\"\"\" wtree . get_widget ( item ) . connect ( '' , callback ) class WebilderDesktopWindow ( UITricks ) : \"\"\"\"\"\" def __init__ ( self ) : UITricks . __init__ ( self , '' , '' ) self . sort_combo . set_active ( ) renderer = gtk . CellRendererText ( ) self . tree . append_column ( column = gtk . TreeViewColumn ( \"\" , renderer , markup = ) ) self . tree . columns_autosize ( ) self . load_collection_tree ( config . get ( '' ) ) self . iconview . set_pixbuf_column ( IV_PIXBUF_COLUMN ) self . iconview . set_markup_column ( IV_TEXT_COLUMN ) self . on_iconview_handle_selection_changed ( self . iconview ) self . collection_monitor = dict ( monitor = None , dir = None ) self . image_popup = ImagePopup ( self ) self . download_dialog = None if gnomevfs : self . tree_monitor = gnomevfs . monitor_add ( config . get ( '' ) , gnomevfs . MONITOR_DIRECTORY , self . collection_tree_changed ) self . restore_window_state ( ) self . top_widget . show_all ( ) self . hand_cursor = gtk . gdk . Cursor ( gtk . gdk . HAND2 ) def load_collection_tree ( self , root ) : \"\"\"\"\"\" model = gtk . TreeStore ( gobject . TYPE_STRING , gobject . TYPE_STRING , gobject . TYPE_STRING ) model . append ( None , ( _ ( '' ) , '' , TV_KIND_RECENT ) ) dirlist = os . listdir ( root ) for entry in sorted ( dirlist ) : fullpath = os . path . join ( root , entry ) entry = html_escape ( entry ) if os . path . isdir ( fullpath ) : model . append ( None , ( entry , fullpath , TV_KIND_DIR ) ) self . tree . set_model ( model ) def on_tree_handle_selection_changed ( self , tree_selection ) : \"\"\"\"\"\" if not tree_selection : return model , selection = tree_selection . get_selected_rows ( ) for path in selection : iterator = model . get_iter ( path ) rootdir = self . tree . get_model ( ) . get_value ( iterator , TV_PATH_COLUMN ) kind = self . tree . get_model ( ) . get_value ( iterator , TV_KIND_COLUMN ) if kind == TV_KIND_DIR : self . load_directory_collection ( rootdir ) else : self . load_recent_photos ( ) def load_directory_collection ( self , dirname ) : \"\"\"\"\"\" images = glob . glob ( os . path . join ( dirname , '' ) ) png_images = glob . glob ( os . path . join ( dirname , '' ) ) images . extend ( png_images ) self . load_collection ( images , monitor_dir = dirname ) def load_recent_photos ( self ) : \"\"\"\"\"\" images = glob . glob ( os . path . join ( config . get ( '' ) , '' , '' ) ) png_images = glob . glob ( os . path . join ( config . get ( '' ) , '' , '' ) ) images . extend ( png_images ) recent_time = time . time ( ) - * images = [ ( os . path . getmtime ( fname ) , fname ) for fname in images ] images = [ pair for pair in images if pair [ ] > recent_time ] images = [ pair [ ] for pair in sorted ( images , reverse = True ) ] self . load_collection ( images ) def load_collection ( self , images , monitor_dir = None ) : \"\"\"\"\"\" model = gtk . ListStore ( gobject . TYPE_STRING , gtk . gdk . Pixbuf , gobject . TYPE_PYOBJECT ) image_list = [ ] for image in images : dirname , filename = os . path . split ( image ) basename , ext = os . path . splitext ( filename ) thumb = os . path . join ( dirname , '' , basename + '' + ext ) info_file = os . path . join ( dirname , basename ) + '' inf = infofile . parse_info_file ( info_file ) title = inf . get ( '' , basename ) album = inf . get ( '' , dirname ) credit = inf . get ( '' , _ ( '' ) ) tags = inf . get ( '' , '' ) title = html_escape ( title ) album = html_escape ( album ) credit = html_escape ( credit ) tags = html_escape ( tags ) data = dict ( title = title , filename = image , thumb = thumb , inf = inf , info_file = info_file , album = album , tags = tags , file_time = os . path . getctime ( image ) , credit = credit ) if len ( title ) > : title = title [ : ] + '' if <= time . time ( ) - os . path . getmtime ( image ) < * : title = _ ( '' ) % title position = model . append ( ( title , EMPTY_PICTURE , data ) ) image_list . append ( dict ( position = position , data = data ) ) old_model = self . iconview . get_model ( ) if old_model is not None : old_model . clear ( ) self . sort_photos ( model ) self . iconview . set_model ( model ) gobject . idle_add ( ThumbLoader ( self . iconview , model , reversed ( image_list ) ) ) self . on_iconview_handle_selection_changed ( self . iconview ) if gnomevfs : if self . collection_monitor [ '' ] is not None : gobject . idle_add ( gnomevfs . monitor_cancel , self . collection_monitor [ '' ] ) self . collection_monitor = dict ( monitor = None , dir = None ) if monitor_dir : self . collection_monitor [ '' ] = monitor_dir self . collection_monitor [ '' ] = gnomevfs . monitor_add ( monitor_dir , gnomevfs . MONITOR_DIRECTORY , self . collection_directory_changed ) gc . collect ( ) def on_set_as_wallpaper_handle_activate ( self , _menu_item ) : \"\"\"\"\"\" selected = self . iconview . get_selected_items ( ) if selected : selected = selected [ - ] if selected : self . on_iconview_handle_item_activated ( self . iconview , selected ) def on_iconview_handle_item_activated ( self , icon_view , path ) : \"\"\"\"\"\" iterator = icon_view . get_model ( ) . get_iter ( path ) data = icon_view . get_model ( ) . get_value ( iterator , IV_DATA_COLUMN ) set_wallpaper ( data [ '' ] ) gc . collect ( ) def on_view_fullscreen_handle_activate ( self , _menu_item ) : \"\"\"\"\"\" selected = self . iconview . get_selected_items ( ) if selected : selected = selected [ - ] path = selected iterator = self . iconview . get_model ( ) . get_iter ( path ) data = self . iconview . get_model ( ) . get_value ( iterator , IV_DATA_COLUMN ) WebilderFullscreen . FullscreenViewer ( self . top_widget , data ) . run ( ) gc . collect ( ) def on_download_photos_handle_activate ( self , _menu_item ) : \"\"\"\"\"\" def remove_reference ( * _args ) : \"\"\"\"\"\" self . download_dialog = None if not self . download_dialog : self . download_dialog = DownloadDialog . DownloadProgressDialog ( config ) self . download_dialog . top_widget . connect ( '' , remove_reference ) self . download_dialog . show ( ) else : self . download_dialog . top_widget . present ( ) def on_iconview_handle_selection_changed ( self , icon_view ) : \"\"\"\"\"\" selection = icon_view . get_selected_items ( ) if len ( selection ) > : selection = selection [ - ] title = album = credit = tags = \"\" if selection : iterator = icon_view . get_model ( ) . get_iter ( selection ) data = icon_view . get_model ( ) . get_value ( iterator , IV_DATA_COLUMN ) title = \"\" % data [ '' ] album = data [ '' ] credit = data [ '' ] tags = data [ '' ] self . photo_title . set_markup ( title ) self . photo_album . set_markup ( album ) self . photo_credit . set_markup ( credit ) self . photo_tags . set_markup ( tags ) def collection_directory_changed ( self , * _args ) : \"\"\"\"\"\" self . on_tree_handle_selection_changed ( self . tree . get_selection ( ) ) def on_preferences_handle_activate ( self , _menu_item ) : \"\"\"\"\"\" configure ( ) def on_iconview_handle_button_press_event ( self , icon_view , event ) : \"\"\"\"\"\" if event . button == : xpos , ypos = [ int ( event . x ) , int ( event . y ) ] path = icon_view . get_path_at_pos ( xpos , ypos ) if not path : return if not ( event . state & gtk . gdk . CONTROL_MASK ) : icon_view . unselect_all ( ) icon_view . select_path ( path ) self . image_popup . top_widget . popup ( None , None , None , event . button , event . time ) return False def collection_tree_changed ( self , * _args ) : \"\"\"\"\"\" self . load_collection_tree ( config . get ( '' ) ) def on_quit_handle_activate ( self , _event ) : \"\"\"\"\"\" self . on_WebilderDesktopWindow_handle_delete_event ( None , None ) def on_about_handle_activate ( self , _event ) : \"\"\"\"\"\" AboutDialog . show_about_dialog ( '' ) def on_WebilderDesktopWindow_handle_delete_event ( self , _widget , _event ) : \"\"\"\"\"\" self . save_window_state ( ) self . destroy ( ) return False def save_window_state ( self ) : \"\"\"\"\"\" top = self . top_widget layout = { '' : top . get_position ( ) , '' : top . get_size ( ) , '' : self . hpaned . get_position ( ) , '' : self . photo_info_expander . get_expanded ( ) , } config . set ( '' , layout ) config . save_config ( ) def restore_window_state ( self ) : \"\"\"\"\"\" d = config . get ( '' ) if d . has_key ( '' ) : self . top_widget . move ( * d [ '' ] ) if d . has_key ( '' ) : self . top_widget . resize ( * d [ '' ] ) if d . has_key ( '' ) : self . hpaned . set_position ( d [ '' ] ) if d . has_key ( '' ) : self . photo_info_expander . set_expanded ( d [ '' ] ) def on_file_webshots_import_handle_activate ( self , _event ) : \"\"\"\"\"\" dlg = gtk . FileChooserDialog ( _ ( '' ) , None , action = gtk . FILE_CHOOSER_ACTION_OPEN , buttons = ( _ ( \"\" ) , gtk . RESPONSE_OK , _ ( \"\" ) , gtk . RESPONSE_CANCEL ) ) dlg . set_select_multiple ( True ) try : response = dlg . run ( ) if response == gtk . RESPONSE_OK : files = dlg . get_filenames ( ) else : files = [ ] finally : dlg . destroy ( ) import_files ( files ) def on_donate_handle_activate ( self , _widget ) : \"\"\"\"\"\" donate_dialog = DonateDialog ( ) donate_dialog . run ( ) donate_dialog . destroy ( ) def on_photo_properties_handle_activate ( self , _event ) : \"\"\"\"\"\" selected = self . iconview . get_selected_items ( ) if not selected : return win = UITricks ( '' , '' ) selected = selected [ - ] path = selected iterator = self . iconview . get_model ( ) . get_iter ( path ) data = self . iconview . get_model ( ) . get_value ( iterator , IV_DATA_COLUMN ) win . title . set_markup ( '' % data [ '' ] ) win . album . set_markup ( data [ '' ] ) win . file . set_text ( data [ '' ] ) win . tags . set_text ( data [ '' ] ) win . size . set_text ( _ ( '' ) % ( os . path . getsize ( data [ '' ] ) / ) ) win . date . set_text ( time . strftime ( '' , time . localtime ( os . path . getctime ( data [ '' ] ) ) ) ) win . url . set_text ( data [ '' ] . get ( '' , '' ) ) win . closebutton . connect ( '' , lambda * args : win . destroy ( ) ) win . show ( ) def sort_photos ( self , model ) : \"\"\"\"\"\" if model is None : return def sort_by_date ( data1 , data2 ) : \"\"\"\"\"\" return - cmp ( data1 [ '' ] , data2 [ '' ] ) def sort_by_title ( data1 , data2 ) : \"\"\"\"\"\" return cmp ( data1 [ '' ] , data2 [ '' ] ) sort_func = { : sort_by_title , : sort_by_date } [ self . sort_combo . get_active ( ) ] model . set_default_sort_func ( lambda m , iter1 , iter2 : ", "answer": "sort_func ("}, {"prompt": " \"\"\"\"\"\" from __future__ import print_function , division _doctest_depends_on = { '' : ( '' , '' , '' ) , '' : ( '' , ) } import sys import os import shutil import tempfile from subprocess import STDOUT , CalledProcessError , check_output from string import Template from sympy . core . cache import cacheit from sympy . core . compatibility import range , iterable from sympy . core . function import Lambda from sympy . core . relational import Eq from sympy . core . symbol import Dummy , Symbol from sympy . tensor . indexed import Idx , IndexedBase from sympy . utilities . codegen import ( make_routine , get_code_generator , OutputArgument , InOutArgument , InputArgument , CodeGenArgumentListError , Result , ResultBase , CCodeGen ) from sympy . utilities . lambdify import implemented_function from sympy . utilities . decorator import doctest_depends_on class CodeWrapError ( Exception ) : pass class CodeWrapper ( object ) : \"\"\"\"\"\" _filename = \"\" _module_basename = \"\" _module_counter = @ property def filename ( self ) : return \"\" % ( self . _filename , CodeWrapper . _module_counter ) @ property def module_name ( self ) : return \"\" % ( self . _module_basename , CodeWrapper . _module_counter ) def __init__ ( self , generator , filepath = None , flags = [ ] , verbose = False ) : \"\"\"\"\"\" self . generator = generator self . filepath = filepath self . flags = flags self . quiet = not verbose @ property def include_header ( self ) : return bool ( self . filepath ) @ property def include_empty ( self ) : return bool ( self . filepath ) def _generate_code ( self , main_routine , routines ) : routines . append ( main_routine ) self . generator . write ( routines , self . filename , True , self . include_header , self . include_empty ) def wrap_code ( self , routine , helpers = [ ] ) : workdir = self . filepath or tempfile . mkdtemp ( \"\" ) if not os . access ( workdir , os . F_OK ) : os . mkdir ( workdir ) oldwork = os . getcwd ( ) os . chdir ( workdir ) try : sys . path . append ( workdir ) self . _generate_code ( routine , helpers ) self . _prepare_files ( routine ) self . _process_files ( routine ) mod = __import__ ( self . module_name ) finally : sys . path . remove ( workdir ) CodeWrapper . _module_counter += os . chdir ( oldwork ) if not self . filepath : try : shutil . rmtree ( workdir ) except OSError : pass return self . _get_wrapped_function ( mod , routine . name ) def _process_files ( self , routine ) : command = self . command command . extend ( self . flags ) try : retoutput = check_output ( command , stderr = STDOUT ) except CalledProcessError as e : raise CodeWrapError ( \"\" % ( \"\" . join ( command ) , e . output . decode ( ) ) ) if not self . quiet : print ( retoutput ) class DummyWrapper ( CodeWrapper ) : \"\"\"\"\"\" template = \"\"\"\"\"\" def _prepare_files ( self , routine ) : return def _generate_code ( self , routine , helpers ) : with open ( '' % self . module_name , '' ) as f : printed = \"\" . join ( [ str ( res . expr ) for res in routine . result_variables ] ) args = filter ( lambda x : not isinstance ( x , OutputArgument ) , routine . arguments ) retvals = [ ] for val in routine . result_variables : if isinstance ( val , Result ) : retvals . append ( '' ) else : retvals . append ( val . result_var ) print ( DummyWrapper . template % { '' : routine . name , '' : printed , '' : \"\" . join ( [ str ( a . name ) for a in args ] ) , '' : \"\" . join ( [ str ( val ) for val in retvals ] ) } , end = \"\" , file = f ) def _process_files ( self , routine ) : return @ classmethod def _get_wrapped_function ( cls , mod , name ) : return getattr ( mod , name ) class CythonCodeWrapper ( CodeWrapper ) : \"\"\"\"\"\" setup_template = ( \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" ", "answer": "\"\""}, {"prompt": " \"\"\"\"\"\" from . . phonemetadata import NumberFormat , PhoneNumberDesc , PhoneMetadata PHONE_METADATA_NO = PhoneMetadata ( id = '' , country_code = , international_prefix = '' , general_desc = PhoneNumberDesc ( national_number_pattern = '' , possible_number_pattern = '' ) , fixed_line = PhoneNumberDesc ( national_number_pattern = '' , possible_number_pattern = '' , example_number = '' ) , mobile = PhoneNumberDesc ( national_number_pattern = '' , possible_number_pattern = '' , example_number = '' ) , toll_free = PhoneNumberDesc ( national_number_pattern = '' , possible_number_pattern = '' , example_number = '' ) , premium_rate = PhoneNumberDesc ( national_number_pattern = '' , possible_number_pattern = '' , example_number = '' ) , shared_cost = PhoneNumberDesc ( national_number_pattern = '' , possible_number_pattern = '' , example_number = '' ) , personal_number = PhoneNumberDesc ( national_number_pattern = '' , possible_number_pattern = '' , example_number = '' ) , voip = PhoneNumberDesc ( national_number_pattern = '' , possible_number_pattern = '' , example_number = '' ) , pager = PhoneNumberDesc ( national_number_pattern = '' , possible_number_pattern = '' ) , uan = PhoneNumberDesc ( national_number_pattern = '' , possible_number_pattern = '' , example_number = '' ) , emergency = PhoneNumberDesc ( national_number_pattern = '' , possible_number_pattern = '' , example_number = '' ) , voicemail = PhoneNumberDesc ( national_number_pattern = '' , possible_number_pattern = '' , example_number = '' ) , no_international_dialling = PhoneNumberDesc ( national_number_pattern = '' , possible_number_pattern = '' ) , ", "answer": "number_format = [ NumberFormat ( pattern = '' , format = u'' , leading_digits_pattern = [ '' ] ) ,"}, {"prompt": " from __future__ import absolute_import ", "answer": "import integration"}, {"prompt": " from __future__ import print_function , unicode_literals import os from alembic . script import ScriptDirectory from alembic . config import Config from alembic . migration import MigrationContext from alembic import command from sqlalchemy import create_engine REGULAR_ALEMBIC_PATH = os . path . join ( os . path . abspath ( os . path . dirname ( __file__ ) ) , '' ) SCHEDULING_ALEMBIC_PATH = os . path . join ( os . path . abspath ( os . path . dirname ( __file__ ) ) , '' ) DEBUG = False class DbUpgrader ( object ) : def __init__ ( self , regular_url , scheduling_url ) : self . regular_upgrader = DbRegularUpgrader ( regular_url ) if scheduling_url is not None : self . scheduling_upgrader = DbSchedulingUpgrader ( scheduling_url ) else : self . scheduling_upgrader = DbNullUpgrader ( ) @ property def regular_head ( self ) : return self . regular_upgrader . head @ property def scheduling_head ( self ) : return self . scheduling_upgrader . head def check_updated ( self ) : return self . regular_upgrader . check ( ) and self . scheduling_upgrader . check ( ) def upgrade ( self ) : self . regular_upgrader . upgrade ( ) self . scheduling_upgrader . upgrade ( ) class DbNullUpgrader ( object ) : @ property def head ( self ) : return None def check ( self ) : return True def upgrade ( self ) : pass class DbParticularUpgrader ( object ) : alembic_path = None def __init__ ( self , url ) : if url . startswith ( '' ) : try : import MySQLdb assert MySQLdb is not None except ImportError : import pymysql_sa pymysql_sa . make_default_mysql_dialect ( ) self . url = url self . config = Config ( os . path . join ( self . alembic_path , \"\" ) ) self . config . set_main_option ( \"\" , self . alembic_path ) ", "answer": "self . config . set_main_option ( \"\" , self . url )"}, {"prompt": " class ConfigError ( Exception ) : pass class NotLoggedInError ( Exception ) : pass class ObjectNotFoundError ( Exception ) : ", "answer": "pass"}, {"prompt": " from django . dispatch import receiver from image_diet . diet import squeeze try : from easy_thumbnails . signals import saved_file , thumbnail_created @ receiver ( saved_file ) def optimize_file ( sender , fieldfile , ** kwargs ) : squeeze ( fieldfile . path ) @ receiver ( thumbnail_created ) def optimize_thumbnail ( sender , ** kwargs ) : squeeze ( sender . path ) ", "answer": "except ImportError :"}, {"prompt": " from os . path import join from twisted . application . internet import TCPServer from twisted . python . log import NullFile from twisted . python . util import sibpath from twisted . web import server , static from smartanthill . dashboard . api import REST from smartanthill . log import Logger from smartanthill . service import SAMultiService class DashboardSite ( server . Site ) : def _openLogFile ( self , path ) : log = Logger ( \"\" ) def wrapper ( msg ) : log . debug ( msg . strip ( ) ) nf = NullFile ( ) nf . write = wrapper return nf class DashboardService ( SAMultiService ) : def __init__ ( self , name , options ) : SAMultiService . __init__ ( self , name , options ) def startService ( self ) : root = static . File ( sibpath ( __file__ , join ( \"\" , \"\" ) ) ) root . putChild ( \"\" , REST ( ) ) TCPServer ( self . options [ '' ] , ", "answer": "DashboardSite ( root , logPath = \"\" ) ) . setServiceParent ( self )"}, {"prompt": " \"\"\"\"\"\" LOOPS = class G ( object ) : pass g = G ( ) import sys from time import clock __version__ = \"\" [ Ident1 , Ident2 , Ident3 , Ident4 , Ident5 ] = range ( , ) class Record ( object ) : def __init__ ( self , PtrComp = None , Discr = , EnumComp = , IntComp = , StringComp = \"\" ) : self . PtrComp = PtrComp self . Discr = Discr self . EnumComp = EnumComp self . IntComp = IntComp self . StringComp = StringComp def copy ( self ) : return Record ( self . PtrComp , self . Discr , self . EnumComp , self . IntComp , self . StringComp ) TRUE = FALSE = def main ( loops = LOOPS ) : benchtime , stones = pystones ( abs ( loops ) ) if loops >= : print \"\" % ( __version__ , loops , benchtime ) print \"\" % stones def pystones ( loops = LOOPS ) : return Proc0 ( loops ) g . IntGlob = g . BoolGlob = FALSE g . Char1Glob = '' g . Char2Glob = '' g . Array1Glob = [ ] * g . Array2Glob = map ( lambda x : x [ : ] , [ g . Array1Glob ] * ) g . PtrGlb = None g . PtrGlbNext = None def Proc0 ( loops = LOOPS ) : starttime = clock ( ) i = while i < loops : i += nulltime = clock ( ) - starttime g . PtrGlbNext = Record ( ) g . PtrGlb = Record ( ) g . PtrGlb . PtrComp = g . PtrGlbNext g . PtrGlb . Discr = Ident1 g . PtrGlb . EnumComp = Ident3 g . PtrGlb . IntComp = g . PtrGlb . StringComp = \"\" String1Loc = \"\" g . Array2Glob [ ] [ ] = EnumLoc = None starttime = clock ( ) i = while i < loops : Proc5 ( ) Proc4 ( ) IntLoc1 = IntLoc2 = String2Loc = \"\" EnumLoc = Ident2 g . BoolGlob = not Func2 ( String1Loc , String2Loc ) while IntLoc1 < IntLoc2 : IntLoc3 = * IntLoc1 - IntLoc2 IntLoc3 = Proc7 ( IntLoc1 , IntLoc2 ) IntLoc1 = IntLoc1 + Proc8 ( g . Array1Glob , g . Array2Glob , IntLoc1 , IntLoc3 ) g . PtrGlb = Proc1 ( g . PtrGlb ) CharIndex = '' while CharIndex <= g . Char2Glob : if EnumLoc == Func1 ( CharIndex , '' ) : EnumLoc = Proc6 ( Ident1 ) CharIndex = chr ( ord ( CharIndex ) + ) IntLoc3 = IntLoc2 * IntLoc1 IntLoc2 = IntLoc3 / IntLoc1 IntLoc2 = * ( IntLoc3 - IntLoc2 ) - IntLoc1 IntLoc1 = Proc2 ( IntLoc1 ) i += benchtime = clock ( ) - starttime - nulltime if benchtime < : benchtime = return benchtime , ( loops / benchtime ) def Proc1 ( PtrParIn ) : PtrParIn . PtrComp = NextRecord = g . PtrGlb . copy ( ) PtrParIn . IntComp = NextRecord . IntComp = PtrParIn . IntComp NextRecord . PtrComp = PtrParIn . PtrComp NextRecord . PtrComp = Proc3 ( NextRecord . PtrComp ) if NextRecord . Discr == Ident1 : NextRecord . IntComp = NextRecord . EnumComp = Proc6 ( PtrParIn . EnumComp ) NextRecord . PtrComp = g . PtrGlb . PtrComp NextRecord . IntComp = Proc7 ( NextRecord . IntComp , ) else : PtrParIn = NextRecord . copy ( ) NextRecord . PtrComp = None return PtrParIn def Proc2 ( IntParIO ) : IntLoc = IntParIO + EnumLoc = None while : if g . Char1Glob == '' : IntLoc = IntLoc - IntParIO = IntLoc - g . IntGlob EnumLoc = Ident1 if EnumLoc == Ident1 : break return IntParIO def Proc3 ( PtrParOut ) : if g . PtrGlb is not None : PtrParOut = g . PtrGlb . PtrComp else : g . IntGlob = g . PtrGlb . IntComp = Proc7 ( , g . IntGlob ) return PtrParOut def Proc4 ( ) : BoolLoc = g . Char1Glob == '' BoolLoc = BoolLoc or g . BoolGlob g . Char2Glob = '' def Proc5 ( ) : g . Char1Glob = '' g . BoolGlob = FALSE def Proc6 ( EnumParIn ) : EnumParOut = EnumParIn if not Func3 ( EnumParIn ) : EnumParOut = Ident4 if EnumParIn == Ident1 : EnumParOut = Ident1 elif EnumParIn == Ident2 : if g . IntGlob > : EnumParOut = Ident1 else : EnumParOut = Ident4 elif EnumParIn == Ident3 : EnumParOut = Ident2 elif EnumParIn == Ident4 : pass elif EnumParIn == Ident5 : EnumParOut = Ident3 return EnumParOut def Proc7 ( IntParI1 , IntParI2 ) : IntLoc = IntParI1 + IntParOut = IntParI2 + IntLoc return IntParOut def Proc8 ( Array1Par , Array2Par , IntParI1 , IntParI2 ) : IntLoc = IntParI1 + Array1Par [ IntLoc ] = IntParI2 Array1Par [ IntLoc + ] = Array1Par [ IntLoc ] Array1Par [ IntLoc + ] = IntLoc for IntIndex in range ( IntLoc , IntLoc + ) : Array2Par [ IntLoc ] [ IntIndex ] = IntLoc Array2Par [ IntLoc ] [ IntLoc - ] = Array2Par [ IntLoc ] [ IntLoc - ] + Array2Par [ IntLoc + ] [ IntLoc ] = Array1Par [ IntLoc ] g . IntGlob = def Func1 ( CharPar1 , CharPar2 ) : CharLoc1 = CharPar1 CharLoc2 = CharLoc1 if CharLoc2 != CharPar2 : return Ident1 else : return Ident2 def Func2 ( StrParI1 , StrParI2 ) : IntLoc = ", "answer": "while IntLoc <= :"}, {"prompt": " from pprint import pprint import subprocess from time import sleep from django . core . management . base import BaseCommand from orchestra . orchestra_api import create_orchestra_project from orchestra . orchestra_api import get_project_information class Command ( BaseCommand ) : help = '' def add_arguments ( self , parser ) : parser . add_argument ( '' , '' , action = '' , default = False , help = '' ) def handle ( self , * args , ** options ) : self . fast_mode = not options [ '' ] continue_demo = self . intro ( ) if not continue_demo : return self . describe_workflow ( ) project_id = self . create_project ( ) self . project_info_1 ( project_id ) self . rating_task ( ) self . project_info_2 ( project_id ) self . conclusion ( ) def pause ( self , n_seconds ) : if not self . fast_mode : sleep ( n_seconds ) def intro ( self ) : subprocess . call ( '' ) print ( '' ) print ( '' ) print ( '' ) self . pause ( ) print ( '' '' ) self . pause ( ) print ( '' '' ) self . pause ( ) ack = input ( '' ) . lower ( ) while ack not in [ '' , '' ] : ack = input ( '' ) . lower ( ) if ack == '' : print ( '' ) return False print ( '' ) return True def describe_workflow ( self ) : print ( '' ) print ( '' '' ) self . pause ( ) print ( '' '' ) self . pause ( ) print ( '' '' ) self . pause ( ) print ( '' '' ) self . pause ( ) print ( '' '' ) self . pause ( ) def create_project ( self ) : print ( '' ) print ( \"\" ) self . pause ( ) print ( \"\" ) self . pause ( ) print ( '' ) print ( '''''' ) self . pause ( ) print ( '' '' ) input ( '' '' ) project_id = create_orchestra_project ( None , '' , '' , '' , , { '' : '' } , '' , ) print ( '' . format ( project_id ) ) self . pause ( ) return project_id def project_info_1 ( self , project_id ) : print ( '' ) print ( '' '' '' ) self . pause ( ) print ( \"\" \"\" ) self . pause ( ) print ( '' ) print ( '' ) print ( '' ) print ( '' ) self . pause ( ) input ( '' '' ) project_info = get_project_information ( project_id ) ", "answer": "print ( \"\" )"}, {"prompt": " import subprocess import sys from distutils . core import setup , Command class TestCommand ( Command ) : user_options = [ ] def initialize_options ( self ) : pass def finalize_options ( self ) : pass def run ( self ) : errno = subprocess . call ( [ sys . executable , '' ] ) raise SystemExit ( errno ) setup ( name = '' , version = '' , author = '' , author_email = '' , py_modules = [ '' , ] , url = '' , license = '' , description = '' , long_description = open ( '' ) . read ( ) , ", "answer": "cmdclass = { '' : TestCommand } ,"}, {"prompt": " import logging from voltron . view import * from voltron . plugin import * from voltron . api import * log = logging . getLogger ( '' ) class BacktraceView ( TerminalView ) : def render ( self ) : height , width = self . window_size ( ) self . title = '' res = self . client . perform_request ( '' , block = self . block , command = '' ) if res . timed_out : return if res and res . is_success : self . body = res . output ", "answer": "else :"}, {"prompt": " \"\" import time from google . appengine . _internal . django . core . cache . backends . base import BaseCache , InvalidCacheBackendError from google . appengine . _internal . django . utils . encoding import smart_unicode , smart_str try : import cmemcache as memcache import warnings warnings . warn ( \"\" , PendingDeprecationWarning ) except ImportError : try : import memcache except : raise InvalidCacheBackendError ( \"\" ) class CacheClass ( BaseCache ) : def __init__ ( self , server , params ) : BaseCache . __init__ ( self , params ) self . _cache = memcache . Client ( server . split ( '' ) ) ", "answer": "def _get_memcache_timeout ( self , timeout ) :"}, {"prompt": " import re from types import FunctionType from importlib import import_module from inspect import getmembers , getargspec from pyinfra import modules def _title_line ( char , string ) : return '' . join ( char for _ in xrange ( , len ( string ) ) ) def _format_doc_line ( line ) : line = re . sub ( r'' , r'' , line ) return line [ : ] def build_facts ( ) : for module_name in modules . __all__ : lines = [ ] print '' . format ( module_name ) module = import_module ( '' . format ( module_name ) ) lines . append ( module_name . title ( ) ) lines . append ( _title_line ( '' , module_name ) ) lines . append ( '' ) if module . __doc__ : lines . append ( module . __doc__ ) operation_functions = [ ( key , value . _pyinfra_op ) for key , value in getmembers ( module ) if ( isinstance ( value , FunctionType ) and value . __module__ == module . __name__ and getattr ( value , '' , False ) and not value . __name__ . startswith ( '' ) ) ] for name , func in operation_functions : title_name = '' . format ( module_name , name ) lines . append ( title_name ) lines . append ( _title_line ( '' , title_name ) ) doc = func . __doc__ if doc : docbits = doc . strip ( ) . split ( '' ) description_lines = [ ] for line in docbits : ", "answer": "if line :"}, {"prompt": " from django . conf . urls import patterns , url from django . views . generic . base import TemplateView urlpatterns = patterns ( '' , url ( r'' , TemplateView . as_view ( template_name = \"\" ) ) , ", "answer": "url ( r'' , '' , name = '' ) ,"}, {"prompt": " \"\"\"\"\"\" from oslo_db . sqlalchemy import models from sqlalchemy . ext . declarative import declarative_base from sqlalchemy import Column , PrimaryKeyConstraint , String , Text from sqlalchemy import UniqueConstraint ", "answer": "BASE = declarative_base ( )"}, {"prompt": " \"\"\"\"\"\" import contextlib import datetime import os import socket import struct import sys import time import traceback import warnings sys . path [ : ] = [ \"\" ] from bson import BSON from bson . codec_options import CodecOptions from bson . py3compat import thread , u from bson . son import SON from bson . tz_util import utc from pymongo import auth , message from pymongo . cursor import CursorType from pymongo . database import Database from pymongo . errors import ( AutoReconnect , ConfigurationError , ConnectionFailure , InvalidName , OperationFailure , CursorNotFound , NetworkTimeout , InvalidURI ) from pymongo . message import _CursorAddress from pymongo . mongo_client import MongoClient from pymongo . pool import SocketInfo from pymongo . read_preferences import ReadPreference from pymongo . server_selectors import ( any_server_selector , writable_server_selector ) from pymongo . server_type import SERVER_TYPE from pymongo . write_concern import WriteConcern from test import ( client_context , client_knobs , host , pair , port , SkipTest , unittest , IntegrationTest , db_pwd , db_user , MockClientTest ) from test . pymongo_mocks import MockClient from test . utils import ( assertRaisesExactly , delay , remove_all_users , server_is_master_with_slave , get_pool , one , connected , wait_until , rs_or_single_client , rs_or_single_client_noauth , lazy_client_trial , NTHREADS ) class ClientUnitTest ( unittest . TestCase ) : \"\"\"\"\"\" @ classmethod def setUpClass ( cls ) : cls . client = MongoClient ( host , port , connect = False , serverSelectionTimeoutMS = ) def test_keyword_arg_defaults ( self ) : client = MongoClient ( socketTimeoutMS = None , connectTimeoutMS = , waitQueueTimeoutMS = None , waitQueueMultiple = None , socketKeepAlive = False , replicaSet = None , read_preference = ReadPreference . PRIMARY , ssl = False , ssl_keyfile = None , ssl_certfile = None , ssl_cert_reqs = , ssl_ca_certs = None , connect = False , serverSelectionTimeoutMS = ) options = client . _MongoClient__options pool_opts = options . pool_options self . assertEqual ( None , pool_opts . socket_timeout ) self . assertEqual ( , pool_opts . connect_timeout ) self . assertEqual ( None , pool_opts . wait_queue_timeout ) self . assertEqual ( None , pool_opts . wait_queue_multiple ) self . assertFalse ( pool_opts . socket_keepalive ) self . assertEqual ( None , pool_opts . ssl_context ) self . assertEqual ( None , options . replica_set_name ) self . assertEqual ( ReadPreference . PRIMARY , client . read_preference ) self . assertAlmostEqual ( , client . server_selection_timeout ) def test_types ( self ) : self . assertRaises ( TypeError , MongoClient , ) self . assertRaises ( TypeError , MongoClient , ) self . assertRaises ( TypeError , MongoClient , \"\" , \"\" ) self . assertRaises ( TypeError , MongoClient , \"\" , ) self . assertRaises ( TypeError , MongoClient , \"\" , [ ] ) self . assertRaises ( ConfigurationError , MongoClient , [ ] ) def test_max_pool_size_zero ( self ) : with self . assertRaises ( ValueError ) : MongoClient ( maxPoolSize = ) def test_get_db ( self ) : def make_db ( base , name ) : return base [ name ] self . assertRaises ( InvalidName , make_db , self . client , \"\" ) self . assertRaises ( InvalidName , make_db , self . client , \"\" ) self . assertRaises ( InvalidName , make_db , self . client , \"\" ) self . assertRaises ( InvalidName , make_db , self . client , \"\" ) self . assertRaises ( InvalidName , make_db , self . client , \"\" ) self . assertRaises ( InvalidName , make_db , self . client , \"\" ) self . assertTrue ( isinstance ( self . client . test , Database ) ) self . assertEqual ( self . client . test , self . client [ \"\" ] ) self . assertEqual ( self . client . test , Database ( self . client , \"\" ) ) def test_get_database ( self ) : codec_options = CodecOptions ( tz_aware = True ) write_concern = WriteConcern ( w = , j = True ) db = self . client . get_database ( '' , codec_options , ReadPreference . SECONDARY , write_concern ) self . assertEqual ( '' , db . name ) self . assertEqual ( codec_options , db . codec_options ) self . assertEqual ( ReadPreference . SECONDARY , db . read_preference ) self . assertEqual ( write_concern , db . write_concern ) def test_getattr ( self ) : self . assertTrue ( isinstance ( self . client [ '' ] , Database ) ) with self . assertRaises ( AttributeError ) as context : self . client . _does_not_exist self . assertIn ( \"\" , str ( context . exception ) ) def test_iteration ( self ) : def iterate ( ) : [ a for a in self . client ] self . assertRaises ( TypeError , iterate ) def test_get_default_database ( self ) : c = MongoClient ( \"\" % ( host , port ) , connect = False ) self . assertEqual ( Database ( c , '' ) , c . get_default_database ( ) ) def test_get_default_database_error ( self ) : c = MongoClient ( \"\" % ( host , port ) , connect = False ) self . assertRaises ( ConfigurationError , c . get_default_database ) def test_get_default_database_with_authsource ( self ) : uri = \"\" % ( host , port ) c = MongoClient ( uri , connect = False ) self . assertEqual ( Database ( c , '' ) , c . get_default_database ( ) ) class TestClient ( IntegrationTest ) : def test_constants ( self ) : MongoClient . HOST = \"\" MongoClient . PORT = with self . assertRaises ( AutoReconnect ) : connected ( MongoClient ( serverSelectionTimeoutMS = ) ) connected ( MongoClient ( host , port ) ) MongoClient . HOST = host MongoClient . PORT = port connected ( MongoClient ( ) ) def test_init_disconnected ( self ) : c = rs_or_single_client ( connect = False ) self . assertIsInstance ( c . is_primary , bool ) c = rs_or_single_client ( connect = False ) self . assertIsInstance ( c . is_mongos , bool ) c = rs_or_single_client ( connect = False ) self . assertIsInstance ( c . max_pool_size , int ) self . assertIsInstance ( c . nodes , frozenset ) c = rs_or_single_client ( connect = False ) self . assertEqual ( c . codec_options , CodecOptions ( ) ) self . assertIsInstance ( c . max_bson_size , int ) c = rs_or_single_client ( connect = False ) self . assertFalse ( c . primary ) self . assertFalse ( c . secondaries ) c = rs_or_single_client ( connect = False ) self . assertIsInstance ( c . max_write_batch_size , int ) if client_context . is_rs : self . assertIsNotNone ( c . address ) else : self . assertEqual ( c . address , ( host , port ) ) bad_host = \"\" c = MongoClient ( bad_host , port , connectTimeoutMS = , serverSelectionTimeoutMS = ) self . assertRaises ( ConnectionFailure , c . pymongo_test . test . find_one ) def test_init_disconnected_with_auth ( self ) : uri = \"\" c = MongoClient ( uri , connectTimeoutMS = , serverSelectionTimeoutMS = ) self . assertRaises ( ConnectionFailure , c . pymongo_test . test . find_one ) def test_equality ( self ) : c = connected ( rs_or_single_client ( ) ) self . assertEqual ( client_context . rs_or_standalone_client , c ) self . assertFalse ( client_context . rs_or_standalone_client != c ) def test_host_w_port ( self ) : with self . assertRaises ( ValueError ) : connected ( MongoClient ( \"\" % host , connectTimeoutMS = , serverSelectionTimeoutMS = ) ) def test_repr ( self ) : import bson client = MongoClient ( '' '' , connect = False , document_class = SON ) the_repr = repr ( client ) self . assertIn ( '' , the_repr ) self . assertIn ( \"\" \"\" \"\" , the_repr ) self . assertIn ( \"\" , the_repr ) self . assertIn ( \"\" , the_repr ) self . assertEqual ( eval ( the_repr ) , client ) @ client_context . require_replica_set def test_repr_replica_set ( self ) : self . assertIn ( \"\" , repr ( self . client ) ) self . assertIn ( pair , repr ( self . client ) ) def test_getters ( self ) : self . assertEqual ( client_context . client . address , ( host , port ) ) self . assertEqual ( client_context . nodes , self . client . nodes ) def test_database_names ( self ) : self . client . pymongo_test . test . insert_one ( { \"\" : u ( \"\" ) } ) self . client . pymongo_test_mike . test . insert_one ( { \"\" : u ( \"\" ) } ) dbs = self . client . database_names ( ) self . assertTrue ( \"\" in dbs ) self . assertTrue ( \"\" in dbs ) def test_drop_database ( self ) : self . assertRaises ( TypeError , self . client . drop_database , ) self . assertRaises ( TypeError , self . client . drop_database , None ) self . client . pymongo_test . test . insert_one ( { \"\" : u ( \"\" ) } ) self . client . pymongo_test2 . test . insert_one ( { \"\" : u ( \"\" ) } ) dbs = self . client . database_names ( ) self . assertIn ( \"\" , dbs ) self . assertIn ( \"\" , dbs ) self . client . drop_database ( \"\" ) self . client . drop_database ( self . client . pymongo_test2 ) raise SkipTest ( \"\" ) dbs = self . client . database_names ( ) self . assertNotIn ( \"\" , dbs ) self . assertNotIn ( \"\" , dbs ) def test_close ( self ) : coll = self . client . pymongo_test . bar self . client . close ( ) self . client . close ( ) coll . count ( ) self . client . close ( ) self . client . close ( ) coll . count ( ) def test_bad_uri ( self ) : with self . assertRaises ( InvalidURI ) : MongoClient ( \"\" ) @ client_context . require_auth def test_auth_from_uri ( self ) : self . client . admin . add_user ( \"\" , \"\" , roles = [ \"\" ] ) self . addCleanup ( self . client . admin . remove_user , '' ) self . addCleanup ( remove_all_users , self . client . pymongo_test ) self . client . pymongo_test . add_user ( \"\" , \"\" , roles = [ '' , '' ] ) with self . assertRaises ( OperationFailure ) : connected ( rs_or_single_client ( \"\" % ( host , port ) ) ) connected ( rs_or_single_client_noauth ( \"\" % ( host , port ) ) ) uri = \"\" % ( host , port ) with self . assertRaises ( OperationFailure ) : connected ( rs_or_single_client ( uri ) ) connected ( rs_or_single_client_noauth ( \"\" % ( host , port ) ) ) rs_or_single_client ( \"\" % ( host , port ) , connect = False ) . pymongo_test . test . find_one ( ) bad_client = rs_or_single_client ( \"\" % ( host , port ) , connect = False ) self . assertRaises ( OperationFailure , bad_client . pymongo_test . test . find_one ) @ client_context . require_auth def test_multiple_logins ( self ) : self . client . pymongo_test . add_user ( '' , '' , roles = [ '' ] ) self . client . pymongo_test . add_user ( '' , '' , roles = [ '' ] ) self . addCleanup ( remove_all_users , self . client . pymongo_test ) client = rs_or_single_client_noauth ( \"\" % ( host , port ) ) client . pymongo_test . test . find_one ( ) with self . assertRaises ( OperationFailure ) : client . pymongo_test . authenticate ( '' , '' ) client . pymongo_test . test . find_one ( ) client . pymongo_test . logout ( ) with self . assertRaises ( OperationFailure ) : client . pymongo_test . test . find_one ( ) client . pymongo_test . authenticate ( '' , '' ) client . pymongo_test . test . find_one ( ) with self . assertRaises ( OperationFailure ) : client . pymongo_test . authenticate ( '' , '' ) client . pymongo_test . test . find_one ( ) @ client_context . require_auth def test_lazy_auth_raises_operation_failure ( self ) : lazy_client = rs_or_single_client ( \"\" % host , connect = False ) assertRaisesExactly ( OperationFailure , lazy_client . test . collection . find_one ) def test_unix_socket ( self ) : if not hasattr ( socket , \"\" ) : raise SkipTest ( \"\" ) mongodb_socket = '' encoded_socket = '' if not os . access ( mongodb_socket , os . R_OK ) : raise SkipTest ( \"\" ) if client_context . auth_enabled : uri = \"\" % ( db_user , db_pwd , encoded_socket ) else : uri = \"\" % encoded_socket client = MongoClient ( uri ) client . pymongo_test . test . insert_one ( { \"\" : \"\" } ) dbs = client . database_names ( ) self . assertTrue ( \"\" in dbs ) self . assertRaises ( ConnectionFailure , connected , MongoClient ( \"\" , serverSelectionTimeoutMS = ) ) def test_fork ( self ) : if sys . platform == \"\" : raise SkipTest ( \"\" ) try : import multiprocessing except ImportError : raise SkipTest ( \"\" ) db = self . client . pymongo_test db . test . find_one ( ) def f ( pipe ) : try : kill_cursors_executor = self . client . _kill_cursors_executor servers = self . client . _topology . select_servers ( any_server_selector ) db . test . find_one ( ) wait_until ( lambda : all ( s . _monitor . _executor . _thread . is_alive ( ) for s in servers ) , \"\" ) wait_until ( lambda : kill_cursors_executor . _thread . is_alive ( ) , \"\" ) except : traceback . print_exc ( ) pipe . send ( True ) parent_pipe , child_pipe = multiprocessing . Pipe ( ) p = multiprocessing . Process ( target = f , args = ( child_pipe , ) ) p . start ( ) p . join ( ) child_pipe . close ( ) try : parent_pipe . recv ( ) self . fail ( ) except EOFError : pass def test_document_class ( self ) : c = self . client db = c . pymongo_test db . test . insert_one ( { \"\" : } ) self . assertEqual ( dict , c . codec_options . document_class ) self . assertTrue ( isinstance ( db . test . find_one ( ) , dict ) ) self . assertFalse ( isinstance ( db . test . find_one ( ) , SON ) ) c = rs_or_single_client ( document_class = SON ) db = c . pymongo_test self . assertEqual ( SON , c . codec_options . document_class ) self . assertTrue ( isinstance ( db . test . find_one ( ) , SON ) ) def test_timeouts ( self ) : client = rs_or_single_client ( connectTimeoutMS = ) ", "answer": "self . assertEqual ( , get_pool ( client ) . opts . connect_timeout )"}, {"prompt": " \"\"\"\"\"\" from . util import UnicodeMixin , ImmutableMixin , mutating_method class CountryCodeSource ( object ) : \"\"\"\"\"\" FROM_NUMBER_WITH_PLUS_SIGN = FROM_NUMBER_WITH_IDD = FROM_NUMBER_WITHOUT_PLUS_SIGN = FROM_DEFAULT_COUNTRY = class PhoneNumber ( UnicodeMixin ) : \"\"\"\"\"\" def __init__ ( self , country_code = None , national_number = None , extension = None , italian_leading_zero = False , raw_input = None , country_code_source = None , preferred_domestic_carrier_code = None ) : self . country_code = country_code self . national_number = national_number self . extension = extension self . italian_leading_zero = italian_leading_zero self . raw_input = raw_input self . country_code_source = country_code_source self . preferred_domestic_carrier_code = preferred_domestic_carrier_code def clear ( self ) : \"\"\"\"\"\" self . country_code = None self . national_number = None self . extension = None self . italian_leading_zero = False self . raw_input = None self . country_code_source = None self . preferred_domestic_carrier_code = None def merge_from ( self , other ) : \"\"\"\"\"\" if other . country_code is not None : self . country_code = other . country_code if other . national_number is not None : self . national_number = other . national_number if other . extension is not None : self . extension = other . extension if other . italian_leading_zero is not None : self . italian_leading_zero = other . italian_leading_zero if other . raw_input is not None : self . raw_input = other . raw_input if other . country_code_source is not None : self . country_code_source = other . country_code_source if other . preferred_domestic_carrier_code is not None : self . preferred_domestic_carrier_code = other . preferred_domestic_carrier_code def __eq__ ( self , other ) : if not isinstance ( other , PhoneNumber ) : return False return ( self . country_code == other . country_code and self . national_number == other . national_number and self . extension == other . extension and self . italian_leading_zero == other . italian_leading_zero and self . raw_input == other . raw_input and self . country_code_source == other . country_code_source and self . preferred_domestic_carrier_code == other . preferred_domestic_carrier_code ) def __ne__ ( self , other ) : return not self . __eq__ ( other ) def __repr__ ( self ) : return ( ( \"\" + \"\" ) % ( self . country_code , self . national_number , self . extension , self . italian_leading_zero , self . country_code_source , self . preferred_domestic_carrier_code ) ) def __unicode__ ( self ) : result = ( \"\" % ( self . country_code , self . national_number ) ) if self . italian_leading_zero is not None : result += \"\" % self . italian_leading_zero if self . extension is not None : ", "answer": "result += \"\" % self . extension"}, {"prompt": " \"\"\"\"\"\" import imp import os import sys import unittest import TestGyp test = TestGyp . TestGyp ( ) sys . path . append ( os . path . join ( test . _cwd , '' ) ) files_to_test = [ '' , '' , '' , '' , '' , '' , '' , ] ", "answer": "suites = [ ]"}, {"prompt": " \"\"\"\"\"\" import unittest from cafe . drivers . unittest . decorators import tags from cloudcafe . common . tools . datagen import rand_name from cloudcafe . compute . common . types import ComputeHypervisors , NovaServerStatusTypes from cloudcafe . compute . config import ComputeConfig from cloudcafe . compute . flavors_api . config import FlavorsConfig from cloudroast . compute . fixtures import ServerFromImageFixture compute_config = ComputeConfig ( ) hypervisor = compute_config . hypervisor . lower ( ) flavors_config = FlavorsConfig ( ) resize_up_enabled = ( flavors_config . resize_up_enabled if flavors_config . resize_up_enabled is not None else flavors_config . resize_enabled ) can_resize = ( resize_up_enabled and hypervisor not in [ ComputeHypervisors . IRONIC , ComputeHypervisors . LXC_LIBVIRT ] ) class ResizeServerDataIntegrityTests ( object ) : @ tags ( type = '' , net = '' ) def test_active_file_inject_during_resize ( self ) : \"\"\"\"\"\" server_to_resize = self . server self . resize_resp = self . servers_client . resize ( server_to_resize . id , self . flavor_ref_alt ) self . server_behaviors . wait_for_server_task_state ( self . server . id , '' , self . servers_config . server_build_timeout ) remote_client = self . server_behaviors . get_remote_instance_client ( self . server , self . servers_config , key = self . key . private_key ) prototype_file = remote_client . create_file ( file_name = '' , file_content = \"\" , file_path = self . servers_config . default_file_path ) . content self . server_behaviors . wait_for_server_status ( server_to_resize . id , NovaServerStatusTypes . VERIFY_RESIZE ) self . confirm_resize_resp = self . servers_client . confirm_resize ( server_to_resize . id ) self . server_behaviors . wait_for_server_status ( server_to_resize . id , NovaServerStatusTypes . ACTIVE ) remote_client = self . server_behaviors . get_remote_instance_client ( self . server , self . servers_config , key = self . key . private_key ) file = remote_client . get_file_details ( file_path = '' . format ( self . servers_config . default_file_path ) ) . content self . assertEqual ( prototype_file , file , msg = \"\" ) @ unittest . skipUnless ( ", "answer": "can_resize , '' )"}, {"prompt": " from py . magic import greenlet import sys import types ", "answer": "def emulate ( ) :"}, {"prompt": " from __future__ import absolute_import ", "answer": "from . celery import app as celery_app "}, {"prompt": " \"\"\"\"\"\" import numpy as np from . generic_features import Feature from . . import utils class Widths ( object ) : \"\"\"\"\"\" fields = ( '' , '' , '' ) def __init__ ( self , features_ref ) : \"\"\"\"\"\" nw = features_ref . nw for partition in self . fields : widths_in_partition = nw . get_partition ( partition , '' ) setattr ( self , partition , np . mean ( widths_in_partition , ) ) @ classmethod def from_disk ( cls , width_ref ) : self = cls . __new__ ( cls ) for partition in self . fields : widths_in_partition = utils . _extract_time_from_disk ( width_ref , partition ) setattr ( self , partition , widths_in_partition ) return self def __eq__ ( self , other ) : return ( utils . correlation ( self . head , other . head , '' ) and utils . correlation ( self . midbody , other . midbody , '' ) and utils . correlation ( self . tail , other . tail , '' ) ) def __repr__ ( self ) : return utils . print_object ( self ) class Length ( Feature ) : def __init__ ( self , wf , feature_name ) : self . name = feature_name self . value = wf . nw . length @ classmethod def from_schafer_file ( cls , wf , feature_name ) : self = cls . __new__ ( cls ) self . name = feature_name self . value = utils . get_nested_h5_field ( wf . h , [ '' , '' ] ) return self class WidthSection ( Feature ) : \"\"\"\"\"\" def __init__ ( self , wf , feature_name , partition_name ) : \"\"\"\"\"\" self . name = feature_name self . partition_name = partition_name widths_in_partition = wf . nw . get_partition ( partition_name , '' ) self . value = np . mean ( widths_in_partition , ) @ classmethod def from_schafer_file ( cls , wf , feature_name , partition_name ) : self = cls . __new__ ( cls ) self . name = feature_name self . value = utils . get_nested_h5_field ( wf . h , [ '' , '' , partition_name ] ) return self class Area ( Feature ) : \"\"\"\"\"\" def __init__ ( self , wf , feature_name ) : self . name = feature_name self . value = wf . nw . area @ classmethod def from_schafer_file ( cls , wf , feature_name ) : self = cls . __new__ ( cls ) self . name = feature_name self . value = utils . get_nested_h5_field ( wf . h , [ '' , '' ] ) return self class AreaPerLength ( Feature ) : \"\"\"\"\"\" def __init__ ( self , wf , feature_name ) : self . name = feature_name area = self . get_feature ( wf , '' ) . value length = self . get_feature ( wf , '' ) . value self . value = area / length @ classmethod def from_schafer_file ( cls , wf , feature_name ) : return cls ( wf , feature_name ) class WidthPerLength ( Feature ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " from __future__ import absolute_import , unicode_literals import re import unicodedata ", "answer": "from django . apps import apps"}, {"prompt": " extensions = [ '' , '' , ", "answer": "]"}, {"prompt": " from setuptools import setup , find_packages import os import sys from distutils import log import sphinx long_desc = '''''' if sys . version_info < ( , ) or ( , ) <= sys . version_info < ( , ) : print ( '' ) sys . exit ( ) requires = [ '' , '' , '' , '' , '' , ", "answer": "'' ,"}, {"prompt": " import imp import os import sys def module_has_submodule ( package , module_name ) : \"\"\"\"\"\" name = \"\" . join ( [ package . __name__ , module_name ] ) try : return sys . modules [ name ] is not None except KeyError : pass for finder in sys . meta_path : if finder . find_module ( name ) : return True for entry in package . __path__ : try : finder = sys . path_importer_cache [ entry ] if finder is None : try : ", "answer": "file_ , _ , _ = imp . find_module ( module_name , [ entry ] )"}, {"prompt": " \"\"\"\"\"\" ", "answer": "import random"}, {"prompt": " import mock from nose . tools import * ", "answer": "from tests . base import OsfTestCase"}, {"prompt": " import time from tooz import coordination ", "answer": "ALIVE_TIME = "}, {"prompt": " import responses import unittest2 as unittest import livescrape class BasePage ( livescrape . ScrapedPage ) : scrape_url = \"\" class Test ( unittest . TestCase ) : def setUp ( self ) : responses . reset ( ) responses . add ( responses . GET , BasePage . scrape_url , \"\"\"\"\"\" ) responses . start ( ) self . addCleanup ( responses . stop ) def test_simplecss ( self ) : class Page ( BasePage ) : foo = livescrape . Css ( \"\" ) x = Page ( ) self . assertEqual ( x . foo , '' ) def test_dict ( self ) : class Page ( BasePage ) : foo = livescrape . Css ( \"\" ) x = Page ( ) self . assertEqual ( x . _dict , { \"\" : '' } ) def test_ambigous ( self ) : class Page ( BasePage ) : foo = livescrape . Css ( \"\" ) x = Page ( ) self . assertEqual ( x . foo , '' ) def test_multiple ( self ) : class Page ( BasePage ) : foo = livescrape . Css ( \"\" , multiple = True ) x = Page ( ) self . assertEqual ( x . foo , [ '' , '' ] ) def test_attribute ( self ) : class Page ( BasePage ) : foo = livescrape . Css ( \"\" , attribute = \"\" ) not_there = livescrape . Css ( \"\" , attribute = \"\" ) x = Page ( ) self . assertEqual ( x . foo , '' ) self . assertIsNone ( x . not_there ) def test_link ( self ) : class Page ( BasePage ) : foo = livescrape . CssLink ( \"\" , \"\" ) x = Page ( ) self . assertIsInstance ( x . foo , Page ) self . assertEqual ( x . foo . scrape_url , \"\" ) def test_float ( self ) : class Page ( BasePage ) : foo = livescrape . CssFloat ( \"\" ) foo_fail = livescrape . CssFloat ( \"\" ) x = Page ( ) self . assertAlmostEqual ( x . foo , ) self . assertIsNone ( x . foo_fail ) def test_int ( self ) : class Page ( BasePage ) : foo = livescrape . CssInt ( \"\" ) foo_fail = livescrape . CssInt ( \"\" ) x = Page ( ) self . assertEqual ( x . foo , ) self . assertIsNone ( x . foo_fail ) def test_date ( self ) : class Page ( BasePage ) : foo = livescrape . CssDate ( \"\" , '' ) foo_fail = livescrape . CssDate ( \"\" , '' ) x = Page ( ) self . assertEqual ( x . foo . year , ) self . assertIsNone ( x . foo_fail ) def test_bool ( self ) : class Page ( BasePage ) : foo = livescrape . CssBoolean ( \"\" ) bar = livescrape . CssBoolean ( \"\" ) x = Page ( ) self . assertTrue ( x . foo ) ", "answer": "self . assertFalse ( x . bar )"}, {"prompt": " import unittest import sys import os import signal from sts . control_flow . peeker import * from tests . unit . sts . event_dag_test import MockInternalEvent from tests . unit . sts . mcs_finder_test import MockInputEvent from sts . replay_event import InternalEvent , ConnectToControllers from sts . event_dag import EventDag from config . experiment_config_lib import ControllerConfig from sts . simulation_state import SimulationConfig from sts . util . convenience import IPAddressSpace import logging sys . path . append ( os . path . dirname ( __file__ ) + \"\" ) _running_simulation = None def handle_int ( sigspec , frame ) : print >> sys . stderr , \"\" % sigspec if _running_simulation is not None : _running_simulation . current_simulation . clean_up ( ) raise RuntimeError ( \"\" % sigspec ) signal . signal ( signal . SIGINT , handle_int ) signal . signal ( signal . SIGTERM , handle_int ) class MockConnectToControllers ( ConnectToControllers ) : def __init__ ( self , fingerprint = None , ** kwargs ) : super ( MockConnectToControllers , self ) . __init__ ( ** kwargs ) self . _fingerprint = fingerprint self . prunable = False @ property def fingerprint ( self ) : return self . _fingerprint def proceed ( self , simulation ) : return True class MockSnapshotter ( object ) : def snapshot_proceed ( * args ) : pass class PeekerTest ( unittest . TestCase ) : def setUp ( self ) : self . input_trace = [ MockInputEvent ( fingerprint = ( \"\" , f ) ) for f in range ( , ) ] self . dag = EventDag ( self . input_trace ) self . prefix_peeker = PrefixPeeker ( None ) IPAddressSpace . _claimed_addresses . clear ( ) ControllerConfig . _controller_labels . clear ( ) controller_cfg = ControllerConfig ( start_cmd = \"\" ) simulation_cfg = SimulationConfig ( controller_configs = [ controller_cfg ] ) self . snapshot_peeker = SnapshotPeeker ( simulation_cfg , default_dp_permit = True ) self . snapshot_peeker . setup_simulation = lambda : ( None , None ) self . snapshot_peeker . snapshot_and_play_forward = lambda * args : ( [ ] , None ) self . snapshot_peeker . replay_interval = lambda * args : [ ] self . mock_snapshotter = MockSnapshotter ( ) def test_basic_noop ( self ) : \"\"\"\"\"\" events = [ MockConnectToControllers ( fingerprint = ( \"\" , ) ) ] + [ MockInputEvent ( fingerprint = ( \"\" , f ) ) for f in range ( , ) ] new_dag = self . prefix_peeker . peek ( EventDag ( events ) ) self . assertEquals ( events , new_dag . events ) new_dag = self . snapshot_peeker . peek ( EventDag ( events ) ) ", "answer": "self . assertEquals ( events , new_dag . events )"}, {"prompt": " from __future__ import absolute_import , unicode_literals from django . contrib . auth import get_user_model from django . contrib . auth . models import Permission from django . contrib . contenttypes . models import ContentType from django . core . exceptions import FieldDoesNotExist , ImproperlyConfigured from django . db . models import Q from django . utils . functional import cached_property class BasePermissionPolicy ( object ) : \"\"\"\"\"\" def __init__ ( self , model ) : self . model = model def user_has_permission ( self , user , action ) : \"\"\"\"\"\" return ( user in self . users_with_permission ( action ) ) def user_has_any_permission ( self , user , actions ) : \"\"\"\"\"\" return any ( self . user_has_permission ( user , action ) for action in actions ) def users_with_any_permission ( self , actions ) : \"\"\"\"\"\" raise NotImplementedError def users_with_permission ( self , action ) : \"\"\"\"\"\" return self . users_with_any_permission ( [ action ] ) def user_has_permission_for_instance ( self , user , action , instance ) : \"\"\"\"\"\" return self . user_has_permission ( user , action ) def user_has_any_permission_for_instance ( self , user , actions , instance ) : \"\"\"\"\"\" return any ( self . user_has_permission_for_instance ( user , action , instance ) for action in actions ) def instances_user_has_any_permission_for ( self , user , actions ) : \"\"\"\"\"\" if self . user_has_any_permission ( user , actions ) : return self . model . objects . all ( ) else : return self . model . objects . none ( ) def instances_user_has_permission_for ( self , user , action ) : \"\"\"\"\"\" return self . instances_user_has_any_permission_for ( user , [ action ] ) def users_with_any_permission_for_instance ( self , actions , instance ) : \"\"\"\"\"\" return self . users_with_any_permission ( actions ) def users_with_permission_for_instance ( self , action , instance ) : return self . users_with_any_permission_for_instance ( [ action ] , instance ) class BlanketPermissionPolicy ( BasePermissionPolicy ) : \"\"\"\"\"\" def user_has_permission ( self , user , action ) : return True def user_has_any_permission ( self , user , actions ) : return True def users_with_any_permission ( self , actions ) : return get_user_model ( ) . objects . filter ( is_active = True ) def users_with_permission ( self , action ) : return get_user_model ( ) . objects . filter ( is_active = True ) class AuthenticationOnlyPermissionPolicy ( BasePermissionPolicy ) : \"\"\"\"\"\" def user_has_permission ( self , user , action ) : return user . is_authenticated ( ) and user . is_active def user_has_any_permission ( self , user , actions ) : return user . is_authenticated ( ) and user . is_active def users_with_any_permission ( self , actions ) : return get_user_model ( ) . objects . filter ( is_active = True ) def users_with_permission ( self , action ) : return get_user_model ( ) . objects . filter ( is_active = True ) class BaseDjangoAuthPermissionPolicy ( BasePermissionPolicy ) : \"\"\"\"\"\" def __init__ ( self , model , auth_model = None ) : super ( BaseDjangoAuthPermissionPolicy , self ) . __init__ ( model ) self . auth_model = auth_model or self . model self . app_label = self . auth_model . _meta . app_label self . model_name = self . auth_model . _meta . model_name @ cached_property def _content_type ( self ) : return ContentType . objects . get_for_model ( self . auth_model ) def _get_permission_name ( self , action ) : \"\"\"\"\"\" return '' % ( self . app_label , action , self . model_name ) ", "answer": "def _get_users_with_any_permission_codenames_filter ( self , permission_codenames ) :"}, {"prompt": " from __future__ import absolute_import from django . core . management . base import BaseCommand from zerver . models import Subscription class Command ( BaseCommand ) : ", "answer": "help = \"\"\"\"\"\""}, {"prompt": " from pypy . rpython . lltypesystem import lltype , llmemory , llheap from pypy . rpython import llinterp from pypy . rpython . annlowlevel import llhelper from pypy . rpython . memory import gctypelayout from pypy . objspace . flow . model import Constant class GCManagedHeap ( object ) : def __init__ ( self , llinterp , flowgraphs , gc_class , GC_PARAMS = { } ) : translator = llinterp . typer . annotator . translator config = translator . config . translation self . gc = gc_class ( config , chunk_size = , ** GC_PARAMS ) self . gc . set_root_walker ( LLInterpRootWalker ( self ) ) self . gc . DEBUG = True self . llinterp = llinterp self . prepare_graphs ( flowgraphs ) self . gc . setup ( ) def prepare_graphs ( self , flowgraphs ) : lltype2vtable = self . llinterp . typer . lltype2vtable layoutbuilder = DirectRunLayoutBuilder ( self . gc . __class__ , lltype2vtable , self . llinterp ) self . get_type_id = layoutbuilder . get_type_id layoutbuilder . initialize_gc_query_function ( self . gc ) constants = collect_constants ( flowgraphs ) for obj in constants : TYPE = lltype . typeOf ( obj ) layoutbuilder . consider_constant ( TYPE , obj , self . gc ) self . constantroots = layoutbuilder . addresses_of_static_ptrs self . constantrootsnongc = layoutbuilder . addresses_of_static_ptrs_in_nongc self . _all_prebuilt_gc = layoutbuilder . all_prebuilt_gc def malloc ( self , TYPE , n = None , flavor = '' , zero = False ) : if flavor == '' : typeid = self . get_type_id ( TYPE ) addr = self . gc . malloc ( typeid , n , zero = zero ) result = llmemory . cast_adr_to_ptr ( addr , lltype . Ptr ( TYPE ) ) if not self . gc . malloc_zero_filled : gctypelayout . zero_gc_pointers ( result ) return result else : return lltype . malloc ( TYPE , n , flavor = flavor , zero = zero ) def malloc_nonmovable ( self , TYPE , n = None , zero = False ) : typeid = self . get_type_id ( TYPE ) if not self . gc . can_malloc_nonmovable ( ) : return lltype . nullptr ( TYPE ) addr = self . gc . malloc_nonmovable ( typeid , n , zero = zero ) result = llmemory . cast_adr_to_ptr ( addr , lltype . Ptr ( TYPE ) ) if not self . gc . malloc_zero_filled : gctypelayout . zero_gc_pointers ( result ) return result def malloc_resizable_buffer ( self , TYPE , n ) : typeid = self . get_type_id ( TYPE ) addr = self . gc . malloc ( typeid , n ) result = llmemory . cast_adr_to_ptr ( addr , lltype . Ptr ( TYPE ) ) if not self . gc . malloc_zero_filled : gctypelayout . zero_gc_pointers ( result ) return result def resize_buffer ( self , obj , old_size , new_size ) : T = lltype . typeOf ( obj ) . TO buf = self . malloc_resizable_buffer ( T , new_size ) arrayfld = T . _arrayfld new_arr = getattr ( buf , arrayfld ) old_arr = getattr ( obj , arrayfld ) for i in range ( old_size ) : new_arr [ i ] = old_arr [ i ] return buf def finish_building_buffer ( self , obj , size ) : return obj def free ( self , TYPE , flavor = '' ) : assert flavor != '' return lltype . free ( TYPE , flavor = flavor ) def setfield ( self , obj , fieldname , fieldvalue ) : STRUCT = lltype . typeOf ( obj ) . TO addr = llmemory . cast_ptr_to_adr ( obj ) addr += llmemory . offsetof ( STRUCT , fieldname ) self . setinterior ( obj , addr , getattr ( STRUCT , fieldname ) , fieldvalue ) def setarrayitem ( self , array , index , newitem ) : ARRAY = lltype . typeOf ( array ) . TO addr = llmemory . cast_ptr_to_adr ( array ) addr += llmemory . itemoffsetof ( ARRAY , index ) self . setinterior ( array , addr , ARRAY . OF , newitem ) def setinterior ( self , toplevelcontainer , inneraddr , INNERTYPE , newvalue ) : if ( lltype . typeOf ( toplevelcontainer ) . TO . _gckind == '' and isinstance ( INNERTYPE , lltype . Ptr ) and INNERTYPE . TO . _gckind == '' ) : self . gc . write_barrier ( llmemory . cast_ptr_to_adr ( newvalue ) , llmemory . cast_ptr_to_adr ( toplevelcontainer ) ) llheap . setinterior ( toplevelcontainer , inneraddr , INNERTYPE , newvalue ) ", "answer": "def collect ( self , * gen ) :"}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import import base64 from PyQt5 . QtCore import Qt , QVariant , QUrlQuery from PyQt5 . QtNetwork import QNetworkRequest import six from splash . qtutils import ( REQUEST_ERRORS_SHORT , OPERATION_NAMES , qt_header_items ) def headers2har ( request_or_reply ) : \"\"\"\"\"\" ", "answer": "return ["}, {"prompt": " from django . db import models ", "answer": "from django . utils . encoding import python_2_unicode_compatible"}, {"prompt": " import os import datetime from collections import defaultdict from django . db import models from django . db . models import F , Q from core . models import PlCoreBase , User , Controller from core . models . plcorebase import StrippedCharField from core . models import Controller , ControllerLinkManager , ControllerLinkDeletionManager class ControllerUser ( PlCoreBase ) : objects = ControllerLinkManager ( ) deleted_objects = ControllerLinkDeletionManager ( ) user = models . ForeignKey ( User , related_name = '' ) controller = models . ForeignKey ( Controller , related_name = '' ) kuser_id = StrippedCharField ( null = True , blank = True , max_length = , help_text = \"\" ) class Meta : unique_together = ( '' , '' ) def __unicode__ ( self ) : return u'' % ( self . controller , self . user ) @ staticmethod def select_by_user ( user ) : if user . is_admin : qs = ControllerUser . objects . all ( ) else : users = User . select_by_user ( user ) qs = ControllerUser . objects . filter ( user__in = users ) return qs def can_update ( self , user ) : return user . can_update_root ( ) class ControllerSitePrivilege ( PlCoreBase ) : objects = ControllerLinkManager ( ) deleted_objects = ControllerLinkDeletionManager ( ) controller = models . ForeignKey ( '' , related_name = '' ) site_privilege = models . ForeignKey ( '' , related_name = '' ) role_id = StrippedCharField ( null = True , blank = True , max_length = , db_index = True , help_text = \"\" ) class Meta : unique_together = ( '' , '' , '' ) def __unicode__ ( self ) : return u'' % ( self . controller , self . site_privilege ) def can_update ( self , user ) : if user . is_readonly : return False if user . is_admin : return True cprivs = ControllerSitePrivilege . objects . filter ( site_privilege__user = user ) for cpriv in dprivs : if cpriv . site_privilege . role . role == [ '' , '' ] : return True return False @ staticmethod def select_by_user ( user ) : if user . is_admin : qs = ControllerSitePrivilege . objects . all ( ) else : cpriv_ids = [ cp . id for cp in ControllerSitePrivilege . objects . filter ( site_privilege__user = user ) ] qs = ControllerSitePrivilege . objects . filter ( id__in = cpriv_ids ) return qs class ControllerSlicePrivilege ( PlCoreBase ) : objects = ControllerLinkManager ( ) deleted_objects = ControllerLinkDeletionManager ( ) controller = models . ForeignKey ( '' , related_name = '' ) slice_privilege = models . ForeignKey ( '' , related_name = '' ) role_id = StrippedCharField ( null = True , blank = True , max_length = , db_index = True , help_text = \"\" ) class Meta : unique_together = ( '' , '' ) def __unicode__ ( self ) : return u'' % ( self . controller , self . slice_privilege ) def can_update ( self , user ) : if user . is_readonly : return False if user . is_admin : return True cprivs = ControllerSlicePrivilege . objects . filter ( slice_privilege__user = user ) for cpriv in dprivs : if cpriv . role . role == [ '' , '' ] : return True ", "answer": "return False"}, {"prompt": " \"\"\"\"\"\" from django . views import generic from openstack_dashboard import api from openstack_dashboard . api . rest import urls from openstack_dashboard . api . rest import utils as rest_utils @ urls . register class Networks ( generic . View ) : \"\"\"\"\"\" url_regex = r'' @ rest_utils . ajax ( ) def get ( self , request ) : \"\"\"\"\"\" tenant_id = request . user . tenant_id result = api . neutron . network_list_for_tenant ( request , tenant_id ) return { '' : [ n . to_dict ( ) for n in result ] } @ rest_utils . ajax ( data_required = True ) def post ( self , request ) : \"\"\"\"\"\" if not api . neutron . is_port_profiles_supported ( ) : request . DATA . pop ( \"\" , None ) new_network = api . neutron . network_create ( request , ** request . DATA ) return rest_utils . CreatedResponse ( ", "answer": "'' % new_network . id ,"}, {"prompt": " import unittest import uuid from random import shuffle from nose import SkipTest from swiftclient import get_auth , http_connection import test . functional as tf def setUpModule ( ) : tf . setup_package ( ) def tearDownModule ( ) : tf . teardown_package ( ) TEST_CASE_FORMAT = ( '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ) RBAC_PUT = [ ( '' , None , None , '' , None , None , None , '' , '' , None , ) , ( '' , None , None , '' , None , None , None , '' , '' , '' , ) , ( '' , None , None , '' , None , None , None , '' , '' , None , ) , ( '' , None , None , '' , None , None , None , '' , '' , None , ) , ( '' , None , None , '' , None , None , None , '' , '' , None , ) , ( '' , None , None , '' , None , None , None , '' , '' , None , ) , ( '' , None , None , '' , None , None , None , '' , '' , None , ) , ( '' , None , None , '' , None , None , None , '' , '' , None , ) , ( '' , None , None , '' , None , None , None , '' , '' , None , ) , ( '' , None , None , '' , None , None , None , '' , '' , None , ) , ( '' , None , None , '' , '' , None , None , '' , '' , None , ) , ( '' , None , None , '' , '' , None , None , '' , '' , '' , ) , ( '' , None , None , '' , '' , None , None , '' , '' , None , ) , ( '' , None , None , '' , '' , None , None , '' , '' , None , ) , ( '' , None , None , '' , '' , None , None , '' , '' , None , ) , ( '' , None , None , '' , '' , None , None , '' , '' , None , ) , ( '' , None , None , '' , '' , None , None , '' , '' , None , ) , ( '' , None , None , '' , '' , None , None , '' , '' , None , ) , ( '' , None , None , '' , '' , None , None , '' , '' , None , ) , ( '' , None , None , '' , '' , None , None , '' , '' , None , ) ] RBAC_PUT_WITH_SERVICE_PREFIX = [ ( '' , None , None , '' , None , None , None , '' , '' , '' , ) , ( '' , None , None , '' , None , None , None , '' , '' , '' , ) , ( '' , None , None , '' , None , None , None , '' , None , '' , ) , ( '' , None , None , '' , None , None , None , '' , '' , None , ) , ( '' , None , None , '' , None , None , None , '' , '' , None , ) , ( '' , None , None , '' , None , None , None , '' , '' , None , ) , ( '' , None , None , '' , '' , None , None , '' , '' , '' , ) , ( '' , None , None , '' , '' , None , None , '' , '' , '' , ) , ( '' , None , None , '' , '' , None , None , '' , None , '' , ) , ( '' , None , None , '' , '' , None , None , '' , '' , None , ) , ( '' , None , None , '' , '' , None , None , '' , '' , None , ) , ( '' , None , None , '' , '' , None , None , '' , '' , None , ) , ( '' , None , None , '' , None , None , '' , '' , '' , '' , ) , ( '' , None , None , '' , None , None , '' , '' , '' , '' , ) , ( '' , None , None , '' , None , None , '' , '' , '' , None , ) , ( '' , None , None , '' , None , None , '' , '' , '' , '' , ) , ( '' , None , None , '' , None , None , '' , '' , None , '' , ) , ( '' , None , None , '' , '' , None , '' , '' , '' , '' , ) , ( '' , None , None , '' , '' , None , '' , '' , '' , '' , ) , ( '' , None , None , '' , '' , None , '' , '' , '' , None , ) , ( '' , None , None , '' , '' , None , '' , '' , '' , '' , ) , ( '' , None , None , '' , '' , None , '' , '' , None , '' , ) , ] RBAC_DELETE = [ ( '' , None , None , '' , None , None , None , '' , '' , None , ) , ( '' , None , None , '' , None , None , None , '' , '' , '' , ) , ( '' , None , None , '' , None , None , None , '' , '' , None , ) , ", "answer": "( '' , None , None , '' , None , None ,"}, {"prompt": " \"\"\"\"\"\" ", "answer": "from smart . accesscontrol import security"}, {"prompt": " import sys sys . path . insert ( , \"\" ) import unittest import neuroml import neuroml . writers as writers import PyOpenWorm from PyOpenWorm import * import networkx import rdflib import rdflib as R import pint as Q import os import subprocess as SP import subprocess import tempfile ", "answer": "import doctest"}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import , division , print_function , with_statement import os import sys if __name__ == \"\" : if sys . path [ ] == os . path . dirname ( __file__ ) : del sys . path [ ] import functools import logging import os import pkgutil import sys import traceback import types import subprocess import weakref from tornado import ioloop from tornado . log import gen_log from tornado import process from tornado . util import exec_in try : import signal except ImportError : signal = None _has_execv = sys . platform != '' _watched_files = set ( ) _reload_hooks = [ ] _reload_attempted = False _io_loops = weakref . WeakKeyDictionary ( ) def start ( io_loop = None , check_time = ) : \"\"\"\"\"\" io_loop = io_loop or ioloop . IOLoop . current ( ) if io_loop in _io_loops : return _io_loops [ io_loop ] = True if len ( _io_loops ) > : gen_log . warning ( \"\" ) if _has_execv : add_reload_hook ( functools . partial ( io_loop . close , all_fds = True ) ) modify_times = { } callback = functools . partial ( _reload_on_update , modify_times ) scheduler = ioloop . PeriodicCallback ( callback , check_time , io_loop = io_loop ) scheduler . start ( ) def wait ( ) : \"\"\"\"\"\" io_loop = ioloop . IOLoop ( ) start ( io_loop ) io_loop . start ( ) def watch ( filename ) : \"\"\"\"\"\" _watched_files . add ( filename ) def add_reload_hook ( fn ) : \"\"\"\"\"\" _reload_hooks . append ( fn ) def _reload_on_update ( modify_times ) : if _reload_attempted : return if process . task_id ( ) is not None : return for module in list ( sys . modules . values ( ) ) : if not isinstance ( module , types . ModuleType ) : continue path = getattr ( module , \"\" , None ) if not path : continue if path . endswith ( \"\" ) or path . endswith ( \"\" ) : path = path [ : - ] _check_file ( modify_times , path ) for path in _watched_files : _check_file ( modify_times , path ) def _check_file ( modify_times , path ) : try : modified = os . stat ( path ) . st_mtime except Exception : return if path not in modify_times : modify_times [ path ] = modified return if modify_times [ path ] != modified : gen_log . info ( \"\" , path ) _reload ( ) def _reload ( ) : global _reload_attempted _reload_attempted = True for fn in _reload_hooks : fn ( ) if hasattr ( signal , \"\" ) : signal . setitimer ( signal . ITIMER_REAL , , ) path_prefix = '' + os . pathsep if ( sys . path [ ] == '' and not os . environ . get ( \"\" , \"\" ) . startswith ( path_prefix ) ) : os . environ [ \"\" ] = ( path_prefix + os . environ . get ( \"\" , \"\" ) ) if not _has_execv : subprocess . Popen ( [ sys . executable ] + sys . argv ) sys . exit ( ) else : try : os . execv ( sys . executable , [ sys . executable ] + sys . argv ) except OSError : os . spawnv ( os . P_NOWAIT , sys . executable , [ sys . executable ] + sys . argv ) os . _exit ( ) _USAGE = \"\"\"\"\"\" def main ( ) : \"\"\"\"\"\" original_argv = sys . argv sys . argv = sys . argv [ : ] if len ( sys . argv ) >= and sys . argv [ ] == \"\" : mode = \"\" module = sys . argv [ ] del sys . argv [ : ] elif len ( sys . argv ) >= : mode = \"\" script = sys . argv [ ] sys . argv = sys . argv [ : ] else : print ( _USAGE , file = sys . stderr ) sys . exit ( ) try : if mode == \"\" : import runpy runpy . run_module ( module , run_name = \"\" , alter_sys = True ) elif mode == \"\" : with open ( script ) as f : global __file__ __file__ = script global __package__ del __package__ exec_in ( f . read ( ) , globals ( ) , globals ( ) ) except SystemExit as e : logging . basicConfig ( ) gen_log . info ( \"\" , e . code ) except Exception as e : logging . basicConfig ( ) gen_log . warning ( \"\" , exc_info = True ) for ( filename , lineno , name , line ) in traceback . extract_tb ( sys . exc_info ( ) [ ] ) : watch ( filename ) if isinstance ( e , SyntaxError ) : watch ( e . filename ) ", "answer": "else :"}, {"prompt": " from setuptools import setup , find_packages import sys , os version = '' try : from mercurial import ui , hg , error repo = hg . repository ( ui . ui ( ) , \"\" ) ver = repo [ version ] except ImportError : pass except error . RepoLookupError : tip = repo [ \"\" ] version = version + \"\" % ( tip . rev ( ) , tip . hex ( ) [ : ] ) except error . RepoError : pass setup ( name = '' , version = version , description = \"\" , long_description = \"\"\"\"\"\" , classifiers = [ \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , ] , ", "answer": "keywords = \"\" ,"}, {"prompt": " from django . http import HttpResponse from django . views . generic import RedirectView from django . core . urlresolvers import reverse_lazy from django . contrib . auth . decorators import user_passes_test def empty_view ( request , * args , ** kwargs ) : return HttpResponse ( '' ) def kwargs_view ( request , arg1 = , arg2 = ) : return HttpResponse ( '' ) def absolute_kwargs_view ( request , arg1 = , arg2 = ) : return HttpResponse ( '' ) def defaults_view ( request , arg1 , arg2 ) : pass def erroneous_view ( request ) : import non_existent def pass_resolver_match_view ( request , * args , ** kwargs ) : response = HttpResponse ( '' ) response . resolver_match = request . resolver_match return response uncallable = \"\" class ViewClass ( object ) : def __call__ ( self , request , * args , ** kwargs ) : return HttpResponse ( '' ) ", "answer": "view_class_instance = ViewClass ( )"}, {"prompt": " from django import forms , template from users . fields import HoneyPotField register = template . Library ( ) @ register . filter def is_checkbox ( field ) : return isinstance ( field . field . widget , forms . CheckboxInput ) @ register . filter def input_class ( field ) : \"\"\"\"\"\" return field . field . widget . __class__ . __name__ . lower ( ) @ register . filter def is_honeypot ( field ) : ", "answer": "return isinstance ( field . field , HoneyPotField ) "}, {"prompt": " import sys ", "answer": "from . program import run"}, {"prompt": " \"\"\"\"\"\" import logging from tornado . web import asynchronous from sockjs . tornado import proto from sockjs . tornado . transports import pollingbase from sockjs . tornado . util import bytes_to_str LOG = logging . getLogger ( \"\" ) class XhrPollingTransport ( pollingbase . PollingTransportBase ) : \"\"\"\"\"\" name = '' @ asynchronous def post ( self , session_id ) : self . preflight ( ) self . handle_session_cookie ( ) self . disable_cache ( ) if not self . _attach_session ( session_id , False ) : return if not self . session : return if not self . session . send_queue : self . session . start_heartbeat ( ) else : self . session . flush ( ) def send_pack ( self , message , binary = False ) : if binary : raise Exception ( '' ) self . active = False try : self . set_header ( '' , '' ) self . set_header ( '' , len ( message ) + ) self . write ( message + '' ) self . flush ( callback = self . send_complete ) except IOError : self . session . delayed_close ( ) class XhrSendHandler ( pollingbase . PollingTransportBase ) : def post ( self , session_id ) : self . preflight ( ) self . handle_session_cookie ( ) self . disable_cache ( ) session = self . _get_session ( session_id ) if session is None or session . is_closed : self . set_status ( ) return data = self . request . body if not data : self . write ( \"\" ) self . set_status ( ) return try : messages = proto . json_decode ( bytes_to_str ( data ) ) except : self . write ( \"\" ) self . set_status ( ) return try : session . on_messages ( messages ) except Exception : ", "answer": "LOG . exception ( '' )"}, {"prompt": " \"\"\"\"\"\" from mockito . matchers import Matcher from pyherc . events import e_event_type ", "answer": "class EventType ( Matcher ) :"}, {"prompt": " from PyDSTool import * from common_lib import * thresh_ev = Events . makeZeroCrossEvent ( '' , , { '' : '' , ", "answer": "'' : ,"}, {"prompt": " '''''' ", "answer": "import os"}, {"prompt": " import os import re import sys import time import urllib import yaml from google . appengine . api import users APPSCALE_HOME = os . environ . get ( \"\" ) HADOOP_VER = \"\" HADOOP_HOME = APPSCALE_HOME + \"\" + HADOOP_VER + \"\" HADOOP_BIN = APPSCALE_HOME + \"\" + HADOOP_VER + \"\" HADOOP_STREAMING = HADOOP_HOME + \"\" + HADOOP_VER + \"\" DBS_W_HADOOP = [ \"\" , \"\" ] class MapReduceException ( Exception ) : \"\"\"\"\"\" pass \"\"\"\"\"\" def can_run_jobs ( ) : \"\"\"\"\"\" stream = file ( \"\" , '' ) contents = yaml . load ( stream ) try : database = contents [ '' ] if database in DBS_W_HADOOP : return True else : return False except KeyError : return False def get_lang ( filename ) : \"\"\"\"\"\" supportedExtensions = { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , } try : extension = filename . split ( \"\" ) [ - ] lang = supportedExtensions [ extension ] return lang except : raise MapReduceException ( \"\" % extension ) def ensure_user_is_mapreduce_authorized ( ) : \"\"\"\"\"\" if not users . is_current_user_capable ( \"\" ) : raise MapReduceException ( \"\" ) def write_temp_file ( suffix , data ) : \"\"\"\"\"\" ensure_user_is_mapreduce_authorized ( ) suffix = urllib . unquote ( suffix ) regex = r\"\" pattern = re . compile ( regex ) suffix = pattern . sub ( '' , suffix ) fileLoc = \"\" + suffix f = open ( fileLoc , \"\" ) f . write ( data ) f . close ( ) return fileLoc def get_all_ips ( ) : \"\"\"\"\"\" ensure_user_is_mapreduce_authorized ( ) all_ips = [ ] fileLoc = \"\" if os . path . exists ( fileLoc ) : f = open ( fileLoc ) text = f . read ( ) all_ips = text . split ( \"\" ) return all_ips def get_num_of_nodes ( ) : \"\"\"\"\"\" ensure_user_is_mapreduce_authorized ( ) num_of_nodes = fileLoc = \"\" if os . path . exists ( fileLoc ) : f = open ( fileLoc ) num_of_nodes = int ( f . read ( ) ) return num_of_nodes def put_mr_input ( data , inputLoc ) : \"\"\"\"\"\" ensure_user_is_mapreduce_authorized ( ) inputLoc = urllib . unquote ( inputLoc ) regex = r\"\" pattern = re . compile ( regex ) inputLoc = pattern . sub ( '' , inputLoc ) fileLoc = \"\" + inputLoc f = open ( fileLoc , \"\" ) f . write ( data ) ", "answer": "f . close ( )"}, {"prompt": " from io import BytesIO import pytest from tests . utils import Command from thefuck . rules . apt_invalid_operation import match , get_new_command , _get_operations invalid_operation = '' . format apt_help = b'''''' apt_operations = [ '' , '' , '' , '' , '' , '' , '' , '' , '' ] apt_get_help = b'''''' apt_get_operations = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ] @ pytest . mark . parametrize ( '' , [ ( '' , invalid_operation ( '' ) ) , ( '' , invalid_operation ( '' ) ) , ( '' , invalid_operation ( '' ) ) ] ) def test_match ( script , stderr ) : assert match ( Command ( script , stderr = stderr ) ) @ pytest . mark . parametrize ( '' , [ ( '' , invalid_operation ( '' ) ) , ( '' , \"\" ) ] ) def test_not_match ( script , stderr ) : assert not match ( Command ( script , stderr = stderr ) ) @ pytest . fixture def set_help ( mocker ) : mock = mocker . patch ( '' ) def _set_text ( text ) : mock . return_value . stdout = BytesIO ( text ) return _set_text @ pytest . mark . parametrize ( '' , [ ( '' , apt_help , apt_operations ) , ( '' , apt_get_help , apt_get_operations ) ] ) def test_get_operations ( set_help , app , help_text , operations ) : set_help ( help_text ) assert _get_operations ( app ) == operations @ pytest . mark . parametrize ( '' , [ ( '' , invalid_operation ( '' ) , apt_get_help , '' ) , ( '' , invalid_operation ( '' ) , apt_help , '' ) , ] ) ", "answer": "def test_get_new_command ( set_help , stderr , script , help_text , result ) :"}, {"prompt": " \"\"\"\"\"\" import setuptools import setup from setup import VERSION , DESCRIPTION , LICENSE , URL , AUTHOR , EMAIL , KEYWORDS , CLASSIFIERS ", "answer": "NAME = ''"}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import , division __all__ = [ '' , '' ] class _UserRecord ( object ) : \"\"\"\"\"\" def __init__ ( self , name , password , uid , gid , gecos , home , shell ) : self . pw_name = name self . pw_passwd = password self . pw_uid = uid self . pw_gid = gid self . pw_gecos = gecos self . pw_dir = home self . pw_shell = shell def __len__ ( self ) : return def __getitem__ ( self , index ) : return ( self . pw_name , self . pw_passwd , self . pw_uid , self . pw_gid , self . pw_gecos , self . pw_dir , self . pw_shell ) [ index ] class UserDatabase ( object ) : \"\"\"\"\"\" def __init__ ( self ) : self . _users = [ ] def addUser ( self , username , password , uid , gid , gecos , home , shell ) : \"\"\"\"\"\" self . _users . append ( _UserRecord ( username , password , uid , gid , gecos , home , shell ) ) def getpwuid ( self , uid ) : \"\"\"\"\"\" for entry in self . _users : if entry . pw_uid == uid : return entry raise KeyError ( ) def getpwnam ( self , name ) : \"\"\"\"\"\" for entry in self . _users : if entry . pw_name == name : return entry raise KeyError ( ) def getpwall ( self ) : \"\"\"\"\"\" return self . _users class _ShadowRecord ( object ) : \"\"\"\"\"\" def __init__ ( self , username , password , lastChange , min , max , warn , inact , expire , flag ) : self . sp_nam = username self . sp_pwd = password self . sp_lstchg = lastChange self . sp_min = min self . sp_max = max self . sp_warn = warn self . sp_inact = inact self . sp_expire = expire self . sp_flag = flag def __len__ ( self ) : return def __getitem__ ( self , index ) : return ( self . sp_nam , self . sp_pwd , self . sp_lstchg , self . sp_min , self . sp_max , self . sp_warn , self . sp_inact , self . sp_expire , self . sp_flag ) [ index ] class ShadowDatabase ( object ) : \"\"\"\"\"\" def __init__ ( self ) : self . _users = [ ] def addUser ( self , username , password , lastChange , min , max , warn , inact , expire , flag ) : \"\"\"\"\"\" self . _users . append ( _ShadowRecord ( username , password , lastChange , min , max , warn , inact , expire , flag ) ) def getspnam ( self , username ) : \"\"\"\"\"\" for entry in self . _users : if entry . sp_nam == username : ", "answer": "return entry"}, {"prompt": " \"\"\"\"\"\" import logging import config import docs import models from google . appengine . ext . deferred import defer from google . appengine . ext import ndb def intClamp ( v , low , high ) : \"\"\"\"\"\" return max ( int ( low ) , min ( int ( v ) , int ( high ) ) ) def updateAverageRating ( review_key ) : \"\"\"\"\"\" ", "answer": "def _tx ( ) :"}, {"prompt": " import threading from training_protocols . ITrainingProtocol import ITrainingProtocol class DuelingTree ( ITrainingProtocol ) : def __init__ ( self , main_window , protocol_operations , targets ) : self . _operations = protocol_operations self . _operations . reset ( ) self . _continue_protocol = True self . _protocol_is_resetting = False self . _left_score = self . _right_score = self . _targets_on_left = [ ] self . _targets_on_right = [ ] self . _wait_event = threading . Event ( ) if self . _find_targets ( targets ) : self . _operations . add_shot_list_columns ( ( \"\" , ) , [ ] ) def _find_targets ( self , targets ) : found_target = False for target in targets : if found_target : break for region in target [ \"\" ] : if \"\" in region : if region [ \"\" ] . startswith ( \"\" ) : self . _targets_on_left . append ( region [ \"\" ] ) found_target = True elif region [ \"\" ] . startswith ( \"\" ) : self . _targets_on_right . append ( region [ \"\" ] ) found_target = True if not found_target : self . _operations . say ( \"\" ) else : self . _operations . show_text_on_feed ( \"\" ) return found_target def shot_listener ( self , shot , shot_list_item , is_hit ) : return def hit_listener ( self , region , tags , shot , shot_list_item ) : if \"\" in tags : if ( tags [ \"\" ] . startswith ( \"\" ) or tags [ \"\" ] . startswith ( \"\" ) ) : if tags [ \"\" ] in self . _targets_on_left : self . _targets_on_left . remove ( tags [ \"\" ] ) self . _targets_on_right . append ( tags [ \"\" ] ) hit_by = \"\" elif tags [ \"\" ] in self . _targets_on_right : self . _targets_on_left . append ( tags [ \"\" ] ) self . _targets_on_right . remove ( tags [ \"\" ] ) hit_by = \"\" self . _operations . append_shot_item_values ( shot_list_item , ( hit_by , ) ) if ( len ( self . _targets_on_right ) == ) : self . _left_score += self . _round_over ( ) if ( len ( self . _targets_on_left ) == ) : self . _right_score += self . _round_over ( ) def _round_over ( self ) : message = \"\" % ( self . _left_score , self . _right_score ) ", "answer": "self . _operations . show_text_on_feed ( message )"}, {"prompt": " import pypandoc with open ( '' , '' ) as f : ", "answer": "f . write ( pypandoc . convert ( '' , '' ) . encode ( '' ) ) "}, {"prompt": " from collections import defaultdict ", "answer": "from sekizai . data import UniqueSequence"}, {"prompt": " def test_function ( ) : ", "answer": "pass"}, {"prompt": " \"\"\"\"\"\" import traceback from twisted . trial import unittest from twisted . internet import error , defer from twisted . test . proto_helpers import StringTransport from twisted . conch . test . test_recvline import ( _TelnetMixin , _SSHMixin , _StdioMixin , stdio , ssh ) from twisted . conch import manhole from twisted . conch . insults import insults def determineDefaultFunctionName ( ) : \"\"\"\"\"\" try : // except : return traceback . extract_stack ( ) [ - ] [ ] defaultFunctionName = determineDefaultFunctionName ( ) class ManholeInterpreterTests ( unittest . TestCase ) : \"\"\"\"\"\" def test_resetBuffer ( self ) : \"\"\"\"\"\" interpreter = manhole . ManholeInterpreter ( None ) interpreter . buffer . extend ( [ \"\" , \"\" ] ) interpreter . resetBuffer ( ) self . assertFalse ( interpreter . buffer ) class ManholeProtocolTests ( unittest . TestCase ) : \"\"\"\"\"\" def test_interruptResetsInterpreterBuffer ( self ) : \"\"\"\"\"\" transport = StringTransport ( ) terminal = insults . ServerProtocol ( manhole . Manhole ) terminal . makeConnection ( transport ) protocol = terminal . terminalProtocol interpreter = protocol . interpreter interpreter . buffer . extend ( [ \"\" , \"\" ] ) ", "answer": "protocol . handle_INT ( )"}, {"prompt": " '''''' __version_info__ = ( '' , '' , '' ) __version__ = '' . join ( __version_info__ ) __author__ = '' __license__ = '' __copyright__ = '' __all__ = [ '' ] from flask import ( _request_ctx_stack , abort , current_app , flash , redirect , request , session , url_for ) from flask . signals import Namespace from werkzeug . local import LocalProxy from werkzeug . security import safe_str_cmp from werkzeug . urls import url_decode , url_encode from datetime import datetime , timedelta from functools import wraps from hashlib import sha1 , md5 import hmac import warnings import sys if sys . version < '' : from urlparse import urlparse , urlunparse else : from urllib . parse import urlparse , urlunparse unicode = str _signals = Namespace ( ) current_user = LocalProxy ( lambda : _get_user ( ) or current_app . login_manager . anonymous_user ( ) ) COOKIE_NAME = '' COOKIE_DURATION = timedelta ( days = ) COOKIE_SECURE = None COOKIE_HTTPONLY = False LOGIN_MESSAGE = u'' LOGIN_MESSAGE_CATEGORY = '' REFRESH_MESSAGE = u'' REFRESH_MESSAGE_CATEGORY = '' class LoginManager ( object ) : '''''' def __init__ ( self , app = None , add_context_processor = True ) : self . anonymous_user = AnonymousUserMixin self . login_view = None self . login_message = LOGIN_MESSAGE self . login_message_category = LOGIN_MESSAGE_CATEGORY self . refresh_view = None self . needs_refresh_message = REFRESH_MESSAGE self . needs_refresh_message_category = REFRESH_MESSAGE_CATEGORY self . session_protection = '' self . token_callback = None self . user_callback = None self . unauthorized_callback = None self . needs_refresh_callback = None if app is not None : self . init_app ( app , add_context_processor ) def setup_app ( self , app , add_context_processor = True ) : '''''' warnings . warn ( '' , DeprecationWarning ) self . init_app ( app , add_context_processor ) def init_app ( self , app , add_context_processor = True ) : '''''' app . login_manager = self app . before_request ( self . _load_user ) app . after_request ( self . _update_remember_cookie ) self . _login_disabled = app . config . get ( '' , app . config . get ( '' , False ) ) if add_context_processor : app . context_processor ( _user_context_processor ) def unauthorized ( self ) : '''''' user_unauthorized . send ( current_app . _get_current_object ( ) ) if self . unauthorized_callback : return self . unauthorized_callback ( ) if not self . login_view : abort ( ) if self . login_message : flash ( self . login_message , category = self . login_message_category ) return redirect ( login_url ( self . login_view , request . url ) ) def user_loader ( self , callback ) : '''''' self . user_callback = callback return callback def token_loader ( self , callback ) : '''''' self . token_callback = callback return callback def unauthorized_handler ( self , callback ) : '''''' self . unauthorized_callback = callback return callback def needs_refresh_handler ( self , callback ) : '''''' self . needs_refresh_callback = callback return callback def needs_refresh ( self ) : '''''' user_needs_refresh . send ( current_app . _get_current_object ( ) ) if self . needs_refresh_callback : return self . needs_refresh_callback ( ) if not self . refresh_view : abort ( ) flash ( self . needs_refresh_message , category = self . needs_refresh_message_category ) return redirect ( login_url ( self . refresh_view , request . url ) ) def reload_user ( self ) : ctx = _request_ctx_stack . top user_id = session . get ( '' ) if user_id is None : ctx . user = self . anonymous_user ( ) else : user = self . user_callback ( user_id ) if user is None : logout_user ( ) else : ctx . user = user def _load_user ( self ) : config = current_app . config if config . get ( '' , self . session_protection ) : deleted = self . _session_protection ( ) if deleted : self . reload_user ( ) return cookie_name = config . get ( '' , COOKIE_NAME ) if cookie_name in request . cookies and '' not in session : return self . _load_from_cookie ( request . cookies [ cookie_name ] ) return self . reload_user ( ) def _session_protection ( self ) : sess = session . _get_current_object ( ) ident = _create_identifier ( ) if '' not in sess : sess [ '' ] = ident elif ident != sess [ '' ] : app = current_app . _get_current_object ( ) mode = app . config . get ( '' , self . session_protection ) if mode == '' or sess . permanent : sess [ '' ] = False session_protected . send ( app ) return False elif mode == '' : sess . clear ( ) sess [ '' ] = '' session_protected . send ( app ) return True return False def _load_from_cookie ( self , cookie ) : if self . token_callback : user = self . token_callback ( cookie ) if user is not None : session [ '' ] = user . get_id ( ) session [ '' ] = False _request_ctx_stack . top . user = user else : self . reload_user ( ) else : user_id = decode_cookie ( cookie ) if user_id is not None : session [ '' ] = user_id session [ '' ] = False self . reload_user ( ) app = current_app . _get_current_object ( ) user_loaded_from_cookie . send ( app , user = _get_user ( ) ) def _update_remember_cookie ( self , response ) : if '' in session : operation = session . pop ( '' , None ) if operation == '' and '' in session : self . _set_cookie ( response ) elif operation == '' : self . _clear_cookie ( response ) return response def _set_cookie ( self , response ) : config = current_app . config cookie_name = config . get ( '' , COOKIE_NAME ) duration = config . get ( '' , COOKIE_DURATION ) domain = config . get ( '' ) secure = config . get ( '' , COOKIE_SECURE ) httponly = config . get ( '' , COOKIE_HTTPONLY ) if self . token_callback : data = current_user . get_auth_token ( ) else : data = encode_cookie ( str ( session [ '' ] ) ) expires = datetime . utcnow ( ) + duration response . set_cookie ( cookie_name , value = data , expires = expires , domain = domain , secure = secure , httponly = httponly ) def _clear_cookie ( self , response ) : config = current_app . config cookie_name = config . get ( '' , COOKIE_NAME ) domain = config . get ( '' ) response . delete_cookie ( cookie_name , domain = domain ) class UserMixin ( object ) : '''''' def is_active ( self ) : return True def is_authenticated ( self ) : return True def is_anonymous ( self ) : return False def get_id ( self ) : try : return unicode ( self . id ) except AttributeError : raise NotImplementedError ( '' ) def __eq__ ( self , other ) : '''''' if isinstance ( other , UserMixin ) : return self . get_id ( ) == other . get_id ( ) return NotImplemented def __ne__ ( self , other ) : '''''' equal = self . __eq__ ( other ) if equal is NotImplemented : return NotImplemented return not equal class AnonymousUserMixin ( object ) : '''''' def is_authenticated ( self ) : return False def is_active ( self ) : return False def is_anonymous ( self ) : return True ", "answer": "def get_id ( self ) :"}, {"prompt": " from . . import NextGenInstanceResource , NextGenListResource class IpAccessControlList ( NextGenInstanceResource ) : \"\"\"\"\"\" def delete ( self ) : \"\"\"\"\"\" return self . parent . delete_instance ( self . name ) class IpAccessControlLists ( NextGenListResource ) : \"\"\"\"\"\" name = \"\" instance = IpAccessControlList key = \"\" def list ( self , ** kwargs ) : \"\"\"\"\"\" return super ( IpAccessControlLists , self ) . list ( ** kwargs ) def create ( self , ip_access_control_list_sid ) : \"\"\"\"\"\" data = { ", "answer": "'' : ip_access_control_list_sid"}, {"prompt": " \"\"\"\"\"\" from pypy . interpreter . astcompiler import ast , assemble , symtable , consts , misc from pypy . interpreter . astcompiler import optimize from pypy . interpreter . pyparser . error import SyntaxError from pypy . tool import stdlib_opcode as ops from pypy . interpreter . pyparser import future from pypy . interpreter . error import OperationError from pypy . module . __builtin__ . __init__ import BUILTIN_TO_INDEX def compile_ast ( space , module , info ) : \"\"\"\"\"\" symbols = symtable . SymtableBuilder ( space , module , info ) return TopLevelCodeGenerator ( space , module , symbols , info ) . assemble ( ) name_ops_default = misc . dict_to_switch ( { ast . Load : ops . LOAD_NAME , ast . Store : ops . STORE_NAME , ast . Del : ops . DELETE_NAME } ) name_ops_fast = misc . dict_to_switch ( { ast . Load : ops . LOAD_FAST , ast . Store : ops . STORE_FAST , ast . Del : ops . DELETE_FAST } ) name_ops_deref = misc . dict_to_switch ( { ast . Load : ops . LOAD_DEREF , ast . Store : ops . STORE_DEREF , } ) name_ops_global = misc . dict_to_switch ( { ast . Load : ops . LOAD_GLOBAL , ast . Store : ops . STORE_GLOBAL , ast . Del : ops . DELETE_GLOBAL } ) unary_operations = misc . dict_to_switch ( { ast . Invert : ops . UNARY_INVERT , ast . Not : ops . UNARY_NOT , ast . UAdd : ops . UNARY_POSITIVE , ast . USub : ops . UNARY_NEGATIVE } ) binary_operations = misc . dict_to_switch ( { ast . Add : ops . BINARY_ADD , ast . Sub : ops . BINARY_SUBTRACT , ast . Mult : ops . BINARY_MULTIPLY , ast . Mod : ops . BINARY_MODULO , ast . Pow : ops . BINARY_POWER , ast . LShift : ops . BINARY_LSHIFT , ast . RShift : ops . BINARY_RSHIFT , ast . BitOr : ops . BINARY_OR , ast . BitAnd : ops . BINARY_AND , ast . BitXor : ops . BINARY_XOR , ast . FloorDiv : ops . BINARY_FLOOR_DIVIDE } ) inplace_operations = misc . dict_to_switch ( { ast . Add : ops . INPLACE_ADD , ast . Sub : ops . INPLACE_SUBTRACT , ast . Mult : ops . INPLACE_MULTIPLY , ast . Mod : ops . INPLACE_MODULO , ast . Pow : ops . INPLACE_POWER , ast . LShift : ops . INPLACE_LSHIFT , ast . RShift : ops . INPLACE_RSHIFT , ast . BitOr : ops . INPLACE_OR , ast . BitAnd : ops . INPLACE_AND , ast . BitXor : ops . INPLACE_XOR , ast . FloorDiv : ops . INPLACE_FLOOR_DIVIDE } ) compare_operations = misc . dict_to_switch ( { ast . Eq : , ast . NotEq : , ast . Lt : , ast . LtE : , ast . Gt : , ast . GtE : , ast . In : , ast . NotIn : , ast . Is : , ast . IsNot : } ) subscr_operations = misc . dict_to_switch ( { ast . AugLoad : ops . BINARY_SUBSCR , ast . Load : ops . BINARY_SUBSCR , ast . AugStore : ops . STORE_SUBSCR , ast . Store : ops . STORE_SUBSCR , ast . Del : ops . DELETE_SUBSCR } ) slice_operations = misc . dict_to_switch ( { ast . AugLoad : ops . SLICE , ast . Load : ops . SLICE , ast . AugStore : ops . STORE_SLICE , ast . Store : ops . STORE_SLICE , ast . Del : ops . DELETE_SLICE } ) F_BLOCK_LOOP = F_BLOCK_EXCEPT = F_BLOCK_FINALLY = F_BLOCK_FINALLY_END = class PythonCodeGenerator ( assemble . PythonCodeMaker ) : \"\"\"\"\"\" def __init__ ( self , space , name , tree , lineno , symbols , compile_info ) : self . scope = symbols . find_scope ( tree ) assemble . PythonCodeMaker . __init__ ( self , space , name , lineno , self . scope , compile_info ) self . symbols = symbols self . frame_blocks = [ ] self . interactive = False self . temporary_name_counter = self . _compile ( tree ) def _compile ( self , tree ) : \"\"\"\"\"\" raise NotImplementedError def current_temporary_name ( self ) : \"\"\"\"\"\" name = \"\" % ( self . temporary_name_counter , ) self . temporary_name_counter += assert self . scope . lookup ( name ) != symtable . SCOPE_UNKNOWN return name def sub_scope ( self , kind , name , node , lineno ) : \"\"\"\"\"\" generator = kind ( self . space , name , node , lineno , self . symbols , self . compile_info ) return generator . assemble ( ) def push_frame_block ( self , kind , block ) : self . frame_blocks . append ( ( kind , block ) ) def pop_frame_block ( self , kind , block ) : actual_kind , old_block = self . frame_blocks . pop ( ) assert actual_kind == kind and old_block is block , \"\" def error ( self , msg , node ) : raise SyntaxError ( msg , node . lineno , node . col_offset , filename = self . compile_info . filename ) def name_op ( self , identifier , ctx ) : \"\"\"\"\"\" scope = self . scope . lookup ( identifier ) op = ops . NOP container = self . names if scope == symtable . SCOPE_LOCAL : if self . scope . can_be_optimized : container = self . var_names op = name_ops_fast ( ctx ) elif scope == symtable . SCOPE_FREE : op = name_ops_deref ( ctx ) container = self . free_vars elif scope == symtable . SCOPE_CELL : try : op = name_ops_deref ( ctx ) except KeyError : assert ctx == ast . Del raise SyntaxError ( \"\" \"\" % ( identifier , ) ) container = self . cell_vars elif scope == symtable . SCOPE_GLOBAL_IMPLICIT : if self . scope . locals_fully_known : op = name_ops_global ( ctx ) elif scope == symtable . SCOPE_GLOBAL_EXPLICIT : op = name_ops_global ( ctx ) if op == ops . NOP : op = name_ops_default ( ctx ) self . emit_op_arg ( op , self . add_name ( container , identifier ) ) def is_docstring ( self , node ) : return isinstance ( node , ast . Expr ) and isinstance ( node . value , ast . Str ) def _get_code_flags ( self ) : return consts . CO_NEWLOCALS def _handle_body ( self , body ) : \"\"\"\"\"\" if body : start = if self . is_docstring ( body [ ] ) : doc_expr = body [ ] assert isinstance ( doc_expr , ast . Expr ) start = doc_expr . value . walkabout ( self ) self . name_op ( \"\" , ast . Store ) for i in range ( start , len ( body ) ) : body [ i ] . walkabout ( self ) return True else : return False def visit_Module ( self , mod ) : if not self . _handle_body ( mod . body ) : self . first_lineno = self . lineno = def visit_Interactive ( self , mod ) : self . interactive = True self . visit_sequence ( mod . body ) def visit_Expression ( self , mod ) : self . add_none_to_final_return = False mod . body . walkabout ( self ) def _make_function ( self , code , num_defaults = ) : \"\"\"\"\"\" code_index = self . add_const ( code ) if code . co_freevars : for free in code . co_freevars : free_scope = self . scope . lookup ( free ) if free_scope == symtable . SCOPE_CELL : index = self . cell_vars [ free ] else : index = self . free_vars [ free ] self . emit_op_arg ( ops . LOAD_CLOSURE , index ) self . emit_op_arg ( ops . BUILD_TUPLE , len ( code . co_freevars ) ) self . emit_op_arg ( ops . LOAD_CONST , code_index ) self . emit_op_arg ( ops . MAKE_CLOSURE , num_defaults ) else : self . emit_op_arg ( ops . LOAD_CONST , code_index ) self . emit_op_arg ( ops . MAKE_FUNCTION , num_defaults ) def visit_FunctionDef ( self , func ) : self . update_position ( func . lineno , True ) if func . decorators : self . visit_sequence ( func . decorators ) if func . args . defaults : self . visit_sequence ( func . args . defaults ) num_defaults = len ( func . args . defaults ) else : num_defaults = code = self . sub_scope ( FunctionCodeGenerator , func . name , func , func . lineno ) self . _make_function ( code , num_defaults ) if func . decorators : for i in range ( len ( func . decorators ) ) : self . emit_op_arg ( ops . CALL_FUNCTION , ) self . name_op ( func . name , ast . Store ) def visit_Lambda ( self , lam ) : self . update_position ( lam . lineno ) if lam . args . defaults : self . visit_sequence ( lam . args . defaults ) default_count = len ( lam . args . defaults ) else : default_count = code = self . sub_scope ( LambdaCodeGenerator , \"\" , lam , lam . lineno ) self . _make_function ( code , default_count ) def visit_ClassDef ( self , cls ) : self . update_position ( cls . lineno , True ) self . load_const ( self . space . wrap ( cls . name ) ) if cls . bases : bases_count = len ( cls . bases ) self . visit_sequence ( cls . bases ) else : bases_count = self . emit_op_arg ( ops . BUILD_TUPLE , bases_count ) code = self . sub_scope ( ClassCodeGenerator , cls . name , cls , cls . lineno ) self . _make_function ( code , ) self . emit_op_arg ( ops . CALL_FUNCTION , ) self . emit_op ( ops . BUILD_CLASS ) self . name_op ( cls . name , ast . Store ) def _op_for_augassign ( self , op ) : if op == ast . Div : if self . compile_info . flags & consts . CO_FUTURE_DIVISION : return ops . INPLACE_TRUE_DIVIDE else : return ops . INPLACE_DIVIDE return inplace_operations ( op ) def visit_AugAssign ( self , assign ) : self . update_position ( assign . lineno , True ) target = assign . target if isinstance ( target , ast . Attribute ) : attr = ast . Attribute ( target . value , target . attr , ast . AugLoad , target . lineno , target . col_offset ) attr . walkabout ( self ) assign . value . walkabout ( self ) self . emit_op ( self . _op_for_augassign ( assign . op ) ) attr . ctx = ast . AugStore attr . walkabout ( self ) elif isinstance ( target , ast . Subscript ) : sub = ast . Subscript ( target . value , target . slice , ast . AugLoad , target . lineno , target . col_offset ) sub . walkabout ( self ) assign . value . walkabout ( self ) self . emit_op ( self . _op_for_augassign ( assign . op ) ) sub . ctx = ast . AugStore sub . walkabout ( self ) elif isinstance ( target , ast . Name ) : self . name_op ( target . id , ast . Load ) assign . value . walkabout ( self ) self . emit_op ( self . _op_for_augassign ( assign . op ) ) self . name_op ( target . id , ast . Store ) else : raise AssertionError ( \"\" ) def visit_Assert ( self , asrt ) : self . update_position ( asrt . lineno ) end = self . new_block ( ) asrt . test . accept_jump_if ( self , True , end ) self . emit_op ( ops . POP_TOP ) self . emit_op_name ( ops . LOAD_GLOBAL , self . names , \"\" ) if asrt . msg : asrt . msg . walkabout ( self ) self . emit_op_arg ( ops . RAISE_VARARGS , ) else : self . emit_op_arg ( ops . RAISE_VARARGS , ) self . use_next_block ( end ) self . emit_op ( ops . POP_TOP ) def _binop ( self , op ) : if op == ast . Div : if self . compile_info . flags & consts . CO_FUTURE_DIVISION : return ops . BINARY_TRUE_DIVIDE else : return ops . BINARY_DIVIDE return binary_operations ( op ) def visit_BinOp ( self , binop ) : self . update_position ( binop . lineno ) binop . left . walkabout ( self ) binop . right . walkabout ( self ) self . emit_op ( self . _binop ( binop . op ) ) def visit_Return ( self , ret ) : self . update_position ( ret . lineno , True ) if ret . value : ret . value . walkabout ( self ) else : self . load_const ( self . space . w_None ) self . emit_op ( ops . RETURN_VALUE ) def visit_Print ( self , pr ) : self . update_position ( pr . lineno , True ) have_dest = bool ( pr . dest ) if have_dest : pr . dest . walkabout ( self ) if pr . values : for value in pr . values : if have_dest : self . emit_op ( ops . DUP_TOP ) value . walkabout ( self ) self . emit_op ( ops . ROT_TWO ) self . emit_op ( ops . PRINT_ITEM_TO ) else : value . walkabout ( self ) self . emit_op ( ops . PRINT_ITEM ) if pr . nl : if have_dest : self . emit_op ( ops . PRINT_NEWLINE_TO ) else : self . emit_op ( ops . PRINT_NEWLINE ) elif have_dest : self . emit_op ( ops . POP_TOP ) def visit_Delete ( self , delete ) : self . update_position ( delete . lineno , True ) self . visit_sequence ( delete . targets ) def visit_If ( self , if_ ) : self . update_position ( if_ . lineno , True ) end = self . new_block ( ) test_constant = if_ . test . as_constant_truth ( self . space ) if test_constant == optimize . CONST_FALSE : if if_ . orelse : self . visit_sequence ( if_ . orelse ) elif test_constant == optimize . CONST_TRUE : self . visit_sequence ( if_ . body ) else : next = self . new_block ( ) if_ . test . accept_jump_if ( self , False , next ) self . emit_op ( ops . POP_TOP ) self . visit_sequence ( if_ . body ) self . emit_jump ( ops . JUMP_FORWARD , end ) self . use_next_block ( next ) self . emit_op ( ops . POP_TOP ) if if_ . orelse : self . visit_sequence ( if_ . orelse ) self . use_next_block ( end ) def visit_Break ( self , br ) : self . update_position ( br . lineno , True ) for f_block in self . frame_blocks : if f_block [ ] == F_BLOCK_LOOP : break else : self . error ( \"\" , br ) self . emit_op ( ops . BREAK_LOOP ) def visit_Continue ( self , cont ) : self . update_position ( cont . lineno , True ) if not self . frame_blocks : self . error ( \"\" , cont ) current_block , block = self . frame_blocks [ - ] if current_block == F_BLOCK_LOOP : self . emit_jump ( ops . JUMP_ABSOLUTE , block , True ) elif current_block == F_BLOCK_EXCEPT or current_block == F_BLOCK_FINALLY : for i in range ( len ( self . frame_blocks ) - , - , - ) : f_type , block = self . frame_blocks [ i ] if f_type == F_BLOCK_LOOP : self . emit_jump ( ops . CONTINUE_LOOP , block , True ) break if self . frame_blocks [ i ] [ ] == F_BLOCK_FINALLY_END : self . error ( \"\" \"\" , cont ) else : self . error ( \"\" , cont ) elif current_block == F_BLOCK_FINALLY_END : self . error ( \"\" , cont ) def visit_For ( self , fr ) : self . update_position ( fr . lineno , True ) start = self . new_block ( ) cleanup = self . new_block ( ) end = self . new_block ( ) self . emit_jump ( ops . SETUP_LOOP , end ) self . push_frame_block ( F_BLOCK_LOOP , start ) fr . iter . walkabout ( self ) self . emit_op ( ops . GET_ITER ) self . use_next_block ( start ) self . lineno_set = False self . emit_jump ( ops . FOR_ITER , cleanup ) fr . target . walkabout ( self ) self . visit_sequence ( fr . body ) self . emit_jump ( ops . JUMP_ABSOLUTE , start , True ) self . use_next_block ( cleanup ) self . emit_op ( ops . POP_BLOCK ) self . pop_frame_block ( F_BLOCK_LOOP , start ) if fr . orelse : self . visit_sequence ( fr . orelse ) self . use_next_block ( end ) def visit_While ( self , wh ) : self . update_position ( wh . lineno , True ) test_constant = wh . test . as_constant_truth ( self . space ) if test_constant == optimize . CONST_FALSE : if wh . orelse : self . visit_sequence ( wh . orelse ) else : end = self . new_block ( ) anchor = None if test_constant == optimize . CONST_NOT_CONST : anchor = self . new_block ( ) self . emit_jump ( ops . SETUP_LOOP , end ) loop = self . new_block ( ) self . push_frame_block ( F_BLOCK_LOOP , loop ) self . use_next_block ( loop ) if test_constant == optimize . CONST_NOT_CONST : self . lineno_set = False wh . test . accept_jump_if ( self , False , anchor ) self . emit_op ( ops . POP_TOP ) self . visit_sequence ( wh . body ) self . emit_jump ( ops . JUMP_ABSOLUTE , loop , True ) if test_constant == optimize . CONST_NOT_CONST : self . use_next_block ( anchor ) self . emit_op ( ops . POP_TOP ) self . emit_op ( ops . POP_BLOCK ) self . pop_frame_block ( F_BLOCK_LOOP , loop ) if wh . orelse : self . visit_sequence ( wh . orelse ) self . use_next_block ( end ) def visit_TryExcept ( self , te ) : self . update_position ( te . lineno , True ) exc = self . new_block ( ) otherwise = self . new_block ( ) end = self . new_block ( ) self . emit_jump ( ops . SETUP_EXCEPT , exc ) body = self . use_next_block ( ) self . push_frame_block ( F_BLOCK_EXCEPT , body ) self . visit_sequence ( te . body ) self . emit_op ( ops . POP_BLOCK ) self . pop_frame_block ( F_BLOCK_EXCEPT , body ) self . emit_jump ( ops . JUMP_FORWARD , otherwise ) self . use_next_block ( exc ) for handler in te . handlers : assert isinstance ( handler , ast . excepthandler ) self . update_position ( handler . lineno , True ) next_except = self . new_block ( ) if handler . type : self . emit_op ( ops . DUP_TOP ) handler . type . walkabout ( self ) self . emit_op_arg ( ops . COMPARE_OP , ) self . emit_jump ( ops . JUMP_IF_FALSE , next_except ) self . emit_op ( ops . POP_TOP ) self . emit_op ( ops . POP_TOP ) if handler . name : handler . name . walkabout ( self ) else : self . emit_op ( ops . POP_TOP ) self . emit_op ( ops . POP_TOP ) self . visit_sequence ( handler . body ) self . emit_jump ( ops . JUMP_FORWARD , end ) self . use_next_block ( next_except ) if handler . type : self . emit_op ( ops . POP_TOP ) self . emit_op ( ops . END_FINALLY ) self . use_next_block ( otherwise ) if te . orelse : self . visit_sequence ( te . orelse ) self . use_next_block ( end ) def visit_TryFinally ( self , tf ) : self . update_position ( tf . lineno , True ) end = self . new_block ( ) self . emit_jump ( ops . SETUP_FINALLY , end ) body = self . use_next_block ( ) self . push_frame_block ( F_BLOCK_FINALLY , body ) self . visit_sequence ( tf . body ) self . emit_op ( ops . POP_BLOCK ) self . pop_frame_block ( F_BLOCK_FINALLY , body ) self . load_const ( self . space . w_None ) self . use_next_block ( end ) self . push_frame_block ( F_BLOCK_FINALLY_END , end ) self . visit_sequence ( tf . finalbody ) self . emit_op ( ops . END_FINALLY ) self . pop_frame_block ( F_BLOCK_FINALLY_END , end ) def _import_as ( self , alias ) : source_name = alias . name dot = source_name . find ( \"\" ) if dot > : while True : start = dot + dot = source_name . find ( \"\" , start ) if dot < : end = len ( source_name ) else : end = dot attr = source_name [ start : end ] self . emit_op_name ( ops . LOAD_ATTR , self . names , attr ) if dot < : break self . name_op ( alias . asname , ast . Store ) def visit_Import ( self , imp ) : self . update_position ( imp . lineno , True ) for alias in imp . names : assert isinstance ( alias , ast . alias ) if self . compile_info . flags & consts . CO_FUTURE_ABSOLUTE_IMPORT : level = else : level = - self . load_const ( self . space . wrap ( level ) ) self . load_const ( self . space . w_None ) self . emit_op_name ( ops . IMPORT_NAME , self . names , alias . name ) if alias . asname : self . _import_as ( alias ) else : dot = alias . name . find ( \"\" ) ", "answer": "if dot < :"}, {"prompt": " import os . path import unittest from resources . setting_utils import TestSettingsHelper ", "answer": "from robotide . preferences . settings import SettingsMigrator"}, {"prompt": " import sys import tempfile import numpy as np import zlib import cStringIO from PIL import Image import pylibmc import time import restargs import ocpcadb import ocpcaproj import ocpcarest import django import posix_ipc import re from ocpca_cy import recolor_cy import logging logger = logging . getLogger ( \"\" ) class ColorCatmaid : \"\"\"\"\"\" def __init__ ( self ) : \"\"\"\"\"\" self . db = None self . mc = pylibmc . Client ( [ \"\" ] , binary = True , behaviors = { \"\" : True , \"\" : True } ) def __del__ ( self ) : pass def loadDB ( self ) : \"\"\"\"\"\" if self . db == None : [ self . db , self . proj , self . projdb ] = ocpcarest . loadDBProj ( self . token ) def buildKey ( self , res , xtile , ytile , zslice , color , brightness ) : return '' . format ( self . token , self . tilesz , self . channel , res , xtile , ytile , zslice , color , brightness ) def falseColor ( self , tile , color ) : \"\"\"\"\"\" data32 = np . uint32 ( tile ) if color == '' or color == '' : fcdata = + np . left_shift ( data32 , ) + np . left_shift ( data32 , ) elif color == '' or color == '' : fcdata = + np . left_shift ( data32 , ) + data32 elif color == '' or color == '' : fcdata = + np . left_shift ( data32 , ) + data32 if color == '' or color == '' : fcdata = + data32 elif color == '' or color == '' : fcdata = + np . left_shift ( data32 , ) elif color == '' or color == '' : fcdata = + np . left_shift ( data32 , ) return fcdata def tile2WebPNG ( self , tile , color , brightness ) : \"\"\"\"\"\" if tile . dtype == np . uint16 : tile = np . uint8 ( tile / ) if tile . dtype != np . uint8 : raise ( \"\" % ( tile . dtype ) ) else : tile = self . falseColor ( tile , color ) img = Image . frombuffer ( '' , [ self . tilesz , self . tilesz ] , tile . flatten ( ) , '' , '' , , ) if brightness != None : from PIL import ImageEnhance enhancer = ImageEnhance . Brightness ( img ) img = enhancer . enhance ( brightness ) return img def cacheMiss ( self , res , xtile , ytile , zslice , color , brightness ) : \"\"\"\"\"\" self . loadDB ( ) if self . tilesz % self . proj . datasetcfg . cubedim [ res ] [ ] != or self . tilesz % self . proj . datasetcfg . cubedim [ res ] [ ] : raise ( \"\" ) xstart = xtile * self . tilesz ystart = ytile * self . tilesz xend = min ( ( xtile + ) * self . tilesz , self . proj . datasetcfg . imagesz [ res ] [ ] ) yend = min ( ( ytile + ) * self . tilesz , self . proj . datasetcfg . imagesz [ res ] [ ] ) imageargs = '' . format ( self . channel , res , xstart , xend , ystart , yend , zslice ) cb = ocpcarest . xySlice ( imageargs , self . proj , self . db ) if cb . data . shape != ( , self . tilesz , self . tilesz ) : tiledata = np . zeros ( ( self . tilesz , self . tilesz ) , cb . data . dtype ) tiledata [ : ( ( yend - ) % self . tilesz + ) , : ( ( xend - ) % self . tilesz + ) ] = cb . data [ , : , : ] else : tiledata = cb . data return self . tile2WebPNG ( tiledata , color , brightness ) def getTile ( self , webargs ) : \"\"\"\"\"\" self . token , tileszstr , self . channel , resstr , xtilestr , ytilestr , zslicestr , color , brightnessstr , rest = webargs . split ( '' , ) self . loadDB ( ) with closing ( ocpcaproj . OCPCAProjectsDB ( ) ) as projdb : self . proj = projdb . loadProject ( self . token ) with closing ( ocpcadb . OCPCADB ( self . proj ) ) as self . db : xtile = int ( xtilestr ) ytile = int ( ytilestr ) res = int ( resstr ) zslice = int ( zslicestr ) - self . proj . datasetcfg . slicerange [ ] self . tilesz = int ( tileszstr ) brightness = float ( brightnessstr ) ", "answer": "mckey = self . buildKey ( res , xtile , ytile , zslice , color , brightness )"}, {"prompt": " from mock import patch from oslo_serialization import jsonutils import yaml from nailgun . objects import Cluster from nailgun . extensions . network_manager . objects . serializers . network_configuration import NeutronNetworkConfigurationSerializer from nailgun . extensions . network_manager . objects . serializers . network_configuration import NovaNetworkConfigurationSerializer from nailgun import consts from nailgun . db . sqlalchemy . models import NeutronConfig from nailgun . db . sqlalchemy . models import NovaNetworkConfig from nailgun . test . base import BaseIntegrationTest from nailgun . utils import reverse class TestNetworkModels ( BaseIntegrationTest ) : network_config = { \"\" : consts . NEUTRON_L23_PROVIDERS . ovs , \"\" : consts . NEUTRON_SEGMENT_TYPES . gre , \"\" : [ , ] , \"\" : [ , ] , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : [ [ \"\" , \"\" ] , [ \"\" , \"\" ] ] , \"\" : [ \"\" , \"\" ] , \"\" : { } } def create_env_using_statuses ( self , cluster_status , node_status ) : cluster = self . env . create ( cluster_kwargs = { '' : consts . CLUSTER_NET_PROVIDERS . neutron , '' : consts . NEUTRON_SEGMENT_TYPES . gre , '' : cluster_status } , nodes_kwargs = [ { '' : False , '' : node_status } , { '' : False , '' : node_status } , { '' : False , '' : node_status } ] ) return cluster def test_cluster_locking_during_deployment ( self ) : cluster = self . create_env_using_statuses ( consts . CLUSTER_STATUSES . deployment , consts . NODE_STATUSES . deploying ) test_nets = self . env . neutron_networks_get ( cluster . id ) . json_body resp_nova_net = self . env . nova_networks_put ( cluster . id , test_nets , expect_errors = True ) resp_neutron_net = self . env . neutron_networks_put ( cluster . id , test_nets , expect_errors = True ) resp_cluster = self . app . put ( reverse ( '' , kwargs = { '' : cluster . id } ) , jsonutils . dumps ( { '' : { \"\" : { \"\" : None } } } ) , headers = self . default_headers , expect_errors = True ) resp_cluster_get = self . app . get ( reverse ( '' , kwargs = { '' : cluster . id } ) , headers = self . default_headers ) self . assertTrue ( resp_cluster_get . json_body [ '' ] ) self . assertEqual ( resp_nova_net . status_code , ) self . assertEqual ( resp_neutron_net . status_code , ) self . assertEqual ( resp_cluster . status_code , ) def test_networks_update_after_deployment ( self ) : cluster = self . create_env_using_statuses ( consts . CLUSTER_STATUSES . operational , consts . NODE_STATUSES . ready ) test_nets = self . env . neutron_networks_get ( cluster . id ) . json_body test_nets [ '' ] [ '' ] = [ '' , '' ] test_network_name = consts . NETWORKS . management mgmt_net = filter ( lambda x : x [ '' ] == test_network_name , test_nets [ '' ] ) [ ] mgmt_net [ '' ] = u'' resp_neutron_net = self . env . neutron_networks_put ( cluster . id , test_nets , expect_errors = True ) self . assertEqual ( , resp_neutron_net . status_code ) self . assertEqual ( \"\" \"\" . format ( test_network_name , mgmt_net [ '' ] ) , resp_neutron_net . json_body [ '' ] ) mgmt_net [ '' ] = u'' resp_neutron_net = self . env . neutron_networks_put ( cluster . id , test_nets ) self . assertEqual ( , resp_neutron_net . status_code ) new_nets = self . env . neutron_networks_get ( cluster . id ) . json_body modified_net = filter ( lambda x : x [ '' ] == test_network_name , new_nets [ '' ] ) [ ] self . assertEqual ( u'' , modified_net [ '' ] ) self . assertDictEqual ( test_nets [ '' ] , new_nets [ '' ] ) def test_admin_network_update_after_deployment ( self ) : cluster = self . create_env_using_statuses ( consts . CLUSTER_STATUSES . operational , consts . NODE_STATUSES . ready ) test_nets = self . env . neutron_networks_get ( cluster . id ) . json_body admin_net = filter ( lambda x : x [ '' ] == consts . NETWORKS . fuelweb_admin , test_nets [ '' ] ) [ ] admin_net [ '' ] = u'' admin_net [ '' ] = [ [ u'' , u'' ] ] resp_neutron_net = self . env . neutron_networks_put ( cluster . id , test_nets , expect_errors = True ) self . assertEqual ( , resp_neutron_net . status_code ) self . assertEqual ( \"\" \"\" . format ( admin_net [ '' ] , admin_net [ '' ] ) , resp_neutron_net . json_body [ '' ] ) for node in self . env . nodes : self . db . delete ( node ) self . db . commit ( ) with patch ( '' ) : resp_neutron_net = self . env . neutron_networks_put ( cluster . id , test_nets ) self . assertEqual ( , resp_neutron_net . status_code ) def test_nova_net_networking_parameters ( self ) : cluster = self . env . create_cluster ( api = False ) self . db . delete ( cluster . network_config ) kw = { \"\" : consts . NOVA_NET_MANAGERS . VlanManager , \"\" : \"\" , \"\" : , \"\" : , \"\" : , ", "answer": "\"\" : [ [ \"\" , \"\" ] ] ,"}, {"prompt": " \"\"\"\"\"\" from bson import ObjectId from website . app import init_app from website import models from framework import Q app = init_app ( ) def impute_log_date ( dry_run = True ) : no_date = models . NodeLog . find ( Q ( '' , '' , None ) ) for log in no_date : oid = ObjectId ( log . _primary_key ) imputed_date = oid . generation_time print u'' . format ( imputed_date . strftime ( '' ) , log . _primary_key , ) if not dry_run : log . _fields [ '' ] . __set__ ( log , imputed_date , safe = True ) ", "answer": "log . save ( )"}, {"prompt": " import os from django . db import models from django . core . exceptions import ValidationError class Person ( models . Model ) : name = models . CharField ( max_length = ) class Triple ( models . Model ) : left = models . IntegerField ( ) middle = models . IntegerField ( ) right = models . IntegerField ( ) class Meta : unique_together = ( ( '' , '' ) , ( u'' , u'' ) ) class FilePathModel ( models . Model ) : path = models . FilePathField ( path = os . path . dirname ( __file__ ) , match = \"\" , blank = True ) class Publication ( models . Model ) : title = models . CharField ( max_length = ) date_published = models . DateField ( ) def __unicode__ ( self ) : return self . title class Article ( models . Model ) : headline = models . CharField ( max_length = ) publications = models . ManyToManyField ( Publication ) def __unicode__ ( self ) : return self . headline class CustomFileField ( models . FileField ) : def save_form_data ( self , instance , data ) : been_here = getattr ( self , '' , False ) assert not been_here , \"\" setattr ( self , '' , True ) class CustomFF ( models . Model ) : f = CustomFileField ( upload_to = '' , blank = True ) class RealPerson ( models . Model ) : name = models . CharField ( max_length = ) def clean ( self ) : if self . name . lower ( ) == '' : raise ValidationError ( \"\" ) class Author ( models . Model ) : publication = models . OneToOneField ( Publication , null = True , blank = True ) full_name = models . CharField ( max_length = ) class Author1 ( models . Model ) : ", "answer": "publication = models . OneToOneField ( Publication , null = False )"}, {"prompt": " \"\"\"\"\"\" class UnsupportedVersion ( Exception ) : \"\"\"\"\"\" pass class UnsupportedAttribute ( AttributeError ) : \"\"\"\"\"\" def __init__ ( self , argument_name , start_version , end_version = None ) : if end_version : ", "answer": "self . message = ("}, {"prompt": " from __future__ import print_function , division from sympy . core . compatibility import reduce from operator import add from sympy . core import Add , Basic , sympify from sympy . functions import adjoint from sympy . matrices . matrices import MatrixBase from sympy . matrices . expressions . transpose import transpose from sympy . strategies import ( rm_id , unpack , flatten , sort , condition , exhaust , do_one , glom ) from sympy . matrices . expressions . matexpr import MatrixExpr , ShapeError , ZeroMatrix from sympy . utilities import default_sort_key , sift class MatAdd ( MatrixExpr ) : \"\"\"\"\"\" is_MatAdd = True def __new__ ( cls , * args , ** kwargs ) : args = list ( map ( sympify , args ) ) check = kwargs . get ( '' , True ) obj = Basic . __new__ ( cls , * args ) if check : validate ( * args ) return obj @ property def shape ( self ) : return self . args [ ] . shape def _entry ( self , i , j ) : return Add ( * [ arg . _entry ( i , j ) for arg in self . args ] ) def _eval_transpose ( self ) : return MatAdd ( * [ transpose ( arg ) for arg in self . args ] ) . doit ( ) def _eval_adjoint ( self ) : return MatAdd ( * [ adjoint ( arg ) for arg in self . args ] ) . doit ( ) ", "answer": "def _eval_trace ( self ) :"}, {"prompt": " from twisted . internet import protocol , reactor , defer , utils from twisted . protocols import basic class FingerProtocol ( basic . LineReceiver ) : def lineReceived ( self , user ) : d = self . factory . getUser ( user ) def onError ( err ) : return '' d . addErrback ( onError ) def writeResponse ( message ) : self . transport . write ( message + '' ) self . transport . loseConnection ( ) ", "answer": "d . addCallback ( writeResponse )"}, {"prompt": " import re from oslo_config import cfg from oslo_log import log as logging import six from sahara import context from sahara import exceptions as e from sahara . i18n import _ from sahara . i18n import _LI from sahara . i18n import _LW from sahara . plugins import exceptions as ex from sahara . plugins import utils from sahara . swift import swift_helper as h from sahara . topology import topology_helper as th CONF = cfg . CONF TOPOLOGY_CONFIG = { \"\" : \"\" , \"\" : \"\" } LOG = logging . getLogger ( __name__ ) def create_service ( name ) : for cls in Service . __subclasses__ ( ) : if cls . get_service_id ( ) == name : return cls ( ) return Service ( name ) class Service ( object ) : def __init__ ( self , name , ambari_managed = True ) : self . name = name self . configurations = set ( [ '' , '' ] ) self . components = [ ] self . users = [ ] self . deployed = False self . ambari_managed = ambari_managed def add_component ( self , component ) : self . components . append ( component ) def add_user ( self , user ) : self . users . append ( user ) def validate ( self , cluster_spec , cluster ) : pass def finalize_configuration ( self , cluster_spec ) : pass def register_user_input_handlers ( self , ui_handlers ) : pass def register_service_urls ( self , cluster_spec , url_info , cluster ) : return url_info def pre_service_start ( self , cluster_spec , ambari_info , started_services ) : pass def finalize_ng_components ( self , cluster_spec ) : pass def is_user_template_component ( self , component ) : return True def is_mandatory ( self ) : return False def _replace_config_token ( self , cluster_spec , token , value , props ) : for config_name , props in six . iteritems ( props ) : config = cluster_spec . configurations [ config_name ] for prop in props : config [ prop ] = config [ prop ] . replace ( token , value ) def _update_config_values ( self , configurations , value , props ) : for absolute_prop_name in props : tokens = absolute_prop_name . split ( '' ) config_name = tokens [ ] prop_name = tokens [ ] config = configurations [ config_name ] config [ prop_name ] = value def _get_common_paths ( self , node_groups ) : sets = [ ] for node_group in node_groups : for instance in node_group . instances : sets . append ( set ( instance . sahara_instance . storage_paths ( ) ) ) return list ( set . intersection ( * sets ) ) if sets else [ ] def _generate_storage_path ( self , storage_paths , path ) : return \"\" . join ( [ p + path for p in storage_paths ] ) def _get_port_from_cluster_spec ( self , cluster_spec , service , prop_name ) : address = cluster_spec . configurations [ service ] [ prop_name ] return utils . get_port_from_address ( address ) class HdfsService ( Service ) : def __init__ ( self ) : super ( HdfsService , self ) . __init__ ( HdfsService . get_service_id ( ) ) self . configurations . add ( '' ) @ classmethod def get_service_id ( cls ) : return '' def validate ( self , cluster_spec , cluster ) : nn_count = cluster_spec . get_deployed_node_group_count ( '' ) jn_count = cluster_spec . get_deployed_node_group_count ( '' ) zkfc_count = cluster_spec . get_deployed_node_group_count ( '' ) if cluster_spec . is_hdfs_ha_enabled ( cluster ) : if nn_count != : raise ex . NameNodeHAConfigurationError ( \"\" \"\" % nn_count ) if not ( jn_count >= and ( jn_count % == ) ) : raise ex . NameNodeHAConfigurationError ( \"\" \"\" \"\" % jn_count ) else : if nn_count != : raise ex . InvalidComponentCountException ( '' , , nn_count ) if jn_count > : raise ex . NameNodeHAConfigurationError ( \"\" \"\" ) if zkfc_count > : raise ex . NameNodeHAConfigurationError ( \"\" \"\" ) def finalize_configuration ( self , cluster_spec ) : nn_hosts = cluster_spec . determine_component_hosts ( '' ) if nn_hosts : props = { '' : [ '' ] , '' : [ '' , '' ] } self . _replace_config_token ( cluster_spec , '' , nn_hosts . pop ( ) . fqdn ( ) , props ) snn_hosts = cluster_spec . determine_component_hosts ( '' ) if snn_hosts : props = { '' : [ '' ] } self . _replace_config_token ( cluster_spec , '' , snn_hosts . pop ( ) . fqdn ( ) , props ) core_site_config = cluster_spec . configurations [ '' ] for prop in self . _get_swift_properties ( ) : core_site_config [ prop [ '' ] ] = prop [ '' ] if CONF . enable_data_locality : for prop in th . vm_awareness_core_config ( ) : core_site_config [ prop [ '' ] ] = prop [ '' ] core_site_config . update ( TOPOLOGY_CONFIG ) nn_ng = cluster_spec . get_node_groups_containing_component ( '' ) [ ] dn_node_groups = cluster_spec . get_node_groups_containing_component ( '' ) common_paths = [ ] if dn_node_groups : common_paths = self . _get_common_paths ( dn_node_groups ) hdfs_site_config = cluster_spec . configurations [ '' ] hdfs_site_config [ '' ] = ( self . _generate_storage_path ( self . _get_common_paths ( [ nn_ng ] ) , '' ) ) if common_paths : hdfs_site_config [ '' ] = ( self . _generate_storage_path ( common_paths , '' ) ) def register_service_urls ( self , cluster_spec , url_info , cluster ) : namenode_ip = cluster_spec . determine_component_hosts ( '' ) . pop ( ) . management_ip ui_port = self . _get_port_from_cluster_spec ( cluster_spec , '' , '' ) nn_port = self . _get_port_from_cluster_spec ( cluster_spec , '' , '' ) url_info [ '' ] = { '' : '' % ( namenode_ip , ui_port ) , '' : '' % ( namenode_ip , nn_port ) } if cluster_spec . is_hdfs_ha_enabled ( cluster ) : url_info [ '' ] . update ( { '' : '' % cluster . name } ) return url_info def finalize_ng_components ( self , cluster_spec ) : hdfs_ng = cluster_spec . get_node_groups_containing_component ( '' ) [ ] components = hdfs_ng . components if not cluster_spec . get_deployed_node_group_count ( '' ) : zk_service = next ( service for service in cluster_spec . services if service . name == '' ) zk_service . deployed = True components . append ( '' ) def is_mandatory ( self ) : return True def _get_swift_properties ( self ) : return h . get_swift_configs ( ) class MapReduce2Service ( Service ) : def __init__ ( self ) : super ( MapReduce2Service , self ) . __init__ ( MapReduce2Service . get_service_id ( ) ) self . configurations . add ( '' ) @ classmethod def get_service_id ( cls ) : return '' def validate ( self , cluster_spec , cluster ) : count = cluster_spec . get_deployed_node_group_count ( '' ) if count != : raise ex . InvalidComponentCountException ( '' , , count ) def finalize_configuration ( self , cluster_spec ) : hs_hosts = cluster_spec . determine_component_hosts ( '' ) if hs_hosts : props = { '' : [ '' , '' ] } self . _replace_config_token ( cluster_spec , '' , hs_hosts . pop ( ) . fqdn ( ) , props ) mapred_site_config = cluster_spec . configurations [ '' ] if CONF . enable_data_locality : for prop in th . vm_awareness_mapred_config ( ) : mapred_site_config [ prop [ '' ] ] = prop [ '' ] def register_service_urls ( self , cluster_spec , url_info , cluster ) : historyserver_ip = cluster_spec . determine_component_hosts ( '' ) . pop ( ) . management_ip ui_port = self . _get_port_from_cluster_spec ( cluster_spec , '' , '' ) hs_port = self . _get_port_from_cluster_spec ( cluster_spec , '' , '' ) url_info [ '' ] = { '' : '' % ( historyserver_ip , ui_port ) , '' : '' % ( historyserver_ip , hs_port ) } return url_info def finalize_ng_components ( self , cluster_spec ) : mr2_ng = cluster_spec . get_node_groups_containing_component ( '' ) [ ] components = mr2_ng . components if '' not in components : components . append ( '' ) def is_mandatory ( self ) : return True class YarnService ( Service ) : def __init__ ( self ) : super ( YarnService , self ) . __init__ ( YarnService . get_service_id ( ) ) self . configurations . add ( '' ) self . configurations . add ( '' ) @ classmethod def get_service_id ( cls ) : return '' def validate ( self , cluster_spec , cluster ) : count = cluster_spec . get_deployed_node_group_count ( '' ) if count != : raise ex . InvalidComponentCountException ( '' , , count ) count = cluster_spec . get_deployed_node_group_count ( '' ) if not count : raise ex . InvalidComponentCountException ( '' , '' , count ) def finalize_configuration ( self , cluster_spec ) : rm_hosts = cluster_spec . determine_component_hosts ( '' ) if rm_hosts : props = { '' : [ '' '' , '' , '' , '' , '' , '' , '' ] } self . _replace_config_token ( cluster_spec , '' , rm_hosts . pop ( ) . fqdn ( ) , props ) mapred_site_config = cluster_spec . configurations [ '' ] if CONF . enable_data_locality : for prop in th . vm_awareness_mapred_config ( ) : mapred_site_config [ prop [ '' ] ] = prop [ '' ] yarn_site_config = cluster_spec . configurations [ '' ] nm_node_groups = cluster_spec . get_node_groups_containing_component ( '' ) if nm_node_groups : common_paths = self . _get_common_paths ( nm_node_groups ) yarn_site_config [ '' ] = ( self . _generate_storage_path ( common_paths , '' ) ) def register_service_urls ( self , cluster_spec , url_info , cluster ) : resourcemgr_ip = cluster_spec . determine_component_hosts ( '' ) . pop ( ) . management_ip ui_port = self . _get_port_from_cluster_spec ( cluster_spec , '' , '' ) rm_port = self . _get_port_from_cluster_spec ( cluster_spec , '' , '' ) url_info [ '' ] = { '' : '' % ( resourcemgr_ip , ui_port ) , '' : '' % ( resourcemgr_ip , rm_port ) } return url_info def is_mandatory ( self ) : return True class HiveService ( Service ) : def __init__ ( self ) : super ( HiveService , self ) . __init__ ( HiveService . get_service_id ( ) ) self . configurations . add ( '' ) @ classmethod def get_service_id ( cls ) : return '' def validate ( self , cluster_spec , cluster ) : count = cluster_spec . get_deployed_node_group_count ( '' ) if count != : raise ex . InvalidComponentCountException ( '' , , count ) def finalize_configuration ( self , cluster_spec ) : hive_servers = cluster_spec . determine_component_hosts ( '' ) if hive_servers : props = { '' : [ '' ] , '' : [ '' ] } self . _replace_config_token ( cluster_spec , '' , hive_servers . pop ( ) . fqdn ( ) , props ) hive_ms = cluster_spec . determine_component_hosts ( '' ) if hive_ms : self . _replace_config_token ( cluster_spec , '' , hive_ms . pop ( ) . fqdn ( ) , { '' : [ '' ] } ) hive_mysql = cluster_spec . determine_component_hosts ( '' ) if hive_mysql : self . _replace_config_token ( cluster_spec , '' , hive_mysql . pop ( ) . fqdn ( ) , { '' : [ '' ] } ) def register_user_input_handlers ( self , ui_handlers ) : ui_handlers [ '' ] = ( self . _handle_user_property_metastore_user ) ui_handlers [ '' ] = ( self . _handle_user_property_metastore_pwd ) def _handle_user_property_metastore_user ( self , user_input , configurations ) : hive_site_config_map = configurations [ '' ] hive_site_config_map [ '' ] = ( user_input . value ) def _handle_user_property_metastore_pwd ( self , user_input , configurations ) : hive_site_config_map = configurations [ '' ] hive_site_config_map [ '' ] = ( user_input . value ) def finalize_ng_components ( self , cluster_spec ) : hive_ng = cluster_spec . get_node_groups_containing_component ( '' ) [ ] components = hive_ng . components if '' not in components : components . append ( '' ) if not cluster_spec . get_deployed_node_group_count ( '' ) : components . append ( '' ) if not cluster_spec . get_deployed_node_group_count ( '' ) : components . append ( '' ) if not cluster_spec . get_deployed_node_group_count ( '' ) : zk_service = next ( service for service in cluster_spec . services if service . name == '' ) zk_service . deployed = True components . append ( '' ) class WebHCatService ( Service ) : def __init__ ( self ) : super ( WebHCatService , self ) . __init__ ( WebHCatService . get_service_id ( ) ) self . configurations . add ( '' ) @ classmethod def get_service_id ( cls ) : return '' def validate ( self , cluster_spec , cluster ) : count = cluster_spec . get_deployed_node_group_count ( '' ) if count != : raise ex . InvalidComponentCountException ( '' , , count ) def finalize_configuration ( self , cluster_spec ) : webhcat_servers = cluster_spec . determine_component_hosts ( '' ) if webhcat_servers : self . _replace_config_token ( cluster_spec , '' , webhcat_servers . pop ( ) . fqdn ( ) , { '' : [ '' ] } ) hive_ms_servers = cluster_spec . determine_component_hosts ( '' ) if hive_ms_servers : self . _replace_config_token ( cluster_spec , '' , hive_ms_servers . pop ( ) . fqdn ( ) , { '' : [ '' ] } ) zk_servers = cluster_spec . determine_component_hosts ( '' ) if zk_servers : zk_list = [ '' . format ( z . fqdn ( ) ) for z in zk_servers ] self . _replace_config_token ( cluster_spec , '' , '' . join ( zk_list ) , { '' : [ '' ] } ) def finalize_ng_components ( self , cluster_spec ) : webhcat_ng = cluster_spec . get_node_groups_containing_component ( '' ) [ ] components = webhcat_ng . components if '' not in components : components . append ( '' ) if '' not in components : components . append ( '' ) if '' not in components : components . append ( '' ) if '' not in components : if not cluster_spec . get_deployed_node_group_count ( '' ) : zk_service = next ( service for service in cluster_spec . services if service . name == '' ) zk_service . deployed = True components . append ( '' ) components . append ( '' ) class HBaseService ( Service ) : property_map = { '' : [ '' , '' ] , '' : [ '' , '' ] , '' : [ '' , '' ] , '' : [ '' , '' ] , '' : [ '' , '' ] , '' : [ '' , '' ] , '' : [ '' , '' ] , '' : [ '' , '' ] , '' : [ '' , '' ] , '' : [ '' , '' ] , '' : [ '' , '' ] , '' : [ '' ] , '' : [ '' , '' ] , '' : [ '' , '' ] , '' : [ '' , '' ] , '' : [ '' , '' , '' ] , '' : [ '' , '' ] } def __init__ ( self ) : super ( HBaseService , self ) . __init__ ( HBaseService . get_service_id ( ) ) self . configurations . add ( '' ) @ classmethod def get_service_id ( cls ) : return '' def validate ( self , cluster_spec , cluster ) : count = cluster_spec . get_deployed_node_group_count ( '' ) if count != : raise ex . InvalidComponentCountException ( '' , , count ) def register_service_urls ( self , cluster_spec , url_info , cluster ) : master_ip = cluster_spec . determine_component_hosts ( '' ) . pop ( ) . management_ip hbase_config = cluster_spec . configurations [ '' ] info_port = hbase_config [ '' ] url_info [ '' ] = { '' : '' % ( master_ip , info_port ) , '' : '' % ( master_ip , info_port ) , '' : '' % ( master_ip , info_port ) , '' : '' % ( master_ip , info_port ) , '' : '' % ( master_ip , info_port ) , '' : '' % ( master_ip , info_port ) } return url_info def register_user_input_handlers ( self , ui_handlers ) : for prop_name in self . property_map : ui_handlers [ prop_name ] = ( self . _handle_config_property_update ) ui_handlers [ '' ] = ( self . _handle_user_property_root_dir ) def _handle_config_property_update ( self , user_input , configurations ) : self . _update_config_values ( configurations , user_input . value , self . property_map [ user_input . config . name ] ) def _handle_user_property_root_dir ( self , user_input , configurations ) : configurations [ '' ] [ '' ] = user_input . value match = re . search ( '' , user_input . value ) if match : configurations [ '' ] [ '' ] = match . group ( ) else : raise e . InvalidDataException ( _ ( \"\" ) % user_input . value ) def finalize_configuration ( self , cluster_spec ) : nn_servers = cluster_spec . determine_component_hosts ( '' ) if nn_servers : self . _replace_config_token ( cluster_spec , '' , nn_servers . pop ( ) . fqdn ( ) , { '' : [ '' ] } ) zk_servers = cluster_spec . determine_component_hosts ( '' ) if zk_servers : zk_list = [ z . fqdn ( ) for z in zk_servers ] self . _replace_config_token ( cluster_spec , '' , '' . join ( zk_list ) , { '' : [ '' ] } ) def finalize_ng_components ( self , cluster_spec ) : hbase_ng = cluster_spec . get_node_groups_containing_component ( '' ) components = hbase_ng [ ] . components if '' not in components : components . append ( '' ) if not cluster_spec . get_deployed_node_group_count ( '' ) : components . append ( '' ) else : hbase_ng = cluster_spec . get_node_groups_containing_component ( '' ) for ng in hbase_ng : components = ng . components if '' not in components : components . append ( '' ) if not cluster_spec . get_deployed_node_group_count ( '' ) : zk_service = next ( service for service in cluster_spec . services if service . name == '' ) zk_service . deployed = True components . append ( '' ) class ZookeeperService ( Service ) : def __init__ ( self ) : super ( ZookeeperService , self ) . __init__ ( ZookeeperService . get_service_id ( ) ) @ classmethod def get_service_id ( cls ) : return '' def validate ( self , cluster_spec , cluster ) : count = cluster_spec . get_deployed_node_group_count ( '' ) if count < : raise ex . InvalidComponentCountException ( '' , '' , count ) if cluster_spec . is_hdfs_ha_enabled ( cluster ) : if not ( count >= and ( count % == ) ) : raise ex . NameNodeHAConfigurationError ( \"\" \"\" \"\" % count ) def is_mandatory ( self ) : return True class OozieService ( Service ) : def __init__ ( self ) : super ( OozieService , self ) . __init__ ( OozieService . get_service_id ( ) ) self . configurations . add ( '' ) @ classmethod def get_service_id ( cls ) : return '' def validate ( self , cluster_spec , cluster ) : count = cluster_spec . get_deployed_node_group_count ( '' ) if count != : raise ex . InvalidComponentCountException ( '' , , count ) count = cluster_spec . get_deployed_node_group_count ( '' ) if not count : raise ex . InvalidComponentCountException ( '' , '' , count ) def finalize_configuration ( self , cluster_spec ) : oozie_servers = cluster_spec . determine_component_hosts ( '' ) if oozie_servers : oozie_server = oozie_servers . pop ( ) name_list = [ oozie_server . fqdn ( ) , oozie_server . internal_ip , oozie_server . management_ip ] self . _replace_config_token ( cluster_spec , '' , oozie_server . fqdn ( ) , { '' : [ '' ] , '' : [ '' ] } ) self . _replace_config_token ( cluster_spec , '' , \"\" . join ( name_list ) , { '' : [ '' ] } ) def finalize_ng_components ( self , cluster_spec ) : oozie_ng = cluster_spec . get_node_groups_containing_component ( '' ) [ ] components = oozie_ng . components if '' not in components : components . append ( '' ) if '' not in components : components . append ( '' ) if '' not in components : components . append ( '' ) client_ngs = cluster_spec . get_node_groups_containing_component ( '' ) for ng in client_ngs : components = ng . components if '' not in components : components . append ( '' ) if '' not in components : components . append ( '' ) def register_service_urls ( self , cluster_spec , url_info , cluster ) : oozie_ip = cluster_spec . determine_component_hosts ( '' ) . pop ( ) . management_ip port = self . _get_port_from_cluster_spec ( cluster_spec , '' , '' ) url_info [ '' ] = { '' : '' % ( oozie_ip , port ) } return url_info def register_user_input_handlers ( self , ui_handlers ) : ui_handlers [ '' ] = ( self . _handle_user_property_db_user ) ui_handlers [ '' ] = ( self . _handle_user_property_db_pwd ) def _handle_user_property_db_user ( self , user_input , configurations ) : oozie_site_config_map = configurations [ '' ] oozie_site_config_map [ '' ] = ( user_input . value ) def _handle_user_property_db_pwd ( self , user_input , configurations ) : oozie_site_config_map = configurations [ '' ] oozie_site_config_map [ '' ] = ( user_input . value ) class GangliaService ( Service ) : def __init__ ( self ) : super ( GangliaService , self ) . __init__ ( GangliaService . get_service_id ( ) ) @ classmethod def get_service_id ( cls ) : return '' def validate ( self , cluster_spec , cluster ) : count = cluster_spec . get_deployed_node_group_count ( '' ) if count != : raise ex . InvalidComponentCountException ( '' , , count ) def is_user_template_component ( self , component ) : return component . name != '' def finalize_ng_components ( self , cluster_spec ) : for ng in cluster_spec . node_groups . values ( ) : if '' not in ng . components : ng . components . append ( '' ) class AmbariService ( Service ) : def __init__ ( self ) : super ( AmbariService , self ) . __init__ ( AmbariService . get_service_id ( ) , False ) self . configurations . add ( '' ) self . admin_user_name = '' @ classmethod def get_service_id ( cls ) : return '' def validate ( self , cluster_spec , cluster ) : count = cluster_spec . get_deployed_node_group_count ( '' ) if count != : raise ex . InvalidComponentCountException ( '' , , count ) def register_service_urls ( self , cluster_spec , url_info , cluster ) : ambari_ip = cluster_spec . determine_component_hosts ( '' ) . pop ( ) . management_ip port = cluster_spec . configurations [ '' ] . get ( '' , '' ) url_info [ '' ] = { '' : '' . format ( ambari_ip , port ) } return url_info def is_user_template_component ( self , component ) : return component . name != '' def register_user_input_handlers ( self , ui_handlers ) : ui_handlers [ '' ] = ( self . _handle_user_property_admin_user ) ui_handlers [ '' ] = ( self . _handle_user_property_admin_password ) def is_mandatory ( self ) : return True def _handle_user_property_admin_user ( self , user_input , configurations ) : admin_user = next ( user for user in self . users if user . name == '' ) admin_user . name = user_input . value self . admin_user_name = user_input . value def _handle_user_property_admin_password ( self , user_input , configurations ) : admin_user = next ( user for user in self . users ", "answer": "if user . name == self . admin_user_name )"}, {"prompt": " from __future__ import unicode_literals from django . db import migrations , models import django . utils . timezone class Migration ( migrations . Migration ) : dependencies = [ ( '' , '' ) , ] operations = [ migrations . AddField ( model_name = '' , name = '' , field = models . DateTimeField ( default = django . utils . timezone . now ) , ) , migrations . AddField ( model_name = '' , ", "answer": "name = '' ,"}, {"prompt": " from sahara . service . edp . oozie . workflow_creator import base_workflow class MapReduceWorkFlowCreator ( base_workflow . OozieWorkflowCreator ) : def __init__ ( self ) : super ( MapReduceWorkFlowCreator , self ) . __init__ ( '' ) def build_workflow_xml ( self , prepare = None , job_xml = None , configuration = None , files = None , archives = None , streaming = None ) : prepare = prepare or { } files = files or [ ] archives = archives or [ ] streaming = streaming or { } for k in sorted ( prepare ) : self . _add_to_prepare_element ( k , prepare [ k ] ) for k in sorted ( streaming ) : self . _add_to_streaming_element ( k , streaming [ k ] ) self . _add_job_xml_element ( job_xml ) self . _add_configuration_elements ( configuration ) ", "answer": "self . _add_files_and_archives ( files , archives ) "}, {"prompt": " import datetime from south . db import db from south . v2 import SchemaMigration from django . db import models class Migration ( SchemaMigration ) : def forwards ( self , orm ) : db . add_column ( u'' , '' , self . gf ( '' ) ( default = , null = True , max_digits = , decimal_places = ) , keep_default = False ) def backwards ( self , orm ) : db . delete_column ( u'' , '' ) models = { u'' : { '' : { '' : '' } , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) } , u'' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , ", "answer": "'' : ( '' , [ ] , { '' : '' } ) ,"}, {"prompt": " from __future__ import division import os . path import random import urllib from datetime import datetime try : from cStringIO import StringIO except ImportError : from StringIO import StringIO from PIL import Image from django . db import models from django . conf import settings from django . core . urlresolvers import reverse class ExternalImage ( models . Model ) : url = models . URLField ( ) etag = models . TextField ( null = True ) last_modified = models . TextField ( null = True ) last_updated = models . DateTimeField ( ) width = models . PositiveIntegerField ( null = True ) height = models . PositiveIntegerField ( null = True ) def save ( self , force_insert = False , force_update = False , * args , ** kwargs ) : self . last_updated = datetime . utcnow ( ) super ( ExternalImage , self ) . save ( force_insert = False , force_update = False , ** kwargs ) def get_external_image_dir ( ) : return getattr ( settings , '' , os . path . join ( settings . CACHE_DIR , '' ) ) class ExternalImageSized ( models . Model ) : external_image = models . ForeignKey ( ExternalImage ) width = models . PositiveIntegerField ( ) height = models . PositiveIntegerField ( ) slug = models . SlugField ( ) content_type = models . TextField ( ) def get_filename ( self ) : external_image_dir = get_external_image_dir ( ) if not self . slug : while not self . slug or ExternalImageSized . objects . filter ( slug = self . slug ) . count ( ) : self . slug = \"\" % random . randint ( , ** - ) if not os . path . exists ( external_image_dir ) : os . makedirs ( external_image_dir ) return os . path . join ( external_image_dir , self . slug ) def get_absolute_url ( self ) : return reverse ( '' , args = [ self . slug ] ) def save ( self , force_insert = False , force_update = False , * args , ** kwargs ) : if not self . id : response = urllib . urlopen ( self . external_image . url ) data = StringIO ( response . read ( ) ) im = Image . open ( data ) size = im . size ratio = size [ ] / size [ ] if self . width >= size [ ] : resized = im else : try : resized = im . resize ( ( self . width , int ( round ( self . width * ratio ) ) ) , Image . ANTIALIAS ) except IOError , e : if e . message == \"\" : resized = im else : raise self . width , self . height = resized . size try : resized . save ( self . get_filename ( ) , format = '' ) self . content_type = '' except IOError , e : try : resized . convert ( '' ) . save ( self . get_filename ( ) , format = '' ) self . content_type = '' except IOError : open ( self . get_filename ( ) , '' ) . write ( data . getvalue ( ) ) self . content_type = response . headers [ '' ] self . external_image . width = size [ ] self . external_image . height = size [ ] super ( ExternalImageSized , self ) . save ( force_insert = False , force_update = False , ** kwargs ) def delete ( self ) : try : os . unlink ( self . get_filename ( ) ) except OSError : pass ", "answer": "super ( ExternalImageSized , self ) . delete ( ) "}, {"prompt": " import logging import re from django . conf import settings from cleanliness import encoding from common import component from common . protocol import base class JID ( object ) : _re_jid = re . compile ( r'' ) def __init__ ( self , node , host , resource = None ) : self . node = node self . host = host self . resource = resource @ classmethod def from_uri ( cls , uri ) : node , rest = uri . split ( '' , ) try : host , rest = rest . split ( '' , ) resource = '' + rest except ValueError : host = rest resource = '' return cls ( node , host , resource ) def base ( self ) : ", "answer": "return '' % ( self . node , self . host )"}, {"prompt": " \"\"\"\"\"\" import sys import traceback def import_class ( import_str ) : \"\"\"\"\"\" mod_str , _sep , class_str = import_str . rpartition ( '' ) __import__ ( mod_str ) try : return getattr ( sys . modules [ mod_str ] , class_str ) except AttributeError : raise ImportError ( '' % ( class_str , ", "answer": "traceback . format_exception ( * sys . exc_info ( ) ) ) )"}, {"prompt": " \"\"\"\"\"\" import os ", "answer": "import warnings"}, {"prompt": " from sympy import ratsimpmodprime , ratsimp , Rational , sqrt , pi , log , erf from sympy . abc import x , y , z , t , a , b , c , d , e , f , g , h , i , k def test_ratsimp ( ) : f , g = / x + / y , ( x + y ) / ( x * y ) assert f != g and ratsimp ( f ) == g f , g = / ( + / x ) , - / ( x + ) assert f != g and ratsimp ( f ) == g f , g = x / ( x + y ) + y / ( x + y ) , assert f != g and ratsimp ( f ) == g f , g = - x - y - y ** / ( x + y ) + x ** / ( x + y ) , - * y assert f != g and ratsimp ( f ) == g f = ( a * c * x * y + a * c * z - b * d * x * y - b * d * z - b * t * x * y - b * t * x - b * t * z + e * x ) / ( x * y + z ) G = [ a * c - b * d - b * t + ( - b * t * x + e * x ) / ( x * y + z ) , ", "answer": "a * c - b * d - b * t - ( b * t * x - e * x ) / ( x * y + z ) ]"}, {"prompt": " def macro ( name ) : '''''' ", "answer": "def inner ( view , context , model , column ) :"}, {"prompt": " import logging import pprint from django . http import HttpResponse , HttpResponseBadRequest from django . views . generic . edit import CreateView from rapidsms . backends . kannel . models import DeliveryReport from rapidsms . backends . kannel . forms import KannelForm from rapidsms . backends . http . views import BaseHttpBackendView logger = logging . getLogger ( __name__ ) class KannelBackendView ( BaseHttpBackendView ) : \"\"\"\"\"\" http_method_names = [ '' ] form_class = KannelForm def get ( self , * args , ** kwargs ) : \"\"\"\"\"\" return self . post ( * args , ** kwargs ) def get_form_kwargs ( self ) : kwargs = super ( KannelBackendView , self ) . get_form_kwargs ( ) kwargs [ '' ] = self . request . GET return kwargs def form_valid ( self , form ) : super ( KannelBackendView , self ) . form_valid ( form ) return HttpResponse ( '' ) class DeliveryReportView ( CreateView ) : model = DeliveryReport fields = ( '' , '' , '' , '' , '' , '' , '' , ) http_method_names = [ '' ] ", "answer": "def get ( self , * args , ** kwargs ) :"}, {"prompt": " \"\"\"\"\"\" import os BASE_DIR = os . path . dirname ( os . path . dirname ( os . path . abspath ( __file__ ) ) ) SECRET_KEY = '' DEBUG = True ALLOWED_HOSTS = [ ] INSTALLED_APPS = ( '' , '' , '' , '' , '' , '' , '' ) MIDDLEWARE_CLASSES = ( '' , '' , '' , '' , '' , '' , '' , '' , ) ", "answer": "ROOT_URLCONF = ''"}, {"prompt": " DECIMAL = TINY = SHORT = LONG = FLOAT = DOUBLE = NULL = TIMESTAMP = LONGLONG = INT24 = DATE = TIME = DATETIME = YEAR = NEWDATE = ", "answer": "VARCHAR = "}, {"prompt": " from ctypes import c_void_p , POINTER , sizeof , Structure , windll , WinError , WINFUNCTYPE from ctypes . wintypes import BOOL , BYTE , DWORD , HANDLE , LPCWSTR , LPWSTR , UINT , WORD LPVOID = c_void_p LPBYTE = POINTER ( BYTE ) LPDWORD = POINTER ( DWORD ) def ErrCheckBool ( result , func , args ) : \"\"\"\"\"\" if not result : raise WinError ( ) return args CloseHandleProto = WINFUNCTYPE ( BOOL , HANDLE ) CloseHandle = CloseHandleProto ( ( \"\" , windll . kernel32 ) ) CloseHandle . errcheck = ErrCheckBool class AutoHANDLE ( HANDLE ) : \"\"\"\"\"\" def Close ( self ) : if self . value : CloseHandle ( self ) self . value = def __del__ ( self ) : self . Close ( ) def __int__ ( self ) : return self . value def ErrCheckHandle ( result , func , args ) : \"\"\"\"\"\" if not result : raise WinError ( ) return AutoHANDLE ( result ) class PROCESS_INFORMATION ( Structure ) : _fields_ = [ ( \"\" , HANDLE ) , ( \"\" , HANDLE ) , ( \"\" , DWORD ) , ( \"\" , DWORD ) ] def __init__ ( self ) : Structure . __init__ ( self ) self . cb = sizeof ( self ) LPPROCESS_INFORMATION = POINTER ( PROCESS_INFORMATION ) class STARTUPINFO ( Structure ) : _fields_ = [ ( \"\" , DWORD ) , ( \"\" , LPWSTR ) , ( \"\" , LPWSTR ) , ( \"\" , LPWSTR ) , ( \"\" , DWORD ) , ( \"\" , DWORD ) , ( \"\" , DWORD ) , ( \"\" , DWORD ) , ( \"\" , DWORD ) , ( \"\" , DWORD ) , ( \"\" , DWORD ) , ( \"\" , DWORD ) , ( \"\" , WORD ) , ( \"\" , WORD ) , ( \"\" , LPBYTE ) , ( \"\" , HANDLE ) , ( \"\" , HANDLE ) , ( \"\" , HANDLE ) ] LPSTARTUPINFO = POINTER ( STARTUPINFO ) STARTF_USESHOWWINDOW = STARTF_USESIZE = STARTF_USEPOSITION = STARTF_USECOUNTCHARS = STARTF_USEFILLATTRIBUTE = STARTF_RUNFULLSCREEN = STARTF_FORCEONFEEDBACK = STARTF_FORCEOFFFEEDBACK = STARTF_USESTDHANDLES = class EnvironmentBlock : \"\"\"\"\"\" def __init__ ( self , dict ) : if not dict : self . _as_parameter_ = None else : values = [ \"\" % ( key , value ) for ( key , value ) in dict . iteritems ( ) ] values . append ( \"\" ) self . _as_parameter_ = LPCWSTR ( \"\" . join ( values ) ) CreateProcessProto = WINFUNCTYPE ( BOOL , LPCWSTR , LPWSTR , LPVOID , LPVOID , BOOL , DWORD , LPVOID , LPCWSTR , LPSTARTUPINFO , LPPROCESS_INFORMATION ) CreateProcessFlags = ( ( , \"\" , None ) , ( , \"\" ) , ( , \"\" , None ) , ( , \"\" , None ) , ( , \"\" , True ) , ( , \"\" , ) , ( , \"\" , None ) , ( , \"\" , None ) , ( , \"\" ) , ( , \"\" ) ) def ErrCheckCreateProcess ( result , func , args ) : ErrCheckBool ( result , func , args ) pi = args [ ] return AutoHANDLE ( pi . hProcess ) , AutoHANDLE ( pi . hThread ) , pi . dwProcessID , pi . dwThreadID CreateProcess = CreateProcessProto ( ( \"\" , windll . kernel32 ) , CreateProcessFlags ) CreateProcess . errcheck = ErrCheckCreateProcess CREATE_BREAKAWAY_FROM_JOB = CREATE_DEFAULT_ERROR_MODE = CREATE_NEW_CONSOLE = CREATE_NEW_PROCESS_GROUP = CREATE_NO_WINDOW = CREATE_SUSPENDED = CREATE_UNICODE_ENVIRONMENT = DEBUG_ONLY_THIS_PROCESS = DEBUG_PROCESS = DETACHED_PROCESS = CreateJobObjectProto = WINFUNCTYPE ( HANDLE , LPVOID , LPCWSTR ) CreateJobObjectFlags = ( ( , \"\" , None ) , ( , \"\" , LPCWSTR ( \"\" ) ) ) CreateJobObject = CreateJobObjectProto ( ( \"\" , windll . kernel32 ) , CreateJobObjectFlags ) CreateJobObject . errcheck = ErrCheckHandle AssignProcessToJobObjectProto = WINFUNCTYPE ( BOOL , HANDLE , HANDLE ) AssignProcessToJobObjectFlags = ( ( , \"\" ) , ( , \"\" ) ) AssignProcessToJobObject = AssignProcessToJobObjectProto ( ( \"\" , windll . kernel32 ) , AssignProcessToJobObjectFlags ) AssignProcessToJobObject . errcheck = ErrCheckBool def ErrCheckResumeThread ( result , func , args ) : if result == - : raise WinError ( ) return args ResumeThreadProto = WINFUNCTYPE ( DWORD , ", "answer": "HANDLE"}, {"prompt": " from __future__ import division , absolute_import import sys import os from setuptools import setup , find_packages from setuptools . command . build_py import build_py from distutils . command . build_scripts import build_scripts class PickyBuildPy ( build_py ) : \"\"\"\"\"\" def find_package_modules ( self , package , package_dir ) : from twisted . python . dist3 import modulesToInstall , testDataFiles modules = [ ", "answer": "module for module"}, {"prompt": " from sys import version_info if version_info >= ( , ) : from collections import OrderedDict ", "answer": "else :"}, {"prompt": " \"\"\"\"\"\" import sys import os import __builtin__ PREFIXES = [ sys . prefix , sys . exec_prefix ] ENABLE_USER_SITE = None USER_SITE = None USER_BASE = None def makepath ( * paths ) : dir = os . path . abspath ( os . path . join ( * paths ) ) return dir , os . path . normcase ( dir ) def abs__file__ ( ) : \"\"\"\"\"\" for m in sys . modules . values ( ) : if hasattr ( m , '' ) : continue try : m . __file__ = os . path . abspath ( m . __file__ ) except AttributeError : continue def removeduppaths ( ) : \"\"\"\"\"\" L = [ ] known_paths = set ( ) for dir in sys . path : dir , dircase = makepath ( dir ) if not dircase in known_paths : L . append ( dir ) known_paths . add ( dircase ) sys . path [ : ] = L return known_paths def addbuilddir ( ) : \"\"\"\"\"\" from distutils . util import get_platform s = \"\" % ( get_platform ( ) , sys . version ) if hasattr ( sys , '' ) : s += '' s = os . path . join ( os . path . dirname ( sys . path [ - ] ) , s ) sys . path . append ( s ) def _init_pathinfo ( ) : \"\"\"\"\"\" d = set ( ) for dir in sys . path : try : if os . path . isdir ( dir ) : dir , dircase = makepath ( dir ) d . add ( dircase ) except TypeError : continue return d def addpackage ( sitedir , name , known_paths ) : \"\"\"\"\"\" if known_paths is None : _init_pathinfo ( ) reset = else : reset = fullname = os . path . join ( sitedir , name ) try : f = open ( fullname , \"\" ) except IOError : return with f : for line in f : if line . startswith ( \"\" ) : continue if line . startswith ( ( \"\" , \"\" ) ) : exec line continue line = line . rstrip ( ) dir , dircase = makepath ( sitedir , line ) ", "answer": "if not dircase in known_paths and os . path . exists ( dir ) :"}, {"prompt": " from . import BaseCommand from flask import render_template class ContactUsCommand ( BaseCommand ) : def process ( self , request , filename , db_session ) : ", "answer": "return render_template ( '' )"}, {"prompt": " READ = '' WRITE = '' ADMIN = '' PERMISSIONS = [ READ , WRITE , ADMIN ] CREATOR_PERMISSIONS = [ READ , WRITE , ADMIN ] DEFAULT_CONTRIBUTOR_PERMISSIONS = [ READ , WRITE ] def expand_permissions ( permission ) : if not permission : return [ ] index = PERMISSIONS . index ( permission ) + return PERMISSIONS [ : index ] def reduce_permissions ( permissions ) : for permission in PERMISSIONS [ : : - ] : if permission in permissions : ", "answer": "return permission"}, {"prompt": " from conary . deps import deps from conary . repository import changeset from conary . repository import errors as repoerrors from conary import errors from conary import versions from conary import trove class BranchError ( errors . ClientError ) : pass class ClientBranch ( object ) : BRANCH_SOURCE = << BRANCH_BINARY = << BRANCH_ALL = BRANCH_SOURCE | BRANCH_BINARY __developer_api__ = True def createBranchChangeSet ( self , newLabel , troveList = [ ] , branchType = BRANCH_ALL , sigKeyId = None ) : return self . _createBranchOrShadow ( newLabel , troveList , shadow = False , branchType = branchType , sigKeyId = sigKeyId ) def createShadowChangeSet ( self , newLabel , troveList = [ ] , branchType = BRANCH_ALL , sigKeyId = None , allowEmptyShadow = False ) : return self . _createBranchOrShadow ( newLabel , troveList , shadow = True , branchType = branchType , sigKeyId = sigKeyId , ", "answer": "allowEmptyShadow = allowEmptyShadow )"}, {"prompt": " import eventlet import random import six from oslo_config import cfg from oslo_serialization import jsonutils from neutron . agent . linux . utils import wait_until_true from dragonflow . common import utils as df_utils from dragonflow . db . db_common import DbUpdate , SEND_ALL_TOPIC from dragonflow . db . pub_sub_api import TableMonitor from dragonflow . tests . common import utils as test_utils from dragonflow . tests . fullstack import test_base from dragonflow . tests . fullstack import test_objects as objects events_num = def get_publisher ( ) : pub_sub_driver = df_utils . load_driver ( cfg . CONF . df . pub_sub_multiproc_driver , df_utils . DF_PUBSUB_DRIVER_NAMESPACE ) publisher = pub_sub_driver . get_publisher ( ) publisher . initialize ( ) return publisher def get_subscriber ( callback ) : pub_sub_driver = df_utils . load_driver ( cfg . CONF . df . pub_sub_driver , df_utils . DF_PUBSUB_DRIVER_NAMESPACE ) subscriber = pub_sub_driver . get_subscriber ( ) subscriber . initialize ( callback ) uri = '' % ( cfg . CONF . df . publisher_transport , '' , cfg . CONF . df . publisher_port ) subscriber . register_listen_address ( uri ) subscriber . daemonize ( ) return subscriber class Namespace ( object ) : pass class TestPubSub ( test_base . DFTestBase ) : def setUp ( self ) : super ( TestPubSub , self ) . setUp ( ) self . events_num = self . do_test = cfg . CONF . df . enable_df_pub_sub self . key = '' . format ( random . random ( ) ) def test_pub_sub_add_port ( self ) : global events_num local_event_num = if not self . do_test : return def _db_change_callback ( table , key , action , value , topic ) : global events_num events_num += subscriber = get_subscriber ( _db_change_callback ) network = self . store ( objects . NetworkTestObj ( self . neutron , self . nb_api ) ) network_id = network . create ( ) eventlet . sleep ( test_utils . DEFAULT_CMD_TIMEOUT ) self . assertNotEqual ( local_event_num , events_num ) local_event_num = events_num port = self . store ( objects . PortTestObj ( self . neutron , self . nb_api , network_id ) ) port . create ( ) eventlet . sleep ( test_utils . DEFAULT_CMD_TIMEOUT ) self . assertNotEqual ( local_event_num , events_num ) local_event_num = events_num port . close ( ) eventlet . sleep ( test_utils . DEFAULT_CMD_TIMEOUT ) self . assertNotEqual ( local_event_num , events_num ) local_event_num = events_num network . close ( ) eventlet . sleep ( test_utils . DEFAULT_CMD_TIMEOUT ) self . assertNotEqual ( local_event_num , events_num ) subscriber . stop ( ) self . assertFalse ( network . exists ( ) ) def test_pub_sub_update_port ( self ) : ns = Namespace ( ) ns . events_num = local_event_num = if not self . do_test : return def _db_change_callback ( table , key , action , value , topic ) : ns . events_num += subscriber = get_subscriber ( _db_change_callback ) network = self . store ( objects . NetworkTestObj ( self . neutron , self . nb_api ) ) network_id = network . create ( ) eventlet . sleep ( test_utils . DEFAULT_CMD_TIMEOUT ) self . assertNotEqual ( local_event_num , ns . events_num ) port = self . store ( objects . PortTestObj ( self . neutron , self . nb_api , network_id ) ) local_event_num = ns . events_num port_id = port . create ( ) eventlet . sleep ( test_utils . DEFAULT_CMD_TIMEOUT ) self . assertNotEqual ( local_event_num , ns . events_num ) local_event_num = ns . events_num update = { '' : { '' : '' } } for i in six . moves . range ( ) : name = \"\" % i update [ '' ] [ '' ] = name self . neutron . update_port ( port_id , update ) eventlet . sleep ( ) eventlet . sleep ( ) self . assertGreaterEqual ( ns . events_num , local_event_num + ) local_event_num = ns . events_num port . close ( ) eventlet . sleep ( test_utils . DEFAULT_CMD_TIMEOUT ) self . assertNotEqual ( local_event_num , ns . events_num ) local_event_num = ns . events_num network . close ( ) eventlet . sleep ( test_utils . DEFAULT_CMD_TIMEOUT ) self . assertNotEqual ( local_event_num , events_num ) subscriber . stop ( ) self . assertFalse ( network . exists ( ) ) def test_pub_sub_event_number_diffrent_port ( self ) : if not self . do_test : return ns = Namespace ( ) ns . events_num = ns . events_action = None def _db_change_callback ( table , key , action , value , topic ) : if '' == key : ns . events_num += ns . events_action = action publisher = get_publisher ( ) subscriber = get_subscriber ( _db_change_callback ) eventlet . sleep ( ) local_events_num = ns . events_num action = \"\" update = DbUpdate ( '' , '' , action , \"\" ) publisher . send_event ( update ) eventlet . sleep ( ) self . assertEqual ( local_events_num + , ns . events_num ) self . assertEqual ( ns . events_action , action ) local_events_num = ns . events_num for i in six . moves . range ( ) : publisher . send_event ( update ) eventlet . sleep ( ) eventlet . sleep ( ) self . assertEqual ( local_events_num + , ns . events_num ) subscriber . stop ( ) def test_pub_sub_add_topic ( self ) : if not self . do_test : return self . events_num_t = self . events_action_t = None def _db_change_callback_topic ( table , key , action , value , topic ) : if '' == key : self . events_num_t += self . events_action_t = action publisher = get_publisher ( ) subscriber = get_subscriber ( _db_change_callback_topic ) eventlet . sleep ( ) topic = \"\" subscriber . register_topic ( topic ) eventlet . sleep ( ) local_events_num = self . events_num_t action = \"\" update = DbUpdate ( '' , '' , action , \"\" ) publisher . send_event ( update , topic ) eventlet . sleep ( ) self . assertEqual ( self . events_action_t , action ) self . assertEqual ( local_events_num + , self . events_num_t ) no_topic_action = '' other_topic = \"\" self . events_action_t = None update = DbUpdate ( '' , None , no_topic_action , \"\" ) publisher . send_event ( update , other_topic ) eventlet . sleep ( ) self . assertEqual ( self . events_action_t , None ) self . assertNotEqual ( local_events_num + , self . events_num_t ) subscriber . unregister_topic ( topic ) publisher . send_event ( update , topic ) self . assertEqual ( self . events_action_t , None ) subscriber . stop ( ) class TestMultiprocPubSub ( test_base . DFTestBase ) : def setUp ( self ) : super ( TestMultiprocPubSub , self ) . setUp ( ) self . do_test = cfg . CONF . df . enable_df_pub_sub self . key = '' . format ( random . random ( ) ) self . event = DbUpdate ( '' , None , \"\" , \"\" , topic = SEND_ALL_TOPIC , ) self . subscriber = None def tearDown ( self ) : if self . subscriber : self . subscriber . stop ( ) super ( TestMultiprocPubSub , self ) . tearDown ( ) def _verify_event ( self , table , key , action , value , topic ) : self . assertEqual ( self . event . table , table ) self . assertEqual ( self . event . key , key ) self . assertEqual ( self . event . action , action ) self . assertEqual ( self . event . topic , topic ) self . event_received = True def test_multiproc_pub_sub ( self ) : if not self . do_test : return self . event_received = False cfg . CONF . df . publisher_multiproc_socket = '' pub_sub_driver = df_utils . load_driver ( cfg . CONF . df . pub_sub_multiproc_driver , df_utils . DF_PUBSUB_DRIVER_NAMESPACE ) publisher = pub_sub_driver . get_publisher ( ) publisher . initialize ( ) self . subscriber = pub_sub_driver . get_subscriber ( ) self . subscriber . initialize ( self . _verify_event ) self . subscriber . daemonize ( ) publisher . send_event ( self . event ) wait_until_true ( lambda : self . event_received ) self . subscriber . stop ( ) self . subscriber = None class TestDbTableMonitors ( test_base . DFTestBase ) : def setUp ( self ) : super ( TestDbTableMonitors , self ) . setUp ( ) self . events_num = enable_df_pub_sub = cfg . CONF . df . enable_df_pub_sub self . do_test = enable_df_pub_sub if not self . do_test : return self . namespace = Namespace ( ) self . namespace . events = [ ] self . publisher = get_publisher ( ) self . subscriber = get_subscriber ( self . _db_change_callback ) self . monitor = self . _create_monitor ( '' ) def tearDown ( self ) : if self . do_test : self . monitor . stop ( ) self . subscriber . stop ( ) super ( TestDbTableMonitors , self ) . tearDown ( ) def _db_change_callback ( self , table , key , action , value , topic ) : self . namespace . events . append ( { '' : table , '' : key , '' : action , '' : value , } ) def _create_monitor ( self , table_name ) : table_monitor = TableMonitor ( table_name , self . nb_api . driver , self . publisher , , ) table_monitor . daemonize ( ) return table_monitor def test_operations ( self ) : if not self . do_test : return expected_event = { '' : unicode ( '' ) , '' : unicode ( '' ) , '' : unicode ( '' ) , '' : None , } self . assertNotIn ( expected_event , self . namespace . events ) self . nb_api . driver . create_key ( '' , '' , jsonutils . dumps ( { '' : '' , '' : '' } ) ) eventlet . sleep ( test_utils . DEFAULT_CMD_TIMEOUT ) self . assertIn ( expected_event , self . namespace . events ) expected_event = { '' : unicode ( '' ) , '' : unicode ( '' ) , ", "answer": "'' : unicode ( '' ) ,"}, {"prompt": " from __future__ import print_function , division from sympy . core . compatibility import range from sympy import SparseMatrix def _doktocsr ( dok ) : \"\"\"\"\"\" row , JA , A = [ list ( i ) for i in zip ( * dok . row_list ( ) ) ] IA = [ ] * ( ( row [ ] if row else ) + ) for i , r in enumerate ( row ) : IA . extend ( [ i ] * ( r - row [ i - ] ) ) IA . extend ( [ len ( A ) ] * ( dok . rows - len ( IA ) + ) ) shape = [ dok . rows , dok . cols ] return [ A , JA , IA , shape ] def _csrtodok ( csr ) : \"\"\"\"\"\" smat = { } ", "answer": "A , JA , IA , shape = csr"}, {"prompt": " import gevent import gevent . monkey import gevent . socket gevent . monkey . patch_all ( ) import subprocess import fcntl import os import errno import sys import urllib import distutils . spawn import gevent . queue import gevent . event import ujson import flask import flask . ext . login import chef import logging app = flask . Flask ( '' ) app . config . update ( DEBUG = True , SECRET_KEY = '' , LOG_FILE = None , LOG_FORMAT = '' , LOG_LEVEL = logging . INFO , ENABLE_BOOTSTRAP = True , ) BOOTSTRAP_ENV = '' if distutils . spawn . find_executable ( '' ) : bootstrap_enabled = True else : bootstrap_enabled = False login_manager = flask . ext . login . LoginManager ( app ) api = chef . autoconfigure ( ) def handler ( environ , start_response ) : handled = False path = environ [ '' ] if path . startswith ( '' ) : ws = environ . get ( '' ) if ws : handle_websocket ( ws , path [ : ] ) handled = True if not handled : return app ( environ , start_response ) websockets = { } def handle_websocket ( ws , env ) : if not env : env = BOOTSTRAP_ENV s = websockets . get ( env ) if s is None : s = websockets [ env ] = [ ] s . append ( ws ) while True : buf = ws . receive ( ) if buf is None : break if ws in s : s . remove ( ws ) @ app . route ( '' ) @ flask . ext . login . login_required def feed ( env = None ) : flask . abort ( ) greenlets = { } def processes ( env = None , node = None , only_executing = True ) : env_greenlets = greenlets . get ( env ) if env_greenlets is None : return [ ] elif node is None : result = [ ] for greenlet in env_greenlets . itervalues ( ) : if not only_executing or not greenlet . ready ( ) : result . append ( greenlet ) return result else : greenlet = env_greenlets . get ( node ) if greenlet is None or ( only_executing and greenlet . ready ( ) ) : return [ ] else : return [ greenlet , ] def broadcast ( env , packet ) : sockets = websockets . get ( env ) if sockets is not None : packet = ujson . encode ( packet ) for ws in list ( sockets ) : if ws . socket is not None : try : ws . send ( packet ) except gevent . socket . error : if ws in sockets : sockets . remove ( ws ) @ app . route ( '' , methods = [ '' ] ) @ app . route ( '' , methods = [ '' ] ) @ flask . ext . login . login_required def converge ( env , node = None ) : if env == BOOTSTRAP_ENV : flask . abort ( ) if len ( processes ( env , node , only_executing = True ) ) > : return ujson . encode ( { '' : '' } ) if node is not None : nodes = { node : chef . Node ( node , api = api ) , } else : nodes = { row . object . name : row . object for row in chef . Search ( '' , '' + env , api = api ) } get_command = lambda n : [ '' , '' , '' , n [ '' ] , '' , '' ] return _run ( nodes , get_command , env = env , progress_status = '' , ) @ app . route ( '' ) @ flask . ext . login . login_required def bootstrap_list ( ) : if not bootstrap_enabled or not app . config . get ( '' ) : flask . abort ( ) nodes = greenlets . get ( BOOTSTRAP_ENV , { } ) . keys ( ) status , output , executing = get_env_status ( BOOTSTRAP_ENV , nodes , progress_status = '' ) return flask . render_template ( '' , status = status , output = output , nodes = nodes , ) @ app . route ( '' , methods = [ '' ] ) @ flask . ext . login . login_required def bootstrap ( ip ) : if not bootstrap_enabled or not app . config . get ( '' ) : flask . abort ( ) if len ( processes ( BOOTSTRAP_ENV , ip , only_executing = True ) ) > : return ujson . encode ( { '' : '' } ) if len ( chef . Search ( '' , '' % ( ip , ip , ip ) , api = api ) ) > : broadcast ( BOOTSTRAP_ENV , { '' : ip , '' : '' , '' : '' } ) return ujson . encode ( { '' : '' } ) get_command = lambda ip : [ '' , '' , '' , ip ] return _run ( { ip : ip , } , get_command , env = BOOTSTRAP_ENV , progress_status = '' , ) def _run ( nodes , get_command , env , progress_status ) : env_greenlets = greenlets . get ( env ) if env_greenlets is None : greenlets [ env ] = env_greenlets = { } for node in nodes : try : del env_greenlets [ node ] except KeyError : pass for hostname in nodes : node_object = nodes [ hostname ] p = subprocess . Popen ( get_command ( node_object ) , shell = False , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) p . chunks = [ ] fcntl . fcntl ( p . stdout , fcntl . F_SETFL , os . O_NONBLOCK ) def read ( host , process ) : broadcast ( env , { '' : host , '' : progress_status } ) while True : chunk = None try : chunk = process . stdout . read ( ) if not chunk : break except IOError , e : chunk = None if e [ ] != errno . EAGAIN : raise sys . exc_clear ( ) if chunk : process . chunks . append ( chunk ) broadcast ( env , { '' : host , '' : chunk , } ) gevent . socket . wait_read ( process . stdout . fileno ( ) ) process . stdout . close ( ) process . wait ( ) errors = process . stderr . read ( ) process . chunks . append ( errors ) broadcast ( env , { '' : host , '' : '' if process . returncode == else '' , '' : errors } ) if len ( processes ( env , only_executing = True ) ) <= : broadcast ( env , { '' : '' } ) return process . returncode greenlet = gevent . spawn ( read , host = hostname , process = p ) greenlet . process = p env_greenlets [ hostname ] = greenlet broadcast ( env , { '' : progress_status } ) return ujson . encode ( { '' : progress_status if len ( nodes ) > else '' } ) @ app . route ( '' ) @ flask . ext . login . login_required def index ( ) : envs = chef . Environment . list ( api = api ) return flask . render_template ( '' , envs = envs . itervalues ( ) , bootstrap_enabled = bootstrap_enabled and app . config . get ( '' ) , ) def get_env_status ( env , nodes , progress_status ) : status = { } output = { } executing = False env_greenlets = greenlets . get ( env ) if env_greenlets is None : ", "answer": "env_greenlets = greenlets [ env ] = { }"}, {"prompt": " import os , sys , time import simplejson as json from zohmg . config import Config sys . path . append ( os . path . dirname ( __file__ ) ) import data_utils class transform ( object ) : def __init__ ( self ) : ", "answer": "self . config = Config ( )"}, {"prompt": " \"\"\"\"\"\" from setuptools import setup , find_packages import mana version = entry_points = { '' : [ ", "answer": "''"}, {"prompt": " from django . core . urlresolvers import reverse_lazy from django . utils . translation import ugettext_lazy as _ from horizon import exceptions from horizon import tabs from gbpui import client from gbpui import column_filters as gfilters import tables class L3PolicyDetailsTab ( tabs . Tab ) : name = _ ( \"\" ) slug = \"\" template_name = \"\" failure_url = reverse_lazy ( '' ) def get_context_data ( self , request ) : l3policy_id = self . tab_group . kwargs [ '' ] try : l3policy = client . l3policy_get ( request , l3policy_id ) except Exception : exceptions . handle ( request , _ ( '' ) , redirect = self . failure_url ) return { '' : l3policy } class L3PolicyTab ( tabs . TableTab ) : table_classes = ( tables . L3PolicyTable , ) name = _ ( \"\" ) slug = \"\" template_name = \"\" def get_l3policy_table_data ( self ) : policies = [ ] try : policies = client . l3policy_list ( self . request , tenant_id = self . request . user . tenant_id ) update = lambda x : gfilters . update_l3_policy_attributes ( self . request , x ) policies = [ update ( item ) for item in policies ] except Exception : policies = [ ] exceptions . handle ( self . tab_group . request , _ ( '' ) ) return policies class L2PolicyTab ( tabs . TableTab ) : table_classes = ( tables . L2PolicyTable , ) name = _ ( \"\" ) slug = \"\" template_name = \"\" def get_l2policy_table_data ( self ) : policies = [ ] try : policies = client . l2policy_list ( self . request , tenant_id = self . request . user . tenant_id ) except Exception : policies = [ ] exceptions . handle ( self . tab_group . request , _ ( '' ) ) return policies class ServicePolicyTab ( tabs . TableTab ) : table_classes = ( tables . ServicePolicyTable , ) name = _ ( \"\" ) slug = \"\" template_name = \"\" def get_service_policy_table_data ( self ) : policies = [ ] try : policies = client . networkservicepolicy_list ( self . request , tenant_id = self . request . user . tenant_id ) update = lambda x : gfilters . update_service_policy_attributes ( x ) policies = [ update ( item ) for item in policies ] except Exception : exceptions . handle ( self . tab_group . request , _ ( '' ) ) return policies class ServicePolicyDetailsTab ( tabs . Tab ) : name = _ ( \"\" ) slug = \"\" template_name = \"\" failure_url = reverse_lazy ( '' ) def get_context_data ( self , request ) : policy_id = self . tab_group . kwargs [ '' ] try : policy = client . get_networkservice_policy ( request , policy_id ) except Exception : exceptions . handle ( request , _ ( '' ) , redirect = self . failure_url ) return { '' : policy } class ExternalConnectivityTab ( tabs . TableTab ) : table_classes = ( tables . ExternalConnectivityTable , ) name = _ ( \"\" ) slug = \"\" template_name = \"\" def get_external_connectivity_table_data ( self ) : external_segment_list = [ ] try : external_segment_list = client . externalconnectivity_list ( self . request , self . request . user . tenant_id ) except Exception : exceptions . handle ( self . tab_group . request , _ ( '' ) ) return external_segment_list class ExternalConnectivityDetailsTab ( tabs . Tab ) : name = _ ( \"\" ) slug = \"\" template_name = \"\" failure_url = reverse_lazy ( '' ) def get_context_data ( self , request ) : external_connectivity_id = self . tab_group . kwargs [ '' ] try : external_connectivity = client . get_externalconnectivity ( request , external_connectivity_id ) except Exception : exceptions . handle ( request , _ ( '' ) , redirect = self . failure_url ) return { '' : external_connectivity } class NATPoolTab ( tabs . TableTab ) : table_classes = ( tables . NATPoolTable , ) name = _ ( \"\" ) slug = \"\" template_name = \"\" def get_nat_pool_table_data ( self ) : nat_pool_list = [ ] try : nat_pools = client . natpool_list ( self . request , self . request . user . tenant_id ) update = lambda x : gfilters . update_nat_pool_attributes ( self . request , x ) nat_pool_list = [ update ( nat_pool ) for nat_pool in nat_pools ] except Exception : exceptions . handle ( self . tab_group . request , _ ( '' ) ) return nat_pool_list class NATPoolDetailsTab ( tabs . Tab ) : name = _ ( \"\" ) slug = \"\" template_name = \"\" failure_url = reverse_lazy ( '' ) def get_context_data ( self , request ) : nat_pool_id = self . tab_group . kwargs [ '' ] try : nat_pool = client . get_natpool ( request , nat_pool_id ) except Exception : exceptions . handle ( request , _ ( '' ) , redirect = self . failure_url ) return { '' : nat_pool } class ServicePolicyDetailsTabs ( tabs . TabGroup ) : slug = \"\" tabs = ( ServicePolicyDetailsTab , ) sticky = True class ExternalConnectivityDetailsTabs ( tabs . TabGroup ) : slug = \"\" tabs = ( ExternalConnectivityDetailsTab , ) sticky = True class NATPoolDetailsTabs ( tabs . TabGroup ) : slug = \"\" tabs = ( NATPoolDetailsTab , ) sticky = True class L3PolicyTabs ( tabs . TabGroup ) : slug = \"\" tabs = ( L3PolicyTab , ServicePolicyTab , ExternalConnectivityTab , NATPoolTab ) sticky = True class L2PolicyDetailsTab ( tabs . Tab ) : name = _ ( \"\" ) slug = \"\" ", "answer": "template_name = \"\""}, {"prompt": " import base64 from selenium . webdriver . remote . command import Command from selenium . webdriver . remote . remote_connection import RemoteConnection from selenium . webdriver . remote . webdriver import WebDriver as RemoteWebDriver from selenium . webdriver . common . desired_capabilities import DesiredCapabilities from selenium . common . exceptions import WebDriverException from selenium . webdriver . phantomjs . service import Service class WebDriver ( RemoteWebDriver ) : \"\"\"\"\"\" def __init__ ( self , executable_path = \"\" , port = , desired_capabilities = DesiredCapabilities . PHANTOMJS , service_args = None , service_log_path = None ) : \"\"\"\"\"\" self . service = Service ( executable_path , port = port , service_args = service_args , log_path = service_log_path ) self . service . start ( ) ", "answer": "command_executor = self . service . service_url"}, {"prompt": " from sixpack import __version__ try : from setuptools import setup except ImportError : from distutils . core import setup setup ( name = '' , version = __version__ , author = '' , author_email = '' , packages = [ '' , '' ] , scripts = [ '' , '' ] , url = '' , license = open ( '' ) . read ( ) , classifiers = [ '' , ] , description = '' , long_description = open ( '' ) . read ( ) + '' + open ( '' ) . read ( ) , tests_require = [ '' ] , test_suite = '' , install_requires = open ( '' ) . readlines ( ) , ", "answer": "include_package_data = True ,"}, {"prompt": " \"\"\"\"\"\" import unittest import sys if __name__ == '' : test_suite = unittest . TestLoader ( ) . discover ( '' , pattern = '' ) ", "answer": "test_results = unittest . TextTestRunner ( verbosity = ) . run ( test_suite )"}, {"prompt": " import pinproc ", "answer": "proc = pinproc . PinPROC ( pinproc . normalize_machine_type ( '' ) )"}, {"prompt": " from __future__ import unicode_literals from django . db import models , migrations class Migration ( migrations . Migration ) : dependencies = [ ( '' , '' ) , ", "answer": "( '' , '' ) ,"}, {"prompt": " from __future__ import absolute_import import mock import unittest from mutornadomon . net import is_local_address from mutornadomon . net import is_private_address class TestIsLocalAddress ( unittest . TestCase ) : @ mock . patch ( '' ) def test_is_local_address_works_with_python2 ( self , is_python2_mock ) : \"\"\"\"\"\" is_python2_mock . return_value = True self . assertTrue ( is_local_address ( u'' ) ) self . assertTrue ( is_local_address ( '' ) ) self . assertFalse ( is_local_address ( '' ) ) @ mock . patch ( '' ) def test_is_local_address_works_with_python3 ( self , is_python2_mock ) : \"\"\"\"\"\" is_python2_mock . return_value = False self . assertTrue ( is_local_address ( u'' ) ) ", "answer": "self . assertTrue ( is_local_address ( '' ) )"}, {"prompt": " import re import sys from readfq import readfq complement = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' } if len ( sys . argv ) < : sys . exit ( \"\" ) seqs = dict ( ) infile = open ( sys . argv [ ] ) for name , seq , qual in readfq ( infile ) : seqs [ name ] = seq motif_str = sys . argv [ ] . upper ( ) ", "answer": "motif_str_rc = \"\" . join ( [ complement [ b ] for b in motif_str [ : : - ] ] )"}, {"prompt": " \"\"\"\"\"\" import logging import os import signal import socket import traceback import zmq from zmq . core . error import ZMQError from zmq . eventloop . ioloop import IOLoop , DelayedCallback from zmq . log . handlers import PUBHandler from spyder . import_util import import_class from spyder . core . constants import ZMQ_SPYDER_MGMT_WORKER from spyder . core . constants import ZMQ_SPYDER_MGMT_WORKER_AVAIL from spyder . core . constants import ZMQ_SPYDER_MGMT_WORKER_QUIT from spyder . core . constants import ZMQ_SPYDER_MGMT_WORKER_QUIT_ACK from spyder . core . messages import MgmtMessage from spyder . core . mgmt import ZmqMgmt from spyder . core . worker import ZmqWorker , AsyncZmqWorker from spyder . processor . fetcher import FetchProcessor def create_worker_management ( settings , zmq_context , io_loop ) : \"\"\"\"\"\" listening_socket = zmq_context . socket ( zmq . SUB ) listening_socket . setsockopt ( zmq . SUBSCRIBE , \"\" ) listening_socket . connect ( settings . ZEROMQ_MGMT_MASTER ) publishing_socket = zmq_context . socket ( zmq . PUB ) publishing_socket . connect ( settings . ZEROMQ_MGMT_WORKER ) return ZmqMgmt ( listening_socket , publishing_socket , io_loop = io_loop ) def create_worker_fetcher ( settings , mgmt , zmq_context , log_handler , io_loop ) : \"\"\"\"\"\" pulling_socket = zmq_context . socket ( zmq . PULL ) pulling_socket . connect ( settings . ZEROMQ_WORKER_PROC_FETCHER_PULL ) pushing_socket = zmq_context . socket ( zmq . PUSH ) pushing_socket . setsockopt ( zmq . HWM , settings . ZEROMQ_WORKER_PROC_FETCHER_PUSH_HWM ) pushing_socket . bind ( settings . ZEROMQ_WORKER_PROC_FETCHER_PUSH ) fetcher = FetchProcessor ( settings , io_loop ) return AsyncZmqWorker ( pulling_socket , pushing_socket , mgmt , fetcher , log_handler , settings . LOG_LEVEL_WORKER , io_loop ) def create_processing_function ( settings , pipeline ) : \"\"\"\"\"\" processors = [ ] for processor in pipeline : processor_class = import_class ( processor ) processors . append ( processor_class ( settings ) ) def processing ( data_message ) : \"\"\"\"\"\" next_message = data_message for processor in processors : next_message = processor ( next_message ) return next_message return processing def create_worker_extractor ( settings , mgmt , zmq_context , log_handler , io_loop ) : \"\"\"\"\"\" pipeline = settings . SPYDER_EXTRACTOR_PIPELINE pipeline . extend ( settings . SPYDER_SCOPER_PIPELINE ) processing = create_processing_function ( settings , pipeline ) pulling_socket = zmq_context . socket ( zmq . PULL ) pulling_socket . connect ( settings . ZEROMQ_WORKER_PROC_EXTRACTOR_PULL ) pushing_socket = zmq_context . socket ( zmq . PUB ) pushing_socket . setsockopt ( zmq . HWM , settings . ZEROMQ_WORKER_PROC_EXTRACTOR_PUB_HWM ) pushing_socket . connect ( settings . ZEROMQ_WORKER_PROC_EXTRACTOR_PUB ) return ZmqWorker ( pulling_socket , pushing_socket , mgmt , processing , log_handler , settings . LOG_LEVEL_WORKER , io_loop = io_loop ) def main ( settings ) : \"\"\"\"\"\" ", "answer": "identity = \"\" % ( socket . gethostname ( ) , os . getpid ( ) )"}, {"prompt": " \"\"\"\"\"\" if __name__ == \"\" : import os import sys ", "answer": "from os . path import dirname , realpath , isfile"}, {"prompt": " from __future__ import unicode_literals import re ", "answer": "from . common import InfoExtractor"}, {"prompt": " from . mono_font import MONO_FONT IDLE_THEME = { \"\" : { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : MONO_FONT } , \"\" : { \"\" : { \"\" : \"\" } , \"\" : { \"\" : \"\" } , \"\" : { \"\" : \"\" } , \"\" : { \"\" : \"\" } , \"\" : { \"\" : \"\" } , \"\" : { \"\" : \"\" } , \"\" : { \"\" : \"\" } , \"\" : { \"\" : \"\" } , \"\" : { ", "answer": "\"\" : \"\""}, {"prompt": " \"\"\"\"\"\" import numpy as np from pystruct . datasets import load_letters from pystruct . models import ChainCRF from pystruct . learners import OneSlackSSVM abc = \"\" letters = load_letters ( ) X , y , folds = letters [ '' ] , letters [ '' ] , letters [ '' ] X , y = np . array ( X ) , np . array ( y ) X_train , X_test = X [ folds == ] , X [ folds != ] y_train , y_test = y [ folds == ] , y [ folds != ] model = ChainCRF ( ) ", "answer": "ssvm = OneSlackSSVM ( model = model , C = , tol = , verbose = , max_iter = )"}, {"prompt": " import unittest import lcs class TestLCS ( unittest . TestCase ) : def test_lcs ( self ) : ", "answer": "self . assertEqual ( lcs . longest_common_subsequence ( \"\" , \"\" ) , ( , \"\" ) )"}, {"prompt": " from google . appengine . api import search import pytest @ pytest . fixture def index ( ) : index = search . Index ( name = '' , namespace = '' ) ", "answer": "doc = search . Document ("}, {"prompt": " import xml . dom . minidom from urllib import urlencode from urllib2 import urlopen from geopy import util try : import json except ImportError : try : import simplejson as json except ImportError : from django . utils import simplejson as json from geopy . geocoders . base import Geocoder class GeoNames ( Geocoder ) : def __init__ ( self , format_string = None , output_format = None , country_bias = None ) : if format_string != None : from warnings import warn ", "answer": "warn ( '' +"}, {"prompt": " from oslo_config import cfg from nova import exception from nova . i18n import _ from nova import utils from nova . virt . libvirt . volume import volume as libvirt_volume volume_opts = [ cfg . StrOpt ( '' , help = '' ) , cfg . StrOpt ( '' , help = '' '' ) , ] CONF = cfg . CONF CONF . register_opts ( volume_opts , '' ) class LibvirtNetVolumeDriver ( libvirt_volume . LibvirtBaseVolumeDriver ) : \"\"\"\"\"\" def __init__ ( self , connection ) : super ( LibvirtNetVolumeDriver , self ) . __init__ ( connection , is_block_dev = False ) def _get_secret_uuid ( self , conf , password = None ) : secret = self . connection . _host . find_secret ( conf . source_protocol , conf . source_name ) if secret is None : secret = self . connection . _host . create_secret ( conf . source_protocol , conf . source_name , password ) return secret . UUIDString ( ) def _delete_secret_by_name ( self , connection_info ) : source_protocol = connection_info [ '' ] netdisk_properties = connection_info [ '' ] if source_protocol == '' : return elif source_protocol == '' : usage_type = '' usage_name = ( \"\" % netdisk_properties ) self . connection . _host . delete_secret ( usage_type , usage_name ) def get_config ( self , connection_info , disk_info ) : \"\"\"\"\"\" conf = super ( LibvirtNetVolumeDriver , self ) . get_config ( connection_info , disk_info ) netdisk_properties = connection_info [ '' ] conf . source_type = \"\" conf . source_protocol = connection_info [ '' ] conf . source_name = netdisk_properties . get ( '' ) conf . source_hosts = netdisk_properties . get ( '' , [ ] ) conf . source_ports = netdisk_properties . get ( '' , [ ] ) auth_enabled = netdisk_properties . get ( '' ) if ( conf . source_protocol == '' and CONF . libvirt . rbd_secret_uuid ) : conf . auth_secret_uuid = CONF . libvirt . rbd_secret_uuid auth_enabled = True if CONF . libvirt . rbd_user : ", "answer": "conf . auth_username = CONF . libvirt . rbd_user"}, {"prompt": " import os from distutils . core import setup def read ( fname ) : return open ( os . path . join ( os . path . dirname ( __file__ ) , fname ) ) . read ( ) setup ( name = '' , version = '' , description = '' , author = '' , ", "answer": "author_email = '' ,"}, {"prompt": " import os import time import pytest from . . base import BaseTopazTest class TestKernel ( BaseTopazTest ) : def test_puts_nil ( self , space , capfd ) : space . execute ( \"\" ) out , err = capfd . readouterr ( ) assert out == \"\" def test_print ( self , space , capfd ) : space . execute ( \"\" ) out , err = capfd . readouterr ( ) assert out == \"\" def test_p ( self , space , capfd ) : space . execute ( \"\" ) out , err = capfd . readouterr ( ) assert out == \"\" def test_lambda ( self , space ) : w_res = space . execute ( \"\"\"\"\"\" ) w_cls , w_lambda = space . listview ( w_res ) assert w_cls is space . w_proc assert w_lambda is space . w_true def test_proc ( self , space ) : w_res = space . execute ( \"\"\"\"\"\" ) w_cls , w_lambda = space . listview ( w_res ) assert w_cls is space . w_proc assert w_lambda is space . w_false def test_singleton_methods ( self , space ) : w_res = space . execute ( \"\"\"\"\"\" ) assert self . unwrap ( space , w_res ) == [ ] w_res = space . execute ( \"\"\"\"\"\" ) assert self . unwrap ( space , w_res ) == [ \"\" ] w_res = space . execute ( \"\"\"\"\"\" ) assert self . unwrap ( space , w_res ) == [ [ \"\" ] , [ ] ] def test_raise ( self , space ) : with self . raises ( space , \"\" , \"\" ) : space . execute ( \"\" ) with self . raises ( space , \"\" , \"\" ) : space . execute ( \"\" ) with self . raises ( space , \"\" , \"\" ) : space . execute ( \"\" ) with self . raises ( space , \"\" , \"\" ) : space . execute ( \"\" ) with self . raises ( space , \"\" , \"\" ) : space . execute ( \"\"\"\"\"\" ) with self . raises ( space , \"\" ) : space . execute ( \"\"\"\"\"\" ) with self . raises ( space , \"\" ) : space . execute ( \"\" ) def test_overriding_raise ( self , space ) : w_res = space . execute ( \"\"\"\"\"\" ) assert self . unwrap ( space , w_res ) == [ '' ] def test_raise_error_subclass ( self , space ) : with self . raises ( space , \"\" , '' ) : space . execute ( \"\"\"\"\"\" ) def test_Array ( self , space ) : w_res = space . execute ( \"\"\"\"\"\" ) assert self . unwrap ( space , w_res ) == [ [ \"\" ] , [ \"\" ] ] assert self . unwrap ( space , space . execute ( \"\" ) ) == [ ] def test_String ( self , space ) : w_res = space . execute ( \"\" ) assert self . unwrap ( space , w_res ) == [ \"\" , \"\" ] def test_Integer ( self , space ) : w_res = space . execute ( \"\" ) assert self . unwrap ( space , w_res ) == [ , ] def test_exit ( self , space ) : with self . raises ( space , \"\" ) : space . execute ( \"\" ) with self . raises ( space , \"\" ) : space . execute ( \"\" ) def test_block_given_p ( self , space ) : assert space . execute ( \"\" ) is space . w_false assert space . execute ( \"\" ) is space . w_false assert space . execute ( \"\" ) is space . w_false w_res = space . execute ( \"\"\"\"\"\" ) assert self . unwrap ( space , w_res ) == [ False , True ] w_res = space . execute ( \"\"\"\"\"\" ) assert self . unwrap ( space , w_res ) == [ False , True ] def test_eqlp ( self , space ) : w_res = space . execute ( \"\"\"\"\"\" ) assert self . unwrap ( space , w_res ) == [ True , False ] def test_eval ( self , space ) : w_res = space . execute ( \"\"\"\"\"\" ) assert space . int_w ( w_res ) == def test_responds_to ( self , space ) : w_res = space . execute ( \"\" ) assert self . unwrap ( space , w_res ) == [ False , True ] def test_Float ( self , space ) : assert space . float_w ( space . execute ( \"\" ) ) == assert space . float_w ( space . execute ( \"\" ) ) == assert space . float_w ( space . execute ( \"\" ) ) == assert space . float_w ( space . execute ( \"\" ) ) == with self . raises ( space , \"\" ) : space . execute ( \"\" ) with self . raises ( space , \"\" ) : space . execute ( \"\" ) w_res = space . execute ( \"\"\"\"\"\" ) assert space . float_w ( w_res ) == def test_loop ( self , space ) : w_res = space . execute ( \"\"\"\"\"\" ) assert self . unwrap ( space , w_res ) == [ , , ] def test_sleep ( self , space ) : now = time . time ( ) w_res = space . execute ( \"\" ) assert space . int_w ( w_res ) == assert time . time ( ) - now >= now = time . time ( ) w_res = space . execute ( \"\" ) assert space . int_w ( w_res ) == assert time . time ( ) - now >= with self . raises ( space , \"\" ) : ", "answer": "space . execute ( \"\" )"}, {"prompt": " from django . utils import timezone from opps . api import BaseHandler from . models import Container , ContainerBox class Handler ( BaseHandler ) : allowed_methods = ( '' , ) def read ( self , request ) : filters = request . GET . dict ( ) filters [ '' ] = timezone . now ( ) filters [ '' ] = True ", "answer": "[ filters . pop ( b , None ) for b in self . blackfield ]"}, {"prompt": " import unittest from mock import patch from tests . tools import create_mock_json from twilio . rest . resources . monitor . events import Events AUTH = ( \"\" , \"\" ) BASE_URI = \"\" EVENT_SID = \"\" class EventTest ( unittest . TestCase ) : @ patch ( '' ) def test_get ( self , request ) : resp = create_mock_json ( '' ) resp . status_code = request . return_value = resp uri = \"\" . format ( BASE_URI , EVENT_SID ) list_resource = Events ( BASE_URI , AUTH ) list_resource . get ( EVENT_SID ) request . assert_called_with ( \"\" , uri , auth = AUTH , use_json_extension = False ) @ patch ( '' ) def test_list ( self , request ) : resp = create_mock_json ( '' ) resp . status_code = request . return_value = resp uri = \"\" . format ( BASE_URI ) list_resource = Events ( BASE_URI , AUTH ) list_resource . list ( ) ", "answer": "request . assert_called_with ( \"\" , uri , params = { } , auth = AUTH , use_json_extension = False ) "}, {"prompt": " import os import sys if __name__ == \"\" : os . environ . setdefault ( \"\" , \"\" ) from django . core . management import execute_from_command_line ", "answer": "execute_from_command_line ( sys . argv ) "}, {"prompt": " from __future__ import ( absolute_import , division , generators , nested_scopes , print_function , unicode_literals , with_statement ) import unittest from pants . help . scope_info_iterator import ScopeInfoIterator from pants . option . arg_splitter import GLOBAL_SCOPE from pants . option . global_options import GlobalOptionsRegistrar from pants . option . scope import ScopeInfo from pants . subsystem . subsystem import Subsystem from pants . subsystem . subsystem_client_mixin import SubsystemDependency from pants . task . task import Task class ScopeInfoIteratorTest ( unittest . TestCase ) : def test_iteration ( self ) : self . maxDiff = None class Subsys1 ( Subsystem ) : options_scope = '' class Subsys2 ( Subsystem ) : options_scope = '' @ classmethod def subsystem_dependencies ( cls ) : return ( SubsystemDependency ( Subsys1 , '' ) , ) class Goal1Task2 ( Task ) : options_scope = '' @ classmethod def subsystem_dependencies ( cls ) : return ( SubsystemDependency ( Subsys1 , '' ) , ) @ classmethod def task_subsystems ( cls ) : return tuple ( ) infos = [ ScopeInfo ( GLOBAL_SCOPE , ScopeInfo . GLOBAL , GlobalOptionsRegistrar ) , ScopeInfo ( '' , ScopeInfo . SUBSYSTEM , Subsys2 ) , ScopeInfo ( '' , ScopeInfo . SUBSYSTEM , Subsys1 ) , ScopeInfo ( '' , ScopeInfo . INTERMEDIATE ) , ScopeInfo ( '' , ScopeInfo . TASK ) , ScopeInfo ( '' , ScopeInfo . TASK , Goal1Task2 ) , ScopeInfo ( '' , ScopeInfo . SUBSYSTEM , Subsys1 ) , ScopeInfo ( '' , ScopeInfo . INTERMEDIATE ) , ScopeInfo ( '' , ScopeInfo . TASK ) , ScopeInfo ( '' , ScopeInfo . TASK ) , ScopeInfo ( '' , ScopeInfo . INTERMEDIATE ) , ScopeInfo ( '' , ScopeInfo . TASK ) , ScopeInfo ( '' , ScopeInfo . TASK ) , ] scope_to_infos = dict ( ( x . scope , x ) for x in infos ) it = ScopeInfoIterator ( scope_to_infos ) actual = list ( it . iterate ( [ GLOBAL_SCOPE , '' , '' , '' ] ) ) expected_scopes = [ GLOBAL_SCOPE , '' , '' , ", "answer": "'' , '' , '' , '' ,"}, {"prompt": " from __future__ import unicode_literals , absolute_import import logging from permissions . models import StoredPermission logger = logging . getLogger ( __name__ ) class ModelPermission ( object ) : _registry = { } _proxies = { } _inheritances = { } @ classmethod def register ( cls , model , permissions ) : cls . _registry . setdefault ( model , [ ] ) for permission in permissions : cls . _registry [ model ] . append ( permission ) @ classmethod def get_for_instance ( cls , instance ) : try : permissions = cls . _registry [ type ( instance ) ] except KeyError : try : permissions = cls . _registry [ cls . _proxies [ type ( instance ) ] ] except KeyError : ", "answer": "permissions = ( )"}, {"prompt": " \"\"\"\"\"\" import re class EndOfText ( RuntimeError ) : \"\"\"\"\"\" class Scanner ( object ) : \"\"\"\"\"\" def __init__ ( self , text , flags = ) : \"\"\"\"\"\" self . data = text self . data_length = len ( text ) self . start_pos = self . pos = ", "answer": "self . flags = flags"}, {"prompt": " \"\"\"\"\"\" import networkx as nx from networkx . utils import not_implemented_for , pairwise __all__ = [ '' ] @ not_implemented_for ( '' ) def is_semiconnected ( G ) : \"\"\"\"\"\" if len ( G ) == : raise nx . NetworkXPointlessConcept ( '' ) if not nx . is_weakly_connected ( G ) : return False G = nx . condensation ( G ) ", "answer": "path = nx . topological_sort ( G )"}, {"prompt": " import base64 import ctypes import ctypes . util import struct import sys if sys . platform == \"\" : openssl_lib_path = \"\" else : openssl_lib_path = ctypes . util . find_library ( \"\" ) openssl = ctypes . CDLL ( openssl_lib_path ) clib = ctypes . CDLL ( ctypes . util . find_library ( \"\" ) ) class RSA ( ctypes . Structure ) : _fields_ = [ ( \"\" , ctypes . c_int ) , ( \"\" , ctypes . c_long ) , ( \"\" , ctypes . c_void_p ) , ( \"\" , ctypes . c_void_p ) , ( \"\" , ctypes . c_void_p ) , ( \"\" , ctypes . c_void_p ) , ( \"\" , ctypes . c_void_p ) , ( \"\" , ctypes . c_void_p ) , ( \"\" , ctypes . c_void_p ) , ( \"\" , ctypes . c_void_p ) , ( \"\" , ctypes . c_void_p ) , ( \"\" , ctypes . c_void_p ) , ( \"\" , ctypes . c_void_p ) , ( \"\" , ctypes . c_int ) , ( \"\" , ctypes . c_int ) , ( \"\" , ctypes . c_int ) , ( \"\" , ctypes . c_void_p ) , ( \"\" , ctypes . c_void_p ) , ( \"\" , ctypes . c_void_p ) , ( \"\" , ctypes . c_char_p ) , ( \"\" , ctypes . c_void_p ) , ( \"\" , ctypes . c_void_p ) ] openssl . RSA_PKCS1_PADDING = openssl . RSA_new . restype = ctypes . POINTER ( RSA ) openssl . BN_bin2bn . restype = ctypes . c_void_p openssl . BN_bin2bn . argtypes = [ ctypes . c_char_p , ctypes . c_int , ctypes . c_void_p ] openssl . BN_new . restype = ctypes . c_void_p openssl . RSA_size . restype = ctypes . c_int openssl . RSA_size . argtypes = [ ctypes . POINTER ( RSA ) ] openssl . RSA_public_encrypt . argtypes = [ ctypes . c_int , ctypes . c_char_p , ", "answer": "ctypes . c_char_p ,"}, {"prompt": " from django . shortcuts import render ", "answer": "from twobuntu . articles . models import Article"}, {"prompt": " DATE_FORMAT = '' TIME_FORMAT = '' YEAR_MONTH_FORMAT = '' ", "answer": "MONTH_DAY_FORMAT = ''"}, {"prompt": " import ipaddress class IPPool ( object ) : _pool = [ ] _capacity = None def __init__ ( self , network ) : if isinstance ( network , str ) : network = network . decode ( ) self . _network = ipaddress . ip_network ( network ) self . _hosts = self . _network . hosts ( ) def _next_host ( self ) : for host in self . _hosts : if host in self . _pool : continue return host def register ( self , address ) : ", "answer": "addr = ipaddress . ip_address ( address )"}, {"prompt": " import py from pypy . tool . pytest . result import ResultFromMime testpath = py . magic . autopath ( ) . dirpath ( '' ) class TestResultCache : def test_timeout ( self ) : test = ResultFromMime ( testpath . join ( '' ) ) assert test . ratio_of_passed ( ) == def test_passed ( self ) : test = ResultFromMime ( testpath . join ( '' ) ) assert test . ratio_of_passed ( ) == def test_unittest_partial ( self ) : test = ResultFromMime ( testpath . join ( '' ) ) assert test . ratio_of_passed ( ) == / def test_doctest_of ( self ) : test = ResultFromMime ( testpath . join ( '' ) ) assert test . ratio_of_passed ( ) == / def test_doctest_slash ( self ) : test = ResultFromMime ( testpath . join ( '' ) ) assert test . ratio_of_passed ( ) == / def test_fail ( self ) : test = ResultFromMime ( testpath . join ( '' ) ) ", "answer": "assert test . ratio_of_passed ( ) == "}, {"prompt": " from django . db import models from railroad . viewhosts . views import slugify class Service ( models . Model ) : host = models . CharField ( max_length = ) service = models . CharField ( max_length = ) start = models . IntegerField ( ) end = models . IntegerField ( ) uniq = models . IntegerField ( ) def __unicode__ ( self ) : return slugify ( self . host + self . service ) def __repr__ ( self ) : return slugify ( '' + self . host + self . service + '' ) class ConfiguratorPage ( models . Model ) : link = models . CharField ( max_length = ) services = models . ManyToManyField ( Service ) creation = models . DateTimeField ( '' ) user = models . CharField ( max_length = ) description = models . CharField ( max_length = , blank = True ) def __unicode__ ( self ) : return self . link def save_services ( self , service_dict ) : for s in service_dict : if not s : continue host = s [ '' ] service = s [ '' ] if s . has_key ( '' ) : start = s [ '' ] else : start = if s . has_key ( '' ) : end = s [ '' ] else : end = if s . has_key ( '' ) : uniq = s [ '' ] else : uniq = self . services . create ( host = host , service = service , start = start , end = end , uniq = uniq ) def load_services ( self ) : service_list = [ ] for s in self . services . all ( ) : host = s . host servicename = s . service start = s . start end = s . end uniq = s . uniq service = { \"\" : host , \"\" : servicename , \"\" : start , \"\" : end , \"\" : uniq , } service_list . append ( service ) ", "answer": "return service_list"}, {"prompt": " from __future__ import unicode_literals from django . contrib . auth . decorators import login_required from djblets . siteconfig . models import SiteConfiguration from djblets . util . decorators import simple_decorator from reviewboard . accounts . models import Profile @ simple_decorator def check_login_required ( view_func ) : \"\"\"\"\"\" ", "answer": "def _check ( * args , ** kwargs ) :"}, {"prompt": " tag = { \"\" : \"\" , \"\" : \"\" } update_all = { \"\" : { \"\" : { \"\" : \"\" } ", "answer": "} ,"}, {"prompt": " import zmq import MySQLdb ctx = zmq . Context ( ) sock = ctx . socket ( zmq . REP ) sock . connect ( '' ) mysql = MySQLdb . connect ( host = '' , user = '' , db = '' ) ", "answer": "while True :"}, {"prompt": " import os import sys import six import unittest2 as unittest from mock . tests import support from mock . tests . support import SomeClass , is_instance , callable from mock import ( NonCallableMock , CallableMixin , patch , sentinel , MagicMock , Mock , NonCallableMagicMock , patch , DEFAULT , call ) from mock . mock import _patch , _get_target builtin_string = '' if six . PY3 : builtin_string = '' unicode = str PTModule = sys . modules [ __name__ ] MODNAME = '' % __name__ def _get_proxy ( obj , get_only = True ) : class Proxy ( object ) : def __getattr__ ( self , name ) : return getattr ( obj , name ) if not get_only : def __setattr__ ( self , name , value ) : setattr ( obj , name , value ) def __delattr__ ( self , name ) : delattr ( obj , name ) Proxy . __setattr__ = __setattr__ Proxy . __delattr__ = __delattr__ return Proxy ( ) something = sentinel . Something something_else = sentinel . SomethingElse class Foo ( object ) : def __init__ ( self , a ) : pass def f ( self , a ) : pass def g ( self ) : pass foo = '' class Bar ( object ) : def a ( self ) : pass foo_name = '' % __name__ def function ( a , b = Foo ) : pass class Container ( object ) : def __init__ ( self ) : self . values = { } def __getitem__ ( self , name ) : return self . values [ name ] def __setitem__ ( self , name , value ) : self . values [ name ] = value def __delitem__ ( self , name ) : del self . values [ name ] def __iter__ ( self ) : return iter ( self . values ) class PatchTest ( unittest . TestCase ) : def assertNotCallable ( self , obj , magic = True ) : MockClass = NonCallableMagicMock if not magic : MockClass = NonCallableMock self . assertRaises ( TypeError , obj ) self . assertTrue ( is_instance ( obj , MockClass ) ) self . assertFalse ( is_instance ( obj , CallableMixin ) ) def test_single_patchobject ( self ) : class Something ( object ) : attribute = sentinel . Original @ patch . object ( Something , '' , sentinel . Patched ) def test ( ) : self . assertEqual ( Something . attribute , sentinel . Patched , \"\" ) test ( ) self . assertEqual ( Something . attribute , sentinel . Original , \"\" ) def test_patchobject_with_none ( self ) : class Something ( object ) : attribute = sentinel . Original @ patch . object ( Something , '' , None ) def test ( ) : self . assertIsNone ( Something . attribute , \"\" ) test ( ) self . assertEqual ( Something . attribute , sentinel . Original , \"\" ) def test_multiple_patchobject ( self ) : class Something ( object ) : attribute = sentinel . Original next_attribute = sentinel . Original2 @ patch . object ( Something , '' , sentinel . Patched ) @ patch . object ( Something , '' , sentinel . Patched2 ) def test ( ) : self . assertEqual ( Something . attribute , sentinel . Patched , \"\" ) self . assertEqual ( Something . next_attribute , sentinel . Patched2 , \"\" ) test ( ) self . assertEqual ( Something . attribute , sentinel . Original , \"\" ) self . assertEqual ( Something . next_attribute , sentinel . Original2 , \"\" ) def test_object_lookup_is_quite_lazy ( self ) : global something original = something @ patch ( '' % __name__ , sentinel . Something2 ) def test ( ) : pass try : something = sentinel . replacement_value test ( ) self . assertEqual ( something , sentinel . replacement_value ) finally : something = original def test_patch ( self ) : @ patch ( '' % __name__ , sentinel . Something2 ) def test ( ) : self . assertEqual ( PTModule . something , sentinel . Something2 , \"\" ) test ( ) self . assertEqual ( PTModule . something , sentinel . Something , \"\" ) @ patch ( '' % __name__ , sentinel . Something2 ) @ patch ( '' % __name__ , sentinel . SomethingElse ) def test ( ) : self . assertEqual ( PTModule . something , sentinel . Something2 , \"\" ) self . assertEqual ( PTModule . something_else , sentinel . SomethingElse , \"\" ) self . assertEqual ( PTModule . something , sentinel . Something , \"\" ) self . assertEqual ( PTModule . something_else , sentinel . SomethingElse , \"\" ) test ( ) self . assertEqual ( PTModule . something , sentinel . Something , \"\" ) self . assertEqual ( PTModule . something_else , sentinel . SomethingElse , \"\" ) mock = Mock ( ) mock . return_value = sentinel . Handle @ patch ( '' % builtin_string , mock ) def test ( ) : self . assertEqual ( open ( '' , '' ) , sentinel . Handle , \"\" ) test ( ) test ( ) self . assertNotEqual ( open , mock , \"\" ) def test_patch_class_attribute ( self ) : @ patch ( '' % __name__ , sentinel . ClassAttribute ) def test ( ) : self . assertEqual ( PTModule . SomeClass . class_attribute , sentinel . ClassAttribute , \"\" ) test ( ) self . assertIsNone ( PTModule . SomeClass . class_attribute , \"\" ) def test_patchobject_with_default_mock ( self ) : class Test ( object ) : something = sentinel . Original something2 = sentinel . Original2 @ patch . object ( Test , '' ) def test ( mock ) : self . assertEqual ( mock , Test . something , \"\" ) self . assertIsInstance ( mock , MagicMock , \"\" ) test ( ) @ patch . object ( Test , '' ) @ patch . object ( Test , '' ) def test ( this1 , this2 , mock1 , mock2 ) : self . assertEqual ( this1 , sentinel . this1 , \"\" ) self . assertEqual ( this2 , sentinel . this2 , \"\" ) self . assertEqual ( mock1 , Test . something2 , \"\" ) self . assertEqual ( mock2 , Test . something , \"\" ) self . assertIsInstance ( mock2 , MagicMock , \"\" ) self . assertIsInstance ( mock2 , MagicMock , \"\" ) self . assertNotEqual ( outerMock1 , mock1 , \"\" ) self . assertNotEqual ( outerMock2 , mock2 , \"\" ) return mock1 , mock2 outerMock1 = outerMock2 = None outerMock1 , outerMock2 = test ( sentinel . this1 , sentinel . this2 ) test ( sentinel . this1 , sentinel . this2 ) def test_patch_with_spec ( self ) : @ patch ( '' % __name__ , spec = SomeClass ) def test ( MockSomeClass ) : self . assertEqual ( SomeClass , MockSomeClass ) self . assertTrue ( is_instance ( SomeClass . wibble , MagicMock ) ) self . assertRaises ( AttributeError , lambda : SomeClass . not_wibble ) test ( ) def test_patchobject_with_spec ( self ) : @ patch . object ( SomeClass , '' , spec = SomeClass ) def test ( MockAttribute ) : self . assertEqual ( SomeClass . class_attribute , MockAttribute ) self . assertTrue ( is_instance ( SomeClass . class_attribute . wibble , MagicMock ) ) self . assertRaises ( AttributeError , lambda : SomeClass . class_attribute . not_wibble ) test ( ) def test_patch_with_spec_as_list ( self ) : @ patch ( '' % __name__ , spec = [ '' ] ) def test ( MockSomeClass ) : self . assertEqual ( SomeClass , MockSomeClass ) self . assertTrue ( is_instance ( SomeClass . wibble , MagicMock ) ) self . assertRaises ( AttributeError , lambda : SomeClass . not_wibble ) test ( ) def test_patchobject_with_spec_as_list ( self ) : @ patch . object ( SomeClass , '' , spec = [ '' ] ) def test ( MockAttribute ) : self . assertEqual ( SomeClass . class_attribute , MockAttribute ) self . assertTrue ( is_instance ( SomeClass . class_attribute . wibble , MagicMock ) ) self . assertRaises ( AttributeError , lambda : SomeClass . class_attribute . not_wibble ) test ( ) def test_nested_patch_with_spec_as_list ( self ) : @ patch ( '' % builtin_string ) @ patch ( '' % __name__ , spec = [ '' ] ) def test ( MockSomeClass , MockOpen ) : self . assertEqual ( SomeClass , MockSomeClass ) self . assertTrue ( is_instance ( SomeClass . wibble , MagicMock ) ) self . assertRaises ( AttributeError , lambda : SomeClass . not_wibble ) test ( ) def test_patch_with_spec_as_boolean ( self ) : @ patch ( '' % __name__ , spec = True ) def test ( MockSomeClass ) : self . assertEqual ( SomeClass , MockSomeClass ) MockSomeClass . wibble self . assertRaises ( AttributeError , lambda : MockSomeClass . not_wibble ) test ( ) def test_patch_object_with_spec_as_boolean ( self ) : @ patch . object ( PTModule , '' , spec = True ) def test ( MockSomeClass ) : self . assertEqual ( SomeClass , MockSomeClass ) MockSomeClass . wibble self . assertRaises ( AttributeError , lambda : MockSomeClass . not_wibble ) test ( ) def test_patch_class_acts_with_spec_is_inherited ( self ) : @ patch ( '' % __name__ , spec = True ) def test ( MockSomeClass ) : self . assertTrue ( is_instance ( MockSomeClass , MagicMock ) ) instance = MockSomeClass ( ) self . assertNotCallable ( instance ) instance . wibble self . assertRaises ( AttributeError , lambda : instance . not_wibble ) test ( ) def test_patch_with_create_mocks_non_existent_attributes ( self ) : @ patch ( '' % builtin_string , sentinel . Frooble , create = True ) def test ( ) : self . assertEqual ( frooble , sentinel . Frooble ) test ( ) self . assertRaises ( NameError , lambda : frooble ) def test_patchobject_with_create_mocks_non_existent_attributes ( self ) : @ patch . object ( SomeClass , '' , sentinel . Frooble , create = True ) def test ( ) : self . assertEqual ( SomeClass . frooble , sentinel . Frooble ) test ( ) self . assertFalse ( hasattr ( SomeClass , '' ) ) def test_patch_wont_create_by_default ( self ) : try : @ patch ( '' % builtin_string , sentinel . Frooble ) def test ( ) : self . assertEqual ( frooble , sentinel . Frooble ) test ( ) except AttributeError : pass else : self . fail ( '' ) self . assertRaises ( NameError , lambda : frooble ) def test_patchobject_wont_create_by_default ( self ) : try : @ patch . object ( SomeClass , '' , sentinel . Frooble ) def test ( ) : self . fail ( '' ) test ( ) except AttributeError : pass else : self . fail ( '' ) self . assertFalse ( hasattr ( SomeClass , '' ) ) def test_patch_builtins_without_create ( self ) : @ patch ( __name__ + '' ) def test_ord ( mock_ord ) : mock_ord . return_value = return ord ( '' ) @ patch ( __name__ + '' ) def test_open ( mock_open ) : m = mock_open . return_value m . read . return_value = '' fobj = open ( '' ) data = fobj . read ( ) fobj . close ( ) return data self . assertEqual ( test_ord ( ) , ) self . assertEqual ( test_open ( ) , '' ) def test_patch_with_static_methods ( self ) : class Foo ( object ) : @ staticmethod def woot ( ) : return sentinel . Static @ patch . object ( Foo , '' , staticmethod ( lambda : sentinel . Patched ) ) def anonymous ( ) : self . assertEqual ( Foo . woot ( ) , sentinel . Patched ) anonymous ( ) self . assertEqual ( Foo . woot ( ) , sentinel . Static ) def test_patch_local ( self ) : foo = sentinel . Foo @ patch . object ( sentinel , '' , '' ) def anonymous ( ) : self . assertEqual ( sentinel . Foo , '' ) anonymous ( ) self . assertEqual ( sentinel . Foo , foo ) def test_patch_slots ( self ) : class Foo ( object ) : __slots__ = ( '' , ) foo = Foo ( ) foo . Foo = sentinel . Foo @ patch . object ( foo , '' , '' ) def anonymous ( ) : self . assertEqual ( foo . Foo , '' ) anonymous ( ) self . assertEqual ( foo . Foo , sentinel . Foo ) def test_patchobject_class_decorator ( self ) : class Something ( object ) : attribute = sentinel . Original class Foo ( object ) : def test_method ( other_self ) : self . assertEqual ( Something . attribute , sentinel . Patched , \"\" ) def not_test_method ( other_self ) : self . assertEqual ( Something . attribute , sentinel . Original , \"\" ) Foo = patch . object ( Something , '' , sentinel . Patched ) ( Foo ) f = Foo ( ) f . test_method ( ) f . not_test_method ( ) self . assertEqual ( Something . attribute , sentinel . Original , \"\" ) def test_patch_class_decorator ( self ) : class Something ( object ) : attribute = sentinel . Original class Foo ( object ) : def test_method ( other_self , mock_something ) : self . assertEqual ( PTModule . something , mock_something , \"\" ) def not_test_method ( other_self ) : self . assertEqual ( PTModule . something , sentinel . Something , \"\" ) Foo = patch ( '' % __name__ ) ( Foo ) f = Foo ( ) f . test_method ( ) f . not_test_method ( ) self . assertEqual ( Something . attribute , sentinel . Original , \"\" ) self . assertEqual ( PTModule . something , sentinel . Something , \"\" ) def test_patchobject_twice ( self ) : class Something ( object ) : attribute = sentinel . Original next_attribute = sentinel . Original2 @ patch . object ( Something , '' , sentinel . Patched ) @ patch . object ( Something , '' , sentinel . Patched ) def test ( ) : self . assertEqual ( Something . attribute , sentinel . Patched , \"\" ) test ( ) self . assertEqual ( Something . attribute , sentinel . Original , \"\" ) def test_patch_dict ( self ) : foo = { '' : object ( ) , '' : '' } original = foo . copy ( ) @ patch . dict ( foo ) def test ( ) : foo [ '' ] = del foo [ '' ] foo [ '' ] = '' test ( ) self . assertEqual ( foo , original ) @ patch . dict ( foo , { '' : '' } ) def test ( ) : self . assertEqual ( len ( foo ) , ) self . assertEqual ( foo [ '' ] , '' ) test ( ) self . assertEqual ( foo , original ) @ patch . dict ( foo , [ ( '' , '' ) ] ) def test ( ) : self . assertEqual ( len ( foo ) , ) self . assertEqual ( foo [ '' ] , '' ) test ( ) self . assertEqual ( foo , original ) def test_patch_dict_with_container_object ( self ) : foo = Container ( ) foo [ '' ] = object ( ) foo [ '' ] = '' original = foo . values . copy ( ) @ patch . dict ( foo ) def test ( ) : foo [ '' ] = del foo [ '' ] foo [ '' ] = '' test ( ) self . assertEqual ( foo . values , original ) @ patch . dict ( foo , { '' : '' } ) def test ( ) : self . assertEqual ( len ( foo . values ) , ) self . assertEqual ( foo [ '' ] , '' ) test ( ) self . assertEqual ( foo . values , original ) def test_patch_dict_with_clear ( self ) : foo = { '' : object ( ) , '' : '' } original = foo . copy ( ) @ patch . dict ( foo , clear = True ) def test ( ) : self . assertEqual ( foo , { } ) foo [ '' ] = foo [ '' ] = '' test ( ) self . assertEqual ( foo , original ) @ patch . dict ( foo , { '' : '' } , clear = True ) def test ( ) : self . assertEqual ( foo , { '' : '' } ) test ( ) self . assertEqual ( foo , original ) @ patch . dict ( foo , [ ( '' , '' ) ] , clear = True ) def test ( ) : self . assertEqual ( foo , { '' : '' } ) test ( ) self . assertEqual ( foo , original ) def test_patch_dict_with_container_object_and_clear ( self ) : foo = Container ( ) foo [ '' ] = object ( ) foo [ '' ] = '' original = foo . values . copy ( ) @ patch . dict ( foo , clear = True ) def test ( ) : self . assertEqual ( foo . values , { } ) foo [ '' ] = foo [ '' ] = '' test ( ) self . assertEqual ( foo . values , original ) @ patch . dict ( foo , { '' : '' } , clear = True ) def test ( ) : self . assertEqual ( foo . values , { '' : '' } ) test ( ) self . assertEqual ( foo . values , original ) def test_name_preserved ( self ) : foo = { } @ patch ( '' % __name__ , object ( ) ) @ patch ( '' % __name__ , object ( ) , autospec = True ) @ patch . object ( SomeClass , object ( ) ) @ patch . dict ( foo ) def some_name ( ) : pass self . assertEqual ( some_name . __name__ , '' ) def test_patch_with_exception ( self ) : foo = { } @ patch . dict ( foo , { '' : '' } ) def test ( ) : raise NameError ( '' ) try : test ( ) except NameError : pass else : self . fail ( '' ) self . assertEqual ( foo , { } ) def test_patch_dict_with_string ( self ) : @ patch . dict ( '' , { '' : '' } ) def test ( ) : self . assertIn ( '' , os . environ ) test ( ) @ unittest . expectedFailure def test_patch_descriptor ( self ) : class Nothing ( object ) : foo = None class Something ( object ) : foo = { } @ patch . object ( Nothing , '' , ) @ classmethod def klass ( cls ) : self . assertIs ( cls , Something ) @ patch . object ( Nothing , '' , ) @ staticmethod def static ( arg ) : return arg @ patch . dict ( foo ) @ classmethod def klass_dict ( cls ) : self . assertIs ( cls , Something ) @ patch . dict ( foo ) @ staticmethod def static_dict ( arg ) : return arg self . assertEqual ( Something . static ( '' ) , '' ) Something . klass ( ) self . assertEqual ( Something . static_dict ( '' ) , '' ) Something . klass_dict ( ) something = Something ( ) self . assertEqual ( something . static ( '' ) , '' ) something . klass ( ) self . assertEqual ( something . static_dict ( '' ) , '' ) something . klass_dict ( ) def test_patch_spec_set ( self ) : ", "answer": "@ patch ( '' % __name__ , spec_set = SomeClass )"}, {"prompt": " import warnings from django . test . utils import get_warnings_state , restore_warnings_state from regressiontests . comment_tests . tests import CommentTestCase class CommentFeedTests ( CommentTestCase ) : urls = '' feed_url = '' def test_feed ( self ) : response = self . client . get ( self . feed_url ) self . assertEquals ( response . status_code , ) self . assertEquals ( response [ '' ] , '' ) self . assertContains ( response , '' ) self . assertContains ( response , '' ) self . assertContains ( response , '' ) self . assertContains ( response , '' ) ", "answer": "class LegacyCommentFeedTests ( CommentFeedTests ) :"}, {"prompt": " from videocore import __version__ from distutils . core import setup setup ( name = '' , version = __version__ , description = '' , author = '' , author_email = '' , url = '' , ", "answer": "packages = [ '' ]"}, {"prompt": " from nova . api . openstack import extensions class Baremetal_ext_status ( extensions . ExtensionDescriptor ) : \"\"\"\"\"\" name = \"\" alias = \"\" ", "answer": "namespace = ( \"\""}, {"prompt": " import tinkerer import tinkerer . paths project = '' tagline = '' ", "answer": "description = ''"}, {"prompt": " from easyprocess import EasyProcess from nose . tools import eq_ , timed , ok_ from unittest import TestCase import sys python = sys . executable class Test ( TestCase ) : def test_timeout ( self ) : p = EasyProcess ( '' ) . start ( ) p . wait ( ) eq_ ( p . is_alive ( ) , True ) p . wait ( ) eq_ ( p . is_alive ( ) , True ) p . wait ( ) eq_ ( p . is_alive ( ) , False ) eq_ ( EasyProcess ( '' ) . call ( ) . return_code == , True ) eq_ ( EasyProcess ( '' ) . call ( timeout = ) . return_code == , False ) eq_ ( EasyProcess ( '' ) . call ( timeout = ) . return_code == , True ) eq_ ( EasyProcess ( '' ) . call ( ) . timeout_happened , False ) eq_ ( EasyProcess ( '' ) . call ( timeout = ) . timeout_happened , True ) eq_ ( EasyProcess ( '' ) . call ( timeout = ) . timeout_happened , False ) @ timed ( ) def test_time_cli1 ( self ) : p = EasyProcess ( ", "answer": "[ python , '' , \"\" ] )"}, {"prompt": " import glob import os class RealFilesystem ( object ) : def create_directories ( self , path ) : return os . makedirs ( path ) def path_exists ( self , path ) : return os . path . exists ( path ) def is_directory ( self , path ) : return os . path . isdir ( path ) def is_file ( self , path ) : return os . path . isfile ( path ) def is_writable ( self , path ) : return os . access ( path , os . W_OK ) def _paths_in_directory ( self , directory , incl_subdirs = False ) : assert self . is_directory ( directory ) pattern = os . path . join ( directory , \"\" ) result = glob . glob ( pattern ) subdir_pattern = os . path . join ( directory , \"\" , \"\" ) subdir_result = glob . glob ( subdir_pattern ) if incl_subdirs else [ ] return result + subdir_result def files_in_directory ( self , directory , include_subdirectories = False ) : assert self . is_directory ( directory ) , \"\" return filter ( os . path . isfile , self . _paths_in_directory ( directory , incl_subdirs = include_subdirectories ) , ) def subdirectories_of_directory ( self , directory , recursive = False ) : assert self . is_directory ( directory ) , \"\" return filter ( os . path . isdir , self . _paths_in_directory ( directory , incl_subdirs = recursive ) , ) class FakeFilesystem ( object ) : def __init__ ( self , root ) : self . root = root self . fs = RealFilesystem ( ) def adjusted_path ( self , path ) : \"\"\"\"\"\" if os . path . realpath ( path ) . startswith ( os . path . realpath ( self . root ) ) : return path to_components = lambda p : os . path . normpath ( p ) . split ( os . sep ) root_components = to_components ( self . root ) path_components = to_components ( path ) if os . path . isabs ( path ) : path_components . pop ( ) return os . sep . join ( root_components + path_components ) def create_directories ( self , path ) : return self . fs . create_directories ( self . adjusted_path ( path ) ) ", "answer": "def path_exists ( self , path ) :"}, {"prompt": " from __future__ import ( absolute_import , division , generators , nested_scopes , print_function , unicode_literals , with_statement ) import os from pants . build_graph . address import Address from pants . build_graph . target import Target from pants_test . backend . jvm . tasks . jvm_compile . base_compile_integration_test import BaseCompileIT class ZincCompileIntegrationTest ( BaseCompileIT ) : def test_java_src_zinc_compile ( self ) : with self . do_test_compile ( '' ) : pass with self . do_test_compile ( '' ) : pass def test_in_process ( self ) : with self . temporary_workdir ( ) as workdir : with self . temporary_cachedir ( ) as cachedir : pants_run = self . run_test_compile ( workdir , cachedir , '' , extra_args = [ '' ] , clean_all = True ) self . assertIn ( '' , pants_run . stdout_data ) self . assertNotIn ( '' , pants_run . stdout_data ) def test_log_level ( self ) : with self . temporary_workdir ( ) as workdir : with self . temporary_cachedir ( ) as cachedir : target = '' pants_run = self . run_test_compile ( workdir , cachedir , target , extra_args = [ '' ] , clean_all = True ) self . assertIn ( '' , pants_run . stdout_data ) self . assertIn ( '' , pants_run . stdout_data ) def test_unicode_source_symbol ( self ) : with self . temporary_workdir ( ) as workdir : with self . temporary_cachedir ( ) as cachedir : ", "answer": "target = ''"}, {"prompt": " import sys import os import cv2 import numpy as np import time import StringIO from misc import WithTimer from numpy_cache import FIFOLimitedArrayCache from app_base import BaseApp from image_misc import norm01 , norm01c , norm0255 , tile_images_normalize , ensure_float01 , tile_images_make_tiles , ensure_uint255_and_resize_to_fit , get_tiles_height_width , get_tiles_height_width_ratio from image_misc import FormattedString , cv2_typeset_text , to_255 from caffe_proc_thread import CaffeProcThread from jpg_vis_loading_thread import JPGVisLoadingThread from caffevis_app_state import CaffeVisAppState from caffevis_helper import get_pretty_layer_name , read_label_file , load_sprite_image , load_square_sprite_image , check_force_backward_true class CaffeVisApp ( BaseApp ) : '''''' def __init__ ( self , settings , key_bindings ) : super ( CaffeVisApp , self ) . __init__ ( settings , key_bindings ) print '' , settings self . settings = settings self . bindings = key_bindings self . _net_channel_swap = ( , , ) self . _net_channel_swap_inv = tuple ( [ self . _net_channel_swap . index ( ii ) for ii in range ( len ( self . _net_channel_swap ) ) ] ) self . _range_scale = sys . path . insert ( , os . path . join ( settings . caffevis_caffe_root , '' ) ) import caffe if settings . caffevis_mode_gpu : caffe . set_mode_gpu ( ) print '' else : caffe . set_mode_cpu ( ) print '' self . net = caffe . Classifier ( settings . caffevis_deploy_prototxt , settings . caffevis_network_weights , mean = None , channel_swap = self . _net_channel_swap , raw_scale = self . _range_scale , ) if isinstance ( settings . caffevis_data_mean , basestring ) : try : self . _data_mean = np . load ( settings . caffevis_data_mean ) except IOError : print '' , settings . caffevis_data_mean print '' print '' print '' print '' raise input_shape = self . net . blobs [ self . net . inputs [ ] ] . data . shape [ - : ] excess_h = self . _data_mean . shape [ ] - input_shape [ ] excess_w = self . _data_mean . shape [ ] - input_shape [ ] assert excess_h >= and excess_w >= , '' % repr ( input_shape ) self . _data_mean = self . _data_mean [ : , ( excess_h / ) : ( excess_h / + input_shape [ ] ) , ( excess_w / ) : ( excess_w / + input_shape [ ] ) ] elif settings . caffevis_data_mean is None : self . _data_mean = None else : self . _data_mean = np . array ( settings . caffevis_data_mean ) while len ( self . _data_mean . shape ) < : self . _data_mean = np . expand_dims ( self . _data_mean , - ) if self . _data_mean is not None : self . net . transformer . set_mean ( self . net . inputs [ ] , self . _data_mean ) check_force_backward_true ( settings . caffevis_deploy_prototxt ) self . labels = None if self . settings . caffevis_labels : self . labels = read_label_file ( self . settings . caffevis_labels ) self . proc_thread = None self . jpgvis_thread = None self . handled_frames = if settings . caffevis_jpg_cache_size < * ** : raise Exception ( '' ) self . img_cache = FIFOLimitedArrayCache ( settings . caffevis_jpg_cache_size ) self . _populate_net_layer_info ( ) def _populate_net_layer_info ( self ) : '''''' self . net_layer_info = { } for key in self . net . blobs . keys ( ) : self . net_layer_info [ key ] = { } blob_shape = self . net . blobs [ key ] . data . shape assert len ( blob_shape ) in ( , ) , '' self . net_layer_info [ key ] [ '' ] = ( len ( blob_shape ) == ) self . net_layer_info [ key ] [ '' ] = blob_shape [ : ] self . net_layer_info [ key ] [ '' ] = blob_shape [ ] self . net_layer_info [ key ] [ '' ] = get_tiles_height_width_ratio ( blob_shape [ ] , self . settings . caffevis_layers_aspect_ratio ) self . net_layer_info [ key ] [ '' ] = self . net_layer_info [ key ] [ '' ] [ ] self . net_layer_info [ key ] [ '' ] = self . net_layer_info [ key ] [ '' ] [ ] def start ( self ) : self . state = CaffeVisAppState ( self . net , self . settings , self . bindings , self . net_layer_info ) self . state . drawing_stale = True self . layer_print_names = [ get_pretty_layer_name ( self . settings , nn ) for nn in self . state . _layers ] if self . proc_thread is None or not self . proc_thread . is_alive ( ) : self . proc_thread = CaffeProcThread ( self . net , self . state , self . settings . caffevis_frame_wait_sleep , self . settings . caffevis_pause_after_keys , self . settings . caffevis_heartbeat_required , self . settings . caffevis_mode_gpu ) self . proc_thread . start ( ) if self . jpgvis_thread is None or not self . jpgvis_thread . is_alive ( ) : self . jpgvis_thread = JPGVisLoadingThread ( self . settings , self . state , self . img_cache , self . settings . caffevis_jpg_load_sleep , self . settings . caffevis_heartbeat_required ) self . jpgvis_thread . start ( ) def get_heartbeats ( self ) : return [ self . proc_thread . heartbeat , self . jpgvis_thread . heartbeat ] def quit ( self ) : print '' with self . state . lock : self . state . quit = True if self . proc_thread != None : for ii in range ( ) : self . proc_thread . join ( ) if not self . proc_thread . is_alive ( ) : break if self . proc_thread . is_alive ( ) : raise Exception ( '' ) self . proc_thread = None print '' def _can_skip_all ( self , panes ) : return ( '' not in panes . keys ( ) ) def handle_input ( self , input_image , panes ) : if self . debug_level > : print '' , self . handled_frames , '' , '' if input_image is None else '' self . handled_frames += if self . _can_skip_all ( panes ) : return with self . state . lock : if self . debug_level > : print '' self . state . next_frame = input_image if self . debug_level > : print '' , self . state . caffe_net_state def redraw_needed ( self ) : return self . state . redraw_needed ( ) def draw ( self , panes ) : if self . _can_skip_all ( panes ) : if self . debug_level > : print '' return False with self . state . lock : do_draw = self . state . drawing_stale and self . state . caffe_net_state == '' if do_draw : self . state . caffe_net_state = '' if do_draw : if self . debug_level > : print '' if '' in panes : self . _draw_control_pane ( panes [ '' ] ) if '' in panes : self . _draw_status_pane ( panes [ '' ] ) layer_data_3D_highres = None if '' in panes : layer_data_3D_highres = self . _draw_layer_pane ( panes [ '' ] ) if '' in panes : self . _draw_aux_pane ( panes [ '' ] , layer_data_3D_highres ) if '' in panes : self . _draw_back_pane ( panes [ '' ] ) if self . state . layers_pane_zoom_mode == : self . _draw_back_pane ( panes [ '' ] ) if '' in panes : self . _draw_jpgvis_pane ( panes [ '' ] ) with self . state . lock : self . state . drawing_stale = False self . state . caffe_net_state = '' return do_draw def _draw_prob_labels_pane ( self , pane ) : '''''' if not self . labels or not self . state . show_label_predictions or not self . settings . caffevis_prob_layer : return defaults = { '' : getattr ( cv2 , self . settings . caffevis_class_face ) , '' : self . settings . caffevis_class_fsize , '' : to_255 ( self . settings . caffevis_class_clr_0 ) , '' : self . settings . caffevis_class_thick } loc = self . settings . caffevis_class_loc [ : : - ] clr_0 = to_255 ( self . settings . caffevis_class_clr_0 ) clr_1 = to_255 ( self . settings . caffevis_class_clr_1 ) probs_flat = self . net . blobs [ self . settings . caffevis_prob_layer ] . data . flatten ( ) top_5 = probs_flat . argsort ( ) [ - : - : - ] strings = [ ] pmax = probs_flat [ top_5 [ ] ] for idx in top_5 : prob = probs_flat [ idx ] text = '' % ( prob , self . labels [ idx ] ) fs = FormattedString ( text , defaults ) fs . clr = tuple ( [ max ( , min ( , clr_1 [ ii ] * prob + clr_0 [ ii ] * ( - prob ) ) ) for ii in range ( ) ] ) strings . append ( [ fs ] ) cv2_typeset_text ( pane . data , strings , loc , line_spacing = self . settings . caffevis_class_line_spacing ) def _draw_control_pane ( self , pane ) : pane . data [ : ] = to_255 ( self . settings . window_background ) with self . state . lock : layer_idx = self . state . layer_idx loc = self . settings . caffevis_control_loc [ : : - ] strings = [ ] defaults = { '' : getattr ( cv2 , self . settings . caffevis_control_face ) , '' : self . settings . caffevis_control_fsize , '' : to_255 ( self . settings . caffevis_control_clr ) , '' : self . settings . caffevis_control_thick } for ii in range ( len ( self . layer_print_names ) ) : fs = FormattedString ( self . layer_print_names [ ii ] , defaults ) this_layer = self . state . _layers [ ii ] if self . state . backprop_selection_frozen and this_layer == self . state . backprop_layer : fs . clr = to_255 ( self . settings . caffevis_control_clr_bp ) fs . thick = self . settings . caffevis_control_thick_bp if this_layer == self . state . layer : if self . state . cursor_area == '' : fs . clr = to_255 ( self . settings . caffevis_control_clr_cursor ) fs . thick = self . settings . caffevis_control_thick_cursor else : if not ( self . state . backprop_selection_frozen and this_layer == self . state . backprop_layer ) : fs . clr = to_255 ( self . settings . caffevis_control_clr_selected ) fs . thick = self . settings . caffevis_control_thick_selected strings . append ( fs ) cv2_typeset_text ( pane . data , strings , loc , line_spacing = self . settings . caffevis_control_line_spacing , wrap = True ) def _draw_status_pane ( self , pane ) : pane . data [ : ] = to_255 ( self . settings . window_background ) defaults = { '' : getattr ( cv2 , self . settings . caffevis_status_face ) , '' : self . settings . caffevis_status_fsize , '' : to_255 ( self . settings . caffevis_status_clr ) , '' : self . settings . caffevis_status_thick } loc = self . settings . caffevis_status_loc [ : : - ] status = StringIO . StringIO ( ) fps = self . proc_thread . approx_fps ( ) with self . state . lock : print >> status , '' if self . state . pattern_mode else ( '' if self . state . layers_show_back else '' ) , print >> status , '' % ( self . state . layer , self . state . selected_unit ) , if not self . state . back_enabled : print >> status , '' , else : print >> status , '' % ( '' if self . state . back_mode == '' else '' ) , print >> status , '' % ( self . state . backprop_layer , self . state . backprop_unit , self . state . back_filt_mode ) , print >> status , '' , print >> status , '' % ( self . state . layer_boost_indiv , self . state . layer_boost_gamma ) if fps > : print >> status , '' % fps if self . state . extra_msg : print >> status , '' , self . state . extra_msg self . state . extra_msg = '' strings = [ FormattedString ( line , defaults ) for line in status . getvalue ( ) . split ( '' ) ] cv2_typeset_text ( pane . data , strings , loc , line_spacing = self . settings . caffevis_status_line_spacing ) def _draw_layer_pane ( self , pane ) : '''''' if self . state . layers_show_back : layer_dat_3D = self . net . blobs [ self . state . layer ] . diff [ ] else : layer_dat_3D = self . net . blobs [ self . state . layer ] . data [ ] if len ( layer_dat_3D . shape ) == : layer_dat_3D = layer_dat_3D [ : , np . newaxis , np . newaxis ] n_tiles = layer_dat_3D . shape [ ] tile_rows , tile_cols = self . net_layer_info [ self . state . layer ] [ '' ] display_3D_highres = None if self . state . pattern_mode : load_layer = self . state . layer if self . settings . caffevis_jpgvis_remap and self . state . layer in self . settings . caffevis_jpgvis_remap : load_layer = self . settings . caffevis_jpgvis_remap [ self . state . layer ] if self . settings . caffevis_jpgvis_layers and load_layer in self . settings . caffevis_jpgvis_layers : jpg_path = os . path . join ( self . settings . caffevis_unit_jpg_dir , '' , load_layer , '' ) display_3D_highres = self . img_cache . get ( ( jpg_path , '' ) , None ) if display_3D_highres is None : try : with WithTimer ( '' , quiet = self . debug_level < ) : display_3D_highres = load_square_sprite_image ( jpg_path , n_sprites = n_tiles ) except IOError : pass else : self . img_cache . set ( ( jpg_path , '' ) , display_3D_highres ) if display_3D_highres is not None : row_downsamp_factor = int ( np . ceil ( float ( display_3D_highres . shape [ ] ) / ( pane . data . shape [ ] / tile_rows - ) ) ) col_downsamp_factor = int ( np . ceil ( float ( display_3D_highres . shape [ ] ) / ( pane . data . shape [ ] / tile_cols - ) ) ) ds = max ( row_downsamp_factor , col_downsamp_factor ) if ds > : display_3D = display_3D_highres [ : , : : ds , : : ds , : ] else : display_3D = display_3D_highres else : display_3D = layer_dat_3D * else : if self . state . layers_show_back : back_what_to_disp = self . get_back_what_to_disp ( ) if back_what_to_disp == '' : layer_dat_3D_normalized = np . tile ( self . settings . window_background , layer_dat_3D . shape + ( , ) ) elif back_what_to_disp == '' : layer_dat_3D_normalized = np . tile ( self . settings . stale_background , layer_dat_3D . shape + ( , ) ) else : layer_dat_3D_normalized = tile_images_normalize ( layer_dat_3D , boost_indiv = self . state . layer_boost_indiv , boost_gamma = self . state . layer_boost_gamma , neg_pos_colors = ( ( , , ) , ( , , ) ) ) else : layer_dat_3D_normalized = tile_images_normalize ( layer_dat_3D , boost_indiv = self . state . layer_boost_indiv , boost_gamma = self . state . layer_boost_gamma ) display_3D = layer_dat_3D_normalized display_3D = ensure_float01 ( display_3D ) if len ( display_3D . shape ) == : display_3D = display_3D [ : , : , : , np . newaxis ] if display_3D . shape [ ] == : display_3D = np . tile ( display_3D , ( , , , ) ) if display_3D . shape [ ] == : display_3D = np . tile ( display_3D , ( , , , ) ) if self . state . layers_show_back and not self . state . pattern_mode : padval = self . settings . caffevis_layer_clr_back_background else : padval = self . settings . window_background highlights = [ None ] * n_tiles with self . state . lock : if self . state . cursor_area == '' : highlights [ self . state . selected_unit ] = self . settings . caffevis_layer_clr_cursor if self . state . backprop_selection_frozen and self . state . layer == self . state . backprop_layer : highlights [ self . state . backprop_unit ] = self . settings . caffevis_layer_clr_back_sel _ , display_2D = tile_images_make_tiles ( display_3D , hw = ( tile_rows , tile_cols ) , padval = padval , highlights = highlights ) if display_3D_highres is None : display_3D_highres = display_3D state_layers_pane_zoom_mode = self . state . layers_pane_zoom_mode assert state_layers_pane_zoom_mode in ( , , ) if state_layers_pane_zoom_mode == : display_2D_resize = ensure_uint255_and_resize_to_fit ( display_2D , pane . data . shape ) elif state_layers_pane_zoom_mode == : unit_data = display_3D_highres [ self . state . selected_unit ] display_2D_resize = ensure_uint255_and_resize_to_fit ( unit_data , pane . data . shape ) else : display_2D_resize = ensure_uint255_and_resize_to_fit ( display_2D , pane . data . shape ) * pane . data [ : ] = to_255 ( self . settings . window_background ) pane . data [ : display_2D_resize . shape [ ] , : display_2D_resize . shape [ ] , : ] = display_2D_resize if self . settings . caffevis_label_layers and self . state . layer in self . settings . caffevis_label_layers and self . labels and self . state . cursor_area == '' : defaults = { '' : getattr ( cv2 , self . settings . caffevis_label_face ) , '' : self . settings . caffevis_label_fsize , '' : to_255 ( self . settings . caffevis_label_clr ) , '' : self . settings . caffevis_label_thick } loc_base = self . settings . caffevis_label_loc [ : : - ] lines = [ FormattedString ( self . labels [ self . state . selected_unit ] , defaults ) ] cv2_typeset_text ( pane . data , lines , loc_base ) return display_3D_highres def _draw_aux_pane ( self , pane , layer_data_normalized ) : pane . data [ : ] = to_255 ( self . settings . window_background ) mode = None with self . state . lock : if self . state . cursor_area == '' : mode = '' else : mode = '' if mode == '' : unit_data = layer_data_normalized [ self . state . selected_unit ] unit_data_resize = ensure_uint255_and_resize_to_fit ( unit_data , pane . data . shape ) pane . data [ : unit_data_resize . shape [ ] , : unit_data_resize . shape [ ] , : ] = unit_data_resize elif mode == '' : self . _draw_prob_labels_pane ( pane ) def _draw_back_pane ( self , pane ) : mode = None with self . state . lock : back_enabled = self . state . back_enabled back_mode = self . state . back_mode back_filt_mode = self . state . back_filt_mode state_layer = self . state . layer selected_unit = self . state . selected_unit back_what_to_disp = self . get_back_what_to_disp ( ) if back_what_to_disp == '' : pane . data [ : ] = to_255 ( self . settings . window_background ) elif back_what_to_disp == '' : pane . data [ : ] = to_255 ( self . settings . stale_background ) else : grad_blob = self . net . blobs [ '' ] . diff grad_blob = grad_blob [ ] grad_blob = grad_blob . transpose ( ( , , ) ) grad_img = grad_blob [ : , : , self . _net_channel_swap_inv ] assert back_mode in ( '' , '' ) assert back_filt_mode in ( '' , '' , '' , '' ) if back_filt_mode == '' : grad_img = norm01c ( grad_img , ) elif back_filt_mode == '' : grad_img = grad_img . mean ( axis = ) grad_img = norm01c ( grad_img , ) elif back_filt_mode == '' : grad_img = np . linalg . norm ( grad_img , axis = ) grad_img = norm01 ( grad_img ) else : grad_img = np . linalg . norm ( grad_img , axis = ) cv2 . GaussianBlur ( grad_img , ( , ) , self . settings . caffevis_grad_norm_blur_radius , grad_img ) grad_img = norm01 ( grad_img ) if len ( grad_img . shape ) == : grad_img = np . tile ( grad_img [ : , : , np . newaxis ] , ) grad_img_resize = ensure_uint255_and_resize_to_fit ( grad_img , pane . data . shape ) pane . data [ : grad_img_resize . shape [ ] , : grad_img_resize . shape [ ] , : ] = grad_img_resize def _draw_jpgvis_pane ( self , pane ) : pane . data [ : ] = to_255 ( self . settings . window_background ) with self . state . lock : state_layer , state_selected_unit , cursor_area , show_unit_jpgs = self . state . layer , self . state . selected_unit , self . state . cursor_area , self . state . show_unit_jpgs try : self . settings . caffevis_jpgvis_layers except : print '' raise if self . settings . caffevis_jpgvis_remap and state_layer in self . settings . caffevis_jpgvis_remap : img_key_layer = self . settings . caffevis_jpgvis_remap [ state_layer ] else : img_key_layer = state_layer if self . settings . caffevis_jpgvis_layers and img_key_layer in self . settings . caffevis_jpgvis_layers and cursor_area == '' and show_unit_jpgs : img_key = ( img_key_layer , state_selected_unit , pane . data . shape ) img_resize = self . img_cache . get ( img_key , None ) if img_resize is None : with self . state . lock : self . state . jpgvis_to_load_key = img_key pane . data [ : ] = to_255 ( self . settings . stale_background ) elif img_resize . nbytes == : pane . data [ : ] = to_255 ( self . settings . window_background ) else : pane . data [ : img_resize . shape [ ] , : img_resize . shape [ ] , : ] = img_resize else : pane . data [ : ] = to_255 ( self . settings . window_background ) def handle_key ( self , key , panes ) : return self . state . handle_key ( key ) def get_back_what_to_disp ( self ) : '''''' ", "answer": "if ( self . state . cursor_area == '' and not self . state . backprop_selection_frozen ) or not self . state . back_enabled :"}, {"prompt": " from archivekit . resource import Resource class Source ( Resource ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " '''''' from __future__ import absolute_import import errno import json import logging import os import salt import salt . netapi H = { : '' , : '' , : '' , : '' , : '' , : '' , : '' , } __virtualname__ = '' logger = logging . getLogger ( __virtualname__ ) def __virtual__ ( ) : mod_opts = __opts__ . get ( __virtualname__ , { } ) if '' in mod_opts : return __virtualname__ return False class HTTPError ( Exception ) : '''''' def __init__ ( self , code , message ) : self . code = code Exception . __init__ ( self , '' . format ( code , message ) ) def mkdir_p ( path ) : '''''' try : os . makedirs ( path ) except OSError as exc : if exc . errno == errno . EEXIST and os . path . isdir ( path ) : pass else : raise def read_body ( environ ) : '''''' length = environ . get ( '' , '' ) length = if length == '' else int ( length ) return environ [ '' ] . read ( length ) def get_json ( environ ) : '''''' content_type = environ . get ( '' , '' ) if content_type != '' : raise HTTPError ( , '' ) try : return json . loads ( read_body ( environ ) ) except ValueError as exc : raise HTTPError ( , exc ) def get_headers ( data , extra_headers = None ) : '''''' response_headers = { '' : str ( len ( data ) ) , } if extra_headers : response_headers . update ( extra_headers ) return list ( response_headers . items ( ) ) def run_chunk ( environ , lowstate ) : '''''' client = environ [ '' ] for chunk in lowstate : yield client . run ( chunk ) def dispatch ( environ ) : '''''' method = environ [ '' ] . upper ( ) if method == '' : return ( \"\" \"\" ) elif method == '' : data = get_json ( environ ) return run_chunk ( environ , data ) else : raise HTTPError ( , '' ) def saltenviron ( environ ) : '''''' if '' not in locals ( ) : import salt . config __opts__ = salt . config . client_config ( os . environ . get ( '' , '' ) ) environ [ '' ] = __opts__ environ [ '' ] = salt . netapi . NetapiClient ( __opts__ ) def application ( environ , start_response ) : '''''' saltenviron ( environ ) try : resp = list ( dispatch ( environ ) ) code = except HTTPError as exc : code = exc . code resp = str ( exc ) except salt . exceptions . EauthAuthenticationError as exc : code = resp = str ( exc ) except Exception as exc : code = resp = str ( exc ) try : ret = json . dumps ( { '' : resp } ) except TypeError as exc : code = ret = str ( exc ) start_response ( H [ code ] , get_headers ( ret , { '' : '' , } ) ) return ( ret , ) def get_opts ( ) : '''''' import salt . config return salt . config . client_config ( os . environ . get ( '' , '' ) ) def start ( ) : '''''' from wsgiref . simple_server import make_server if '' not in globals ( ) : globals ( ) [ '' ] = get_opts ( ) if __virtual__ ( ) is False : raise SystemExit ( ) mod_opts = __opts__ . get ( __virtualname__ , { } ) httpd = make_server ( '' , mod_opts [ '' ] , application ) try : httpd . serve_forever ( ) ", "answer": "except KeyboardInterrupt :"}, {"prompt": " import os import pytest import bayeslite from bayeslite . metamodels . crosscat import CrosscatMetamodel import bayeslite . read_csv as read_csv import crosscat . LocalEngine root = os . path . dirname ( os . path . abspath ( __file__ ) ) dha_csv = os . path . join ( root , '' ) dha_models = os . path . join ( root , '' ) dha_codebook = os . path . join ( root , '' ) def test_legacy_models__ci_slow ( ) : bdb = bayeslite . bayesdb_open ( builtin_metamodels = False ) cc = crosscat . LocalEngine . LocalEngine ( seed = ) metamodel = CrosscatMetamodel ( cc ) bayeslite . bayesdb_register_metamodel ( bdb , metamodel ) with pytest . raises ( ValueError ) : bayeslite . bayesdb_load_legacy_models ( bdb , '' , '' , '' , dha_models , create = True ) with open ( dha_csv , '' ) as f : read_csv . bayesdb_read_csv ( bdb , '' , f , header = True , create = True ) bayeslite . bayesdb_load_legacy_models ( bdb , '' , '' , '' , dha_models , create = True ) bdb . execute ( '' ) bayeslite . bayesdb_load_codebook_csv_file ( bdb , '' , dha_codebook ) bayeslite . bayesdb_load_codebook_csv_file ( bdb , '' , dha_codebook ) bql = '''''' with bdb . savepoint ( ) : assert bdb . execute ( bql , ( '' , ) ) . fetchall ( ) == [ ( '' , ) , ( '' , ) , ( '' , ) , ( '' , ) , ( '' , ) , ( '' , ) , ( '' , ) , ( '' , ) , ( '' , ) , ( '' , ) , ] bql = '''''' with bdb . savepoint ( ) : assert bdb . execute ( bql ) . fetchall ( ) == [ ( '' , ) , ( '' , ) , ( '' , ) , ( '' , ) , ( '' , ) , ( '' , ) , ( '' , ) , ( '' , ) , ( '' , ) , ", "answer": "( '' , ) ,"}, {"prompt": " C = def norm ( n ) : return n & class U32 : v = def __init__ ( self , value = ) : self . v = C + norm ( abs ( int ( value ) ) ) def set ( self , value = ) : self . v = C + norm ( abs ( int ( value ) ) ) def __repr__ ( self ) : return hex ( norm ( self . v ) ) def __long__ ( self ) : return int ( norm ( self . v ) ) def __int__ ( self ) : return int ( norm ( self . v ) ) def __chr__ ( self ) : return chr ( norm ( self . v ) ) def __add__ ( self , b ) : r = U32 ( ) r . v = C + norm ( self . v + b . v ) return r def __sub__ ( self , b ) : r = U32 ( ) if self . v < b . v : r . v = C + norm ( - ( b . v - self . v ) ) else : r . v = C + norm ( self . v - b . v ) return r def __mul__ ( self , b ) : r = U32 ( ) r . v = C + norm ( self . v * b . v ) return r def __div__ ( self , b ) : r = U32 ( ) r . v = C + ( norm ( self . v ) / norm ( b . v ) ) return r def __mod__ ( self , b ) : r = U32 ( ) r . v = C + ( norm ( self . v ) % norm ( b . v ) ) return r def __neg__ ( self ) : return U32 ( self . v ) def __pos__ ( self ) : return U32 ( self . v ) def __abs__ ( self ) : return U32 ( self . v ) def __invert__ ( self ) : r = U32 ( ) r . v = C + norm ( ~ self . v ) return r def __lshift__ ( self , b ) : r = U32 ( ) r . v = C + norm ( self . v << b ) return r def __rshift__ ( self , b ) : r = U32 ( ) r . v = C + ( norm ( self . v ) >> b ) return r def __and__ ( self , b ) : r = U32 ( ) r . v = C + norm ( self . v & b . v ) return r def __or__ ( self , b ) : r = U32 ( ) r . v = C + norm ( self . v | b . v ) return r def __xor__ ( self , b ) : r = U32 ( ) r . v = C + norm ( self . v ^ b . v ) ", "answer": "return r"}, {"prompt": " import logging import socket import datetime import wx from camera_view import CameraPanel class MainWindow ( wx . Frame ) : def __init__ ( self , parent , title , controller , server_name , rpc_port , camera_port ) : self . controller = controller self . _server_name = server_name self . _rpc_port = rpc_port self . _camera_port = camera_port wx . Frame . __init__ ( self , parent , title = title , size = ( , ) ) self . panel = wx . Panel ( self ) self . sizer = wx . BoxSizer ( wx . VERTICAL ) self . sizer_view = wx . BoxSizer ( wx . HORIZONTAL ) self . sizer_control = wx . BoxSizer ( wx . HORIZONTAL ) self . sizer . Add ( self . sizer_view , , wx . EXPAND | wx . LEFT | wx . RIGHT | wx . TOP , ) self . sizer . Add ( self . sizer_control , , wx . EXPAND | wx . ALL , ) self . map_frame = MapPanel ( self . panel , controller ) self . sizer_view . Add ( self . map_frame , , wx . EXPAND | wx . RIGHT , ) cam_enabled = self . controller . model . capture_img_enabled self . camera_frame = CameraPanel ( self . panel , server_name , camera_port , cam_enabled ) self . sizer_view . Add ( self . camera_frame , , wx . EXPAND ) self . camera_update_count = self . waypoint_frame = WayPointPanel ( self . panel ) self . sizer_control . Add ( self . waypoint_frame , , wx . EXPAND | wx . RIGHT , ) self . display_frame = DisplayPanel ( self . panel , controller ) self . sizer_control . Add ( self . display_frame , , wx . EXPAND | wx . RIGHT , ) self . autopilot_frame = AutoPilotPanel ( self . panel , controller ) self . sizer_control . Add ( self . autopilot_frame , , wx . EXPAND | wx . RIGHT , ) self . manualpilot_frame = ManualPilotPanel ( self . panel , controller ) self . sizer_control . Add ( self . manualpilot_frame , , wx . EXPAND ) self . CreateStatusBar ( ) self . panel . SetSizerAndFit ( self . sizer ) self . Bind ( wx . EVT_CLOSE , self . OnClose ) interval_time = self . timer = wx . Timer ( self ) self . Bind ( wx . EVT_TIMER , self . on_timer , self . timer ) self . timer . Start ( interval_time , False ) def on_timer ( self , event ) : self . update ( ) def OnClose ( self , event ) : logging . debug ( \"\" ) if self . controller : self . controller . close_connection ( ) def update ( self ) : \"\"\"\"\"\" logging . debug ( \"\" ) self . controller . update ( ) self . display_frame . update ( ) if self . camera_update_count > : self . camera_frame . update ( ) self . camera_update_count = else : self . camera_update_count += @ property def server ( self ) : \"\"\"\"\"\" return self . _server @ property def rpc_port ( self ) : \"\"\"\"\"\" return self . _rpc_port @ property def camera_port ( self ) : \"\"\"\"\"\" return self . _camera_port class MapPanel ( wx . Panel ) : def __init__ ( self , parent , view_controller ) : wx . Panel . __init__ ( self , parent , style = wx . SUNKEN_BORDER ) self . _view_controller = view_controller class WayPointPanel ( wx . Panel ) : def __init__ ( self , parent ) : wx . Panel . __init__ ( self , parent , style = wx . SUNKEN_BORDER ) self . sizer = wx . GridBagSizer ( vgap = , hgap = ) self . header = wx . StaticText ( self , label = \"\" ) self . sizer . Add ( self . header , ( , ) , ( , ) , wx . EXPAND | wx . ALL , ) self . sizer . Add ( wx . StaticLine ( self ) , ( , ) , ( , ) , wx . EXPAND | wx . ALL , ) self . SetSizerAndFit ( self . sizer ) class DisplayPanel ( wx . Panel ) : def __init__ ( self , parent , controller ) : wx . Panel . __init__ ( self , parent , style = wx . SUNKEN_BORDER ) self . controller = controller self . sizer = wx . GridBagSizer ( vgap = , hgap = ) self . header = wx . StaticText ( self , label = \"\" ) self . sizer . Add ( self . header , ( , ) , ( , ) , wx . EXPAND | wx . ALL , ) self . sizer . Add ( wx . StaticLine ( self ) , ( , ) , ( , ) , wx . EXPAND | wx . ALL , ) self . l1 = wx . StaticText ( self , label = \"\" ) self . sizer . Add ( self . l1 , ( , ) , ( , ) , wx . EXPAND | wx . LEFT | wx . RIGHT , ) self . l2 = wx . StaticText ( self , label = \"\" ) self . sizer . Add ( self . l2 , ( , ) , ( , ) , wx . EXPAND | wx . LEFT | wx . RIGHT , ) self . t2 = wx . TextCtrl ( self , value = \"\" , style = wx . TE_READONLY ) self . sizer . Add ( self . t2 , ( , ) , ( , ) , wx . EXPAND | wx . LEFT | wx . RIGHT , ) self . l3 = wx . StaticText ( self , label = \"\" ) self . sizer . Add ( self . l3 , ( , ) , ( , ) , wx . EXPAND | wx . LEFT | wx . RIGHT , ) self . t3 = wx . TextCtrl ( self , value = \"\" , style = wx . TE_READONLY ) self . sizer . Add ( self . t3 , ( , ) , ( , ) , wx . EXPAND | wx . LEFT | wx . RIGHT , ) self . l4 = wx . StaticText ( self , label = \"\" ) self . sizer . Add ( self . l4 , ( , ) , ( , ) , wx . EXPAND | wx . LEFT | wx . RIGHT , ) self . t4 = wx . TextCtrl ( self , value = \"\" , style = wx . TE_READONLY ) self . sizer . Add ( self . t4 , ( , ) , ( , ) , wx . EXPAND | wx . LEFT | wx . RIGHT , ) self . l5 = wx . StaticText ( self , label = \"\" ) self . sizer . Add ( self . l5 , ( , ) , ( , ) , wx . EXPAND | wx . LEFT | wx . RIGHT , ) self . t5 = wx . TextCtrl ( self , value = \"\" , style = wx . TE_READONLY ) self . sizer . Add ( self . t5 , ( , ) , ( , ) , wx . EXPAND | wx . LEFT | wx . RIGHT , ) self . l6 = wx . StaticText ( self , label = \"\" ) self . sizer . Add ( self . l6 , ( , ) , ( , ) , wx . EXPAND | wx . LEFT | wx . RIGHT , ) self . t6 = wx . TextCtrl ( self , value = \"\" , style = wx . TE_READONLY ) self . sizer . Add ( self . t6 , ( , ) , ( , ) , wx . EXPAND | wx . LEFT | wx . RIGHT , ) self . l7 = wx . StaticText ( self , label = \"\" ) self . sizer . Add ( self . l7 , ( , ) , ( , ) , wx . EXPAND | wx . LEFT | wx . RIGHT , ) self . t7 = wx . TextCtrl ( self , value = \"\" , style = wx . TE_READONLY ) self . sizer . Add ( self . t7 , ( , ) , ( , ) , wx . EXPAND | wx . LEFT | wx . RIGHT , ) self . cb_fix = wx . CheckBox ( self , label = \"\" ) self . cb_fix . SetValue ( False ) self . sizer . Add ( self . cb_fix , ( , ) , ( , ) , wx . EXPAND | wx . LEFT | wx . RIGHT , ) self . l8 = wx . StaticText ( self , label = \"\" ) self . sizer . Add ( self . l8 , ( , ) , ( , ) , wx . EXPAND | wx . LEFT | wx . RIGHT , ) self . t8 = wx . TextCtrl ( self , value = \"\" , style = wx . TE_READONLY ) self . sizer . Add ( self . t8 , ( , ) , ( , ) , wx . EXPAND | wx . LEFT | wx . RIGHT , ) self . sizer . Add ( wx . StaticLine ( self ) , ( , ) , ( , ) , wx . EXPAND | wx . ALL , ) self . l9 = wx . StaticText ( self , label = \"\" ) self . sizer . Add ( self . l9 , ( , ) , ( , ) , wx . EXPAND | wx . ALL , ) self . l10 = wx . StaticText ( self , label = \"\" ) self . sizer . Add ( self . l10 , ( , ) , ( , ) , wx . EXPAND | wx . LEFT | wx . RIGHT , ) self . t10 = wx . TextCtrl ( self , value = \"\" , style = wx . TE_READONLY ) self . sizer . Add ( self . t10 , ( , ) , ( , ) , wx . EXPAND | wx . LEFT | wx . RIGHT , ) self . l11 = wx . StaticText ( self , label = \"\" ) self . sizer . Add ( self . l11 , ( , ) , ( , ) , wx . EXPAND | wx . LEFT | wx . RIGHT , ) self . t11 = wx . TextCtrl ( self , value = \"\" , style = wx . TE_READONLY ) self . sizer . Add ( self . t11 , ( , ) , ( , ) , wx . EXPAND | wx . LEFT | wx . RIGHT , ) self . l12 = wx . StaticText ( self , label = \"\" ) self . sizer . Add ( self . l12 , ( , ) , ( , ) , wx . EXPAND | wx . LEFT | wx . RIGHT , ) self . t12 = wx . TextCtrl ( self , value = \"\" , style = wx . TE_READONLY ) self . sizer . Add ( self . t12 , ( , ) , ( , ) , wx . EXPAND | wx . LEFT | wx . RIGHT , ) self . sizer . AddGrowableCol ( ) self . SetSizerAndFit ( self . sizer ) def update ( self ) : self . t2 . SetValue ( str ( self . controller . model . GPS_latitude ) ) self . t3 . SetValue ( str ( self . controller . model . GPS_longitude ) ) self . t5 . SetValue ( str ( self . controller . model . GPS_heading ) ) self . t6 . SetValue ( str ( self . controller . model . GPS_speed ) ) self . t7 . SetValue ( str ( self . controller . model . GPS_altitude ) ) self . cb_fix . SetValue ( self . controller . model . GPS_fix ) self . t8 . SetValue ( str ( self . controller . model . GPS_satellite_count ) ) self . t4 . SetValue ( str ( self . controller . model . compass_heading ) ) self . t10 . SetValue ( str ( self . controller . model . time ) ) self . t11 . SetValue ( str ( self . controller . model . date ) ) self . t12 . SetValue ( str ( self . controller . model . temperature ) ) class AutoPilotPanel ( wx . Panel ) : def __init__ ( self , parent , controller ) : wx . Panel . __init__ ( self , parent , style = wx . SUNKEN_BORDER ) self . controller = controller self . sizer = wx . GridBagSizer ( vgap = , hgap = ) self . SetSizerAndFit ( self . sizer ) self . header = wx . StaticText ( self , label = \"\" ) self . sizer . Add ( self . header , ( , ) , ( , ) , wx . EXPAND | wx . ALL , ) self . sizer . Add ( wx . StaticLine ( self ) , ( , ) , ( , ) , wx . EXPAND | wx . ALL , ) self . lblHeading = wx . StaticText ( self , label = \"\" ) self . sizer . Add ( self . lblHeading , ( , ) , ( , ) , wx . CENTER | wx . ALIGN_CENTER_HORIZONTAL | wx . ALL , ) self . heading = wx . Slider ( self , value = , minValue = - , maxValue = , style = wx . SL_HORIZONTAL ) self . heading . Bind ( wx . EVT_SCROLL , self . on_heading_scroll ) self . sizer . Add ( self . heading , ( , ) , ( , ) , wx . EXPAND | wx . ALL , ) self . btnCentreRudder = wx . Button ( self , - , \"\" ) self . btnCentreRudder . Bind ( wx . EVT_BUTTON , self . zero_heading ) self . sizer . Add ( self . btnCentreRudder , ( , ) , ( , ) , wx . ALIGN_CENTER | wx . ALL , ) self . lblThrottle = wx . StaticText ( self , label = \"\" ) self . sizer . Add ( self . lblThrottle , ( , ) , ( , ) , wx . CENTER | wx . ALIGN_CENTER_VERTICAL | wx . ALIGN_RIGHT | wx . ALL , ) self . speed = wx . Slider ( self , value = , minValue = - , maxValue = , style = wx . SL_VERTICAL ) self . speed . Bind ( wx . EVT_SCROLL , self . on_speed_scroll ) self . sizer . Add ( self . speed , ( , ) , ( , ) , wx . EXPAND | wx . ALL , ) self . btnZeroThrottle = wx . Button ( self , - , \"\" ) self . btnZeroThrottle . Bind ( wx . EVT_BUTTON , self . zero_speed ) ", "answer": "self . sizer . Add ( self . btnZeroThrottle , ( , ) , ( , ) , wx . ALIGN_CENTER | wx . ALL , )"}, {"prompt": " '''''' from firefly . utils . singleton import Singleton class MAdminManager : __metaclass__ = Singleton ", "answer": "def __init__ ( self ) :"}, {"prompt": " import logging import functools from pymongo . errors import OperationFailure from framework . mongo import database as proxy_database from framework . transactions import commands , messages , utils logger = logging . getLogger ( __name__ ) class TokuTransaction ( object ) : \"\"\"\"\"\" def __init__ ( self , database = None ) : self . database = database or proxy_database self . pending = False def __enter__ ( self ) : try : commands . begin ( self . database ) self . pending = True except OperationFailure as error : message = utils . get_error_message ( error ) ", "answer": "if messages . TRANSACTION_EXISTS_ERROR not in message :"}, {"prompt": " import shutil from osgeo import gdal from osgeo import ogr from ogrkit . cli import OGRKitUtility from ogrkit . utils import get_bounding_box gdal . UseExceptions ( ) class OGRDifference ( OGRKitUtility ) : description = '' def add_arguments ( self ) : self . argparser . add_argument ( '' , metavar = '' , nargs = '' , type = str ) def main ( self ) : source = ogr . Open ( self . args . input , False ) source_layer = source . GetLayer ( ) try : shutil . rmtree ( self . args . output ) ", "answer": "except OSError :"}, {"prompt": " \"\"\"\"\"\" from setuptools import setup setup ( name = '' , version = '' , url = '' , license = '' , author = '' , author_email = '' , maintainer = '' , maintainer_email = '' , description = '' , long_description = __doc__ , py_modules = [ '' ] , zip_safe = False , platforms = '' , ", "answer": "install_requires = [ '' , '' ] ,"}, {"prompt": " def grade ( tid , answer ) : if answer . find ( \"\" ) != - : return { \"\" : True , \"\" : \"\" } ", "answer": "return { \"\" : False , \"\" : \"\" } "}, {"prompt": " from pysb . testing import * from pysb import * from pysb . kappa import * from pysb . bng import generate_network import subprocess from re import split import pygraphviz as pgv @ with_model def test_kappa_simulation_results ( ) : Monomer ( '' , [ '' ] ) Monomer ( '' , [ '' ] ) Initial ( A ( b = None ) , Parameter ( '' , ) ) Initial ( B ( b = None ) , Parameter ( '' , ) ) Rule ( '' , A ( b = None ) + B ( b = None ) >> A ( b = ) % B ( b = ) , Parameter ( '' , ) ) Rule ( '' , A ( b = ) % B ( b = ) >> A ( b = None ) + B ( b = None ) , Parameter ( '' , ) ) Observable ( '' , A ( b = ) % B ( b = ) ) npts = kres = run_simulation ( model , time = , points = npts ) ok_ ( len ( kres [ '' ] ) == npts + ) ok_ ( len ( kres [ '' ] ) == npts + ) ok_ ( kres [ '' ] [ ] == ) ok_ ( sorted ( kres [ '' ] ) [ - ] == ) @ with_model def test_kappa_expressions ( ) : Monomer ( '' , [ '' ] , { '' : [ '' ] } ) Parameter ( '' , ) Parameter ( '' , ) Parameter ( '' , ) Expression ( '' , / two ) Initial ( A ( site = ( '' ) ) , num_A ) Rule ( '' , A ( site = '' ) + A ( site = '' ) >> A ( site = ( '' , ) ) % A ( site = ( '' , ) ) , kf ) Rule ( '' , A ( site = ( '' , ) ) % A ( site = ( '' , ) ) >> A ( site = '' ) + A ( site = '' ) , kr ) run_simulation ( model , time = ) Rule ( '' , A ( site = ( '' , ANY ) ) >> None , kr ) Observable ( '' , A ( site = ( '' , ANY ) ) ) run_simulation ( model , time = ) @ with_model def test_flux_map ( ) : \"\"\"\"\"\" Monomer ( '' , [ '' ] ) Monomer ( '' , [ '' , '' ] ) Monomer ( '' , [ '' ] ) Parameter ( '' , ) Rule ( '' , A ( b = None ) + B ( a = None ) >> A ( b = ) % B ( a = ) , k ) Rule ( '' , C ( b = None ) + B ( c = None ) >> C ( b = ) % B ( c = ) , k ) Observable ( '' , A ( b = ) % B ( a = , c = ) % C ( b = ) ) Initial ( A ( b = None ) , Parameter ( '' , ) ) Initial ( B ( a = None , c = None ) , Parameter ( '' , ) ) Initial ( C ( b = None ) , Parameter ( '' , ) ) res = run_simulation ( model , time = , points = , flux_map = True , output_dir = '' , cleanup = True , verbose = False ) simdata = res . timecourse ok_ ( len ( simdata [ '' ] ) == ) ok_ ( len ( simdata [ '' ] ) == ) ok_ ( simdata [ '' ] [ ] == ) ok_ ( sorted ( simdata [ '' ] ) [ - ] == ) fluxmap = res . flux_map ok_ ( isinstance ( fluxmap , pgv . AGraph ) ) @ with_model def test_kappa_wild ( ) : Monomer ( '' , [ '' ] ) Monomer ( '' , [ '' ] ) Initial ( A ( site = None ) , Parameter ( '' , ) ) Initial ( B ( site = None ) , Parameter ( '' , ) ) Initial ( A ( site = ) % B ( site = ) , Parameter ( '' , ) ) Rule ( '' , A ( site = pysb . WILD ) >> None , Parameter ( '' , ) ) Observable ( '' , A ( ) ) run_simulation ( model , time = ) @ raises ( ValueError ) @ with_model def test_run_static_analysis_valueerror ( ) : Monomer ( '' , [ '' ] ) Monomer ( '' , [ '' ] ) Rule ( '' , A ( b = None ) + B ( b = None ) >> A ( b = ) % B ( b = ) , Parameter ( '' , ) ) Observable ( '' , A ( b = ) % B ( b = ) ) res = run_static_analysis ( model , contact_map = False , influence_map = False , output_dir = '' ) @ with_model def test_run_static_analysis_cmap ( ) : \"\"\"\"\"\" Monomer ( '' , [ '' ] ) Monomer ( '' , [ '' ] ) Rule ( '' , A ( b = None ) + B ( b = None ) >> A ( b = ) % B ( b = ) , Parameter ( '' , ) ) Observable ( '' , A ( b = ) % B ( b = ) ) res = run_static_analysis ( model , contact_map = True , influence_map = False , output_dir = '' ) ok_ ( isinstance ( res . contact_map , pgv . AGraph ) ) ok_ ( res . influence_map is None ) @ with_model def test_run_static_analysis_imap ( ) : \"\"\"\"\"\" Monomer ( '' , [ ] ) Monomer ( '' , [ '' ] , { '' : [ '' , '' ] } ) Monomer ( '' , [ '' ] , { '' : [ '' , '' ] } ) Initial ( A ( ) , Parameter ( '' , ) ) Initial ( B ( active = '' ) , Parameter ( '' , ) ) Initial ( C ( active = '' ) , Parameter ( '' , ) ) Rule ( '' , A ( ) + B ( active = '' ) >> A ( ) + B ( active = '' ) , Parameter ( '' , ) ) Rule ( '' , B ( active = '' ) + C ( active = '' ) >> B ( active = '' ) + C ( active = '' ) , Parameter ( '' , ) ) res = run_static_analysis ( model , contact_map = False , influence_map = True , output_dir = '' ) ok_ ( isinstance ( res . influence_map , pgv . AGraph ) ) ok_ ( res . contact_map is None ) @ with_model def test_run_static_analysis_both ( ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " from flask_table import Table , Col class ItemTable ( Table ) : name = Col ( '' ) description = Col ( '' ) class Item ( object ) : def __init__ ( self , name , description ) : self . name = name self . description = description ", "answer": "items = [ Item ( '' , '' ) ,"}, {"prompt": " \"\"\"\"\"\" import re from django . conf import settings from django . core . urlresolvers import reverse from django . http import HttpResponseRedirect EXEMPT_URLS = [ re . compile ( settings . LOGIN_URL . lstrip ( '' ) ) ] if hasattr ( settings , '' ) : EXEMPT_URLS += [ re . compile ( exempt_url ) for exempt_url in settings . LOGIN_EXEMPT_URLS ] ", "answer": "class InviteMiddleware ( object ) :"}, {"prompt": " from operator import attrgetter from django . core . exceptions import FieldError from django . test import TestCase from models import ( Chef , CommonInfo , ItalianRestaurant , ParkingLot , Place , Post , Restaurant , Student , StudentWorker , Supplier , Worker , MixinModel ) class ModelInheritanceTests ( TestCase ) : def test_abstract ( self ) : w1 = Worker . objects . create ( name = \"\" , age = , job = \"\" ) w2 = Worker . objects . create ( name = \"\" , age = , job = \"\" ) s = Student . objects . create ( name = \"\" , age = , school_class = \"\" ) self . assertEqual ( unicode ( w1 ) , \"\" ) self . assertEqual ( unicode ( s ) , \"\" ) self . assertQuerysetEqual ( Worker . objects . values ( \"\" ) , [ { \"\" : \"\" } , { \"\" : \"\" } , ] , lambda o : o ) self . assertEqual ( Student . _meta . ordering , [ ] ) self . assertRaises ( AttributeError , lambda : CommonInfo . objects . all ( ) ) self . assertRaises ( Student . DoesNotExist , StudentWorker . objects . get , pk = ) self . assertRaises ( Worker . DoesNotExist , StudentWorker . objects . get , pk = ) sw1 = StudentWorker ( ) sw1 . name = \"\" sw1 . age = sw1 . save ( ) sw2 = StudentWorker ( ) sw2 . name = \"\" sw2 . age = sw2 . save ( ) self . assertRaises ( Student . MultipleObjectsReturned , StudentWorker . objects . get , pk__lt = sw2 . pk + ) self . assertRaises ( Worker . MultipleObjectsReturned , StudentWorker . objects . get , pk__lt = sw2 . pk + ) def test_multiple_table ( self ) : post = Post . objects . create ( title = \"\" ) post . attached_comment_set . create ( content = \"\" , is_spam = True ) post . attached_link_set . create ( content = \"\" , url = \"\" ) self . assertRaises ( AttributeError , getattr , post , \"\" ) p1 = Place . objects . create ( name = \"\" , address = \"\" ) p2 = Place . objects . create ( name = \"\" , address = \"\" ) r = Restaurant . objects . create ( name = \"\" , address = \"\" , serves_hot_dogs = True , serves_pizza = False , rating = ) c = Chef . objects . create ( name = \"\" ) ir = ItalianRestaurant . objects . create ( name = \"\" , address = \"\" , serves_hot_dogs = False , serves_pizza = False , serves_gnocchi = True , rating = , chef = c ) self . assertQuerysetEqual ( ItalianRestaurant . objects . filter ( address = \"\" ) , [ \"\" , ] , attrgetter ( \"\" ) ) ir . address = \"\" ir . save ( ) self . assertQuerysetEqual ( ItalianRestaurant . objects . filter ( address = \"\" ) , [ \"\" , ] , attrgetter ( \"\" ) ) self . assertEqual ( [ f . name for f in Restaurant . _meta . fields ] , [ \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ] ) self . assertEqual ( [ f . name for f in ItalianRestaurant . _meta . fields ] , [ \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ] , ) self . assertEqual ( Restaurant . _meta . ordering , [ \"\" ] ) self . assertQuerysetEqual ( Place . objects . filter ( supplier__name = \"\" ) , [ ] ) self . assertRaises ( FieldError , Restaurant . objects . filter , supplier__name = \"\" ) self . assertQuerysetEqual ( Restaurant . objects . filter ( name = \"\" ) , [ \"\" , ] , attrgetter ( \"\" ) ) self . assertQuerysetEqual ( ItalianRestaurant . objects . filter ( address = \"\" ) , [ \"\" , ] , attrgetter ( \"\" ) ) p = Place . objects . get ( name = \"\" ) self . assertIs ( type ( p ) , Place ) self . assertEqual ( p . restaurant , Restaurant . objects . get ( name = \"\" ) ) self . assertEqual ( Place . objects . get ( name = \"\" ) . restaurant . italianrestaurant , ItalianRestaurant . objects . get ( name = \"\" ) ) self . assertEqual ( Restaurant . objects . get ( name = \"\" ) . italianrestaurant , ItalianRestaurant . objects . get ( name = \"\" ) ) self . assertRaises ( ItalianRestaurant . DoesNotExist , lambda : p . restaurant . italianrestaurant ) self . assertRaises ( Place . DoesNotExist , ItalianRestaurant . objects . get , name = \"\" ) self . assertRaises ( Place . MultipleObjectsReturned , Restaurant . objects . get , id__lt = ) s1 = Supplier . objects . create ( name = \"\" , address = \"\" ) s1 . customers = [ r , ir ] s2 = Supplier . objects . create ( name = \"\" , address = \"\" ) s2 . customers = [ ir ] p = Place . objects . get ( name = \"\" ) self . assertRaises ( Restaurant . DoesNotExist , lambda : p . restaurant ) self . assertEqual ( p . supplier , s1 ) self . assertQuerysetEqual ( ir . provider . order_by ( \"\" ) , [ \"\" , \"\" ] , attrgetter ( \"\" ) ) self . assertQuerysetEqual ( Restaurant . objects . filter ( provider__name__contains = \"\" ) , [ \"\" , \"\" , ] , attrgetter ( \"\" ) ) self . assertQuerysetEqual ( ItalianRestaurant . objects . filter ( provider__name__contains = \"\" ) , [ \"\" , ] , attrgetter ( \"\" ) , ) park1 = ParkingLot . objects . create ( name = \"\" , address = \"\" , main_site = s1 ) park2 = ParkingLot . objects . create ( name = \"\" , address = \"\" , main_site = ir ) self . assertEqual ( Restaurant . objects . get ( lot__name = \"\" ) . name , \"\" ) rows = Restaurant . objects . filter ( serves_hot_dogs = True , name__contains = \"\" ) . update ( name = \"\" , serves_hot_dogs = False ) self . assertEqual ( rows , ) r1 = Restaurant . objects . get ( pk = r . pk ) self . assertFalse ( r1 . serves_hot_dogs ) self . assertEqual ( r1 . name , \"\" ) self . assertQuerysetEqual ( ItalianRestaurant . objects . values ( \"\" , \"\" ) , [ { \"\" : , \"\" : \"\" } ] , lambda o : o ) self . assertNumQueries ( , ", "answer": "lambda : ItalianRestaurant . objects . all ( ) [ ] . chef"}, {"prompt": " \"\"\"\"\"\" import pika SERVER_QUEUE = '' ", "answer": "def main ( ) :"}, {"prompt": " from django . db import models ", "answer": "from django . contrib . auth . models import AbstractUser"}, {"prompt": " \"\"\"\"\"\" __author__ = '' import logging from periodically import decorators from services . configuration . models import tle as tle_models logger = logging . getLogger ( '' ) @ decorators . daily ( ) def update_tle_database ( ) : \"\"\"\"\"\" logger . info ( \"\" ) tle_models . TwoLineElementsManager . load_celestrak ( ) ", "answer": "logger . info ( '' ) "}, {"prompt": " from datetime import datetime import json import logging import os from httpsig . requests_auth import HTTPSignatureAuth import jwt import requests from requests . adapters import HTTPAdapter from stream import exceptions , serializer from stream . signing import sign from stream . utils import validate_feed_slug , validate_user_id from requests import Request logger = logging . getLogger ( __name__ ) class StreamClient ( object ) : base_url = '' def __init__ ( self , api_key , api_secret , app_id , version = '' , timeout = , base_url = None , location = None ) : '''''' self . api_key = api_key self . api_secret = api_secret self . app_id = app_id self . version = version self . timeout = timeout self . location = location if os . environ . get ( '' ) : self . base_url = '' self . timeout = elif base_url is not None : self . base_url = base_url elif location is not None : self . base_url = '' % location self . base_analytics_url = '' self . session = requests . Session ( ) self . session . mount ( self . base_url , HTTPAdapter ( max_retries = ) ) self . auth = HTTPSignatureAuth ( api_key , secret = api_secret ) def feed ( self , feed_slug , user_id ) : '''''' from stream . feed import Feed feed_slug = validate_feed_slug ( feed_slug ) ", "answer": "user_id = validate_user_id ( user_id )"}, {"prompt": " from __future__ import unicode_literals ", "answer": "from django_evolution . mutations import AddField"}, {"prompt": " \"\"\"\"\"\" import webob . exc from nova import compute from nova import exception from nova import flags from nova import log as logging from nova . api . openstack import common from nova . api . openstack import extensions from nova . api . openstack import faults from nova . api . openstack . contrib import admin_only from nova . scheduler import api as scheduler_api LOG = logging . getLogger ( \"\" ) FLAGS = flags . FLAGS def _list_hosts ( req , service = None ) : \"\"\"\"\"\" context = req . environ [ '' ] hosts = scheduler_api . get_host_list ( context ) if service : hosts = [ host for host in hosts if host [ \"\" ] == service ] return hosts def check_host ( fn ) : \"\"\"\"\"\" def wrapped ( self , req , id , service = None , * args , ** kwargs ) : listed_hosts = _list_hosts ( req , service ) hosts = [ h [ \"\" ] for h in listed_hosts ] if id in hosts : return fn ( self , req , id , * args , ** kwargs ) else : raise exception . HostNotFound ( host = id ) return wrapped class HostController ( object ) : \"\"\"\"\"\" def __init__ ( self ) : self . compute_api = compute . API ( ) super ( HostController , self ) . __init__ ( ) def index ( self , req ) : return { '' : _list_hosts ( req ) } @ check_host def update ( self , req , id , body ) : for raw_key , raw_val in body . iteritems ( ) : key = raw_key . lower ( ) . strip ( ) val = raw_val . lower ( ) . strip ( ) if key == \"\" : if val [ : ] in ( \"\" , \"\" ) : return self . _set_enabled_status ( req , id , enabled = ( val . startswith ( \"\" ) ) ) else : explanation = _ ( \"\" ) % raw_val raise webob . exc . HTTPBadRequest ( explanation = explanation ) else : explanation = _ ( \"\" ) % raw_key raise webob . exc . HTTPBadRequest ( explanation = explanation ) def _set_enabled_status ( self , req , host , enabled ) : \"\"\"\"\"\" context = req . environ [ '' ] state = \"\" if enabled else \"\" LOG . audit ( _ ( \"\" ) % locals ( ) ) result = self . compute_api . set_host_enabled ( context , host = host , enabled = enabled ) if result not in ( \"\" , \"\" ) : raise webob . exc . HTTPBadRequest ( explanation = result ) return { \"\" : host , \"\" : result } def _host_power_action ( self , req , host , action ) : \"\"\"\"\"\" context = req . environ [ '' ] try : result = self . compute_api . host_power_action ( context , host = host , action = action ) except NotImplementedError as e : ", "answer": "raise webob . exc . HTTPBadRequest ( explanation = e . msg )"}, {"prompt": " \"\"\"\"\"\" import requests from flask import json from py . test import raises , fixture from tentd . documents . entity import Follower from tentd . tests . http import POST , SPUT , SDELETE from tentd . tests . mock import MockFunction , MockResponse from tentd . utils . exceptions import APIBadRequest PROFILE_FORMAT = '' @ fixture def follower_mocks ( request , monkeypatch ) : follower_identity = '' follower_api_root = '' monkeypatch . setattr ( requests , '' , MockFunction ( ) ) requests . head [ follower_identity ] = MockResponse ( headers = { '' : PROFILE_FORMAT . format ( follower_api_root ) } ) monkeypatch . setattr ( requests , '' , MockFunction ( ) ) requests . get [ follower_api_root + '' ] = MockResponse ( ) requests . get [ follower_api_root + '' ] = MockResponse ( json = { \"\" : { \"\" : follower_identity , \"\" : [ follower_api_root ] , \"\" : [ ] , \"\" : \"\" , } } ) assert isinstance ( requests . head , MockFunction ) assert isinstance ( requests . get , MockFunction ) @ request . addfinalizer def teardown_mocks ( ) : monkeypatch . delattr ( requests , '' ) monkeypatch . delattr ( requests , '' ) return { '' : follower_identity , '' : follower_api_root , '' : follower_api_root + '' } @ fixture def new_follower_mocks ( request , follower_mocks ) : new_follower_identity = '' new_follower_api_root = '' requests . head [ new_follower_identity ] = MockResponse ( ", "answer": "headers = { '' : PROFILE_FORMAT . format ( new_follower_api_root ) } )"}, {"prompt": " \"\"\"\"\"\" import larch from larch import isParameter , Parameter , isgroup , Group import numpy as np def encode4js ( obj ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " '''''' import os , sys , re from arelle import PluginManager from arelle import ModelDocument , XbrlConst , XmlUtil , UrlUtil , LeiUtil from arelle . HashUtil import md5hash , Md5Sum from arelle . ModelDtsObject import ModelConcept , ModelType , ModelLocator , ModelResource from arelle . ModelFormulaObject import Aspect from arelle . ModelObject import ModelObject from arelle . ModelRelationshipSet import ModelRelationshipSet from arelle . ModelValue import qname , qnameEltPfxName from arelle . ValidateUtr import ValidateUtr from arelle . XbrlConst import qnEnumerationItemType try : import regex as re except ImportError : import re from lxml import etree from collections import defaultdict qnFIndicators = qname ( \"\" ) qnFilingIndicator = qname ( \"\" ) qnPercentItemType = qname ( \"\" ) qnPureItemType = qname ( \"\" ) qnMetReportingCurrency = qname ( \"\" ) integerItemTypes = { \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" } schemaRefDatePattern = re . compile ( r\"\" ) s_2_18_c_a_met = { \"\"\"\"\"\" \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" } CANONICAL_PREFIXES = { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" } def dislosureSystemTypes ( disclosureSystem , * args , ** kwargs ) : return ( ( \"\" , \"\" ) , ( \"\" , \"\" ) ) def disclosureSystemConfigURL ( disclosureSystem , * args , ** kwargs ) : return os . path . join ( os . path . dirname ( __file__ ) , \"\" ) def validateSetup ( val , parameters = None , * args , ** kwargs ) : val . validateEBA = val . validateDisclosureSystem and getattr ( val . disclosureSystem , \"\" , False ) val . validateEIOPA = val . validateDisclosureSystem and getattr ( val . disclosureSystem , \"\" , False ) if not ( val . validateEBA or val . validateEIOPA ) : return val . validateUTR = False val . utrValidator = ValidateUtr ( val . modelXbrl , \"\" , \"\" ) val . isEIOPAfullVersion = val . isEIOPA_2_0_1 = False modelDocument = val . modelXbrl . modelDocument if modelDocument . type == ModelDocument . Type . INSTANCE : for doc , docRef in modelDocument . referencesDocument . items ( ) : if docRef . referenceType == \"\" : if docRef . referringModelObject . localName == \"\" : _match = schemaRefDatePattern . match ( doc . uri ) if _match : val . isEIOPAfullVersion = _match . group ( ) > \"\" val . isEIOPA_2_0_1 = _match . group ( ) >= \"\" break else : val . modelXbrl . error ( \"\" , _ ( '' ) , modelObject = modelDocument , schemaRef = doc . uri ) val . qnDimAF = val . qnDimOC = val . qnCAx1 = None _nsmap = val . modelXbrl . modelDocument . xmlRootElement . nsmap if val . isEIOPA_2_0_1 : _hasPiInstanceGenerator = False for pi in modelDocument . processingInstructions : if pi . target == \"\" : _hasPiInstanceGenerator = True if not all ( pi . get ( attr ) for attr in ( \"\" , \"\" , \"\" ) ) : val . modelXbrl . warning ( \"\" , _ ( '' ) , modelObject = modelDocument ) if not _hasPiInstanceGenerator : val . modelXbrl . warning ( \"\" , _ ( '' ) , modelObject = modelDocument ) val . qnDimAF = qname ( \"\" , _nsmap ) val . qnDimOC = qname ( \"\" , _nsmap ) val . qnCAx1 = qname ( \"\" , _nsmap ) val . prefixNamespace = { } val . namespacePrefix = { } val . idObjects = { } val . typedDomainQnames = set ( ) val . typedDomainElements = set ( ) for modelConcept in val . modelXbrl . qnameConcepts . values ( ) : if modelConcept . isTypedDimension : typedDomainElement = modelConcept . typedDomainElement if isinstance ( typedDomainElement , ModelConcept ) : val . typedDomainQnames . add ( typedDomainElement . qname ) val . typedDomainElements . add ( typedDomainElement ) val . filingIndicators = { } val . numFilingIndicatorTuples = val . cntxEntities = set ( ) val . cntxDates = defaultdict ( set ) val . unusedCntxIDs = set ( ) val . unusedUnitIDs = set ( ) val . currenciesUsed = { } val . reportingCurrency = None val . namespacePrefixesUsed = defaultdict ( set ) val . prefixesUnused = set ( ) for prefix , ns in _nsmap . items ( ) : val . prefixesUnused . add ( prefix ) val . namespacePrefixesUsed [ ns ] . add ( prefix ) val . firstFactObjectIndex = sys . maxsize val . firstFact = None val . footnotesRelationshipSet = ModelRelationshipSet ( val . modelXbrl , \"\" ) def prefixUsed ( val , ns , prefix ) : val . namespacePrefixesUsed [ ns ] . add ( prefix ) for _prefix in val . namespacePrefixesUsed [ ns ] : val . prefixesUnused . discard ( _prefix ) def validateStreamingFacts ( val , factsToCheck , * args , ** kwargs ) : if not ( val . validateEBA or val . validateEIOPA ) : return True validateFacts ( val , factsToCheck ) def validateFacts ( val , factsToCheck ) : modelXbrl = val . modelXbrl modelDocument = modelXbrl . modelDocument timelessDatePattern = re . compile ( r\"\" ) for cntx in modelXbrl . contexts . values ( ) : if getattr ( cntx , \"\" , False ) : continue cntx . _batchChecked = True val . cntxEntities . add ( cntx . entityIdentifier ) dateElts = XmlUtil . descendants ( cntx , XbrlConst . xbrli , ( \"\" , \"\" , \"\" ) ) if any ( not timelessDatePattern . match ( e . textValue ) for e in dateElts ) : modelXbrl . error ( ( \"\" , \"\" ) , _ ( '' ) , modelObject = cntx , dates = \"\" . join ( e . text for e in dateElts ) ) if cntx . isForeverPeriod : modelXbrl . error ( ( \"\" , \"\" ) , _ ( '' ) , modelObject = cntx ) elif cntx . isStartEndPeriod : modelXbrl . error ( ( \"\" , \"\" ) , _ ( '' ) , modelObject = cntx ) elif cntx . isInstantPeriod : val . cntxDates [ cntx . instantDatetime ] . add ( modelXbrl if getattr ( val . modelXbrl , \"\" , False ) else cntx ) if cntx . hasSegment : modelXbrl . error ( ( \"\" , \"\" ) , _ ( \"\" ) , modelObject = cntx , cntx = cntx . id ) if cntx . nonDimValues ( \"\" ) : modelXbrl . error ( ( \"\" , \"\" if val . isEIOPAfullVersion else \"\" ) , _ ( \"\" ) , modelObject = cntx , cntx = cntx . id , messageCodes = ( \"\" , \"\" , \"\" ) ) val . unusedCntxIDs . add ( cntx . id ) if val . isEIOPA_2_0_1 and len ( cntx . id ) > : modelXbrl . warning ( \"\" , _ ( \"\" ) , modelObject = cntx , cntx = cntx . id ) for unit in modelXbrl . units . values ( ) : if getattr ( unit , \"\" , False ) : continue unit . _batchChecked = True val . unusedUnitIDs . add ( unit . id ) factsByQname = defaultdict ( set ) for f in factsToCheck : factsByQname [ f . qname ] . add ( f ) val . unusedCntxIDs . discard ( f . contextID ) val . unusedUnitIDs . discard ( f . unitID ) if f . objectIndex < val . firstFactObjectIndex : val . firstFactObjectIndex = f . objectIndex val . firstFact = f for fIndicators in factsByQname [ qnFIndicators ] : val . numFilingIndicatorTuples += for fIndicator in fIndicators . modelTupleFacts : _value = ( getattr ( fIndicator , \"\" , None ) or fIndicator . value ) _filed = fIndicator . get ( \"\" , \"\" ) in ( \"\" , \"\" ) if _value in val . filingIndicators : modelXbrl . error ( ( \"\" , \"\" ) , _ ( '' ) , modelObject = ( fIndicator , val . filingIndicators [ _value ] ) , filingIndicator = _value ) if _filed and not val . filingIndicators [ _value ] : val . filingIndicators [ _value ] = _filed else : val . filingIndicators [ _value ] = _filed val . unusedCntxIDs . discard ( fIndicator . contextID ) cntx = fIndicator . context if cntx is not None and ( cntx . hasSegment or cntx . hasScenario ) : modelXbrl . error ( \"\" if val . isEIOPAfullVersion else \"\" , _ ( '' ) , modelObject = fIndicator , filingIndicator = _value ) if fIndicators . objectIndex > val . firstFactObjectIndex : modelXbrl . warning ( \"\" , _ ( '' ) , modelObject = ( fIndicators , val . firstFact ) , firstFact = val . firstFact . qname ) if val . isEIOPAfullVersion : for fIndicator in factsByQname [ qnFilingIndicator ] : if fIndicator . getparent ( ) . qname == XbrlConst . qnXbrliXbrl : _isPos = fIndicator . get ( \"\" , \"\" ) in ( \"\" , \"\" ) _value = ( getattr ( fIndicator , \"\" , None ) or fIndicator . value ) modelXbrl . error ( \"\" if _isPos else \"\" , _ ( '' ) , modelObject = fIndicator , filingIndicator = _value , messageCodes = ( \"\" , \"\" ) ) otherFacts = { } nilFacts = [ ] stringFactsWithXmlLang = [ ] nonMonetaryNonPureFacts = [ ] for qname , facts in factsByQname . items ( ) : for f in facts : if f . qname == qnFilingIndicator : continue if modelXbrl . skipDTS : c = f . qname . localName [ ] isNumeric = c in ( '' , '' , '' , '' ) isMonetary = c == '' isInteger = c == '' isPercent = c == '' isString = c == '' isEnum = c == '' else : concept = f . concept if concept is not None : isNumeric = concept . isNumeric isMonetary = concept . isMonetary isInteger = concept . baseXbrliType in integerItemTypes isPercent = concept . typeQname in ( qnPercentItemType , qnPureItemType ) isString = concept . baseXbrliType in ( \"\" , \"\" ) isEnum = concept . typeQname == qnEnumerationItemType else : isNumeric = isString = isEnum = False k = ( f . getparent ( ) . objectIndex , f . qname , f . context . contextDimAwareHash if f . context is not None else None , f . unit . hash if f . unit is not None else None , hash ( f . xmlLang ) ) if f . qname == qnFIndicators and val . validateEIOPA : pass elif k not in otherFacts : otherFacts [ k ] = { f } else : matches = [ o for o in otherFacts [ k ] if ( f . getparent ( ) . objectIndex == o . getparent ( ) . objectIndex and f . qname == o . qname and f . context . isEqualTo ( o . context ) if f . context is not None and o . context is not None else True ) and ( f . xmlLang == o . xmlLang ) ] if matches : contexts = [ f . contextID ] + [ o . contextID for o in matches ] modelXbrl . error ( ( \"\" , \"\" if val . isEIOPAfullVersion else \"\" ) , _ ( '' ) , modelObject = [ f ] + matches , fact = f . qname , contexts = '' . join ( contexts ) , messageCodes = ( \"\" , \"\" , \"\" ) ) else : otherFacts [ k ] . add ( f ) if isNumeric : if f . precision : modelXbrl . error ( ( \"\" , \"\" ) , _ ( \"\" ) , modelObject = f , fact = f . qname , contextID = f . contextID , precision = f . precision ) if f . decimals and not f . isNil : if f . decimals == \"\" : if not val . isEIOPAfullVersion : modelXbrl . error ( \"\" , _ ( \"\" ) , modelObject = f , fact = f . qname , contextID = f . contextID , decimals = f . decimals ) else : try : xValue = f . xValue dec = int ( f . decimals ) if isMonetary : if val . isEIOPA_2_0_1 : _absXvalue = abs ( xValue ) if str ( f . qname ) in s_2_18_c_a_met : dMin = elif _absXvalue >= : dMin = - elif > _absXvalue >= : dMin = - elif > _absXvalue >= : dMin = - else : dMin = - if dMin > dec : modelXbrl . error ( \"\" , _ ( \"\" ) , modelObject = f , fact = f . qname , contextID = f . contextID , minimumDecimals = dMin , decimals = f . decimals ) elif dec < - : modelXbrl . error ( ( \"\" , \"\" ) , _ ( \"\" ) , modelObject = f , fact = f . qname , contextID = f . contextID , decimals = f . decimals ) else : if - < xValue < : dMin = elif - < xValue < : dMin = elif - < xValue < : dMin = elif - < xValue < : dMin = - elif - < xValue < : dMin = - else : dMin = - if dMin > dec : modelXbrl . warning ( \"\" , _ ( \"\" ) , modelObject = f , fact = f . qname , contextID = f . contextID , value = xValue , decimals = f . decimals , mindec = dMin ) elif isInteger : if dec != : modelXbrl . error ( ( \"\" , \"\" ) , _ ( \"\" ) , modelObject = f , fact = f . qname , contextID = f . contextID , decimals = f . decimals ) elif isPercent : if dec < : modelXbrl . error ( ( \"\" , \"\" ) , _ ( \"\" ) , modelObject = f , fact = f . qname , contextID = f . contextID , decimals = f . decimals ) if val . isEIOPA_2_0_1 and xValue > : modelXbrl . warning ( ( \"\" ) , _ ( \"\" ) , modelObject = f , fact = f . qname , contextID = f . contextID , value = xValue ) else : if - < xValue < : dMin = elif - < xValue < : dMin = elif - < xValue < : dMin = elif - < xValue < : dMin = else : dMin = if dMin > dec : modelXbrl . warning ( \"\" , _ ( \"\" ) , modelObject = f , fact = f . qname , contextID = f . contextID , value = xValue , decimals = f . decimals , mindec = dMin ) except ( AttributeError , ValueError ) : pass '''''' unit = f . unit if unit is not None : if isMonetary : if unit . measures [ ] : _currencyMeasure = unit . measures [ ] [ ] if val . isEIOPA_2_0_1 and f . context is not None : if f . context . dimMemberQname ( val . qnDimAF ) == val . qnCAx1 and val . qnDimOC in f . context . qnameDims : _ocCurrency = f . context . dimMemberQname ( val . qnDimOC ) . localName if _currencyMeasure . localName != _ocCurrency : modelXbrl . error ( \"\" , _ ( \"\" ) , modelObject = f , metric = f . qname , ocCurrency = _ocCurrency , unitCurrency = _currencyMeasure . localName ) else : val . currenciesUsed [ _currencyMeasure ] = unit else : val . currenciesUsed [ _currencyMeasure ] = unit elif not unit . isSingleMeasure or unit . measures [ ] [ ] != XbrlConst . qnXbrliPure : nonMonetaryNonPureFacts . append ( f ) if isEnum : _eQn = getattr ( f , \"\" , None ) or qnameEltPfxName ( f , f . value ) if _eQn : prefixUsed ( val , _eQn . namespaceURI , _eQn . prefix ) if val . isEIOPA_2_0_1 and f . qname . localName == \"\" : val . reportingCurrency = _eQn . localName elif isString : if f . xmlLang : stringFactsWithXmlLang . append ( f ) if f . isNil : nilFacts . append ( f ) if val . footnotesRelationshipSet . fromModelObject ( f ) : modelXbrl . warning ( \"\" , _ ( \"\" ) , modelObject = f , fact = f . qname , contextID = f . contextID ) if nilFacts : modelXbrl . error ( ( \"\" , \"\" ) , _ ( '' ) , modelObject = nilFacts , nilFacts = \"\" . join ( str ( f . qname ) for f in nilFacts ) ) if stringFactsWithXmlLang : modelXbrl . warning ( \"\" , _ ( \"\" ) , modelObject = stringFactsWithXmlLang , factsWithLang = \"\" . join ( set ( str ( f . qname ) for f in stringFactsWithXmlLang ) ) ) if nonMonetaryNonPureFacts : modelXbrl . error ( ( \"\" , \"\" ) , _ ( \"\" ) , modelObject = nonMonetaryNonPureFacts , langLessFacts = \"\" . join ( set ( str ( f . qname ) for f in nonMonetaryNonPureFacts ) ) ) val . utrValidator . validateFacts ( ) unitHashes = { } for unit in modelXbrl . units . values ( ) : h = unit . hash if h in unitHashes and unit . isEqualTo ( unitHashes [ h ] ) : modelXbrl . warning ( \"\" , _ ( \"\" ) , modelObject = ( unit , unitHashes [ h ] ) , unit1 = unit . id , unit2 = unitHashes [ h ] . id ) if not getattr ( modelXbrl , \"\" , False ) : modelXbrl . error ( \"\" , _ ( \"\" ) , modelObject = ( unit , unitHashes [ h ] ) , unit1 = unit . id , unit2 = unitHashes [ h ] . id ) else : unitHashes [ h ] = unit for _measures in unit . measures : for _measure in _measures : prefixUsed ( val , _measure . namespaceURI , _measure . prefix ) del unitHashes cntxHashes = { } for cntx in modelXbrl . contexts . values ( ) : h = cntx . contextDimAwareHash if h in cntxHashes and cntx . isEqualTo ( cntxHashes [ h ] ) : if not getattr ( modelXbrl , \"\" , False ) : modelXbrl . log ( \"\" if val . isEIOPAfullVersion else \"\" , \"\" , _ ( \"\" ) , modelObject = ( cntx , cntxHashes [ h ] ) , cntx1 = cntx . id , cntx2 = cntxHashes [ h ] . id ) else : cntxHashes [ h ] = cntx for _dim in cntx . qnameDims . values ( ) : _dimQn = _dim . dimensionQname prefixUsed ( val , _dimQn . namespaceURI , _dimQn . prefix ) if _dim . isExplicit : _memQn = _dim . memberQname else : _memQn = _dim . typedMember . qname if _memQn : prefixUsed ( val , _memQn . namespaceURI , _memQn . prefix ) for elt in modelDocument . xmlRootElement . iter ( ) : ", "answer": "if isinstance ( elt , ModelObject ) :"}, {"prompt": " from helpers import unittest import os import luigi import luigi . contrib . hdfs from luigi import six from luigi . mock import MockTarget from helpers import with_config from luigi . contrib . external_program import ExternalProgramRunError from luigi . contrib . spark import SparkSubmitTask , PySparkTask from mock import patch , call , MagicMock BytesIO = six . BytesIO def poll_generator ( ) : yield None yield def setup_run_process ( proc ) : poll_gen = poll_generator ( ) proc . return_value . poll = lambda : next ( poll_gen ) proc . return_value . returncode = proc . return_value . stdout = BytesIO ( ) proc . return_value . stderr = BytesIO ( ) class TestSparkSubmitTask ( SparkSubmitTask ) : deploy_mode = \"\" ", "answer": "name = \"\""}, {"prompt": " NAME = '' def is_waf ( self ) : \"\"\"\"\"\" if self . matchcookie ( '' ) : return True if self . matchheader ( ( '' , '' ) , attack = True ) : return True if self . matchheader ( ( '' , '' ) , attack = True ) : return True if self . matchheader ( ( '' , '' ) , attack = True ) : return True ", "answer": "if self . matchheader ( ( '' , '' ) , attack = True ) :"}, {"prompt": " from __future__ import absolute_import , division , print_function , unicode_literals \"\"\"\"\"\" import math import demo import pi3d DISPLAY = pi3d . Display . create ( x = , y = , background = ( , , , ) ) shader = pi3d . Shader ( \"\" ) flatsh = pi3d . Shader ( \"\" ) blockimg = pi3d . Texture ( \"\" ) roofedgeimg = pi3d . Texture ( \"\" ) roofimg = pi3d . Texture ( \"\" ) greenimg = pi3d . Texture ( \"\" ) ectex = pi3d . loadECfiles ( \"\" , \"\" , \"\" ) myecube = pi3d . EnvironmentCube ( size = , maptype = \"\" ) myecube . set_draw_details ( flatsh , ectex ) mapwidth = mapdepth = mapheight = floorimg = pi3d . Texture ( \"\" ) bumpimg = pi3d . Texture ( \"\" ) mymap = pi3d . ElevationMap ( mapfile = \"\" , width = mapwidth , depth = mapdepth , height = mapheight , divx = , divy = ) mymap . set_draw_details ( shader , [ floorimg , bumpimg ] , , ) mymap . set_fog ( ( , , , ) , ) pi3d . corridor ( , , mymap , details = [ shader , [ blockimg , blockimg ] , , , , ] , walls = \"\" ) pi3d . corridor ( , - , mymap , details = [ shader , [ blockimg , blockimg ] , , , , ] , walls = \"\" ) openSectionSchemeMultimodel = { \"\" : , ( , None ) : [ [ \"\" , ] ] , ( , None ) : [ [ \"\" , ] , [ \"\" , ] ] , ( , , \"\" ) : [ [ \"\" , ] , [ \"\" , ] ] , ( , , \"\" ) : [ [ \"\" , ] , [ \"\" , ] ] , ( , , \"\" ) : [ [ \"\" , ] , [ \"\" , ] ] , ( , , \"\" ) : [ [ \"\" , ] ] , ( , ) : [ [ \"\" , ] ] , ( , ) : [ [ \"\" , ] , [ \"\" , ] ] , ( , ) : [ [ \"\" , ] ] } details = [ [ shader , [ blockimg , blockimg ] , , , , ] , [ shader , [ greenimg , greenimg ] , , , , ] , [ shader , [ roofimg , blockimg ] , , , , ] , [ shader , [ roofedgeimg ] , , , , ] , ] building = pi3d . Building ( \"\" , , , mymap , width = , depth = , height = , name = \"\" , draw_details = details , yoff = - , scheme = openSectionSchemeMultimodel ) outLight = pi3d . Light ( lightpos = ( , - , ) , lightcol = ( , , ) , lightamb = ( , , ) ) inLight = pi3d . Light ( lightpos = ( , - , ) , lightcol = ( , , ) , lightamb = ( , , ) ) for b in building . model : b . set_light ( inLight , ) mymap . set_light ( inLight , ) inFlag = True scshots = rot = tilt = avhgt = aveyelevel = aveyeleveladjust = aveyelevel - avhgt / man = pi3d . SolidObject ( \"\" , pi3d . Size ( , avhgt , ) , pi3d . Position ( , ( mymap . calcHeight ( , ) + avhgt / ) , ) , ) inputs = pi3d . InputEvents ( ) inputs . get_mouse_movement ( ) mouseOn = True frame = record = False CAMERA = pi3d . Camera . instance ( ) while DISPLAY . loop_running ( ) and not inputs . key_state ( \"\" ) : CAMERA . reset ( ) CAMERA . rotate ( tilt , rot , ) CAMERA . position ( ( man . x ( ) , man . y ( ) , man . z ( ) - aveyeleveladjust ) ) myecube . position ( man . x ( ) , man . y ( ) , man . z ( ) - aveyeleveladjust ) pi3d . SolidObject . drawall ( ) building . drawAll ( ) mymap . draw ( ) myecube . draw ( ) inputs . do_input_events ( ) \"\"\"\"\"\" mx , my , mv , mh , md = inputs . get_mouse_movement ( ) rot -= ( mx ) * tilt -= ( my ) * jrx , jry = inputs . get_joystickR ( ) if abs ( jrx ) > : rot -= jrx * if abs ( jry ) > : tilt -= jry * xm = man . x ( ) ym = man . y ( ) zm = man . z ( ) jx , jy = inputs . get_joystick ( ) if abs ( jy ) > : xm += math . sin ( math . radians ( rot ) ) * jy zm -= math . cos ( math . radians ( rot ) ) * jy if abs ( jx ) > : xm -= math . sin ( math . radians ( rot - ) ) * jx zm += math . cos ( math . radians ( rot - ) ) * jx if inputs . key_state ( \"\" ) : xm -= math . sin ( math . radians ( rot ) ) ", "answer": "zm += math . cos ( math . radians ( rot ) )"}, {"prompt": " import threading import os import sys import json import logging import logging . handlers try : import argparse except ImportError : sys . exit ( \"\" ) from time import sleep from pypxe import tftp from pypxe import dhcp from pypxe import http from pypxe import nbd args = None SETTINGS = { '' : '' , '' : '' , '' : '' , '' : , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : None , '' : , '' : False , '' : False , '' : True , '' : True , '' : False , '' : '' , '' : False , '' : True , '' : False , '' : False , '' : '' , '' : , '' : '' , '' : '' } def parse_cli_arguments ( ) : parser = argparse . ArgumentParser ( description = '' , formatter_class = argparse . ArgumentDefaultsHelpFormatter ) ipxeexclusive = parser . add_mutually_exclusive_group ( required = False ) ipxeexclusive . add_argument ( '' , action = '' , dest = '' , help = '' , default = SETTINGS [ '' ] ) ipxeexclusive . add_argument ( '' , action = '' , dest = '' , help = '' , default = not SETTINGS [ '' ] ) httpexclusive = parser . add_mutually_exclusive_group ( required = False ) httpexclusive . add_argument ( '' , action = '' , dest = '' , help = '' , default = SETTINGS [ '' ] ) httpexclusive . add_argument ( '' , action = '' , dest = '' , help = '' , default = not SETTINGS [ '' ] ) tftpexclusive = parser . add_mutually_exclusive_group ( required = False ) tftpexclusive . add_argument ( '' , action = '' , dest = '' , help = '' , default = SETTINGS [ '' ] ) tftpexclusive . add_argument ( '' , action = '' , dest = '' , help = '' , default = not SETTINGS [ '' ] ) parser . add_argument ( '' , action = '' , dest = '' , help = '' , default = SETTINGS [ '' ] ) parser . add_argument ( '' , action = '' , dest = '' , help = '' , default = SETTINGS [ '' ] ) parser . add_argument ( '' , action = '' , dest = '' , help = '' , default = '' ) parser . add_argument ( '' , action = '' , dest = '' , help = '' , default = '' ) parser . add_argument ( '' , action = '' , dest = '' , help = '' , default = '' ) parser . add_argument ( '' , action = '' , dest = '' , help = '' , default = SETTINGS [ '' ] ) parser . add_argument ( '' , action = '' , dest = '' , help = '' , default = SETTINGS [ '' ] ) dhcp_group = parser . add_argument_group ( title = '' , description = '' ) exclusive = dhcp_group . add_mutually_exclusive_group ( required = False ) exclusive . add_argument ( '' , action = '' , dest = '' , help = '' , default = not SETTINGS [ '' ] ) exclusive . add_argument ( '' , action = '' , dest = '' , help = '' , default = SETTINGS [ '' ] ) exclusive . add_argument ( '' , action = '' , dest = '' , help = '' , default = SETTINGS [ '' ] ) dhcp_group . add_argument ( '' , action = '' , dest = '' , help = '' , default = SETTINGS [ '' ] ) dhcp_group . add_argument ( '' , action = '' , dest = '' , help = '' , default = SETTINGS [ '' ] ) dhcp_group . add_argument ( '' , action = '' , dest = '' , help = '' , default = SETTINGS [ '' ] ) dhcp_group . add_argument ( '' , action = '' , dest = '' , help = '' , default = SETTINGS [ '' ] ) dhcp_group . add_argument ( '' , action = '' , dest = '' , help = '' , default = SETTINGS [ '' ] ) dhcp_group . add_argument ( '' , action = '' , dest = '' , help = '' , default = SETTINGS [ '' ] ) dhcp_group . add_argument ( '' , action = '' , dest = '' , help = '' , default = SETTINGS [ '' ] ) dhcp_group . add_argument ( '' , action = '' , dest = '' , help = '' , default = SETTINGS [ '' ] ) dhcp_group . add_argument ( '' , action = '' , dest = '' , help = '' , default = SETTINGS [ '' ] ) dhcp_group . add_argument ( '' , action = '' , dest = '' , help = '' , default = False ) parser . add_argument ( '' , action = '' , dest = '' , help = '' , default = SETTINGS [ '' ] ) parser . add_argument ( '' , action = '' , dest = '' , help = '' , default = SETTINGS [ '' ] ) nbd_group = parser . add_argument_group ( title = '' , description = '' ) nbd_group . add_argument ( '' , action = '' , dest = '' , help = '' , default = SETTINGS [ '' ] ) nbd_group . add_argument ( '' , action = '' , dest = '' , help = '' , default = SETTINGS [ '' ] ) nbd_group . add_argument ( '' , action = '' , dest = '' , help = '' , default = SETTINGS [ '' ] ) ", "answer": "nbd_group . add_argument ( '' , action = '' , dest = '' , help = '' , default = SETTINGS [ '' ] )"}, {"prompt": " import mock from oslo_utils import uuidutils from neutron . agent . l3 import dvr_snat_ns from neutron . agent . l3 import namespace_manager from neutron . agent . l3 import namespaces from neutron . agent . linux import ip_lib from neutron . tests . functional import base _uuid = uuidutils . generate_uuid class NamespaceManagerTestFramework ( base . BaseSudoTestCase ) : def setUp ( self ) : super ( NamespaceManagerTestFramework , self ) . setUp ( ) self . agent_conf = mock . MagicMock ( ) self . metadata_driver_mock = mock . Mock ( ) self . namespace_manager = namespace_manager . NamespaceManager ( self . agent_conf , driver = None , metadata_driver = self . metadata_driver_mock ) def _create_namespace ( self , router_id , ns_class ) : namespace = ns_class ( router_id , self . agent_conf , driver = None , use_ipv6 = False ) namespace . create ( ) self . addCleanup ( self . _delete_namespace , namespace ) return namespace . name def _delete_namespace ( self , namespace ) : try : namespace . delete ( ) except RuntimeError as e : if '' not in str ( e ) : raise e def _namespace_exists ( self , namespace ) : ip = ip_lib . IPWrapper ( namespace = namespace ) return ip . netns . exists ( namespace ) class NamespaceManagerTestCase ( NamespaceManagerTestFramework ) : def test_namespace_manager ( self ) : router_id = _uuid ( ) router_id_to_delete = _uuid ( ) to_keep = set ( ) to_delete = set ( ) to_retrieve = set ( ) to_keep . add ( self . _create_namespace ( router_id , ", "answer": "namespaces . RouterNamespace ) )"}, {"prompt": " from web2py_env import local_import , db , gis_map_tables test_utils = local_import ( \"\" ) s3gis = local_import ( \"\" ) gis_map_tables ( ) InsertedRecord = test_utils . InsertedRecord AddedRole = test_utils . AddedRole ExpectedException = test_utils . ExpectedException Change = test_utils . Change ExpectSessionWarning = test_utils . ExpectSessionWarning def check_scripts ( actual_output , scripts , request ) : substitutions = dict ( application_name = request . application ) for script in scripts : script_string = \"\" % ( script % substitutions ) assert script_string in actual_output def layer_test ( db , layer_table , layer_data , data_structure_lhs , data_structure_rhs , session , request , check_output = None , scripts = [ ] , ) : with InsertedRecord ( db , layer_table , layer_data ) : with AddedRole ( session , session . s3 . system_roles . MAP_ADMIN ) : actual_output = str ( s3gis . GIS ( ) . show_map ( window = True , catalogue_toolbar = True , toolbar = True , search = True , catalogue_layers = True , projection = , ) ) def found ( data_structure ) : ", "answer": "test_utils . assert_equal ("}, {"prompt": " from ctypes import * import sys , py from support import BaseCTypesTestChecker def setup_module ( mod ) : import conftest mod . lib = CDLL ( str ( conftest . sofile ) ) class TestCast ( BaseCTypesTestChecker ) : def test_array2pointer ( self ) : array = ( c_int * ) ( , , ) ptr = cast ( array , POINTER ( c_int ) ) assert [ ptr [ i ] for i in range ( ) ] == [ , , ] if * sizeof ( c_short ) == sizeof ( c_int ) : ptr = cast ( array , POINTER ( c_short ) ) if sys . byteorder == \"\" : assert [ ptr [ i ] for i in range ( ) ] == ( [ , , , , , ] ) else : assert [ ptr [ i ] for i in range ( ) ] == ( [ , , , , , ] ) def test_address2pointer ( self ) : array = ( c_int * ) ( , , ) address = addressof ( array ) ptr = cast ( c_void_p ( address ) , POINTER ( c_int ) ) assert [ ptr [ i ] for i in range ( ) ] == [ , , ] ptr = cast ( address , POINTER ( c_int ) ) assert [ ptr [ i ] for i in range ( ) ] == [ , , ] def test_p2a_objects ( self ) : py . test . skip ( \"\" ) array = ( c_char_p * ) ( ) assert array . _objects is None array [ ] = \"\" assert array . _objects == { '' : \"\" } p = cast ( array , POINTER ( c_char_p ) ) assert p . _objects is array . _objects assert array . _objects == { '' : \"\" , id ( array ) : array } p [ ] = \"\" assert p . _objects == { '' : \"\" , id ( array ) : array } assert array . _objects is p . _objects p [ ] = \"\" assert p . _objects == { '' : '' , '' : \"\" , id ( array ) : array } assert array . _objects is p . _objects def test_other ( self ) : p = cast ( ( c_int * ) ( , , , ) , POINTER ( c_int ) ) assert p [ : ] == [ , , , ] c_int ( ) assert p [ : ] == [ , , , ] p [ ] = assert p [ : ] == [ , , , ] ", "answer": "c_int ( )"}, {"prompt": " from skimage . _build import cython import os . path base_path = os . path . abspath ( os . path . dirname ( __file__ ) ) ", "answer": "def configuration ( parent_package = '' , top_path = None ) :"}, {"prompt": " \"\"\"\"\"\" import __builtin__ import imp import os import re import sys import types import urllib import unittest import google try : import lxml except ImportError : raise unittest . SkipTest ( '' ) try : import PIL except ImportError : raise unittest . SkipTest ( '' ) import mox from google . appengine . tools . devappserver2 import runtime_config_pb2 from google . appengine . tools . devappserver2 . python import sandbox from google . appengine . tools . devappserver2 . python import stubs class SandboxTest ( unittest . TestCase ) : def setUp ( self ) : super ( SandboxTest , self ) . setUp ( ) self . mox = mox . Mox ( ) self . old_path = sys . path self . old_meta_path = sys . meta_path self . old_library_format_string = sandbox . _THIRD_PARTY_LIBRARY_FORMAT_STRING self . config = runtime_config_pb2 . Config ( ) self . app_root = '' self . config . application_root = self . app_root self . config . app_id = '' self . config . version_id = '' self . builtins = __builtin__ . __dict__ . copy ( ) self . modules = sys . modules . copy ( ) def tearDown ( self ) : sys . modules . clear ( ) sys . modules . update ( self . modules ) __builtin__ . __dict__ . update ( self . builtins ) sys . meta_path = self . old_meta_path sys . path = self . old_path sandbox . _THIRD_PARTY_LIBRARY_FORMAT_STRING = self . old_library_format_string self . mox . UnsetStubs ( ) super ( SandboxTest , self ) . tearDown ( ) def test_enable_libraries ( self ) : sandbox . _THIRD_PARTY_LIBRARY_FORMAT_STRING = ( '' ) libs = self . config . libraries libs . add ( name = '' , version = '' ) libs . add ( name = '' , version = '' ) self . assertEqual ( [ os . path . join ( os . path . dirname ( os . path . dirname ( google . __file__ ) ) , '' ) , os . path . join ( os . path . dirname ( os . path . dirname ( google . __file__ ) ) , '' ) ] , sandbox . _enable_libraries ( libs ) ) def test_enable_libraries_no_libraries ( self ) : libs = self . config . libraries self . assertEqual ( [ ] , sandbox . _enable_libraries ( libs ) ) self . assertEqual ( self . old_path , sys . path ) class ModuleOverrideImportHookTest ( unittest . TestCase ) : def setUp ( self ) : super ( ModuleOverrideImportHookTest , self ) . setUp ( ) self . test_policies = { } self . path = sys . path [ : ] self . hook = sandbox . ModuleOverrideImportHook ( self . test_policies ) sys . path_importer_cache = { } sys . modules . pop ( '' , None ) __import__ ( '' ) . __path__ . insert ( , '' ) sys . modules . pop ( '' , None ) sys . modules . pop ( '' , None ) self . imported_modules = set ( sys . modules ) self . path_hooks = sys . path_hooks def tearDown ( self ) : sys . path_hooks = self . path_hooks sys . path_importer_cache = { } sys . path = self . path added_modules = set ( sys . modules ) - self . imported_modules for name in added_modules : del sys . modules [ name ] distutils_modules = [ module for module in sys . modules if module . startswith ( '' ) ] for name in distutils_modules : del sys . modules [ name ] sys . modules . pop ( '' , None ) super ( ModuleOverrideImportHookTest , self ) . tearDown ( ) def test_load_builtin_pass_through ( self ) : symbols = dir ( __import__ ( '' ) ) del sys . modules [ '' ] self . test_policies [ '' ] = sandbox . ModuleOverridePolicy ( None , [ ] , { } , default_pass_through = True ) thread = self . hook . load_module ( '' ) self . assertTrue ( isinstance ( thread , types . ModuleType ) ) self . assertTrue ( isinstance ( thread . __doc__ , str ) ) self . assertItemsEqual ( symbols + [ '' ] , dir ( thread ) ) self . assertEqual ( self . hook , thread . __loader__ ) def test_load_builtin_no_pass_through ( self ) : self . test_policies [ '' ] = sandbox . ModuleOverridePolicy ( None , [ ] , { } , default_pass_through = False ) thread = self . hook . load_module ( '' ) self . assertTrue ( isinstance ( thread , types . ModuleType ) ) self . assertItemsEqual ( [ '' , '' , '' , '' ] , dir ( thread ) ) self . assertEqual ( self . hook , thread . __loader__ ) def test_load_with_path_hook ( self ) : class DummyPathHook ( object ) : def __init__ ( self , path ) : if path != '' : raise ImportError ", "answer": "def find_module ( self , unused_fullname ) :"}, {"prompt": " import unittest import os \"\"\"\"\"\" import sys import inspect gCantRun = False try : import nose except ImportError : gCantRun = True print ( '' ) if not gCantRun : thisDir = os . path . dirname ( inspect . getsourcefile ( lambda : None ) ) try : import pymel_test except ImportError : sys . path . append ( thisDir ) try : import pymel_test except ImportError : gCantRun = True ", "answer": "import traceback"}, {"prompt": " from __future__ import unicode_literals from django . utils import six from django . utils . six . moves import range from reviewboard . scmtools . core import Branch , Commit , ChangeSet from reviewboard . scmtools . git import GitTool class TestTool ( GitTool ) : name = '' supports_post_commit = True def get_repository_info ( self ) : return { '' : '' , '' : '' , } def get_fields ( self ) : return [ '' , '' ] def get_diffs_use_absolute_paths ( self ) : return False def get_branches ( self ) : return [ Branch ( id = '' , commit = '' , default = True ) , Branch ( id = '' , commit = '' , default = False ) , ] def get_commits ( self , branch = None , start = None ) : return [ Commit ( '' % i , six . text_type ( i ) , '' % i , '' % i , six . text_type ( i - ) ) for i in range ( int ( start or ) , , - ) ] def get_change ( self , commit_id ) : return Commit ( author_name = '' , id = commit_id , date = '' , message = '' , diff = b'' . join ( [ b\"\" , ", "answer": "b\"\""}, {"prompt": " \"\"\"\"\"\" from __future__ import division , print_function from sympy . core . compatibility import is_sequence from sympy . core . containers import Tuple from sympy . core . basic import Basic from sympy . core . sympify import sympify from sympy . functions import cos , sin from sympy . matrices import eye from sympy . sets import Set ordering_of_classes = [ \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ] class GeometryEntity ( Basic ) : \"\"\"\"\"\" def __new__ ( cls , * args , ** kwargs ) : def is_seq_and_not_point ( a ) : if hasattr ( a , '' ) and a . is_Point : return False return is_sequence ( a ) args = [ Tuple ( * a ) if is_seq_and_not_point ( a ) else sympify ( a ) for a in args ] return Basic . __new__ ( cls , * args ) def _sympy_ ( self ) : return self def __getnewargs__ ( self ) : return tuple ( self . args ) def intersection ( self , o ) : \"\"\"\"\"\" raise NotImplementedError ( ) def rotate ( self , angle , pt = None ) : \"\"\"\"\"\" newargs = [ ] for a in self . args : if isinstance ( a , GeometryEntity ) : newargs . append ( a . rotate ( angle , pt ) ) else : newargs . append ( a ) return type ( self ) ( * newargs ) def scale ( self , x = , y = , pt = None ) : \"\"\"\"\"\" from sympy . geometry . point import Point if pt : pt = Point ( pt ) return self . translate ( * ( - pt ) . args ) . scale ( x , y ) . translate ( * pt . args ) return type ( self ) ( * [ a . scale ( x , y ) for a in self . args ] ) def translate ( self , x = , y = ) : \"\"\"\"\"\" ", "answer": "newargs = [ ]"}, {"prompt": " from unittest import TestCase from pyschema import Record , dumps , loads , ispyschema , no_auto_store from pyschema . types import * import pyschema . core class RevertDefinitionsTest ( TestCase ) : def setUp ( self ) : self . _original_schemas = pyschema . core . auto_store pyschema . core . auto_store = self . _original_schemas . clone ( ) def tearDown ( self ) : pyschema . core . auto_store = self . _original_schemas class TestNestedRecord ( RevertDefinitionsTest ) : def test_full_circle ( self ) : class Foo ( Record ) : bin = Bytes ( ) class MyRecord ( Record ) : a_string = Text ( ) a_float = Float ( ) record = List ( SubRecord ( Foo ) ) rec = MyRecord ( a_string = u\"\" ) rec . record = [ Foo ( bin = \"\" ) ] s = dumps ( rec ) reloaded_obj = loads ( s ) self . assertEquals ( reloaded_obj . a_string , u\"\" ) self . assertTrue ( reloaded_obj . a_float is None ) self . assertTrue ( reloaded_obj . record [ ] . bin , \"\" ) class TestBaseRecordNotInStore ( TestCase ) : def test ( self ) : self . assertTrue ( Record not in pyschema . core . auto_store ) class TestBasicUsage ( TestCase ) : def setUp ( self ) : @ no_auto_store ( ) class Foo ( Record ) : t = Text ( ) i = Integer ( ) b = Boolean ( ) def calculated ( self ) : return self . t * self . Foo = Foo def test_class_field ( self ) : record = self . Foo ( t = u\"\" ) self . assertEquals ( record . t , u\"\" ) def test_post_declaration_field ( self ) : ", "answer": "record = self . Foo ( i = )"}, {"prompt": " \"\"\"\"\"\" from django import template from django . template . loader_tags import BlockNode , do_block ", "answer": "from django . conf import settings"}, {"prompt": " from SimPEG import * from SimPEG . FLOW import Richards def run ( plotIt = True ) : \"\"\"\"\"\" M = Mesh . TensorMesh ( [ np . ones ( ) ] ) M . setCellGradBC ( '' ) params = Richards . Empirical . HaverkampParams ( ) . celia1990 params [ '' ] = np . log ( params [ '' ] ) E = Richards . Empirical . Haverkamp ( M , ** params ) bc = np . array ( [ - , - ] ) h = np . zeros ( M . nC ) + bc [ ] def getFields ( timeStep , method ) : timeSteps = np . ones ( / timeStep ) * timeStep prob = Richards . RichardsProblem ( M , mapping = E , timeSteps = timeSteps , boundaryConditions = bc , initialConditions = h , doNewton = False , method = method ) return prob . fields ( params [ '' ] ) Hs_M10 = getFields ( , '' ) Hs_M30 = getFields ( , '' ) Hs_M120 = getFields ( , '' ) Hs_H10 = getFields ( , '' ) Hs_H30 = getFields ( , '' ) Hs_H120 = getFields ( , '' ) if not plotIt : return import matplotlib . pyplot as plt plt . figure ( figsize = ( , ) ) ", "answer": "plt . subplot ( )"}, {"prompt": " from django . shortcuts import redirect from django . conf import settings from django . http import Http404 , HttpResponse from django . template . base import TemplateDoesNotExist from django . views . generic import TemplateView , FormView from django . contrib . auth . decorators import user_passes_test from django . contrib import messages from . import factory , exceptions admin_required = user_passes_test ( lambda x : x . is_superuser ) class MailListView ( TemplateView ) : \"\"\"\"\"\" template_name = '' def get_context_data ( self , ** kwargs ) : \"\"\"\"\"\" data = super ( MailListView , self ) . get_context_data ( ** kwargs ) mail_list = [ ] for mail_name , mail_class in sorted ( factory . _registry . items ( ) , key = lambda x : x [ ] ) : mail_list . append ( ( mail_name , mail_class . __name__ ) ) data [ '' ] = mail_list return data class MailPreviewMixin ( object ) : def get_html_alternative ( self , message ) : \"\"\"\"\"\" alternatives = dict ( ( v , k ) for k , v in message . alternatives ) if '' in alternatives : return alternatives [ '' ] def get_mail_preview ( self , template_name , lang , cid_to_data = False ) : \"\"\"\"\"\" form_class = factory . get_mail_form ( self . mail_name ) form = form_class ( mail_class = self . mail_class ) form = form_class ( form . get_context_data ( ) , mail_class = self . mail_class ) data = form . get_context_data ( ) if form . is_valid ( ) : data . update ( form . cleaned_data ) data . update ( form . get_preview_data ( ) ) mail = self . mail_class ( data ) message = mail . create_email_msg ( [ settings . ADMINS ] , lang = lang ) try : message . html = factory . get_html_for ( self . mail_name , data , lang = lang , cid_to_data = True ) except TemplateDoesNotExist : message . html = False return message class MailFormView ( MailPreviewMixin , FormView ) : template_name = '' def dispatch ( self , request , mail_name ) : self . mail_name = mail_name try : self . mail_class = factory . get_mail_class ( self . mail_name ) except exceptions . MailFactoryError : raise Http404 self . raw = '' in request . POST self . send = '' in request . POST self . email = request . POST . get ( '' ) return super ( MailFormView , self ) . dispatch ( request ) def get_form_kwargs ( self ) : kwargs = super ( MailFormView , self ) . get_form_kwargs ( ) kwargs [ '' ] = self . mail_class return kwargs def get_form_class ( self ) : return factory . get_mail_form ( self . mail_name ) def form_valid ( self , form ) : if self . raw : return HttpResponse ( '' % factory . get_raw_content ( self . mail_name , [ settings . DEFAULT_FROM_EMAIL ] , form . cleaned_data ) . message ( ) ) if self . send : factory . mail ( self . mail_name , [ self . email ] , form . cleaned_data ) messages . success ( self . request , '' % ( self . mail_name , self . email ) ) return redirect ( '' ) data = None if form : data = form . get_context_data ( ) if hasattr ( form , '' ) : data . update ( form . cleaned_data ) try : html = factory . get_html_for ( self . mail_name , data , cid_to_data = True ) ", "answer": "except TemplateDoesNotExist :"}, {"prompt": " from __future__ import unicode_literals ", "answer": "from django . utils . translation import ugettext_lazy as _"}, {"prompt": " import gc import unittest import unittest . mock import asyncio import asyncio . test_utils from vase . http import ( HttpRequest , HttpParser , HttpWriter , BadRequestException , _FORM_URLENCODED , ) from vase . util import MultiDict class RequestTests ( unittest . TestCase ) : def _get_request ( self ) : request = HttpRequest ( method = \"\" , uri = \"\" , version = \"\" , extra = { '' : ( '' , '' ) } ) request . add_header ( \"\" , \"\" ) request . add_header ( '' , _FORM_URLENCODED ) return request def test_request ( self ) : req = self . _get_request ( ) self . assertEqual ( req . GET , MultiDict ( foo = [ '' ] , baz = [ '' ] ) ) self . assertEqual ( req . GET , MultiDict ( foo = [ '' ] , baz = [ '' ] ) ) def test_has_form ( self ) : req = self . _get_request ( ) self . assertTrue ( req . _has_form ( ) ) req . replace_header ( '' , '' ) self . assertFalse ( req . _has_form ( ) ) def test_cookies ( self ) : req = self . _get_request ( ) self . assertEqual ( req . COOKIES , { '' : '' , '' : '' } ) self . assertEqual ( req . COOKIES , { '' : '' , '' : '' } ) def test_maybe_init_post ( self ) : req = self . _get_request ( ) loop = asyncio . new_event_loop ( ) stream = asyncio . StreamReader ( loop = loop ) data = b'' req . add_header ( '' , str ( len ( data ) ) ) req . body = stream task = asyncio . Task ( req . _maybe_init_post ( ) , loop = loop ) def feed ( ) : stream . feed_data ( b'' ) stream . feed_eof ( ) loop . call_soon ( feed ) loop . run_until_complete ( task ) self . assertEqual ( req . POST , MultiDict ( foo = [ '' ] , baz = [ '' ] ) ) req = self . _get_request ( ) stream . _eof = False task = asyncio . Task ( req . _maybe_init_post ( ) , loop = loop ) def feed ( ) : stream . feed_data ( b'' ) stream . feed_eof ( ) loop . call_soon ( feed ) loop . run_until_complete ( task ) req . replace_header ( '' , '' ) req . body = stream stream . _eof = False task = asyncio . Task ( req . _maybe_init_post ( ) , loop = loop ) loop . call_soon ( feed ) loop . run_until_complete ( task ) self . assertEqual ( req . POST , MultiDict ( ) ) class HttpParserTests ( unittest . TestCase ) : def setUp ( self ) : self . loop = asyncio . new_event_loop ( ) asyncio . set_event_loop ( None ) def tearDown ( self ) : asyncio . test_utils . run_briefly ( self . loop ) self . loop . close ( ) gc . collect ( ) def test_eof ( self ) : stream = asyncio . StreamReader ( loop = self . loop ) task = asyncio . Task ( HttpParser . parse ( stream ) , loop = self . loop ) self . loop . call_soon ( lambda : stream . feed_eof ( ) ) req = self . loop . run_until_complete ( task ) self . assertIs ( req , None ) req = self . loop . run_until_complete ( task ) transport = unittest . mock . Mock ( ) transport . get_extra_info . return_value = ( '' , ) stream = asyncio . StreamReader ( loop = self . loop ) stream . set_transport ( transport ) task = asyncio . Task ( HttpParser . parse ( stream ) , loop = self . loop ) def feed ( ) : stream . feed_data ( b'' ) stream . feed_eof ( ) self . loop . call_soon ( feed ) req = self . loop . run_until_complete ( task ) self . assertIs ( req , None ) def test_bad_version ( self ) : stream = asyncio . StreamReader ( loop = self . loop ) task = asyncio . Task ( HttpParser . parse ( stream ) , loop = self . loop ) self . loop . call_soon ( lambda : stream . feed_data ( b'' ) ) self . assertRaises ( BadRequestException , self . loop . run_until_complete , task ) def test_headers ( self ) : req = b'' transport = unittest . mock . Mock ( ) transport . get_extra_info . return_value = ( '' , ) stream = asyncio . StreamReader ( loop = self . loop ) stream . set_transport ( transport ) task = asyncio . Task ( HttpParser . parse ( stream ) , loop = self . loop ) self . loop . call_soon ( lambda : stream . feed_data ( req ) ) result = self . loop . run_until_complete ( task ) self . assertEqual ( result . method , '' ) self . assertEqual ( result . path , '' ) self . assertEqual ( result . version , '' ) self . assertEqual ( result . get ( '' ) , '' ) def test_multiline_headers ( self ) : req = b'' transport = unittest . mock . Mock ( ) transport . get_extra_info . return_value = ( '' , ) stream = asyncio . StreamReader ( loop = self . loop ) stream . set_transport ( transport ) task = asyncio . Task ( HttpParser . parse ( stream ) , loop = self . loop ) self . loop . call_soon ( lambda : stream . feed_data ( req ) ) result = self . loop . run_until_complete ( task ) self . assertEqual ( result . get ( '' ) , '' ) self . assertEqual ( result . get ( '' ) , '' ) def test_invalid_headers ( self ) : req = b'' transport = unittest . mock . Mock ( ) transport . get_extra_info . return_value = ( '' , ) stream = asyncio . StreamReader ( loop = self . loop ) stream . set_transport ( transport ) task = asyncio . Task ( HttpParser . parse ( stream ) , loop = self . loop ) self . loop . call_soon ( lambda : stream . feed_data ( req ) ) self . assertRaises ( BadRequestException , self . loop . run_until_complete , task ) def test_no_body ( self ) : req = b'' transport = unittest . mock . Mock ( ) transport . get_extra_info . return_value = ( '' , ) stream = asyncio . StreamReader ( loop = self . loop ) stream . set_transport ( transport ) task = asyncio . Task ( HttpParser . parse ( stream ) , loop = self . loop ) self . loop . call_soon ( lambda : stream . feed_data ( req ) ) result = self . loop . run_until_complete ( task ) body = self . loop . run_until_complete ( asyncio . Task ( result . body . read ( ) , loop = self . loop ) ) self . assertEqual ( body , b'' ) def test_with_body ( self ) : req = b'' transport = unittest . mock . Mock ( ) transport . get_extra_info . return_value = ( '' , ) stream = asyncio . StreamReader ( loop = self . loop ) stream . set_transport ( transport ) task = asyncio . Task ( HttpParser . parse ( stream ) , loop = self . loop ) self . loop . call_soon ( lambda : stream . feed_data ( req ) ) result = self . loop . run_until_complete ( task ) body = self . loop . run_until_complete ( asyncio . Task ( result . body . read ( ) , loop = self . loop ) ) self . assertEqual ( body , b'' ) def test_with_invalid_content_length ( self ) : req = b'' transport = unittest . mock . Mock ( ) transport . get_extra_info . return_value = ( '' , ) stream = asyncio . StreamReader ( loop = self . loop ) stream . set_transport ( transport ) task = asyncio . Task ( HttpParser . parse ( stream ) , loop = self . loop ) self . loop . call_soon ( lambda : stream . feed_data ( req ) ) result = self . loop . run_until_complete ( task ) body = self . loop . run_until_complete ( asyncio . Task ( result . body . read ( ) , loop = self . loop ) ) self . assertEqual ( body , b'' ) class HttpWriterTests ( unittest . TestCase ) : @ unittest . mock . patch . object ( HttpWriter , '' ) def test_write_status ( self , write_method ) : writer = HttpWriter ( None , None , None , None ) writer . status = self . assertFalse ( writer . _headers_sent ) writer . flush ( ) self . assertTrue ( writer . _headers_sent ) write_method . assert_called_with ( b'' ) def test_write_header_raises_when_headers_sent ( self ) : writer = HttpWriter ( None , None , None , None ) writer . _headers_sent = True self . assertRaises ( AssertionError , writer . __setitem__ , '' , '' ) @ unittest . mock . patch . object ( HttpWriter , '' ) def test_write_header ( self , write_method ) : writer = HttpWriter ( None , None , None , None ) writer . status = writer [ '' ] = '' ", "answer": "writer . flush ( )"}, {"prompt": " \"\"\"\"\"\" from django . shortcuts import redirect from . utils . auth import login_maybe_required @ login_maybe_required ", "answer": "def home ( request ) :"}, {"prompt": " from __future__ import unicode_literals import time from django . core . exceptions import ImproperlyConfigured ", "answer": "from django . http import HttpResponseForbidden , HttpResponse"}, {"prompt": " from . _base import client_v2_patterns from synapse . http . servlet import RestServlet , parse_json_object_from_request from synapse . api . errors import AuthError from twisted . internet import defer import logging logger = logging . getLogger ( __name__ ) class AccountDataServlet ( RestServlet ) : \"\"\"\"\"\" PATTERNS = client_v2_patterns ( \"\" ) def __init__ ( self , hs ) : super ( AccountDataServlet , self ) . __init__ ( ) self . auth = hs . get_auth ( ) self . store = hs . get_datastore ( ) self . notifier = hs . get_notifier ( ) @ defer . inlineCallbacks def on_PUT ( self , request , user_id , account_data_type ) : requester = yield self . auth . get_user_by_req ( request ) if user_id != requester . user . to_string ( ) : raise AuthError ( , \"\" ) body = parse_json_object_from_request ( request ) max_id = yield self . store . add_account_data_for_user ( user_id , account_data_type , body ) self . notifier . on_new_event ( \"\" , max_id , users = [ user_id ] ) defer . returnValue ( ( , { } ) ) class RoomAccountDataServlet ( RestServlet ) : \"\"\"\"\"\" PATTERNS = client_v2_patterns ( \"\" \"\" \"\" ", "answer": ")"}, {"prompt": " '''''' import unittest from pyRMSD . condensedMatrix import CondensedMatrix import numpy from pyproct . postprocess . actions . confSpaceComparison . overlapCalculator import OverlapCalculator class Test ( unittest . TestCase ) : def test_calculate_global_overlap ( self ) : distance_matrix = CondensedMatrix ( [ , , , , , ] ) decomposed_clusters = [ { \"\" : [ ] , \"\" : [ ] } , { \"\" : [ ] , \"\" : [ ] } ] self . assertEqual ( , OverlapCalculator . calculate_global_overlap ( decomposed_clusters , distance_matrix , , ) ) decomposed_clusters = [ { \"\" : [ ] , \"\" : [ ] } , { \"\" : [ ] } , { \"\" : [ ] } ] self . assertEqual ( , OverlapCalculator . calculate_global_overlap ( decomposed_clusters , distance_matrix , , ) ) def test_calculate_cluster_overlap ( self ) : ", "answer": "distance_matrix = CondensedMatrix ( [ , ,"}, {"prompt": " import sys import logging from collections import namedtuple from django . http import Http404 from django . conf import settings from django . contrib . gis . geos import Point from django . core . exceptions import ImproperlyConfigured , PermissionDenied ", "answer": "from django . middleware . locale import LocaleMiddleware"}, {"prompt": " import os import socket import datetime import copy import gluon . contenttype import gluon . fileutils try : import pygraphviz as pgv except ImportError : pgv = None global_env = copy . copy ( globals ( ) ) global_env [ '' ] = datetime http_host = request . env . http_host . split ( '' ) [ ] remote_addr = request . env . remote_addr try : hosts = ( http_host , socket . gethostname ( ) , socket . gethostbyname ( http_host ) , '' , '' , '' ) except : hosts = ( http_host , ) if request . env . http_x_forwarded_for or request . is_https : session . secure ( ) elif ( remote_addr not in hosts ) and ( remote_addr != \"\" ) and ( request . function != '' ) : raise HTTP ( , T ( '' ) ) if request . function == '' : if not '' in globals ( ) or not request . args : redirect ( URL ( request . controller , '' ) ) manager_action = auth . settings . manager_actions . get ( request . args ( ) , None ) if manager_action is None and request . args ( ) == '' : manager_action = dict ( role = auth . settings . auth_manager_role , heading = T ( '' ) , tables = [ auth . table_user ( ) , auth . table_group ( ) , auth . table_permission ( ) ] ) manager_role = manager_action . get ( '' , None ) if manager_action else None auth . requires_membership ( manager_role ) ( lambda : None ) ( ) menu = False elif ( request . application == '' and not session . authorized ) or ( request . application != '' and not gluon . fileutils . check_credentials ( request ) ) : redirect ( URL ( '' , '' , '' , vars = dict ( send = URL ( args = request . args , vars = request . vars ) ) ) ) else : response . subtitle = T ( '' ) menu = True ignore_rw = True response . view = '' if menu : response . menu = [ [ T ( '' ) , False , URL ( '' , '' , '' , args = [ request . application ] ) ] , [ T ( '' ) , False , URL ( '' ) ] , [ T ( '' ) , False , URL ( '' ) ] , [ T ( '' ) , False , URL ( '' ) ] ] if False and request . tickets_db : from gluon . restricted import TicketStorage ts = TicketStorage ( ) ts . _get_table ( request . tickets_db , ts . tablename , request . application ) def get_databases ( request ) : dbs = { } for ( key , value ) in global_env . items ( ) : cond = False try : cond = isinstance ( value , GQLDB ) except : cond = isinstance ( value , SQLDB ) if cond : dbs [ key ] = value return dbs databases = get_databases ( None ) def eval_in_global_env ( text ) : exec ( '' % text , { } , global_env ) return global_env [ '' ] def get_database ( request ) : if request . args and request . args [ ] in databases : return eval_in_global_env ( request . args [ ] ) else : session . flash = T ( '' ) redirect ( URL ( '' ) ) def get_table ( request ) : db = get_database ( request ) if len ( request . args ) > and request . args [ ] in db . tables : return ( db , request . args [ ] ) else : session . flash = T ( '' ) redirect ( URL ( '' ) ) def get_query ( request ) : try : return eval_in_global_env ( request . vars . query ) except Exception : return None def query_by_table_type ( tablename , db , request = request ) : keyed = hasattr ( db [ tablename ] , '' ) if keyed : firstkey = db [ tablename ] [ db [ tablename ] . _primarykey [ ] ] cond = '' if firstkey . type in [ '' , '' ] : cond = '' qry = '' % ( request . args [ ] , request . args [ ] , firstkey . name , cond ) else : qry = '' % tuple ( request . args [ : ] ) return qry def index ( ) : return dict ( databases = databases ) def insert ( ) : ( db , table ) = get_table ( request ) form = SQLFORM ( db [ table ] , ignore_rw = ignore_rw ) if form . accepts ( request . vars , session ) : response . flash = T ( '' ) return dict ( form = form , table = db [ table ] ) def download ( ) : import os db = get_database ( request ) return response . download ( request , db ) def csv ( ) : import gluon . contenttype response . headers [ '' ] = gluon . contenttype . contenttype ( '' ) db = get_database ( request ) query = get_query ( request ) if not query : return None response . headers [ '' ] = '' % tuple ( request . vars . query . split ( '' ) [ : ] ) return str ( db ( query , ignore_common_filters = True ) . select ( ) ) def import_csv ( table , file ) : table . import_from_csv_file ( file ) def select ( ) : import re db = get_database ( request ) dbname = request . args [ ] try : is_imap = db . _uri . startswith ( \"\" ) except ( KeyError , AttributeError , TypeError ) : is_imap = False regex = re . compile ( '' ) if len ( request . args ) > and hasattr ( db [ request . args [ ] ] , '' ) : regex = re . compile ( '' ) if request . vars . query : match = regex . match ( request . vars . query ) if match : request . vars . query = '' % ( request . args [ ] , match . group ( '' ) , match . group ( '' ) , match . group ( '' ) ) else : request . vars . query = session . last_query query = get_query ( request ) if request . vars . start : start = int ( request . vars . start ) else : start = nrows = step = fields = [ ] if is_imap : step = stop = start + step table = None rows = [ ] orderby = request . vars . orderby if orderby : orderby = dbname + '' + orderby if orderby == session . last_orderby : if orderby [ ] == '' : orderby = orderby [ : ] else : orderby = '' + orderby session . last_orderby = orderby session . last_query = request . vars . query form = FORM ( TABLE ( TR ( T ( '' ) , '' , INPUT ( _style = '' , _name = '' , _value = request . vars . query or '' , requires = IS_NOT_EMPTY ( error_message = T ( \"\" ) ) ) ) , TR ( T ( '' ) , INPUT ( _name = '' , _type = '' , value = False ) , INPUT ( _style = '' , _name = '' , _value = request . vars . update_fields or '' ) ) , TR ( T ( '' ) , INPUT ( _name = '' , _class = '' , _type = '' , value = False ) , '' ) , TR ( '' , '' , INPUT ( _type = '' , _value = T ( '' ) ) ) ) , _action = URL ( r = request , args = request . args ) ) tb = None if form . accepts ( request . vars , formname = None ) : regex = re . compile ( request . args [ ] + '' ) match = regex . match ( form . vars . query . strip ( ) ) if match : table = match . group ( '' ) try : nrows = db ( query , ignore_common_filters = True ) . count ( ) if form . vars . update_check and form . vars . update_fields : db ( query , ignore_common_filters = True ) . update ( ** eval_in_global_env ( '' % form . vars . update_fields ) ) response . flash = T ( '' , nrows ) elif form . vars . delete_check : db ( query , ignore_common_filters = True ) . delete ( ) response . flash = T ( '' , nrows ) nrows = db ( query , ignore_common_filters = True ) . count ( ) if is_imap : fields = [ db [ table ] [ name ] for name in ( \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ) ] if orderby : rows = db ( query , ignore_common_filters = True ) . select ( * fields , limitby = ( start , stop ) , orderby = eval_in_global_env ( orderby ) ) else : rows = db ( query , ignore_common_filters = True ) . select ( * fields , limitby = ( start , stop ) ) except Exception , e : import traceback tb = traceback . format_exc ( ) ( rows , nrows ) = ( [ ] , ) response . flash = DIV ( T ( '' ) , PRE ( str ( e ) ) ) csv_table = table or request . vars . table if csv_table : formcsv = FORM ( str ( T ( '' ) ) + \"\" , INPUT ( _type = '' , _name = '' ) , INPUT ( _type = '' , _value = csv_table , _name = '' ) , INPUT ( _type = '' , _value = T ( '' ) ) ) else : formcsv = None if formcsv and formcsv . process ( ) . accepted : try : import_csv ( db [ request . vars . table ] , request . vars . csvfile . file ) response . flash = T ( '' ) except Exception , e : response . flash = DIV ( T ( '' ) , PRE ( str ( e ) ) ) return dict ( form = form , table = table , start = start , stop = stop , step = step , nrows = nrows , rows = rows , query = request . vars . query , formcsv = formcsv , tb = tb ) def update ( ) : ( db , table ) = get_table ( request ) keyed = hasattr ( db [ table ] , '' ) record = None db [ table ] . _common_filter = None if keyed : key = [ f for f in request . vars if f in db [ table ] . _primarykey ] if key : record = db ( db [ table ] [ key [ ] ] == request . vars [ key [ ] ] ) . select ( ) . first ( ) else : record = db ( db [ table ] . id == request . args ( ) ) . select ( ) . first ( ) if not record : qry = query_by_table_type ( table , db ) session . flash = T ( '' ) redirect ( URL ( '' , args = request . args [ : ] , vars = dict ( query = qry ) ) ) if keyed : for k in db [ table ] . _primarykey : db [ table ] [ k ] . writable = False form = SQLFORM ( db [ table ] , record , deletable = True , delete_label = T ( '' ) , ignore_rw = ignore_rw and not keyed , linkto = URL ( '' , args = request . args [ : ] ) , upload = URL ( r = request , f = '' , args = request . args [ : ] ) ) if form . accepts ( request . vars , session ) : session . flash = T ( '' ) qry = query_by_table_type ( table , db ) redirect ( URL ( '' , args = request . args [ : ] , vars = dict ( query = qry ) ) ) return dict ( form = form , table = db [ table ] ) def state ( ) : return dict ( ) def ccache ( ) : cache . ram . initialize ( ) cache . disk . initialize ( ) form = FORM ( P ( TAG . BUTTON ( T ( \"\" ) , _type = \"\" , _name = \"\" , _value = \"\" ) ) , P ( TAG . BUTTON ( T ( \"\" ) , _type = \"\" , _name = \"\" , _value = \"\" ) ) , P ( TAG . BUTTON ( T ( \"\" ) , _type = \"\" , _name = \"\" , _value = \"\" ) ) , ) if form . accepts ( request . vars , session ) : clear_ram = False clear_disk = False session . flash = \"\" if request . vars . yes : clear_ram = clear_disk = True if request . vars . ram : clear_ram = True if request . vars . disk : clear_disk = True if clear_ram : cache . ram . clear ( ) session . flash += T ( \"\" ) if clear_disk : cache . disk . clear ( ) session . flash += T ( \"\" ) redirect ( URL ( r = request ) ) try : from guppy import hpy hp = hpy ( ) except ImportError : hp = False import shelve import os import copy import time import math from gluon import portalocker ", "answer": "ram = {"}, {"prompt": " import six from barbicanclient import client from barbicanclient import barbican as barb from barbicanclient . tests import keystone_client_fixtures from barbicanclient . tests import test_client ", "answer": "from barbicanclient . barbican import Barbican"}, {"prompt": " \"\"\"\"\"\" from __future__ import print_function , absolute_import import sys import ast import json from base64 import encodestring as encodebytes , decodestring as decodebytes pyversion = sys . version_info NoneType = None . __class__ if pyversion >= ( , ) : basestring = str docheck = '' in sys . modules def parse ( code , comments = False ) : \"\"\"\"\"\" converter = NativeAstConverter ( code ) return converter . convert ( comments ) class Node ( object ) : \"\"\"\"\"\" __slots__ = [ '' , '' ] class OPS : \"\"\"\"\"\" UAdd = '' ", "answer": "USub = ''"}, {"prompt": " \"\"\"\"\"\" from ctypes import * from ctypes import util from libraw import errors from libraw . callbacks import data_callback from libraw . callbacks import memory_callback from libraw . callbacks import progress_callback from libraw . errors import c_error from libraw import structs_16 from libraw import structs_17 class LibRaw ( CDLL ) : \"\"\"\"\"\" def __init__ ( self ) : libraw = util . find_library ( '' ) try : if libraw is not None : super ( LibRaw , self ) . __init__ ( libraw ) else : raise ImportError except ( ImportError , AttributeError , OSError , IOError ) : raise ImportError ( '' ) try : structs = { : structs_16 , : structs_17 , } [ self . version_number [ ] ] except KeyError : raise ImportError ( '' % self . version_number ) libraw_data_t = structs . libraw_data_t libraw_decoder_info_t = structs . libraw_decoder_info_t libraw_processed_image_t = structs . libraw_processed_image_t self . libraw_init . argtypes = [ c_int ] self . libraw_strprogress . argtypes = [ c_int ] self . libraw_unpack_function_name . argtypes = [ POINTER ( libraw_data_t ) ] self . libraw_subtract_black . argtypes = [ POINTER ( libraw_data_t ) ] self . libraw_open_file . argtypes = [ POINTER ( libraw_data_t ) , c_char_p ] self . libraw_open_file_ex . argtypes = [ POINTER ( libraw_data_t ) , c_char_p , c_int64 ] self . libraw_open_buffer . argtypes = [ POINTER ( libraw_data_t ) , c_void_p , c_int64 ] self . libraw_unpack . argtypes = [ POINTER ( libraw_data_t ) ] self . libraw_unpack_thumb . argtypes = [ POINTER ( libraw_data_t ) ] self . libraw_recycle_datastream . argtypes = [ POINTER ( libraw_data_t ) ] self . libraw_recycle . argtypes = [ POINTER ( libraw_data_t ) ] self . libraw_close . argtypes = [ POINTER ( libraw_data_t ) ] self . libraw_set_memerror_handler . argtypes = [ POINTER ( libraw_data_t ) , memory_callback , c_void_p , ] self . libraw_set_dataerror_handler . argtypes = [ POINTER ( libraw_data_t ) , data_callback , c_void_p , ] self . libraw_set_progress_handler . argtypes = [ POINTER ( libraw_data_t ) , progress_callback , c_void_p , ] self . libraw_adjust_sizes_info_only . argtypes = [ POINTER ( libraw_data_t ) ] self . libraw_dcraw_ppm_tiff_writer . argtypes = [ POINTER ( libraw_data_t ) , c_char_p ] self . libraw_dcraw_thumb_writer . argtypes = [ POINTER ( libraw_data_t ) , c_char_p ] self . libraw_dcraw_process . argtypes = [ POINTER ( libraw_data_t ) ] self . libraw_dcraw_make_mem_image . argtypes = [ POINTER ( libraw_data_t ) , POINTER ( c_int ) ] self . libraw_dcraw_make_mem_thumb . argtypes = [ POINTER ( libraw_data_t ) , POINTER ( c_int ) ] self . libraw_dcraw_clear_mem . argtypes = [ POINTER ( libraw_processed_image_t ) ] self . libraw_raw2image . argtypes = [ POINTER ( libraw_data_t ) ] self . libraw_free_image . argtypes = [ POINTER ( libraw_data_t ) ] self . libraw_get_decoder_info . argtypes = [ POINTER ( libraw_data_t ) , POINTER ( libraw_decoder_info_t ) ] self . libraw_COLOR . argtypes = [ POINTER ( libraw_data_t ) , c_int , c_int ] self . libraw_init . restype = POINTER ( libraw_data_t ) self . libraw_version . restype = c_char_p self . libraw_strprogress . restype = c_char_p self . libraw_versionNumber . restype = c_int self . libraw_cameraCount . restype = c_int self . libraw_cameraList . restype = POINTER ( c_char_p * self . libraw_cameraCount ( ) ) self . libraw_unpack_function_name . restype = c_char_p self . libraw_subtract_black . restype = POINTER ( libraw_data_t ) self . libraw_open_file . restype = c_error self . libraw_open_file_ex . restype = c_error self . libraw_open_buffer . restype = c_error self . libraw_unpack . restype = c_error self . libraw_unpack_thumb . restype = c_error self . libraw_adjust_sizes_info_only . restype = c_error self . libraw_dcraw_ppm_tiff_writer . restype = c_error self . libraw_dcraw_thumb_writer . restype = c_error self . libraw_dcraw_process . restype = c_error self . libraw_dcraw_make_mem_image . restype = POINTER ( libraw_processed_image_t ) self . libraw_dcraw_make_mem_thumb . restype = POINTER ( libraw_processed_image_t ) self . libraw_raw2image . restype = c_error self . libraw_get_decoder_info . restype = c_error self . libraw_COLOR . restype = c_int try : self . libraw_open_wfile . argtypes = [ POINTER ( libraw_data_t ) , c_wchar_p ] self . libraw_open_wfile_ex . argtypes = [ POINTER ( libraw_data_t ) , c_wchar_p , c_int64 ] self . libraw_open_wfile . restype = c_error self . libraw_open_wfile_ex . restype = c_error except AttributeError : pass @ property def version_number ( self ) : \"\"\"\"\"\" v = self . libraw_versionNumber ( ) return ( ( v >> ) & , ( v >> ) & , v & ) @ property ", "answer": "def version ( self ) :"}, {"prompt": " from ironic . common import policy from ironic . tests import base class PolicyTestCase ( base . TestCase ) : \"\"\"\"\"\" def test_admin_api ( self ) : creds = ( { '' : [ u'' ] } , { '' : [ '' ] } , { '' : [ '' , '' ] } ) for c in creds : ", "answer": "self . assertTrue ( policy . enforce ( '' , c , c ) )"}, {"prompt": " from signal import setitimer , signal , SIGALRM , ITIMER_REAL from robotide . lib . robot . errors import TimeoutError class Timeout ( object ) : def __init__ ( self , timeout , error ) : self . _timeout = timeout self . _error = error def execute ( self , runnable ) : self . _start_timer ( ) ", "answer": "try :"}, {"prompt": " from __future__ import absolute_import from . facebook import facebook_compliance_fix from . linkedin import linkedin_compliance_fix ", "answer": "from . weibo import weibo_compliance_fix "}, {"prompt": " import sys import unittest sys . path . append ( '' ) from composer . index import Index from composer . writer import FileWriter class DummyFileWriter ( FileWriter ) : def __init__ ( self , * args , ** kw ) : self . reset ( ) super ( DummyFileWriter , self ) . __init__ ( * args , ** kw ) def reset ( self ) : self . _made_dirs = [ ] ", "answer": "self . _written_files = [ ]"}, {"prompt": " from optparse import make_option from django . core . management . base import BaseCommand from planet . tasks import process_feed class Command ( BaseCommand ) : help = \"\" args = \"\" option_list = BaseCommand . option_list + ( make_option ( '' , '' , action = '' , dest = '' , default = None , metavar = '' , help = '' ) , ) ", "answer": "def handle ( self , * args , ** options ) :"}, {"prompt": " \"\"\"\"\"\" import functools import runpy from . util import AbstractStateMachine from . util import defaultproperty from . import Setting def require_ready ( func ) : \"\"\"\"\"\" @ functools . wraps ( func ) def wrapped ( self , * args , ** kwargs ) : try : self . state . wait ( \"\" , self . ready_timeout ) except Exception , e : pass if not self . ready : raise RuntimeWarning ( \"\" ) return func ( self , * args , ** kwargs ) return wrapped def autospawn ( func ) : \"\"\"\"\"\" @ functools . wraps ( func ) def wrapped ( self , * args , ** kwargs ) : self . spawn ( func , self , * args , ** kwargs ) return wrapped class ServiceStateMachine ( AbstractStateMachine ) : \"\"\"\"\"\" initial_state = \"\" ", "answer": "allow_wait = [ \"\" , \"\" ]"}, {"prompt": " from pulsar . apps . http import HttpClient from . utils import wait class GreenHttp : \"\"\"\"\"\" def __init__ ( self , http = None ) : self . _http = http or HttpClient ( ) def __getattr__ ( self , name ) : return getattr ( self . _http , name ) def get ( self , url , ** kwargs ) : kwargs . setdefault ( '' , True ) ", "answer": "return self . request ( '' , url , ** kwargs )"}, {"prompt": " \"\"\"\"\"\" from __future__ import ( absolute_import , division , print_function , unicode_literals ) from . autoshape import Shape from . base import BaseShape from . . enum . shapes import MSO_SHAPE_TYPE , PP_PLACEHOLDER from . graphfrm import GraphicFrame from . . oxml . shapes . graphfrm import CT_GraphicalObjectFrame from . . oxml . shapes . picture import CT_Picture from . picture import Picture from . . util import Emu class _InheritsDimensions ( object ) : \"\"\"\"\"\" @ property def height ( self ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " \"\"\"\"\"\" from __future__ import division , print_function , absolute_import from . isolve import * from . dsolve import * from . interface import * ", "answer": "from . eigen import *"}, {"prompt": " import subprocess import re from . import ARM_CS_TOOLS class LineReader ( object ) : def __init__ ( self , elf_path ) : self . elf = elf_path def _exec_tool ( self ) : return subprocess . check_output ( [ ARM_CS_TOOLS + \"\" , \"\" , self . elf ] ) def get_line_listing ( self ) : decoded = self . _exec_tool ( ) lines = [ { '' : x . group ( ) , '' : int ( x . group ( ) ) , '' : int ( x . group ( ) , ) } for x in re . finditer ( r\"\" , decoded , re . MULTILINE ) ] files = [ x . group ( ) for x in re . finditer ( r\"\" , decoded , re . MULTILINE ) ] return files , lines def get_compact_listing ( self ) : files , lines = self . get_line_listing ( ) file_id_lookup = { files [ x ] : x for x in xrange ( len ( files ) ) } compact_lines = [ ( x [ '' ] , file_id_lookup [ x [ '' ] ] , x [ '' ] ) for x in lines ] compact_lines . sort ( key = lambda x : x [ ] ) return { '' : files , '' : compact_lines } class FunctionRange ( object ) : def __init__ ( self , name , start , end , line = None ) : \"\"\"\"\"\" ", "answer": "self . name = name"}, {"prompt": " \"\"\"\"\"\" import sys , os , inspect from getpass import getuser as _getuser import system import maya . mel as _mm import maya . cmds as _mc import pymel . util as util import pymel . internal . pmcmds as cmds import pymel . internal . factories as _factories import pymel . internal . cmdcache as _cmdcache import pymel . api as _api import datatypes MELTYPES = [ '' , '' , '' , '' , '' , '' , '' , '' ] def isValidMelType ( typStr ) : \"\"\"\"\"\" return typStr in MELTYPES def _flatten ( iterables ) : for it in iterables : if util . isIterable ( it ) : for element in it : yield element else : yield it def pythonToMel ( arg ) : \"\"\"\"\"\" if arg is None : return '' if arg is True or arg is False : return str ( arg ) . lower ( ) if util . isNumeric ( arg ) : return str ( arg ) if isinstance ( arg , datatypes . Vector ) : return '' % ( arg [ ] , arg [ ] , arg [ ] ) if util . isIterable ( arg ) : if util . isMapping ( arg ) : arg = list ( _flatten ( arg . iteritems ( ) ) ) else : arg = list ( _flatten ( arg ) ) forceString = False for each in arg : if not util . isNumeric ( each ) : forceString = True break if forceString : newargs = [ '' % x for x in arg ] else : newargs = [ str ( x ) for x in arg ] return '' % '' . join ( newargs ) return '' % cmds . encodeString ( str ( arg ) ) def pythonToMelCmd ( command , * args , ** kwargs ) : '''''' strArgs = [ pythonToMel ( arg ) for arg in args ] if kwargs : strFlags = [ ] if command in _factories . cmdlist : flags = _factories . cmdlist [ command ] [ '' ] shortFlags = _factories . cmdlist [ command ] [ '' ] else : flags = { } shortFlags = { } for key , val in kwargs . iteritems ( ) : flagInfo = None if key in flags : flagInfo = flags [ key ] elif key in shortFlags : flagInfo = flags [ shortFlags [ key ] ] if ( flagInfo and flagInfo . get ( '' ) == bool and flagInfo . get ( '' ) == ) : strFlags . append ( '' % key ) elif ( isinstance ( val , ( tuple , list ) ) and len ( val ) == flagInfo . get ( '' ) ) : strFlags . append ( '' % ( key , '' . join ( pythonToMel ( x ) for x in val ) ) ) else : strFlags . append ( '' % ( key , pythonToMel ( val ) ) ) cmdStr = '' % ( command , '' . join ( strFlags ) , '' . join ( strArgs ) ) else : cmdStr = '' % ( command , '' . join ( strArgs ) ) return cmdStr def getMelType ( pyObj , exactOnly = True , allowBool = False , allowMatrix = False ) : \"\"\"\"\"\" if inspect . isclass ( pyObj ) : if issubclass ( pyObj , basestring ) : return '' elif allowBool and issubclass ( pyObj , bool ) : return '' elif issubclass ( pyObj , int ) : return '' elif issubclass ( pyObj , float ) : return '' elif issubclass ( pyObj , datatypes . VectorN ) : return '' elif issubclass ( pyObj , datatypes . MatrixN ) : if allowMatrix : return '' else : return '' elif not exactOnly : return pyObj . __name__ else : if isinstance ( pyObj , datatypes . VectorN ) : return '' elif isinstance ( pyObj , datatypes . MatrixN ) : if allowMatrix : return '' else : return '' elif util . isIterable ( pyObj ) : try : return getMelType ( pyObj [ ] , exactOnly = True ) + '' except IndexError : return '' except : return if isinstance ( pyObj , basestring ) : return '' elif allowBool and isinstance ( pyObj , bool ) : return '' elif isinstance ( pyObj , int ) : return '' elif isinstance ( pyObj , float ) : return '' elif not exactOnly : return type ( pyObj ) . __name__ class MelGlobals ( dict ) : \"\"\"\"\"\" melTypeToPythonType = { '' : str , '' : int , '' : float , '' : datatypes . Vector } class MelGlobalArray ( util . defaultlist ) : def __init__ ( self , type , variable , * args , ** kwargs ) : if type . endswith ( '' ) : type = type [ : - ] pyType = MelGlobals . melTypeToPythonType [ type ] util . defaultlist . __init__ ( self , pyType , * args , ** kwargs ) declaration = MelGlobals . _get_decl_statement ( type , variable ) self . _setItemCmd = \"\" % ( declaration , variable ) self . _setItemCmd += '' def __setitem__ ( self , index , value ) : _mm . eval ( self . _setItemCmd % ( index , pythonToMel ( value ) ) ) super ( MelGlobalArray , self ) . __setitem__ ( index , value ) setItem = __setitem__ def append ( self , val ) : raise AttributeError def extend ( self , val ) : raise AttributeError typeMap = { } VALID_TYPES = MELTYPES def __getitem__ ( self , variable ) : return self . __class__ . get ( variable ) def __setitem__ ( self , variable , value ) : return self . __class__ . set ( variable , value ) @ classmethod def _formatVariable ( cls , variable ) : if not variable . startswith ( '' ) : variable = '' + variable if variable . endswith ( '' ) : variable = variable [ : - ] return variable @ classmethod def getType ( cls , variable ) : variable = cls . _formatVariable ( variable ) info = mel . whatIs ( variable ) . split ( ) if len ( info ) == and info [ ] == '' : MelGlobals . typeMap [ variable ] = info [ ] return info [ ] raise TypeError , \"\" @ classmethod def _get_decl_statement ( cls , type , variable ) : decl_name = cls . _formatVariable ( variable ) if type . endswith ( '' ) : type = type [ : - ] decl_name += '' return \"\" % ( type , decl_name ) @ classmethod def initVar ( cls , type , variable ) : if type not in MELTYPES : raise TypeError , \"\" % '' . join ( [ \"\" % x for x in MELTYPES ] ) variable = cls . _formatVariable ( variable ) _mm . eval ( cls . _get_decl_statement ( type , variable ) ) MelGlobals . typeMap [ variable ] = type return variable @ classmethod def get ( cls , variable , type = None ) : \"\"\"\"\"\" variable = cls . _formatVariable ( variable ) if type is None : try : type = MelGlobals . typeMap [ variable ] ", "answer": "except KeyError :"}, {"prompt": " from django . conf import settings from django . core . exceptions import ImproperlyConfigured from django . utils . importlib import import_module geom_backend = getattr ( settings , '' , '' ) try : module = import_module ( '' % geom_backend , '' ) ", "answer": "except ImportError :"}, {"prompt": " import sys import os sys . path . insert ( , os . path . abspath ( '' ) ) import geoip2 extensions = [ '' , '' , '' , '' ] templates_path = [ '' ] source_suffix = '' master_doc = '' project = '' copyright = '' version = geoip2 . __version__ release = geoip2 . __version__ exclude_patterns = [ '' ] pygments_style = '' html_theme = '' html_static_path = [ '' ] htmlhelp_basename = '' latex_elements = { } ", "answer": "latex_documents = ["}, {"prompt": " from django import forms from nose . tools import eq_ from pyquery import PyQuery as pq from kitsune . sumo . form_fields import StrippedCharField from kitsune . sumo . tests import TestCase class ExampleForm ( forms . Form ) : \"\"\"\"\"\" char = forms . CharField ( max_length = ) char_optional = forms . CharField ( required = False , widget = forms . TextInput ( ) ) file = forms . FileField ( max_length = ) choice = forms . ChoiceField ( choices = ( ( , ) , ( , ) ) ) stripped_char = StrippedCharField ( max_length = ) bool = forms . BooleanField ( ) textarea = StrippedCharField ( widget = forms . Textarea ( ) ) email = forms . EmailField ( ) url = forms . URLField ( required = False ) date = forms . DateField ( ) ", "answer": "time = forms . TimeField ( )"}, {"prompt": " \"\"\"\"\"\" import sys import idc import idaapi def winio_decode ( ioctl_code ) : \"\"\"\"\"\" access_names = [ '' , '' , '' , '' , ] method_names = [ '' , '' , '' , '' , ] device_name_unknown = '' device_names = [ device_name_unknown , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , ", "answer": "'' ,"}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import from contextlib import contextmanager import datetime import itertools import logging import os import stat import time from eventlet import sleep , timeout import sqlite3 from glance . common import cfg from glance . common import exception from glance . image_cache . drivers import base logger = logging . getLogger ( __name__ ) DEFAULT_SQL_CALL_TIMEOUT = class SqliteConnection ( sqlite3 . Connection ) : \"\"\"\"\"\" def __init__ ( self , * args , ** kwargs ) : self . timeout_seconds = kwargs . get ( '' , DEFAULT_SQL_CALL_TIMEOUT ) kwargs [ '' ] = sqlite3 . Connection . __init__ ( self , * args , ** kwargs ) def _timeout ( self , call ) : with timeout . Timeout ( self . timeout_seconds ) : while True : try : return call ( ) except sqlite3 . OperationalError , e : if '' not in str ( e ) : raise sleep ( ) def execute ( self , * args , ** kwargs ) : return self . _timeout ( lambda : sqlite3 . Connection . execute ( self , * args , ** kwargs ) ) def commit ( self ) : return self . _timeout ( lambda : sqlite3 . Connection . commit ( self ) ) def dict_factory ( cur , row ) : return dict ( ( ( col [ ] , row [ idx ] ) for idx , col in enumerate ( cur . description ) ) ) class Driver ( base . Driver ) : \"\"\"\"\"\" opts = [ cfg . StrOpt ( '' , default = '' ) , ] def configure ( self ) : \"\"\"\"\"\" super ( Driver , self ) . configure ( ) self . conf . register_opts ( self . opts ) self . initialize_db ( ) def initialize_db ( self ) : db = self . conf . image_cache_sqlite_db self . db_path = os . path . join ( self . base_dir , db ) try : conn = sqlite3 . connect ( self . db_path , check_same_thread = False , factory = SqliteConnection ) conn . executescript ( \"\"\"\"\"\" ) conn . close ( ) except sqlite3 . DatabaseError , e : msg = _ ( \"\" \"\" ) % e logger . error ( msg ) raise exception . BadDriverConfiguration ( driver_name = '' , reason = msg ) def get_cache_size ( self ) : \"\"\"\"\"\" sizes = [ ] for path in self . get_cache_files ( self . base_dir ) : if path == self . db_path : continue file_info = os . stat ( path ) sizes . append ( file_info [ stat . ST_SIZE ] ) return sum ( sizes ) def get_hit_count ( self , image_id ) : \"\"\"\"\"\" if not self . is_cached ( image_id ) : return hits = with self . get_db ( ) as db : cur = db . execute ( \"\"\"\"\"\" , ( image_id , ) ) hits = cur . fetchone ( ) [ ] return hits def get_cached_images ( self ) : \"\"\"\"\"\" logger . debug ( _ ( \"\" ) ) with self . get_db ( ) as db : cur = db . execute ( \"\"\"\"\"\" ) cur . row_factory = dict_factory return [ r for r in cur ] def is_cached ( self , image_id ) : \"\"\"\"\"\" return os . path . exists ( self . get_image_filepath ( image_id ) ) def is_cacheable ( self , image_id ) : \"\"\"\"\"\" return not ( self . is_cached ( image_id ) or self . is_being_cached ( image_id ) ) def is_being_cached ( self , image_id ) : \"\"\"\"\"\" path = self . get_image_filepath ( image_id , '' ) return os . path . exists ( path ) def is_queued ( self , image_id ) : \"\"\"\"\"\" path = self . get_image_filepath ( image_id , '' ) return os . path . exists ( path ) def delete_all_cached_images ( self ) : \"\"\"\"\"\" deleted = with self . get_db ( ) as db : for path in self . get_cache_files ( self . base_dir ) : delete_cached_file ( path ) deleted += db . execute ( \"\"\"\"\"\" ) ", "answer": "db . commit ( )"}, {"prompt": " import sys from debtcollector import moves from neutron_lib . api import converters as lib_converters from neutron_lib . api import validators as lib_validators from neutron_lib import constants import six import webob . exc from neutron . _i18n import _ from neutron . common import _deprecate from neutron . common import constants as n_const SHARED = '' _deprecate . _DeprecateSubset . and_also ( '' , lib_validators ) NAME_MAX_LEN = TENANT_ID_MAX_LEN = DESCRIPTION_MAX_LEN = LONG_DESCRIPTION_MAX_LEN = DEVICE_ID_MAX_LEN = DEVICE_OWNER_MAX_LEN = def _lib ( old_name ) : \"\"\"\"\"\" new_func = getattr ( lib_validators , old_name , None ) if not new_func : new_func = getattr ( lib_validators , old_name [ : ] , None ) if not new_func : new_func = getattr ( lib_converters , old_name , None ) assert new_func return moves . moved_function ( new_func , old_name , __name__ , message = '' , version = '' , removal_version = '' ) _verify_dict_keys = _lib ( '' ) is_attr_set = _lib ( '' ) _validate_list_of_items = _lib ( '' ) _validate_values = _lib ( '' ) _validate_not_empty_string_or_none = _lib ( '' ) _validate_not_empty_string = _lib ( '' ) _validate_string_or_none = _lib ( '' ) _validate_string = _lib ( '' ) validate_list_of_unique_strings = _lib ( '' ) _validate_boolean = _lib ( '' ) _validate_range = _lib ( '' ) _validate_no_whitespace = _lib ( '' ) _validate_mac_address = _lib ( '' ) _validate_mac_address_or_none = _lib ( '' ) _validate_ip_address = _lib ( '' ) _validate_ip_pools = _lib ( '' ) _validate_fixed_ips = _lib ( '' ) _validate_nameservers = _lib ( '' ) _validate_hostroutes = _lib ( '' ) _validate_ip_address_or_none = _lib ( '' ) _validate_subnet = _lib ( '' ) _validate_subnet_or_none = _lib ( '' ) _validate_subnet_list = _lib ( '' ) _validate_regex = _lib ( '' ) _validate_regex_or_none = _lib ( '' ) _validate_subnetpool_id = _lib ( '' ) _validate_subnetpool_id_or_none = _lib ( '' ) _validate_uuid = _lib ( '' ) _validate_uuid_or_none = _lib ( '' ) _validate_uuid_list = _lib ( '' ) _validate_dict_item = _lib ( '' ) _validate_dict = _lib ( '' ) _validate_dict_or_none = _lib ( '' ) _validate_dict_or_empty = _lib ( '' ) _validate_dict_or_nodata = _lib ( '' ) _validate_non_negative = _lib ( '' ) convert_to_boolean = _lib ( '' ) convert_to_boolean_if_not_none = _lib ( '' ) convert_to_int = _lib ( '' ) convert_to_int_if_not_none = _lib ( '' ) convert_to_positive_float_or_none = _lib ( '' ) convert_kvp_str_to_list = _lib ( '' ) convert_kvp_list_to_dict = _lib ( '' ) convert_none_to_empty_list = _lib ( '' ) convert_none_to_empty_dict = _lib ( '' ) convert_to_list = _lib ( '' ) _deprecate . _DeprecateSubset . and_also ( '' , lib_validators ) _deprecate . _DeprecateSubset . and_also ( '' , lib_validators ) NETWORK = '' NETWORKS = '' % NETWORK PORT = '' PORTS = '' % PORT SUBNET = '' SUBNETS = '' % SUBNET SUBNETPOOL = '' SUBNETPOOLS = '' % SUBNETPOOL RESOURCE_ATTRIBUTE_MAP = { NETWORKS : { '' : { '' : False , '' : False , '' : { '' : None } , '' : True , '' : True } , '' : { '' : True , '' : True , '' : { '' : NAME_MAX_LEN } , '' : '' , '' : True } , '' : { '' : False , '' : False , '' : [ ] , '' : True } , '' : { '' : True , '' : True , '' : True , '' : lib_converters . convert_to_boolean , '' : True } , '' : { '' : False , '' : False , '' : True } , '' : { '' : True , '' : False , '' : { '' : TENANT_ID_MAX_LEN } , '' : True , '' : True } , SHARED : { '' : True , '' : True , '' : False , '' : lib_converters . convert_to_boolean , '' : True , '' : True , '' : True } , } , PORTS : { '' : { '' : False , '' : False , '' : { '' : None } , '' : True , '' : True } , '' : { '' : True , '' : True , '' : '' , '' : { '' : NAME_MAX_LEN } , '' : True } , '' : { '' : True , '' : False , '' : True , '' : { '' : None } , '' : True } , '' : { '' : True , '' : True , '' : True , '' : lib_converters . convert_to_boolean , '' : True } , '' : { '' : True , '' : True , '' : constants . ATTR_NOT_SPECIFIED , '' : { '' : None } , '' : True , '' : True } , '' : { '' : True , '' : True , '' : constants . ATTR_NOT_SPECIFIED , '' : lib_converters . convert_kvp_list_to_dict , '' : { '' : None } , '' : True , '' : True } , '' : { '' : True , '' : True , '' : { '' : DEVICE_ID_MAX_LEN } , '' : '' , '' : True } , '' : { '' : True , '' : True , '' : { '' : DEVICE_OWNER_MAX_LEN } , '' : '' , '' : True , '' : True } , '' : { '' : True , '' : False , '' : { '' : TENANT_ID_MAX_LEN } , '' : True , '' : True } , '' : { '' : False , '' : False , '' : True } , } , SUBNETS : { '' : { '' : False , '' : False , '' : { '' : None } , '' : True , '' : True } , '' : { '' : True , '' : True , '' : '' , '' : { '' : NAME_MAX_LEN } , '' : True } , '' : { '' : True , '' : False , '' : lib_converters . convert_to_int , '' : { '' : [ , ] } , '' : True } , '' : { '' : True , '' : False , '' : True , '' : { '' : None } , '' : True } , '' : { '' : True , '' : False , '' : constants . ATTR_NOT_SPECIFIED , '' : False , '' : { '' : None } , '' : True } , '' : { '' : True , '' : False , '' : { '' : None } , '' : lib_converters . convert_to_int , '' : constants . ATTR_NOT_SPECIFIED , '' : False , '' : False } , '' : { '' : True , '' : False , '' : constants . ATTR_NOT_SPECIFIED , '' : { '' : None } , '' : False , '' : True } , '' : { '' : True , '' : True , '' : constants . ATTR_NOT_SPECIFIED , '' : { '' : None } , '' : True } , '' : { '' : True , '' : True , '' : constants . ATTR_NOT_SPECIFIED , '' : { '' : None } , '' : True } , '' : { '' : True , '' : True , '' : lib_converters . convert_none_to_empty_list , '' : constants . ATTR_NOT_SPECIFIED , '' : { '' : None } , '' : True } , '' : { '' : True , '' : True , '' : lib_converters . convert_none_to_empty_list , '' : constants . ATTR_NOT_SPECIFIED , '' : { '' : None } , '' : True } , '' : { '' : True , '' : False , '' : { '' : TENANT_ID_MAX_LEN } , '' : True , '' : True } , '' : { '' : True , '' : True , '' : True , '' : lib_converters . convert_to_boolean , '' : True } , '' : { '' : True , '' : False , '' : constants . ATTR_NOT_SPECIFIED , '' : { '' : n_const . IPV6_MODES } , '' : True } , '' : { '' : True , '' : False , '' : constants . ATTR_NOT_SPECIFIED , '' : { '' : n_const . IPV6_MODES } , '' : True } , SHARED : { '' : False , '' : False , '' : False , '' : lib_converters . convert_to_boolean , '' : False , '' : True , '' : True } , } , SUBNETPOOLS : { '' : { '' : False , '' : False , '' : { '' : None } , '' : True , '' : True } , '' : { '' : True , '' : True , '' : { '' : None } , '' : True } , '' : { '' : True , '' : False , '' : { '' : TENANT_ID_MAX_LEN } , '' : True , ", "answer": "'' : True } ,"}, {"prompt": " \"\"\"\"\"\" try : from urllib import unquote except ImportError : from urllib . parse import unquote from werkzeug . http import parse_options_header , parse_cache_control_header , parse_set_header from werkzeug . useragents import UserAgent from werkzeug . datastructures import Headers , ResponseCacheControl class CGIRootFix ( object ) : \"\"\"\"\"\" def __init__ ( self , app , app_root = '' ) : self . app = app self . app_root = app_root def __call__ ( self , environ , start_response ) : if '' not in environ or environ [ '' ] < '' : environ [ '' ] = environ . get ( '' , '' ) + environ . get ( '' , '' ) environ [ '' ] = self . app_root . strip ( '' ) return self . app ( environ , start_response ) LighttpdCGIRootFix = CGIRootFix class PathInfoFromRequestUriFix ( object ) : \"\"\"\"\"\" def __init__ ( self , app ) : self . app = app def __call__ ( self , environ , start_response ) : for key in '' , '' , '' : if key not in environ : continue request_uri = unquote ( environ [ key ] ) script_name = unquote ( environ . get ( '' , '' ) ) if request_uri . startswith ( script_name ) : environ [ '' ] = request_uri [ len ( script_name ) : ] . split ( '' , ) [ ] break return self . app ( environ , start_response ) class ProxyFix ( object ) : \"\"\"\"\"\" def __init__ ( self , app , num_proxies = ) : self . app = app self . num_proxies = num_proxies def get_remote_addr ( self , forwarded_for ) : \"\"\"\"\"\" if len ( forwarded_for ) >= self . num_proxies : return forwarded_for [ - * self . num_proxies ] def __call__ ( self , environ , start_response ) : getter = environ . get forwarded_proto = getter ( '' , '' ) forwarded_for = getter ( '' , '' ) . split ( '' ) forwarded_host = getter ( '' , '' ) environ . update ( { '' : getter ( '' ) , '' : getter ( '' ) , '' : getter ( '' ) } ) forwarded_for = [ x for x in [ x . strip ( ) for x in forwarded_for ] if x ] ", "answer": "remote_addr = self . get_remote_addr ( forwarded_for )"}, {"prompt": " \"\"\"\"\"\" from pytest import fixture import datetime from . dbf import DBF @ fixture def table ( ) : return DBF ( '' ) @ fixture def loaded_table ( ) : return DBF ( '' , load = True ) records = [ { u'' : u'' , u'' : datetime . date ( , , ) , u'' : u'' } , { u'' : u'' , u'' : datetime . date ( , , ) , u'' : u'' } ] deleted_records = [ { u'' : u'' , u'' : datetime . date ( , , ) , u'' : u'' } ] ", "answer": "def test_len ( ) :"}, {"prompt": " from services import root_dir , nice_json from flask import Flask from werkzeug . exceptions import NotFound import json app = Flask ( __name__ ) ", "answer": "with open ( \"\" . format ( root_dir ( ) ) , \"\" ) as f :"}, {"prompt": " \"\"\"\"\"\" try : from threading import RLock lock = RLock ( ) except ImportError : lock = None class Cache ( object ) : def __init__ ( self ) : self . content = { } self . _building = { } def getorbuild ( self , key ) : if lock : lock . acquire ( ) try : try : return self . content [ key ] except KeyError : if key in self . _building : raise Exception , \"\" % ( self , key ) self . _building [ key ] = True try : result = self . _build ( key ) self . content [ key ] = result finally : del self . _building [ key ] self . _ready ( result ) return result ", "answer": "finally :"}, {"prompt": " import textwrap from robot . utils import MultiMatcher , console_encode from robot . errors import DataError class ConsoleViewer ( object ) : def __init__ ( self , libdoc ) : self . _libdoc = libdoc self . _keywords = KeywordMatcher ( libdoc ) @ classmethod def handles ( cls , command ) : return command . lower ( ) in [ '' , '' , '' ] @ classmethod def validate_command ( cls , command , args ) : if not cls . handles ( command ) : raise DataError ( \"\" % command ) if command . lower ( ) == '' and args : raise DataError ( \"\" ) def view ( self , command , * args ) : self . validate_command ( command , args ) getattr ( self , command . lower ( ) ) ( * args ) def list ( self , * patterns ) : for kw in self . _keywords . search ( '' % p for p in patterns ) : self . _console ( kw . name ) def show ( self , * names ) : if MultiMatcher ( names , match_if_no_patterns = True ) . match ( '' ) : self . _show_intro ( self . _libdoc ) if self . _libdoc . inits : self . _show_inits ( self . _libdoc ) for kw in self . _keywords . search ( names ) : self . _show_keyword ( kw ) def version ( self ) : self . _console ( self . _libdoc . version or '' ) def _console ( self , msg ) : print ( console_encode ( msg ) ) def _show_intro ( self , lib ) : self . _header ( lib . name , underline = '' ) named_args = '' if lib . named_args else '' self . _data ( [ ( '' , lib . version ) , ( '' , lib . scope ) , ( '' , named_args ) ] ) self . _doc ( lib . doc ) def _show_inits ( self , lib ) : self . _header ( '' , underline = '' ) for init in lib . inits : self . _show_keyword ( init , show_name = False ) def _show_keyword ( self , kw , show_name = True ) : if show_name : self . _header ( kw . name , underline = '' ) self . _data ( [ ( '' , '' % '' . join ( kw . args ) ) ] ) self . _doc ( kw . doc ) def _header ( self , name , underline ) : self . _console ( '' % ( name , underline * len ( name ) ) ) ", "answer": "def _data ( self , items ) :"}, {"prompt": " \"\"\"\"\"\" import vim import vimp def is_available ( ) : \"\"\"\"\"\" for v in [ '' , '' ] : if v in vimp . var : return True return False def add_filetypes ( filetypes ) : if isinstance ( filetypes , str ) : ft = filetypes elif isinstance ( filetypes , list ) : ft = '' . join ( filetypes ) ", "answer": "vim . command ( '' + ft ) "}, {"prompt": " import os import sys import re ", "answer": "import json"}, {"prompt": " import os , struct , threading , errno , select from ctypes import CDLL , CFUNCTYPE , POINTER , c_int , c_char_p , c_uint32 , get_errno from . common import FSEvent , FSMonitorOSError module_loaded = True libc = CDLL ( \"\" ) strerror = CFUNCTYPE ( c_char_p , c_int ) ( ( \"\" , libc ) ) inotify_init = CFUNCTYPE ( c_int , use_errno = True ) ( ( \"\" , libc ) ) inotify_add_watch = CFUNCTYPE ( c_int , c_int , c_char_p , c_uint32 , use_errno = True ) ( ( \"\" , libc ) ) inotify_rm_watch = CFUNCTYPE ( c_int , c_int , c_int , use_errno = True ) ( ( \"\" , libc ) ) IN_ACCESS = IN_MODIFY = IN_ATTRIB = IN_CLOSE_WRITE = IN_CLOSE_NOWRITE = IN_CLOSE = IN_CLOSE_WRITE | IN_CLOSE_NOWRITE IN_OPEN = IN_MOVED_FROM = IN_MOVED_TO = IN_MOVE = IN_MOVED_FROM | IN_MOVED_TO IN_CREATE = IN_DELETE = IN_DELETE_SELF = IN_MOVE_SELF = ", "answer": "IN_UNMOUNT = "}, {"prompt": " from . devicelist import ( ChannelList , ChannelInfo , DevicePINInfo , DeviceTokenList , DevicePINList , APIDList , Feedback , ) from . tag import ( TagList , Tag , DeleteTag , BatchTag , ) from . segment import ( Segment , SegmentList ) from . channel_uninstall import ( ", "answer": "ChannelUninstall"}, {"prompt": " import os import sys import install_venv_common as install_venv def print_help ( venv , root ) : help = \"\"\"\"\"\" print ( help % ( venv , root ) ) def main ( argv ) : root = os . path . dirname ( os . path . dirname ( os . path . realpath ( __file__ ) ) ) if os . environ . get ( '' ) : ", "answer": "root = os . environ [ '' ]"}, {"prompt": " from mock import Mock , MagicMock import unittest2 as unittest from contextlib import contextmanager from monocle . callback import defer from helpers import mock_db , listen_for , mock_worker def _account_for_test ( config = None , db = None ) : from tinymail . account import Account if config is None : config = { '' : '' , '' : '' , '' : '' , '' : '' , } if db is None : db = MagicMock ( ) return Account ( config , db ) msg13_data = ( , set ( [ r'' ] ) , \"\" ) msg22_data = ( , set ( [ ] ) , \"\" ) class AccountTest ( unittest . TestCase ) : def test_list_folders ( self ) : account = _account_for_test ( ) fol1 , fol2 = Mock ( ) , Mock ( ) account . _folders = { '' : fol1 , '' : fol2 } folders = list ( account . list_folders ( ) ) self . assertEqual ( folders , [ fol1 , fol2 ] ) def test_get_folder ( self ) : account = _account_for_test ( ) fol1 , fol2 = Mock ( ) , Mock ( ) account . _folders = { '' : fol1 , '' : fol2 } ret_fol1 = account . get_folder ( '' ) self . assertTrue ( ret_fol1 is fol1 ) class FolderTest ( unittest . TestCase ) : def test_list_messages ( self ) : from tinymail . account import Folder folder = Folder ( Mock ( ) , '' ) msg1 , msg2 = Mock ( ) , Mock ( ) folder . _messages = { : msg1 , : msg2 } messages = list ( folder . list_messages ( ) ) self . assertEqual ( messages , [ msg1 , msg2 ] ) def test_get_message ( self ) : from tinymail . account import Folder folder = Folder ( Mock ( ) , '' ) msg1 , msg2 = Mock ( ) , Mock ( ) folder . _messages = { : msg1 , : msg2 } self . assertEqual ( folder . get_message ( ) , msg1 ) self . assertEqual ( folder . get_message ( ) , msg2 ) class AccountUpdateTest ( unittest . TestCase ) : def test_list_folders ( self ) : from tinymail . account import account_updated account = _account_for_test ( ) folders = { '' : { } , '' : { } } with mock_worker ( ** folders ) : with listen_for ( account_updated ) as caught_signals : account . perform_update ( ) self . assertEqual ( set ( f . name for f in account . list_folders ( ) ) , set ( folders ) ) self . assertEqual ( caught_signals , [ ( account , { } ) ] ) def test_list_messages ( self ) : from tinymail . account import folder_updated account = _account_for_test ( ) with mock_worker ( fol1 = { : None } ) : account . perform_update ( ) with mock_worker ( fol1 = { : None , : None } ) : with listen_for ( folder_updated ) as caught_signals : account . perform_update ( ) fol1 = account . get_folder ( '' ) self . assertEqual ( set ( m . uid for m in fol1 . list_messages ( ) ) , set ( [ , ] ) ) event_data = { '' : [ ] , '' : [ ] , '' : [ ] } self . assertEqual ( caught_signals , [ ( fol1 , event_data ) ] ) def test_message_removed_on_server ( self ) : from tinymail . account import folder_updated account = _account_for_test ( ) with mock_worker ( fol1 = { : None , : None } ) : account . perform_update ( ) with mock_worker ( fol1 = { : None } ) : with listen_for ( folder_updated ) as caught_signals : account . perform_update ( ) fol1 = account . get_folder ( '' ) self . assertEqual ( [ m . uid for m in fol1 . list_messages ( ) ] , [ ] ) event_data = { '' : [ ] , '' : [ ] , '' : [ ] } self . assertEqual ( caught_signals , [ ( fol1 , event_data ) ] ) def test_only_get_new_headers ( self ) : account = _account_for_test ( ) with mock_worker ( fol1 = { : None , : None } ) : account . perform_update ( ) with mock_worker ( fol1 = { : None , : None , : None } ) as worker : account . perform_update ( ) worker . get_message_headers . assert_called_once_with ( set ( [ ] ) ) def test_empty_folder ( self ) : account = _account_for_test ( ) with mock_worker ( fol1 = { } ) as worker : account . perform_update ( ) self . assertFalse ( worker . get_message_headers . called ) def test_load_full_message ( self ) : from tinymail . account import message_updated account = _account_for_test ( ) mime_message = \"\" with mock_worker ( fol1 = { : None } ) as worker : account . perform_update ( ) message = account . get_folder ( '' ) . _messages [ ] worker . get_message_body . return_value = defer ( mime_message ) worker . close_mailbox . reset_mock ( ) with listen_for ( message_updated ) as caught_signals : message . load_full ( ) self . assertEqual ( message . raw_full , mime_message ) self . assertEqual ( caught_signals , [ ( message , { } ) ] ) worker . close_mailbox . assert_called_once_with ( ) def test_folder_removed_on_server ( self ) : account = _account_for_test ( ) with mock_worker ( fol1 = { } , fol2 = { } ) : account . perform_update ( ) with mock_worker ( fol1 = { } ) : account . perform_update ( ) self . assertEqual ( [ f . name for f in account . list_folders ( ) ] , [ '' ] ) def test_trust_uidvalidity ( self ) : account = _account_for_test ( ) msg13_bis_data = ( , set ( [ r'' ] ) , \"\" ) with mock_worker ( fol1 = { : msg13_data } ) : account . perform_update ( ) with mock_worker ( fol1 = { : msg13_bis_data } ) : account . perform_update ( ) fol1 = account . get_folder ( '' ) self . assertEqual ( [ m . raw_headers for m in fol1 . list_messages ( ) ] , [ msg13_data [ ] ] ) def test_uidvalidity_changed ( self ) : account = _account_for_test ( ) msg13_bis_data = ( , set ( [ r'' ] ) , \"\" ) with mock_worker ( fol1 = { : msg13_data , '' : } ) : account . perform_update ( ) with mock_worker ( fol1 = { : msg13_bis_data , '' : } ) : account . perform_update ( ) fol1 = account . get_folder ( '' ) self . assertEqual ( [ m . raw_headers for m in fol1 . list_messages ( ) ] , [ msg13_bis_data [ ] ] ) def test_message_flags_changed ( self ) : from tinymail . account import folder_updated account = _account_for_test ( ) msg13_bis_data = ( , set ( [ r'' ] ) , \"\" ) with mock_worker ( fol1 = { : msg13_data } ) : account . perform_update ( ) with mock_worker ( fol1 = { : msg13_bis_data } ) : with listen_for ( folder_updated ) as caught_signals : account . perform_update ( ) fol1 = account . get_folder ( '' ) self . assertEqual ( [ m . flags for m in fol1 . list_messages ( ) ] , [ set ( [ '' ] ) ] ) event_data = { '' : [ ] , '' : [ ] , '' : [ ] } self . assertEqual ( caught_signals , [ ( fol1 , event_data ) ] ) def test_close_mailbox_after_update ( self ) : account = _account_for_test ( ) with mock_worker ( fol1 = { } ) as worker : account . perform_update ( ) worker . close_mailbox . assert_called_once_with ( ) class PersistenceTest ( unittest . TestCase ) : def test_folders ( self ) : db = mock_db ( ) account = _account_for_test ( db = db ) with mock_worker ( myfolder = { } ) as worker : account . perform_update ( ) account2 = _account_for_test ( db = db ) folders = list ( account2 . list_folders ( ) ) self . assertEqual ( len ( folders ) , ) self . assertEqual ( folders [ ] . name , '' ) def test_folders_removed ( self ) : db = mock_db ( ) account = _account_for_test ( db = db ) with mock_worker ( fol1 = { } , fol2 = { } ) : account . perform_update ( ) with mock_worker ( fol1 = { } ) : account . perform_update ( ) account2 = _account_for_test ( db = db ) self . assertEqual ( [ f . name for f in account2 . list_folders ( ) ] , [ '' ] ) def test_messages ( self ) : db = mock_db ( ) account = _account_for_test ( db = db ) msg4_data = ( , set ( [ r'' ] ) , \"\" ) msg22_data = ( , set ( [ r'' , r'' ] ) , \"\" ) ", "answer": "with mock_worker ( myfolder = { : msg4_data , : msg22_data } ) as worker :"}, {"prompt": " from . resource import Resource class NetworkSecurityGroup ( Resource ) : \"\"\"\"\"\" _validation = { '' : { '' : True } , '' : { '' : True } , } _attribute_map = { '' : { '' : '' , '' : '' } , '' : { '' : '' , '' : '' } , '' : { '' : '' , '' : '' } , ", "answer": "'' : { '' : '' , '' : '' } ,"}, {"prompt": " import os ", "answer": "from google . appengine . _internal . django . core . management . base import copy_helper , CommandError , LabelCommand"}, {"prompt": " from django . test import TestCase from mock import Mock import sys from data_importer import forms from imp import reload ", "answer": "class TestFileUploadForm ( TestCase ) :"}, {"prompt": " \"\"\"\"\"\" revision = '' down_revision = '' from alembic import op import sqlalchemy as sa def upgrade ( ) : op . add_column ( '' , ", "answer": "sa . Column ( '' , sa . String ( length = ) ) ) "}, {"prompt": " import pandas as pd ; import SETTINGS as sts ; from fitting_models import * import analysis def train_sex_age_model ( info , train_true ) : print ( \"\" ) ; sa_model = SexAgeModel ( ) ; sa_model . fit ( info , train_true ) ; sa_predict = sa_model . predict ( info ) ; analysis . evaluate_pred ( sa_predict , train_true ) ; return sa_predict ; def train_ch4_model ( ch4_data , train_true ) : print ( \"\" ) ; ch4_model = Ch4Model ( ) ; ch4_model . fit ( ch4_data , train_true ) ; ch4_pred = ch4_model . predict ( ch4_data ) ; analysis . evaluate_pred ( ch4_pred , train_true ) ; return ch4_pred ; def train_sax_model ( areas_all , train_true , version , cleaner = [ ] ) : print ( \"\" ) ; sax_model = SaxModel ( version = version ) ; result = analysis . get_preliminary_volume ( areas_all , cleaner = cleaner ) ; sax_model . fit ( result , train_true ) ; sax_predict = sax_model . predict ( result ) ; analysis . evaluate_pred ( sax_predict , train_true ) ; return sax_predict ; def train_sax_cnt_model ( areas_all , cont_all , train_true , version = , cleaner = [ ] ) : print ( \"\" ) ; cnt_sax_model = SaxModel ( version = version ) ; cnt_result = analysis . get_preliminary_volume_cnt ( areas_all , cont_all , cleaner = cleaner ) ; cnt_sax_model . fit ( cnt_result , train_true ) ; cnt_sax_predict = cnt_sax_model . predict ( cnt_result ) ; analysis . evaluate_pred ( cnt_sax_predict , train_true ) ; return cnt_sax_predict ; def train_sax_cnt_filter_model ( areas_all , cont_all , train_true , cleaner = [ ] ) : print ( \"\" ) ; cnt_result = analysis . get_preliminary_volume_cnt_filter ( areas_all , cont_all , cleaner = cleaner ) ; cnt_sax_model = SaxFilterModel ( ) ; cnt_sax_model . fit ( cnt_result , train_true ) ; cnt_sax_predict = cnt_sax_model . predict ( cnt_result ) ; analysis . evaluate_pred ( cnt_sax_predict , train_true ) ; return cnt_sax_predict ; def train_oneslice_model ( areas_all , train_true ) : print ( \"\" ) ; oneslice_model = OneSliceModel ( ) ; oneslice_model . fit ( areas_all , train_true ) ; oneslice_predict = oneslice_model . predict ( areas_all ) ; analysis . evaluate_pred ( oneslice_predict , train_true ) ; return oneslice_predict ; def build_default_model ( oneslice_pred , ch4_pred , sa_predict , p_1 = ) : print ( \"\" ) ; default_pred = { } ; def _bdm_ave ( x1 , x2 , x0 ) : if np . isnan ( x1 [ ] ) : return x0 if np . isnan ( x2 [ ] ) else x2 ; elif np . isnan ( x2 [ ] ) : return x1 ; return np . asarray ( [ x1 [ ] * p_1 + x2 [ ] * ( - p_1 ) , min ( x1 [ ] , x2 [ ] ) ] ) ; for case , value in sa_predict . iteritems ( ) : pred1 = oneslice_pred . get ( case ) ; pred2 = ch4_pred . get ( case ) ; if pred1 is None : pred1 = np . zeros ( ) ; pred1 [ : ] = np . nan ; if pred2 is None : pred2 = np . zeros ( ) ; pred2 [ : ] = np . nan ; x = np . zeros ( ) ; x [ : ] = _bdm_ave ( pred1 [ : ] , pred2 [ : ] , value [ : ] ) ; x [ : ] = _bdm_ave ( pred1 [ : ] , pred2 [ : ] , value [ : ] ) ; default_pred [ case ] = x ; return default_pred ; if __name__ == '' : cleaner = [ , , ] ; info = pd . read_csv ( sts . output_dir + '' ) ch4_data = { int ( r [ ] ) : ( r [ ] , r [ ] ) for _ , r in pd . read_csv ( sts . tencia_output_dir + '' , header = False ) . iterrows ( ) } ; tencia_files = [ '' , '' ] ; tencia_areas = [ analysis . get_cnn_results ( sts . tencia_output_dir + '' . format ( x ) ) for x in tencia_files ] ; qifiles = [ '' , '' , '' , '' , '' , '' , '' , '' , ] ; qi_areas = [ analysis . get_cnn_results ( sts . output_dir + \"\" . format ( v ) ) for v in qifiles ] ; qi_cnts = [ analysis . get_cnn_results ( sts . output_dir + \"\" . format ( v ) ) for v in qifiles ] ; train_true = pd . read_csv ( sts . data_kaggle + '' ) ; Ntrain = train_true . shape [ ] ; print ( \"\" . format ( Ntrain ) ) ; filter_ll = - ; sa_predict = train_sex_age_model ( info , train_true ) ; ch4_predict = train_ch4_model ( ch4_data , train_true ) ; pick = [ , ] ; qi_best , qi_best_cont = analysis . take_best_contour ( [ qi_areas [ i ] for i in pick ] , [ qi_cnts [ i ] for i in pick ] , method = , filter_ll = filter_ll ) ; oneslice_pred = train_oneslice_model ( qi_best , train_true ) ; default_pred = build_default_model ( oneslice_pred , ch4_predict , sa_predict ) ; analysis . evaluate_pred ( default_pred , train_true ) ; tencia_best = analysis . take_best ( tencia_areas , method = , filter_ll = - ) ; tencia_predict = train_sax_model ( tencia_best , train_true , version = ) ; pick = [ , ] ; qi_best , qi_best_cont = analysis . take_best_contour ( [ qi_areas [ i ] for i in pick ] , [ qi_cnts [ i ] for i in pick ] , method = , filter_ll = filter_ll ) ; qi_sax_pred = train_sax_model ( qi_best , train_true , version = , cleaner = cleaner ) ; qi_sax_cnt_pred = train_sax_cnt_model ( qi_best , qi_best_cont , train_true , version = , cleaner = cleaner ) ; qi_sax_filter_pred = train_sax_cnt_filter_model ( qi_best , qi_best_cont , train_true , cleaner = cleaner ) ; pick = [ , ] ; qi_best , qi_best_cont = analysis . take_best_contour ( [ qi_areas [ i ] for i in pick ] , [ qi_cnts [ i ] for i in pick ] , method = , filter_ll = filter_ll ) ; qi_sax_pred2 = train_sax_model ( qi_best , train_true , version = , cleaner = cleaner ) ; qi_sax_cnt_pred2 = train_sax_cnt_model ( qi_best , qi_best_cont , train_true , version = , cleaner = cleaner ) ; ", "answer": "qi_sax_filter_pred2 = train_sax_cnt_filter_model ( qi_best , qi_best_cont , train_true , cleaner = cleaner ) ;"}, {"prompt": " from django . http import HttpResponse , HttpResponseForbidden from django . template . loader import render_to_string from django . views . decorators . csrf import csrf_exempt from uwsgi_it_api . utils import spit_json , check_body from uwsgi_it_api . decorators import need_certificate from uwsgi_it_api . models import * from uwsgi_it_api . config import UWSGI_IT_BASE_UID import json import datetime @ need_certificate @ csrf_exempt def private_server_file_metadata ( request ) : try : server = Server . objects . get ( address = request . META [ '' ] ) if request . method == '' : response = check_body ( request ) if response : return response j = json . loads ( request . read ( ) ) metadata = ServerFileMetadata . objects . get ( filename = j [ '' ] ) sm , created = ServerMetadata . objects . get_or_create ( server = server , metadata = metadata ) sm . value = j [ '' ] sm . save ( ) response = HttpResponse ( '' ) response . status_code = return response files = [ ] for _file in ServerFileMetadata . objects . all ( ) : files . append ( _file . filename ) return spit_json ( request , files ) except : import sys print sys . exc_info ( ) return HttpResponseForbidden ( '' ) @ need_certificate def private_custom_services ( request ) : try : server = Server . objects . get ( address = request . META [ '' ] ) j = [ { '' : service . customer . pk , '' : service . config , '' : service . munix , '' : service . pk } for service in server . customservice_set . all ( ) ] return spit_json ( request , j ) except : return HttpResponseForbidden ( '' ) @ need_certificate def private_containers ( request ) : try : server = Server . objects . get ( address = request . META [ '' ] ) j = [ { '' : container . uid , '' : container . munix , '' : container . ssh_keys_munix } for container in server . container_set . exclude ( distro__isnull = True ) . exclude ( ssh_keys_raw__exact = '' ) . exclude ( ssh_keys_raw__isnull = True ) ] return spit_json ( request , j ) except : return HttpResponseForbidden ( '' ) @ need_certificate def private_loopboxes ( request ) : try : server = Server . objects . get ( address = request . META [ '' ] ) j = [ { '' : loopbox . pk , '' : loopbox . container . uid , '' : loopbox . filename , '' : loopbox . mountpoint , '' : loopbox . ro } for loopbox in Loopbox . objects . filter ( container__server = server ) ] return spit_json ( request , j ) except : return HttpResponseForbidden ( '' ) @ need_certificate def private_portmappings ( request ) : ", "answer": "try :"}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import , print_function from copy import deepcopy from . . enum . section import WD_ORIENTATION , WD_SECTION_START from . simpletypes import ST_SignedTwipsMeasure , ST_TwipsMeasure from . xmlchemy import BaseOxmlElement , OptionalAttribute , ZeroOrOne class CT_PageMar ( BaseOxmlElement ) : \"\"\"\"\"\" top = OptionalAttribute ( '' , ST_SignedTwipsMeasure ) right = OptionalAttribute ( '' , ST_TwipsMeasure ) bottom = OptionalAttribute ( '' , ST_SignedTwipsMeasure ) left = OptionalAttribute ( '' , ST_TwipsMeasure ) header = OptionalAttribute ( '' , ST_TwipsMeasure ) footer = OptionalAttribute ( '' , ST_TwipsMeasure ) gutter = OptionalAttribute ( '' , ST_TwipsMeasure ) class CT_PageSz ( BaseOxmlElement ) : \"\"\"\"\"\" w = OptionalAttribute ( '' , ST_TwipsMeasure ) h = OptionalAttribute ( '' , ST_TwipsMeasure ) orient = OptionalAttribute ( '' , WD_ORIENTATION , default = WD_ORIENTATION . PORTRAIT ) class CT_SectPr ( BaseOxmlElement ) : \"\"\"\"\"\" __child_sequence__ = ( '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , ) type = ZeroOrOne ( '' , successors = ( __child_sequence__ [ __child_sequence__ . index ( '' ) + : ] ) ) pgSz = ZeroOrOne ( '' , successors = ( __child_sequence__ [ __child_sequence__ . index ( '' ) + : ] ) ) pgMar = ZeroOrOne ( '' , successors = ( __child_sequence__ [ __child_sequence__ . index ( '' ) + : ] ) ) @ property def bottom_margin ( self ) : \"\"\"\"\"\" pgMar = self . pgMar if pgMar is None : return None return pgMar . bottom @ bottom_margin . setter def bottom_margin ( self , value ) : pgMar = self . get_or_add_pgMar ( ) pgMar . bottom = value def clone ( self ) : \"\"\"\"\"\" clone_sectPr = deepcopy ( self ) clone_sectPr . attrib . clear ( ) return clone_sectPr @ property def footer ( self ) : \"\"\"\"\"\" pgMar = self . pgMar if pgMar is None : return None return pgMar . footer @ footer . setter def footer ( self , value ) : pgMar = self . get_or_add_pgMar ( ) pgMar . footer = value @ property def gutter ( self ) : \"\"\"\"\"\" pgMar = self . pgMar if pgMar is None : return None return pgMar . gutter @ gutter . setter ", "answer": "def gutter ( self , value ) :"}, {"prompt": " from setuptools import setup , find_packages setup ( name = '' , version = '' , license = '' , packages = find_packages ( ) , include_package_data = True , ", "answer": "description = '' ,"}, {"prompt": " assert_has_feature ( ", "answer": " , , , '' ,"}, {"prompt": " from metakernel . tests . utils import ( get_kernel , get_log_text , clear_log_text , EvalKernel ) import re import os from metakernel . config import get_local_magics_dir filename = get_local_magics_dir ( ) + os . sep + \"\" def test_install_magic_magic ( ) : kernel = get_kernel ( EvalKernel ) kernel . do_execute ( \"\" ) text = get_log_text ( kernel ) assert re . match ( \"\" , text , re . DOTALL | re . M ) , \"\" assert os . path . isfile ( filename ) , ( \"\" % filename ) ", "answer": "def teardown ( ) :"}, {"prompt": " \"\"\"\"\"\" __docformat__ = '' COPYRIGHT = \"\"\"\"\"\" TITLE = __doc__ SOURCE = \"\"\"\"\"\" DESCRSHORT = \"\"\"\"\"\" DESCRLONG = \"\"\"\"\"\" NOTE = \"\"\"\"\"\" from numpy import recfromtxt , column_stack , array from statsmodels . datasets import utils as du from os . path import dirname , abspath def load ( ) : \"\"\"\"\"\" data = _get_data ( ) return du . process_recarray ( data , endog_idx = , dtype = float ) def load_pandas ( ) : \"\"\"\"\"\" data = _get_data ( ) return du . process_recarray_pandas ( data , endog_idx = , dtype = float ) ", "answer": "def _get_data ( ) :"}, {"prompt": " from pages . desktop . base import Base from selenium . webdriver . common . by import By class LoginPage ( Base ) : \"\"\"\"\"\" URL_TEMPLATE = '' _page_title = '' _username_box_locator = ( By . ID , '' ) _password_box_locator = ( By . ID , '' ) _log_in_button_locator = ( By . CSS_SELECTOR , \"\" ) _login_error_locator = ( By . CSS_SELECTOR , '' ) _logged_in_as_div_locator = ( By . CSS_SELECTOR , '' ) _logged_in_text = '' def log_in ( self , username , password ) : self . selenium . find_element ( * self . _username_box_locator ) . send_keys ( username ) self . selenium . find_element ( * self . _password_box_locator ) . send_keys ( password ) self . selenium . find_element ( * self . _log_in_button_locator ) . click ( ) ", "answer": "if not self . header . is_user_logged_in :"}, {"prompt": " import datetime import logging from threading import local from django . conf import settings from django . core import signals from django . db import models from django . db . models . signals import pre_delete , post_save , m2m_changed from django . dispatch import receiver from elasticutils . contrib . django import MappingType , Indexable , MLT from elasticsearch . exceptions import NotFoundError from kitsune . search import es_utils from kitsune . search . tasks import index_task , unindex_task from kitsune . sumo . models import ModelBase log = logging . getLogger ( '' ) _search_mapping_types = { } def get_mapping_types ( mapping_types = None ) : \"\"\"\"\"\" if mapping_types is None : values = _search_mapping_types . values ( ) else : values = [ _search_mapping_types [ name ] for name in mapping_types ] values . sort ( key = lambda cls : cls . get_mapping_type_name ( ) ) return values _local = local ( ) def _local_tasks ( ) : \"\"\"\"\"\" if getattr ( _local , '' , None ) is None : _local . tasks = set ( ) return _local . tasks class SearchMixin ( object ) : \"\"\"\"\"\" @ classmethod def get_mapping_type ( cls ) : \"\"\"\"\"\" raise NotImplementedError def index_later ( self ) : \"\"\"\"\"\" _local_tasks ( ) . add ( ( index_task . delay , ( self . get_mapping_type ( ) , ( self . pk , ) ) ) ) def unindex_later ( self ) : \"\"\"\"\"\" _local_tasks ( ) . add ( ( unindex_task . delay , ( self . get_mapping_type ( ) , ( self . pk , ) ) ) ) class SearchMappingType ( MappingType , Indexable ) : \"\"\"\"\"\" list_keys = [ ] @ classmethod def search ( cls ) : return es_utils . Sphilastic ( cls ) @ classmethod def get_index ( cls ) : return es_utils . write_index ( cls . get_index_group ( ) ) @ classmethod def get_index_group ( cls ) : return '' @ classmethod def get_query_fields ( cls ) : \"\"\"\"\"\" raise NotImplementedError @ classmethod def get_localized_fields ( cls ) : return [ ] @ classmethod def get_indexable ( cls ) : return cls . get_model ( ) . objects . order_by ( '' ) . values_list ( '' , flat = True ) @ classmethod def reshape ( cls , results ) : \"\"\"\"\"\" list_keys = cls . list_keys return [ dict ( ( key , ( val if key in list_keys else val [ ] ) ) for key , val in result . items ( ) ) for result in results ] @ classmethod def index ( cls , * args , ** kwargs ) : if not settings . ES_LIVE_INDEXING : return super ( SearchMappingType , cls ) . index ( * args , ** kwargs ) @ classmethod def unindex ( cls , * args , ** kwargs ) : if not settings . ES_LIVE_INDEXING : return try : super ( SearchMappingType , cls ) . unindex ( * args , ** kwargs ) except NotFoundError : pass @ classmethod def morelikethis ( cls , id_ , s , fields ) : \"\"\"\"\"\" return list ( MLT ( id_ , s , fields , min_term_freq = , min_doc_freq = ) ) def _identity ( s ) : return s def register_for_indexing ( app , sender_class , instance_to_indexee = _identity , m2m = False ) : \"\"\"\"\"\" def maybe_call_method ( instance , is_raw , method_name ) : \"\"\"\"\"\" obj = instance_to_indexee ( instance ) if obj is not None and not is_raw : getattr ( obj , method_name ) ( ) def update ( sender , instance , ** kw ) : \"\"\"\"\"\" maybe_call_method ( instance , kw . get ( '' ) , '' ) def delete ( sender , instance , ** kw ) : \"\"\"\"\"\" maybe_call_method ( instance , kw . get ( '' ) , '' ) def indexing_receiver ( signal , signal_name ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " \"\"\"\"\"\" ", "answer": "import json"}, {"prompt": " \"\"\"\"\"\" import os from os . path import join as pjoin import sys from functools import partial if os . path . exists ( '' ) : os . remove ( '' ) if len ( set ( ( '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ) ) . intersection ( sys . argv ) ) > : import setup_egg from distutils . core import setup from nisext . sexts import get_comrec_build , package_check , install_scripts_bat cmdclass = { '' : get_comrec_build ( '' ) , '' : install_scripts_bat } ver_file = os . path . join ( '' , '' ) exec ( open ( ver_file ) . read ( ) ) if '' in sys . modules : extra_setuptools_args = dict ( tests_require = [ '' ] , test_suite = '' , zip_safe = False , extras_require = dict ( doc = '' , test = '' ) , ) pkg_chk = partial ( package_check , setuptools_args = extra_setuptools_args ) else : extra_setuptools_args = { } pkg_chk = package_check pkg_chk ( '' , NUMPY_MIN_VERSION ) custom_pydicom_messages = { '' : '' '' } pkg_chk ( '' , PYDICOM_MIN_VERSION , optional = '' , messages = custom_pydicom_messages ) def main ( ** extra_args ) : setup ( name = NAME , maintainer = MAINTAINER , maintainer_email = MAINTAINER_EMAIL , description = DESCRIPTION , long_description = LONG_DESCRIPTION , url = URL , download_url = DOWNLOAD_URL , license = LICENSE , classifiers = CLASSIFIERS , author = AUTHOR , author_email = AUTHOR_EMAIL , platforms = PLATFORMS , version = VERSION , requires = REQUIRES , provides = PROVIDES , packages = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ] , ", "answer": "package_data = { '' :"}, {"prompt": " from box import BoundingBox , FloatBox from entity import Entity , TileEntity ", "answer": "from faces import faceDirections , FaceXDecreasing , FaceXIncreasing , FaceYDecreasing , FaceYIncreasing , FaceZDecreasing , FaceZIncreasing , MaxDirections"}, {"prompt": " \"\"\"\"\"\" from pyjamas . Canvas . CanvasGradientImplDefault import CanvasGradientImplDefault \"\"\"\"\"\" ", "answer": "class RadialGradientImplDefault ( CanvasGradientImplDefault ) :"}, {"prompt": " from django . contrib . staticfiles . urls import staticfiles_urlpatterns from django . conf . urls import patterns , include , url from django . core . urlresolvers import reverse , RegexURLPattern from django . conf import settings from django . conf . urls . i18n import i18n_patterns ", "answer": "from django . utils import importlib"}, {"prompt": " import logging from gevent import Greenlet , sleep from shaveet . config import MAX_CLIENTS_GC , CLIENT_GC_INTERVAL from shaveet . lookup import all_clients , discard_client ", "answer": "logger = logging . getLogger ( \"\" )"}, {"prompt": " \"\"\"\"\"\" __docformat__ = '' import re , types , sys from epydoc import log from epydoc . util import plaintext_to_html , plaintext_to_latex import epydoc from epydoc . compat import * _markup_language_registry = { '' : '' , '' : '' , '' : '' , '' : '' , } def register_markup_language ( name , parse_function ) : \"\"\"\"\"\" _markup_language_registry [ name . lower ( ) ] = parse_function MARKUP_LANGUAGES_USED = set ( ) def parse ( docstring , markup = '' , errors = None , ** options ) : \"\"\"\"\"\" raise_on_error = ( errors is None ) if errors == None : errors = [ ] markup = markup . lower ( ) if not re . match ( r'' , markup ) : _parse_warn ( '' '' % markup ) import epydoc . markup . plaintext as plaintext return plaintext . parse_docstring ( docstring , errors , ** options ) if markup not in _markup_language_registry : _parse_warn ( '' '' % markup ) import epydoc . markup . plaintext as plaintext return plaintext . parse_docstring ( docstring , errors , ** options ) parse_docstring = _markup_language_registry [ markup ] if isinstance ( parse_docstring , basestring ) : try : exec ( '' % parse_docstring ) except ImportError , e : _parse_warn ( '' % ( parse_docstring , markup , e ) ) import epydoc . markup . plaintext as plaintext return plaintext . parse_docstring ( docstring , errors , ** options ) _markup_language_registry [ markup ] = parse_docstring MARKUP_LANGUAGES_USED . add ( markup ) try : parsed_docstring = parse_docstring ( docstring , errors , ** options ) except KeyboardInterrupt : raise except Exception , e : if epydoc . DEBUG : raise log . error ( '' '' % e ) import epydoc . markup . plaintext as plaintext return plaintext . parse_docstring ( docstring , errors , ** options ) fatal_errors = [ e for e in errors if e . is_fatal ( ) ] if fatal_errors and raise_on_error : raise fatal_errors [ ] if fatal_errors : import epydoc . markup . plaintext as plaintext return plaintext . parse_docstring ( docstring , errors , ** options ) return parsed_docstring _parse_warnings = { } def _parse_warn ( estr ) : \"\"\"\"\"\" global _parse_warnings if estr in _parse_warnings : return _parse_warnings [ estr ] = log . warning ( estr ) class ParsedDocstring : \"\"\"\"\"\" def split_fields ( self , errors = None ) : \"\"\"\"\"\" return self , [ ] def summary ( self ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " import shutil from filebrowser . decorators import get_path , get_file from filebrowser . sites import site from tests import FilebrowserTestCase as TestCase class GetPathTests ( TestCase ) : def test_empty ( self ) : self . assertEqual ( get_path ( '' , site ) , '' ) def test_starts_with_period ( self ) : self . assertIsNone ( get_path ( '' , site ) ) self . assertIsNone ( get_path ( '' , site ) ) def test_is_absolute ( self ) : self . assertIsNone ( get_path ( '' , site ) ) self . assertIsNone ( get_path ( '' , site ) ) def test_does_not_exist ( self ) : self . assertIsNone ( get_path ( '' , site ) ) def test_valid ( self ) : ", "answer": "self . assertTrue ( get_path ( '' , site ) )"}, {"prompt": " \"\"\"\"\"\" from __future__ import division import numpy as np from sklearn . neighbors import NearestNeighbors def smote ( T , N = , k = ) : \"\"\"\"\"\" if T . shape [ ] <= k + : idx = np . random . choice ( T . shape [ ] , size = ( k + , ) ) T = T [ idx , : ] if N < : sz = int ( T . shape [ ] * ( N / ) ) idx = np . random . choice ( T . shape [ ] , size = ( sz , ) , replace = False ) T = T [ idx , : ] N = if N % != : raise ValueError ( '' ) N = int ( N / ) n_minority_samples , n_features = T . shape ", "answer": "n_synthetic_samples = N * n_minority_samples"}, {"prompt": " from __future__ import ( absolute_import , division , generators , nested_scopes , print_function , unicode_literals , with_statement ) import os import re import subprocess from pants . backend . codegen . subsystems . thrift_defaults import ThriftDefaults from pants . backend . codegen . tasks . simple_codegen_task import SimpleCodegenTask from pants . base . build_environment import get_buildroot from pants . base . exceptions import TaskError from pants . base . workunit import WorkUnitLabel from pants . binaries . thrift_binary import ThriftBinary from pants . util . dirutil import safe_mkdir from pants . util . memo import memoized_property from twitter . common . collections import OrderedSet from pants . contrib . go . targets . go_thrift_library import GoThriftGenLibrary , GoThriftLibrary class GoThriftGen ( SimpleCodegenTask ) : @ classmethod def register_options ( cls , register ) : super ( GoThriftGen , cls ) . register_options ( register ) register ( '' , default = True , fingerprint = True , type = bool , help = '' ) register ( '' , advanced = True , fingerprint = True , help = '' ) register ( '' , advanced = True , help = '' ) register ( '' , advanced = True , help = '' ) @ classmethod def global_subsystems ( cls ) : return super ( GoThriftGen , cls ) . global_subsystems ( ) + ( ThriftDefaults , ) @ classmethod def task_subsystems ( cls ) : return super ( GoThriftGen , cls ) . task_subsystems ( ) + ( ThriftBinary . Factory , ) ", "answer": "@ classmethod"}, {"prompt": " \"\"\"\"\"\" import argparse import unittest import mock import gce_cluster from gce_cluster import GceCluster class GceClusterTest ( unittest . TestCase ) : \"\"\"\"\"\" def tearDown ( self ) : mock . patch . stopall ( ) def _SetUpMocksForClusterStart ( self ) : \"\"\"\"\"\" mock_gce_api_class = mock . patch ( '' ) . start ( ) mock_subprocess_call = mock . patch ( '' , return_value = ) . start ( ) mock_popen = mock . patch ( '' ) . start ( ) mock_popen . return_value . returncode = None mock_popen . return_value . poll . return_value = mock_builtin_open = mock . patch ( '' ) . start ( ) mock_sleep = mock . patch ( '' ) . start ( ) parent_mock = mock . MagicMock ( ) parent_mock . attach_mock ( mock_gce_api_class , '' ) parent_mock . attach_mock ( mock_gce_api_class . return_value . CreateInstance , '' ) parent_mock . attach_mock ( mock_gce_api_class . return_value . GetInstance , '' ) parent_mock . attach_mock ( mock_gce_api_class . return_value . CreateDisk , '' ) parent_mock . attach_mock ( mock_gce_api_class . return_value . GetDisk , '' ) parent_mock . attach_mock ( mock_subprocess_call , '' ) parent_mock . attach_mock ( mock_popen , '' ) parent_mock . attach_mock ( mock_popen . return_value . poll , '' ) parent_mock . attach_mock ( mock_builtin_open , '' ) parent_mock . attach_mock ( mock_sleep , '' ) mock_gce_api_class . return_value . GetInstance . return_value = { '' : '' , '' : [ { '' : [ { '' : '' , } ] , } ] , } mock_gce_api_class . return_value . GetDisk . side_effect = [ None , { '' : '' } , None , { '' : '' } , None , { '' : '' } , None , { '' : '' } , None , { '' : '' } , None , { '' : '' } , ] return parent_mock def testEnvironmentSetUp_Success ( self ) : \"\"\"\"\"\" with mock . patch ( '' , return_value = ) as mock_subprocess_call : GceCluster ( argparse . Namespace ( project = '' , bucket = '' ) ) . EnvironmentSetUp ( ) mock_subprocess_call . assert_called_once_with ( mock . ANY , shell = True ) self . assertRegexpMatches ( mock_subprocess_call . call_args [ ] [ ] , '' ) def testEnvironmentSetUp_Error ( self ) : \"\"\"\"\"\" with mock . patch ( '' , return_value = ) as mock_subprocess_call : self . assertRaises ( gce_cluster . EnvironmentSetUpError , GceCluster ( argparse . Namespace ( project = '' , bucket = '' ) ) . EnvironmentSetUp ) mock_subprocess_call . assert_called_once_with ( mock . ANY , shell = True ) self . assertRegexpMatches ( mock_subprocess_call . call_args [ ] [ ] , '' ) def testStartCluster ( self ) : \"\"\"\"\"\" parent_mock = self . _SetUpMocksForClusterStart ( ) GceCluster ( argparse . Namespace ( project = '' , bucket = '' , machinetype = '' , image = '' , zone = '' , num_workers = , command = '' , external_ip = '' ) ) . StartCluster ( ) method_calls = parent_mock . method_calls . __iter__ ( ) call = method_calls . next ( ) self . assertEqual ( '' , call [ ] ) call = method_calls . next ( ) self . assertEqual ( '' , call [ ] ) self . assertEqual ( '' , call [ ] [ ] ) call = method_calls . next ( ) self . assertEqual ( '' , call [ ] ) self . assertEqual ( '' , call [ ] [ ] ) call = method_calls . next ( ) self . assertEqual ( '' , call [ ] ) self . assertEqual ( '' , call [ ] [ ] ) call = method_calls . next ( ) self . assertEqual ( '' , call [ ] ) self . assertEqual ( '' , call [ ] [ ] ) call = method_calls . next ( ) self . assertEqual ( '' , call [ ] ) self . assertEqual ( '' , call [ ] [ ] ) call = method_calls . next ( ) self . assertEqual ( '' , call [ ] ) self . assertEqual ( '' , call [ ] [ ] ) call = method_calls . next ( ) self . assertEqual ( '' , call [ ] ) self . assertRegexpMatches ( call [ ] [ ] , '' ) call = method_calls . next ( ) self . assertEqual ( '' , call [ ] ) self . assertRegexpMatches ( call [ ] [ ] , '' ) call = method_calls . next ( ) self . assertEqual ( '' , call [ ] ) self . assertRegexpMatches ( call [ ] [ ] , '' ) call = method_calls . next ( ) self . assertEqual ( '' , call [ ] ) self . assertEqual ( '' , call [ ] [ ] ) self . assertTrue ( call [ ] [ '' ] ) self . assertFalse ( call [ ] [ '' ] ) call = method_calls . next ( ) self . assertEqual ( '' , call [ ] ) self . assertEqual ( '' , call [ ] [ ] ) call = method_calls . next ( ) self . assertEqual ( '' , call [ ] ) self . assertRegexpMatches ( call [ ] [ ] , '' ) call = method_calls . next ( ) self . assertEqual ( '' , call [ ] ) self . assertEqual ( '' , call [ ] [ ] ) call = method_calls . next ( ) self . assertEqual ( '' , call [ ] ) self . assertEqual ( '' , call [ ] [ ] ) call = method_calls . next ( ) self . assertEqual ( '' , call [ ] ) self . assertEqual ( '' , call [ ] [ ] ) call = method_calls . next ( ) self . assertEqual ( '' , call [ ] ) self . assertEqual ( '' , call [ ] [ ] ) call = method_calls . next ( ) self . assertEqual ( '' , call [ ] ) self . assertEqual ( '' , call [ ] [ ] ) call = method_calls . next ( ) self . assertEqual ( '' , call [ ] ) self . assertEqual ( '' , call [ ] [ ] ) call = method_calls . next ( ) self . assertEqual ( '' , call [ ] ) self . assertEqual ( '' , call [ ] [ ] ) self . assertTrue ( call [ ] [ '' ] ) self . assertFalse ( call [ ] [ '' ] ) call = method_calls . next ( ) self . assertEqual ( '' , call [ ] ) self . assertEqual ( '' , call [ ] [ ] ) call = method_calls . next ( ) self . assertEqual ( '' , call [ ] ) self . assertEqual ( '' , call [ ] [ ] ) call = method_calls . next ( ) self . assertEqual ( '' , call [ ] ) self . assertEqual ( '' , call [ ] [ ] ) call = method_calls . next ( ) self . assertEqual ( '' , call [ ] ) self . assertEqual ( '' , call [ ] [ ] ) call = method_calls . next ( ) self . assertEqual ( '' , call [ ] ) self . assertEqual ( '' , call [ ] [ ] ) call = method_calls . next ( ) self . assertEqual ( '' , call [ ] ) self . assertEqual ( '' , call [ ] [ ] ) call = method_calls . next ( ) self . assertEqual ( '' , call [ ] ) self . assertEqual ( '' , call [ ] [ ] ) self . assertTrue ( call [ ] [ '' ] ) self . assertFalse ( call [ ] [ '' ] ) call = method_calls . next ( ) self . assertEqual ( '' , call [ ] ) self . assertEqual ( '' , call [ ] [ ] ) call = method_calls . next ( ) self . assertEqual ( '' , call [ ] ) self . assertEqual ( '' , call [ ] [ ] ) call = method_calls . next ( ) self . assertEqual ( '' , call [ ] ) self . assertEqual ( '' , call [ ] [ ] ) self . assertRaises ( StopIteration , method_calls . next ) def testStartCluster_NoExternalIp ( self ) : \"\"\"\"\"\" parent_mock = self . _SetUpMocksForClusterStart ( ) GceCluster ( argparse . Namespace ( project = '' , bucket = '' , machinetype = '' , image = '' , zone = '' , num_workers = , command = '' , external_ip = '' ) ) . StartCluster ( ) call = parent_mock . method_calls [ ] self . assertEqual ( '' , call [ ] ) self . assertEqual ( '' , call [ ] [ ] ) self . assertTrue ( call [ ] [ '' ] ) self . assertTrue ( call [ ] [ '' ] ) call = parent_mock . method_calls [ ] self . assertEqual ( '' , call [ ] ) self . assertEqual ( '' , call [ ] [ ] ) self . assertFalse ( call [ ] [ '' ] ) self . assertFalse ( call [ ] [ '' ] ) call = parent_mock . method_calls [ ] self . assertEqual ( '' , call [ ] ) self . assertEqual ( '' , call [ ] [ ] ) self . assertFalse ( call [ ] [ '' ] ) self . assertFalse ( call [ ] [ '' ] ) def testStartCluster_InstanceStatusError ( self ) : \"\"\"\"\"\" parent_mock = self . _SetUpMocksForClusterStart ( ) parent_mock . GceApi . return_value . GetInstance . return_value = { '' : '' , } self . assertRaises ( gce_cluster . ClusterSetUpError , gce_cluster . GceCluster ( argparse . Namespace ( project = '' , bucket = '' , machinetype = '' , image = '' , zone = '' , num_workers = , command = '' , external_ip = '' ) ) . StartCluster ) self . assertLessEqual ( , parent_mock . GetInstance . call_count ) self . assertLessEqual ( , parent_mock . sleep . call_count ) def testTeardownCluster ( self ) : \"\"\"\"\"\" with mock . patch ( '' ) as mock_gce_api_class : mock_gce_api_class . return_value . ListInstances . side_effect = [ [ { '' : '' } , ", "answer": "{ '' : '' } ,"}, {"prompt": " from django . contrib . auth . decorators import login_required from django . core . paginator import Paginator , EmptyPage , PageNotAnInteger from django . shortcuts import render , get_object_or_404 , redirect from actstream import models from raspberryio . userprofile . models import Profile from django . contrib . auth import login as auth_login from django . contrib . messages import info from django . utils . translation import ugettext_lazy as _ from django . views . decorators . cache import cache_page from django . views . decorators . csrf import csrf_protect from mezzanine . utils . models import get_user_model from mezzanine . accounts . forms import LoginForm from mezzanine . utils . urls import login_redirect User = get_user_model ( ) @ cache_page ( * ) @ csrf_protect def login ( request , template = \"\" ) : \"\"\"\"\"\" form = LoginForm ( request . POST or None ) if request . method == \"\" and form . is_valid ( ) : authenticated_user = form . save ( ) info ( request , _ ( \"\" ) ) auth_login ( request , authenticated_user ) return login_redirect ( request ) context = { \"\" : form , \"\" : _ ( \"\" ) } return render ( request , template , context ) def profile_related_list ( request , username , relation ) : \"\" profile = get_object_or_404 ( Profile , user__username__iexact = username ) user = profile . user if relation == '' : related_users = models . followers ( user ) elif relation == '' : related_users = models . following ( user ) paginator = Paginator ( related_users , ) page = request . GET . get ( '' ) try : related_users = paginator . page ( page ) except PageNotAnInteger : related_users = paginator . page ( ) except EmptyPage : related_users = paginator . page ( paginator . num_pages ) return render ( request , \"\" , { '' : user , '' : profile , '' : related_users , } ) def profile_actions ( request , username ) : \"\" profile = get_object_or_404 ( Profile , user__username__iexact = username ) user = profile . user return render ( request , \"\" , { '' : user , '' : profile , '' : models . actor_stream ( user ) , } ) @ login_required ", "answer": "def profile_dashboard ( request ) :"}, {"prompt": " import six from flask import Flask , jsonify , abort , request , make_response , url_for from flask . ext . httpauth import HTTPBasicAuth app = Flask ( __name__ , static_url_path = \"\" ) auth = HTTPBasicAuth ( ) @ auth . get_password def get_password ( username ) : if username == '' : return '' return None @ auth . error_handler def unauthorized ( ) : return make_response ( jsonify ( { '' : '' } ) , ) @ app . errorhandler ( ) def bad_request ( error ) : return make_response ( jsonify ( { '' : '' } ) , ) @ app . errorhandler ( ) def not_found ( error ) : return make_response ( jsonify ( { '' : '' } ) , ) tasks = [ { '' : , '' : u'' , '' : u'' , '' : False } , { '' : , '' : u'' , '' : u'' , '' : False } ] def make_public_task ( task ) : new_task = { } for field in task : if field == '' : new_task [ '' ] = url_for ( '' , task_id = task [ '' ] , _external = True ) else : new_task [ field ] = task [ field ] return new_task @ app . route ( '' , methods = [ '' ] ) @ auth . login_required def get_tasks ( ) : ", "answer": "return jsonify ( { '' : [ make_public_task ( task ) for task in tasks ] } )"}, {"prompt": " from __future__ import ( absolute_import , division , generators , nested_scopes , print_function , unicode_literals , with_statement ) import os import re from contextlib import contextmanager from textwrap import dedent from six . moves import range from twitter . common . collections import maybe_list from pants . backend . jvm . targets . java_agent import JavaAgent from pants . backend . jvm . targets . jvm_binary import JvmBinary from pants . backend . jvm . tasks . jar_task import JarBuilderTask , JarTask from pants . build_graph . build_file_aliases import BuildFileAliases from pants . util . contextutil import open_zip , temporary_dir , temporary_file from pants . util . dirutil import safe_mkdir , safe_mkdtemp , safe_rmtree from pants_test . jvm . jar_task_test_base import JarTaskTestBase class BaseJarTaskTest ( JarTaskTestBase ) : @ property def alias_groups ( self ) : return super ( BaseJarTaskTest , self ) . alias_groups . merge ( BuildFileAliases ( targets = { '' : JavaAgent , '' : JvmBinary , } , ) ) def setUp ( self ) : super ( BaseJarTaskTest , self ) . setUp ( ) self . workdir = safe_mkdtemp ( ) self . jar_task = self . prepare_execute ( self . context ( ) ) def tearDown ( self ) : super ( BaseJarTaskTest , self ) . tearDown ( ) if self . workdir : safe_rmtree ( self . workdir ) @ contextmanager def jarfile ( self ) : with temporary_file ( root_dir = self . workdir , suffix = '' ) as fd : fd . close ( ) yield fd . name def assert_listing ( self , jar , * expected_items ) : self . assertEquals ( { '' , '' } | set ( expected_items ) , set ( jar . namelist ( ) ) ) class JarTaskTest ( BaseJarTaskTest ) : MAX_SUBPROC_ARGS = class TestJarTask ( JarTask ) : def execute ( self ) : pass @ classmethod def task_type ( cls ) : return cls . TestJarTask def setUp ( self ) : super ( JarTaskTest , self ) . setUp ( ) self . set_options ( max_subprocess_args = self . MAX_SUBPROC_ARGS ) self . jar_task = self . prepare_execute ( self . context ( ) ) def test_update_write ( self ) : with temporary_dir ( ) as chroot : _path = os . path . join ( chroot , '' ) safe_mkdir ( _path ) data_file = os . path . join ( _path , '' ) with open ( data_file , '' ) as fd : fd . write ( '' ) with self . jarfile ( ) as existing_jarfile : with self . jar_task . open_jar ( existing_jarfile ) as jar : jar . write ( data_file , '' ) with open_zip ( existing_jarfile ) as jar : self . assert_listing ( jar , '' , '' , '' ) self . assertEquals ( '' , jar . read ( '' ) ) def test_update_writestr ( self ) : def assert_writestr ( path , contents , * entries ) : with self . jarfile ( ) as existing_jarfile : with self . jar_task . open_jar ( existing_jarfile ) as jar : jar . writestr ( path , contents ) with open_zip ( existing_jarfile ) as jar : self . assert_listing ( jar , * entries ) self . assertEquals ( contents , jar . read ( path ) ) assert_writestr ( '' , b'' , '' ) assert_writestr ( '' , b'' , '' , '' , '' ) def test_overwrite_write ( self ) : with temporary_dir ( ) as chroot : _path = os . path . join ( chroot , '' ) safe_mkdir ( _path ) data_file = os . path . join ( _path , '' ) with open ( data_file , '' ) as fd : fd . write ( '' ) with self . jarfile ( ) as existing_jarfile : with self . jar_task . open_jar ( existing_jarfile , overwrite = True ) as jar : jar . write ( data_file , '' ) with open_zip ( existing_jarfile ) as jar : self . assert_listing ( jar , '' , '' , '' ) self . assertEquals ( '' , jar . read ( '' ) ) def test_overwrite_writestr ( self ) : with self . jarfile ( ) as existing_jarfile : with self . jar_task . open_jar ( existing_jarfile , overwrite = True ) as jar : jar . writestr ( '' , b'' ) with open_zip ( existing_jarfile ) as jar : self . assert_listing ( jar , '' ) self . assertEquals ( '' , jar . read ( '' ) ) def test_custom_manifest ( self ) : contents = b'' with self . jarfile ( ) as existing_jarfile : with self . jar_task . open_jar ( existing_jarfile , overwrite = True ) as jar : jar . writestr ( '' , b'' ) with open_zip ( existing_jarfile ) as jar : self . assert_listing ( jar , '' ) self . assertEquals ( '' , jar . read ( '' ) ) self . assertNotEqual ( contents , jar . read ( '' ) ) with self . jar_task . open_jar ( existing_jarfile , overwrite = False ) as jar : jar . writestr ( '' , contents ) with open_zip ( existing_jarfile ) as jar : self . assert_listing ( jar , '' ) self . assertEquals ( '' , jar . read ( '' ) ) self . assertEquals ( contents , jar . read ( '' ) ) def test_classpath ( self ) : def manifest_content ( classpath ) : return ( b'' + b'' + b'' ) . format ( '' . join ( maybe_list ( classpath ) ) ) def assert_classpath ( classpath ) : with self . jarfile ( ) as existing_jarfile : with self . jar_task . open_jar ( existing_jarfile ) as jar : jar . append_classpath ( os . path . join ( self . workdir , '' ) ) with self . jar_task . open_jar ( existing_jarfile ) as jar : jar . append_classpath ( [ os . path . join ( self . workdir , jar_path ) for jar_path in classpath ] ) with open_zip ( existing_jarfile ) as jar : self . assertEqual ( manifest_content ( classpath ) , jar . read ( '' ) ) assert_classpath ( [ '' ] ) assert_classpath ( [ '' , '' ] ) def test_update_jars ( self ) : with self . jarfile ( ) as main_jar : with self . jarfile ( ) as included_jar : with self . jar_task . open_jar ( main_jar ) as jar : jar . writestr ( '' , b'' ) with self . jar_task . open_jar ( included_jar ) as jar : jar . writestr ( '' , b'' ) with self . jar_task . open_jar ( main_jar ) as jar : jar . writejar ( included_jar ) with open_zip ( main_jar ) as jar : self . assert_listing ( jar , '' , '' , '' , '' ) def test_overwrite_jars ( self ) : with self . jarfile ( ) as main_jar : with self . jarfile ( ) as included_jar : with self . jar_task . open_jar ( main_jar ) as jar : jar . writestr ( '' , b'' ) with self . jar_task . open_jar ( included_jar ) as jar : jar . writestr ( '' , b'' ) with self . jar_task . open_jar ( main_jar , overwrite = True ) as jar : for i in range ( self . MAX_SUBPROC_ARGS + ) : jar . writejar ( included_jar ) with open_zip ( main_jar ) as jar : self . assert_listing ( jar , '' , '' ) class JarBuilderTest ( BaseJarTaskTest ) : class TestJarBuilderTask ( JarBuilderTask ) : def execute ( self ) : pass @ classmethod def task_type ( cls ) : return cls . TestJarBuilderTask def setUp ( self ) : super ( JarBuilderTest , self ) . setUp ( ) self . set_options ( max_subprocess_args = ) def test_agent_manifest ( self ) : self . add_to_build_file ( '' , dedent ( \"\"\"\"\"\" ) . strip ( ) ) java_agent = self . target ( '' ) context = self . context ( target_roots = [ java_agent ] ) jar_builder_task = self . prepare_execute ( context ) self . add_to_runtime_classpath ( context , java_agent , { '' : '' } ) with self . jarfile ( ) as existing_jarfile : with jar_builder_task . open_jar ( existing_jarfile ) as jar : ", "answer": "with jar_builder_task . create_jar_builder ( jar ) as jar_builder :"}, {"prompt": " try : import cPickle as pickle except ImportError : import pickle import hashlib from django . conf import settings from django . utils . crypto import salted_hmac def security_hash ( request , form , * args ) : \"\"\"\"\"\" import warnings warnings . warn ( \"\" , ", "answer": "DeprecationWarning )"}, {"prompt": " \"\"\"\"\"\" __all__ = [ \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , ", "answer": "\"\" ,"}, {"prompt": " from servent import * class PeerManager : ", "answer": "def __init__ ( self , argv , peergov ) :"}, {"prompt": " __author__ = '' import matplotlib as mpl import matplotlib . pyplot as plt def remove_chartjunk ( ax , spines , grid = None , ticklabels = None , show_ticks = False , xkcd = False ) : '''''' all_spines = [ '' , '' , '' , '' , '' ] for spine in spines : try : ax . spines [ spine ] . set_visible ( False ) except KeyError : pass if not xkcd : for spine in set ( all_spines ) . difference ( set ( spines ) ) : try : ax . spines [ spine ] . set_linewidth ( ) except KeyError : pass x_pos = set ( [ '' , '' ] ) y_pos = set ( [ '' , '' ] ) xy_pos = [ x_pos , y_pos ] xy_ax_names = [ '' , '' ] for ax_name , pos in zip ( xy_ax_names , xy_pos ) : axis = ax . __dict__ [ ax_name ] if show_ticks or axis . get_scale ( ) == '' : for p in pos . difference ( spines ) : axis . set_tick_params ( direction = '' ) axis . set_ticks_position ( p ) else : axis . set_ticks_position ( '' ) if grid is not None : for g in grid : assert g in ( '' , '' ) ax . grid ( axis = grid , color = '' , linestyle = '' , linewidth = ) if ticklabels is not None : if type ( ticklabels ) is str : assert ticklabels in set ( ( '' , '' ) ) if ticklabels == '' : ax . set_xticklabels ( [ ] ) if ticklabels == '' : ax . set_yticklabels ( [ ] ) else : assert set ( ticklabels ) | set ( ( '' , '' ) ) > if '' in ticklabels : ax . set_xticklabels ( [ ] ) elif '' in ticklabels : ax . set_yticklabels ( [ ] ) def maybe_get_ax ( * args , ** kwargs ) : \"\"\"\"\"\" if '' in kwargs : ax = kwargs . pop ( '' ) elif len ( args ) == : fig = plt . gcf ( ) ax = plt . gca ( ) elif isinstance ( args [ ] , mpl . axes . Axes ) : ax = args [ ] args = args [ : ] else : ", "answer": "ax = plt . gca ( )"}, {"prompt": " \"\"\"\"\"\" import os import re import shutil import tempfile import sqlite3 import cPickle import base64 import zlib import xmlrpclib import SocketServer import socket from SimpleXMLRPCServer import ( SimpleXMLRPCServer , SimpleXMLRPCRequestHandler ) try : from sage . rings . all import is_Integer , is_RealNumber except : is_Integer = lambda x : False is_RealNumber = lambda x : False class VerifyingServer ( SocketServer . ForkingMixIn , SimpleXMLRPCServer ) : def __init__ ( self , username , password , * args , ** kargs ) : self . username = username self . password = password class VerifyingRequestHandler ( SimpleXMLRPCRequestHandler ) : def parse_request ( myself ) : if SimpleXMLRPCRequestHandler . parse_request ( myself ) : if self . authenticate ( myself . headers ) : return True else : myself . send_error ( , '' ) return False SimpleXMLRPCServer . __init__ ( self , requestHandler = VerifyingRequestHandler , logRequests = False , * args , ** kargs ) def authenticate ( self , headers ) : ( basic , _ , encoded ) = headers . get ( '' ) . partition ( '' ) assert basic == '' , '' ( username , _ , password ) = base64 . b64decode ( encoded ) . partition ( '' ) return username == self . username and password == self . password class Server ( object ) : \"\"\"\"\"\" _test_mode = False def __init__ ( self , username = '' , password = '' , directory = '' , address = \"\" , port = , auto_run = True ) : \"\"\"\"\"\" if '' in username or '' in password or '' in address or '' in directory : raise ValueError , '' self . pid = self . test = self . __class__ . _test_mode if self . test : directory = tempfile . mkdtemp ( ) self . directory = str ( directory ) self . username = username self . password = password if not os . path . exists ( directory ) : os . makedirs ( directory ) self . address = str ( address ) self . port = int ( port ) self . _dbs = { } if auto_run : self . _run ( ) def __del__ ( self ) : try : self . quit ( ) finally : if hasattr ( self , '' ) and self . test : shutil . rmtree ( self . directory , ignore_errors = True ) def db ( self , file ) : \"\"\"\"\"\" try : return self . _dbs [ file ] except KeyError : db = sqlite3 . connect ( file ) self . _dbs [ file ] = db return db def quit ( self ) : \"\"\"\"\"\" if hasattr ( self , '' ) and self . pid : os . kill ( self . pid , ) self . pid = def _run ( self , max_tries = ) : \"\"\"\"\"\" port = self . port success = False for i in range ( max_tries ) : try : server = VerifyingServer ( self . username , self . password , ( self . address , port ) , allow_none = True ) success = True break except socket . error : port += if not success : raise RuntimeError ( \"\" ) self . port = port pid = os . fork ( ) if pid != : self . pid = pid self . port = port return port def execute ( cmds , t , file = '' , many = False ) : db = self . db ( os . path . join ( self . directory , file ) if file != '' else file ) cursor = db . cursor ( ) if isinstance ( cmds , str ) : if t is not None : cmds = [ ( cmds , t ) ] else : cmds = [ cmds ] v = [ ] for c in cmds : try : if isinstance ( c , tuple ) : o = cursor . executemany ( * c ) if many else cursor . execute ( * c ) else : o = cursor . execute ( c ) except sqlite3 . OperationalError , e : raise RuntimeError ( \"\" % e ) v . extend ( list ( o ) ) db . commit ( ) return v server . register_function ( execute , '' ) server . serve_forever ( ) def help ( self ) : \"\"\"\"\"\" fqdn = socket . getfqdn ( ) print ( \"\" * ) print ( self ) s = \"\" % ( self . port , self . username ) if self . address != '' : s += \"\" % self . address else : s += \"\" print s print ( \"\" ) if self . address == '' : print ( \"\" ) print ( \"\" ) print ( \"\" % ( self . port , self . port , fqdn ) ) print ( \"\" ) print ( \"\" % ( self . port , self . username ) ) print ( \"\" ) print ( \"\" % os . getpid ( ) ) print ( \"\" * ) def __repr__ ( self ) : \"\"\"\"\"\" if self . pid == : return \"\" s = \"\" % self . port if self . address != '' : s += '' % self . address return s class LocalServer ( object ) : def __init__ ( self , directory ) : self . directory = directory self . _dbs = { } if not os . path . exists ( directory ) : os . makedirs ( directory ) def db ( self , file ) : try : return self . _dbs [ file ] except KeyError : db = sqlite3 . connect ( file ) self . _dbs [ file ] = db return db def execute ( self , cmds , t , file = '' , many = False ) : db = self . db ( os . path . join ( self . directory , file ) if file != '' else file ) cursor = db . cursor ( ) if isinstance ( cmds , str ) : if t is not None : cmds = [ ( cmds , t ) ] else : cmds = [ cmds ] v = [ ] for c in cmds : try : if isinstance ( c , tuple ) : o = cursor . executemany ( * c ) if many else cursor . execute ( * c ) else : o = cursor . execute ( c ) except sqlite3 . OperationalError , e : raise RuntimeError ( \"\" % e ) v . extend ( list ( o ) ) db . commit ( ) return v socket . setdefaulttimeout ( ) class Client ( object ) : \"\"\"\"\"\" def __init__ ( self , port_or_dir = , username = '' , password = '' , address = \"\" ) : \"\"\"\"\"\" if '' in str ( port_or_dir ) or '' in username or '' in password or '' in address : raise ValueError , '' if isinstance ( port_or_dir , str ) : self . server = LocalServer ( port_or_dir ) else : self . address = str ( address ) self . port = int ( port_or_dir ) self . server = xmlrpclib . Server ( '' % ( username , password , address , self . port ) , allow_none = True ) def __repr__ ( self ) : \"\"\"\"\"\" s = \"\" % self . port if self . address != '' : s += '' % self . address return s def __call__ ( self , cmd , t = None , file = '' , many = False , coerce = True ) : \"\"\"\"\"\" if not isinstance ( cmd , str ) : raise TypeError ( \"\" % cmd ) if coerce : if many : t = [ tuple ( [ self . _coerce_ ( x ) for x in y ] ) for y in t ] else : if t is not None : t = tuple ( [ self . _coerce_ ( x ) for x in t ] ) try : return self . server . execute ( cmd , t , file , many ) except xmlrpclib . Fault , e : raise RuntimeError , str ( e ) + '' % cmd def __getattr__ ( self , name ) : \"\"\"\"\"\" if name == '' : name = '' return Database ( self , name ) def _coerce_ ( self , x ) : \"\"\"\"\"\" if isinstance ( x , bool ) : x = int ( x ) elif isinstance ( x , ( str , int , long , float ) ) : pass elif x is None : pass elif is_Integer ( x ) and x . nbits ( ) < : x = int ( x ) elif is_RealNumber ( x ) and x . prec ( ) == : return float ( x ) elif isinstance ( x , unicode ) : return str ( x ) else : x = '' + base64 . b64encode ( zlib . compress ( cPickle . dumps ( x , ) ) ) ", "answer": "return x"}, {"prompt": " from twisted . internet import defer from . _base import BaseHandler from synapse . api . constants import LoginType from synapse . types import UserID from synapse . api . errors import AuthError , LoginError , Codes from synapse . util . async import run_on_reactor from twisted . web . client import PartialDownloadError import logging import bcrypt import pymacaroons import simplejson import synapse . util . stringutils as stringutils logger = logging . getLogger ( __name__ ) class AuthHandler ( BaseHandler ) : SESSION_EXPIRE_MS = * * * def __init__ ( self , hs ) : super ( AuthHandler , self ) . __init__ ( hs ) self . checkers = { LoginType . PASSWORD : self . _check_password_auth , LoginType . RECAPTCHA : self . _check_recaptcha , LoginType . EMAIL_IDENTITY : self . _check_email_identity , LoginType . DUMMY : self . _check_dummy_auth , } self . bcrypt_rounds = hs . config . bcrypt_rounds self . sessions = { } self . INVALID_TOKEN_HTTP_STATUS = @ defer . inlineCallbacks def check_auth ( self , flows , clientdict , clientip ) : \"\"\"\"\"\" authdict = None sid = None if clientdict and '' in clientdict : authdict = clientdict [ '' ] del clientdict [ '' ] if '' in authdict : sid = authdict [ '' ] session = self . _get_session_info ( sid ) if len ( clientdict ) > : session [ '' ] = clientdict self . _save_session ( session ) elif '' in session : clientdict = session [ '' ] if not authdict : defer . returnValue ( ( False , self . _auth_dict_for_flows ( flows , session ) , clientdict , session [ '' ] ) ) if '' not in session : session [ '' ] = { } creds = session [ '' ] if '' in authdict : if authdict [ '' ] not in self . checkers : raise LoginError ( , \"\" , Codes . UNRECOGNIZED ) result = yield self . checkers [ authdict [ '' ] ] ( authdict , clientip ) if result : creds [ authdict [ '' ] ] = result self . _save_session ( session ) for f in flows : if len ( set ( f ) - set ( creds . keys ( ) ) ) == : logger . info ( \"\" , creds ) defer . returnValue ( ( True , creds , clientdict , session [ '' ] ) ) ret = self . _auth_dict_for_flows ( flows , session ) ret [ '' ] = creds . keys ( ) defer . returnValue ( ( False , ret , clientdict , session [ '' ] ) ) @ defer . inlineCallbacks def add_oob_auth ( self , stagetype , authdict , clientip ) : \"\"\"\"\"\" if stagetype not in self . checkers : raise LoginError ( , \"\" , Codes . MISSING_PARAM ) if '' not in authdict : raise LoginError ( , \"\" , Codes . MISSING_PARAM ) sess = self . _get_session_info ( authdict [ '' ] ) if '' not in sess : sess [ '' ] = { } creds = sess [ '' ] result = yield self . checkers [ stagetype ] ( authdict , clientip ) if result : creds [ stagetype ] = result self . _save_session ( sess ) defer . returnValue ( True ) defer . returnValue ( False ) def get_session_id ( self , clientdict ) : \"\"\"\"\"\" sid = None if clientdict and '' in clientdict : authdict = clientdict [ '' ] if '' in authdict : sid = authdict [ '' ] return sid def set_session_data ( self , session_id , key , value ) : \"\"\"\"\"\" sess = self . _get_session_info ( session_id ) sess . setdefault ( '' , { } ) [ key ] = value self . _save_session ( sess ) def get_session_data ( self , session_id , key , default = None ) : \"\"\"\"\"\" sess = self . _get_session_info ( session_id ) return sess . setdefault ( '' , { } ) . get ( key , default ) @ defer . inlineCallbacks def _check_password_auth ( self , authdict , _ ) : if \"\" not in authdict or \"\" not in authdict : raise LoginError ( , \"\" , Codes . MISSING_PARAM ) user_id = authdict [ \"\" ] password = authdict [ \"\" ] if not user_id . startswith ( '' ) : user_id = UserID . create ( user_id , self . hs . hostname ) . to_string ( ) user_id , password_hash = yield self . _find_user_id_and_pwd_hash ( user_id ) self . _check_password ( user_id , password , password_hash ) defer . returnValue ( user_id ) @ defer . inlineCallbacks def _check_recaptcha ( self , authdict , clientip ) : try : user_response = authdict [ \"\" ] except KeyError : raise LoginError ( , \"\" , errcode = Codes . CAPTCHA_NEEDED ) logger . info ( \"\" , user_response , clientip ) try : client = self . hs . get_simple_http_client ( ) resp_body = yield client . post_urlencoded_get_json ( self . hs . config . recaptcha_siteverify_api , args = { '' : self . hs . config . recaptcha_private_key , '' : user_response , '' : clientip , } ) except PartialDownloadError as pde : data = pde . response resp_body = simplejson . loads ( data ) if '' in resp_body and resp_body [ '' ] : defer . returnValue ( True ) raise LoginError ( , \"\" , errcode = Codes . UNAUTHORIZED ) @ defer . inlineCallbacks def _check_email_identity ( self , authdict , _ ) : yield run_on_reactor ( ) if '' not in authdict : raise LoginError ( , \"\" , Codes . MISSING_PARAM ) threepid_creds = authdict [ '' ] identity_handler = self . hs . get_handlers ( ) . identity_handler logger . info ( \"\" % ( threepid_creds , ) ) threepid = yield identity_handler . threepid_from_creds ( threepid_creds ) if not threepid : raise LoginError ( , \"\" , errcode = Codes . UNAUTHORIZED ) threepid [ '' ] = authdict [ '' ] defer . returnValue ( threepid ) @ defer . inlineCallbacks def _check_dummy_auth ( self , authdict , _ ) : yield run_on_reactor ( ) defer . returnValue ( True ) def _get_params_recaptcha ( self ) : return { \"\" : self . hs . config . recaptcha_public_key } def _auth_dict_for_flows ( self , flows , session ) : public_flows = [ ] for f in flows : public_flows . append ( f ) get_params = { LoginType . RECAPTCHA : self . _get_params_recaptcha , } params = { } for f in public_flows : for stage in f : if stage in get_params and stage not in params : params [ stage ] = get_params [ stage ] ( ) return { \"\" : session [ '' ] , \"\" : [ { \"\" : f } for f in public_flows ] , \"\" : params } def _get_session_info ( self , session_id ) : if session_id not in self . sessions : session_id = None if not session_id : while session_id is None or session_id in self . sessions : session_id = stringutils . random_string ( ) self . sessions [ session_id ] = { \"\" : session_id , } return self . sessions [ session_id ] @ defer . inlineCallbacks def login_with_password ( self , user_id , password ) : \"\"\"\"\"\" user_id , password_hash = yield self . _find_user_id_and_pwd_hash ( user_id ) self . _check_password ( user_id , password , password_hash ) logger . info ( \"\" , user_id ) access_token = yield self . issue_access_token ( user_id ) refresh_token = yield self . issue_refresh_token ( user_id ) defer . returnValue ( ( user_id , access_token , refresh_token ) ) @ defer . inlineCallbacks def get_login_tuple_for_user_id ( self , user_id ) : \"\"\"\"\"\" user_id , ignored = yield self . _find_user_id_and_pwd_hash ( user_id ) logger . info ( \"\" , user_id ) access_token = yield self . issue_access_token ( user_id ) refresh_token = yield self . issue_refresh_token ( user_id ) defer . returnValue ( ( user_id , access_token , refresh_token ) ) @ defer . inlineCallbacks def does_user_exist ( self , user_id ) : try : yield self . _find_user_id_and_pwd_hash ( user_id ) defer . returnValue ( True ) except LoginError : defer . returnValue ( False ) @ defer . inlineCallbacks def _find_user_id_and_pwd_hash ( self , user_id ) : \"\"\"\"\"\" user_infos = yield self . store . get_users_by_id_case_insensitive ( user_id ) if not user_infos : logger . warn ( \"\" , user_id ) raise LoginError ( , \"\" , errcode = Codes . FORBIDDEN ) if len ( user_infos ) > : if user_id not in user_infos : logger . warn ( \"\" \"\" , user_id , user_infos . keys ( ) ) raise LoginError ( , \"\" , errcode = Codes . FORBIDDEN ) defer . returnValue ( ( user_id , user_infos [ user_id ] ) ) else : defer . returnValue ( user_infos . popitem ( ) ) def _check_password ( self , user_id , password , stored_hash ) : \"\"\"\"\"\" if not self . validate_hash ( password , stored_hash ) : logger . warn ( \"\" , user_id ) raise LoginError ( , \"\" , errcode = Codes . FORBIDDEN ) @ defer . inlineCallbacks def issue_access_token ( self , user_id ) : ", "answer": "access_token = self . generate_access_token ( user_id )"}, {"prompt": " \"\"\"\"\"\" import numpy as np import seaborn as sns sns . set ( style = \"\" ) rs = np . random . RandomState ( ) x = rs . normal ( , , ) ", "answer": "y = + * x + rs . normal ( , , )"}, {"prompt": " \"\"\"\"\"\" revision = '' down_revision = '' branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa ", "answer": "def upgrade ( ) :"}, {"prompt": " import inspect from . patterns import * class DecoratorBase ( object ) : pattern = None def __init__ ( self , functor ) : self . _functor = functor self . __doc__ = functor . __doc__ ", "answer": "self . __name__ = functor . __name__"}, {"prompt": " class FontConfigPackage ( Package ) : def __init__ ( self ) : Package . __init__ ( self , '' , '' , configure_flags = [ '' ] , sources = [ '' ] , ", "answer": ")"}, {"prompt": " from __future__ import unicode_literals , division , absolute_import , print_function import sys if sys . platform == '' : from . _osx . tls import ( TLSSession , TLSSocket , ) elif sys . platform == '' : ", "answer": "from . _win . tls import ("}, {"prompt": " from django . core . urlresolvers import get_resolver from devil import Resource try : from collections import OrderedDict as dict except ImportError : pass class DocumentedResource ( Resource ) : \"\"\"\"\"\" methods = ( '' , '' , '' , '' , ) def get_documentation ( self , request , * args , ** kw ) : \"\"\"\"\"\" ret = dict ( ) ret [ '' ] = self . name ( ) ret [ '' ] = self . _get_url_doc ( ) ret [ '' ] = self . __doc__ ret [ '' ] = self . _get_representation_doc ( ) ret [ '' ] = self . _get_method_doc ( ) return ret def _serialize_object ( self , response_data , request ) : \"\"\"\"\"\" if self . _is_doc_request ( request ) : return response_data else : return super ( DocumentedResource , self ) . _serialize_object ( response_data , request ) def _validate_output_data ( self , original_res , serialized_res , formatted_res , request ) : \"\"\"\"\"\" if self . _is_doc_request ( request ) : return else : return super ( DocumentedResource , self ) . _validate_output_data ( original_res , serialized_res , formatted_res , request ) def _get_method ( self , request ) : \"\"\"\"\"\" if self . _is_doc_request ( request ) : return self . get_documentation else : return super ( DocumentedResource , self ) . _get_method ( request ) def _is_doc_request ( self , request ) : \"\"\"\"\"\" return '' in request . GET def _get_representation_doc ( self ) : \"\"\"\"\"\" if not self . representation : return '' fields = { } for name , field in self . representation . fields . items ( ) : fields [ name ] = self . _get_field_doc ( field ) return fields def _get_field_doc ( self , field ) : \"\"\"\"\"\" fieldspec = dict ( ) fieldspec [ '' ] = field . __class__ . __name__ fieldspec [ '' ] = field . required fieldspec [ '' ] = [ { validator . __class__ . __name__ : validator . __dict__ } for validator in field . validators ] return fieldspec def _get_url_doc ( self ) : \"\"\"\"\"\" resolver = get_resolver ( None ) possibilities = resolver . reverse_dict . getlist ( self ) urls = [ possibility [ ] for possibility in possibilities ] return urls def _get_method_doc ( self ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " import os , tempfile from setuptools import setup from distutils . command . build_scripts import build_scripts import versioneer commands = versioneer . get_cmdclass ( ) . copy ( ) class my_build_scripts ( build_scripts ) : def run ( self ) : versions = versioneer . get_versions ( ) tempdir = tempfile . mkdtemp ( ) generated = os . path . join ( tempdir , \"\" ) with open ( generated , \"\" ) as f : for line in open ( \"\" , \"\" ) : if line . strip ( ) . decode ( \"\" ) == \"\" : f . write ( ( '' % ( versions , ) ) . encode ( \"\" ) ) else : f . write ( line ) self . scripts = [ generated ] rc = build_scripts . run ( self ) os . unlink ( generated ) os . rmdir ( tempdir ) return rc commands [ \"\" ] = my_build_scripts setup ( name = \"\" , version = versioneer . get_version ( ) , description = \"\" , url = \"\" , ", "answer": "author = \"\" ,"}, {"prompt": " import warnings import sys import errno import functools import logging import socket from nose . plugins . skip import SkipTest from urllib3 . exceptions import MaxRetryError , HTTPWarning from urllib3 . packages import six TARPIT_HOST = '' VALID_SOURCE_ADDRESSES = [ ( ( '' , ) , True ) , ( ( '' , ) , False ) ] INVALID_SOURCE_ADDRESSES = [ ( '' , ) , ( '' , ) ] def clear_warnings ( cls = HTTPWarning ) : new_filters = [ ] for f in warnings . filters : if issubclass ( f [ ] , cls ) : continue new_filters . append ( f ) warnings . filters [ : ] = new_filters def setUp ( ) : clear_warnings ( ) warnings . simplefilter ( '' , HTTPWarning ) def onlyPy26OrOlder ( test ) : \"\"\"\"\"\" @ functools . wraps ( test ) def wrapper ( * args , ** kwargs ) : msg = \"\" . format ( name = test . __name__ ) if sys . version_info >= ( , ) : raise SkipTest ( msg ) return test ( * args , ** kwargs ) return wrapper def onlyPy27OrNewer ( test ) : \"\"\"\"\"\" @ functools . wraps ( test ) def wrapper ( * args , ** kwargs ) : msg = \"\" . format ( name = test . __name__ ) if sys . version_info < ( , ) : raise SkipTest ( msg ) ", "answer": "return test ( * args , ** kwargs )"}, {"prompt": " import sublime , sublime_plugin , subprocess , thread , os , functools , glob , fnmatch class JumpToTestCommand ( sublime_plugin . TextCommand ) : def run ( self , edit ) : current_file = self . view . file_name ( ) self . base_dir = current_file . partition ( \"\" ) [ ] if current_file . endswith ( \"\" ) : target_file = current_file . replace ( \"\" , \"\" ) . replace ( \"\" , \"\" ) else : target_file = current_file . replace ( \"\" , \"\" ) . replace ( \"\" , \"\" ) if not os . path . exists ( target_file ) : sublime . error_message ( \"\" + target_file ) self . view . window ( ) . open_file ( target_file ) class BaseScalaTestCommand ( sublime_plugin . TextCommand ) : def load_config ( self ) : s = sublime . load_settings ( \"\" ) global SCALA ; SCALA = s . get ( \"\" ) global useScalaTest ; useScalaTest = s . get ( \"\" ) == \"\" def run ( self , edit ) : self . load_config ( ) self . show_tests_panel ( ) self . base_dir = self . view . file_name ( ) . partition ( \"\" ) [ ] runner = \"\" if useScalaTest else \"\" scala_args = \"\" + runner + self . junit_args ( ) command = wrap_in_cd ( self . base_dir , SCALA + \"\" + scala_args ) self . proc = subprocess . Popen ( command , shell = True , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) thread . start_new_thread ( self . read_stdout , ( ) ) thread . start_new_thread ( self . read_stderr , ( ) ) def relative_path_to_class_name ( self , partition_folder , relative_path , suffix ) : return relative_path . rpartition ( partition_folder + \"\" ) [ ] . replace ( \"\" , \"\" ) . replace ( suffix , \"\" ) def read_stdout ( self ) : self . copy_stream_to_output_view ( self . proc . stdout ) def read_stderr ( self ) : self . copy_stream_to_output_view ( self . proc . stderr ) def copy_stream_to_output_view ( self , stream ) : while True : data = os . read ( stream . fileno ( ) , ** ) if data != \"\" : sublime . set_timeout ( functools . partial ( self . append_data , self . proc , data ) , ) else : stream . close ( ) break def window ( self ) : return self . view . window ( ) def append_data ( self , proc , data ) : self . output_view . set_read_only ( False ) edit = self . output_view . begin_edit ( ) ", "answer": "self . output_view . insert ( edit , self . output_view . size ( ) , data )"}, {"prompt": " import cStringIO as StringIO import subprocess import unittest import mox import portable_platform def subprocess_mock ( mox , * args , ** kw ) : mock_process = mox . CreateMock ( subprocess . Popen ) mox . StubOutWithMock ( subprocess , '' , use_mock_anything = True ) ", "answer": "subprocess . Popen ( * args , ** kw ) . AndReturn ("}, {"prompt": " \"\"\"\"\"\" import os ", "answer": "import time"}, {"prompt": " import math class DrawableElement ( object ) : '''''' def __init__ ( self , pts , center , angle , color ) : self . color = color self . pts = pts self . center = center self . angle = angle def initialize ( self , canvas ) : self . canvas = canvas self . id = self . canvas . create_polygon ( * self . pts , fill = self . color ) def intersects ( self ) : pass def move ( self , v ) : '''''' vx , vy = v vx , vy = vx * math . cos ( self . angle ) - vy * math . sin ( self . angle ) , vx * math . sin ( self . angle ) + vy * math . cos ( self . angle ) def _move ( xy ) : x , y = xy return x + vx , y + vy self . pts = [ p for p in map ( lambda x : _move ( x ) , self . pts ) ] self . center = _move ( self . center ) def rotate ( self , angle ) : '''''' self . angle = ( self . angle + angle ) % ( math . pi * ) c = math . cos ( angle ) s = math . sin ( angle ) px , py = self . center def _rotate_point ( xy ) : x , y = xy x = x - px y = y - py return ( x * c - y * s ) + px , ( x * s + y * c ) + py self . pts = [ p for p in map ( lambda x : _rotate_point ( x ) , self . pts ) ] def set_color ( self , color ) : self . color = color self . canvas . itemconfig ( self . id , fill = color ) def update_coordinates ( self ) : if hasattr ( self , '' ) : pts = [ c for p in self . pts for c in p ] self . canvas . coords ( self . id , * pts ) def perform_move ( self ) : self . update_coordinates ( ) class CompositeElement ( object ) : ", "answer": "''''''"}, {"prompt": " AUTHOR = \"\" ", "answer": "DESCRIPTION = \"\""}, {"prompt": " from novaclient . tests . functional import base from novaclient . tests . functional . v2 import fake_crypto from novaclient . tests . functional . v2 . legacy import test_keypairs class TestKeypairsNovaClientV22 ( test_keypairs . TestKeypairsNovaClient ) : \"\"\"\"\"\" COMPUTE_API_VERSION = \"\" def test_create_keypair ( self ) : keypair = super ( TestKeypairsNovaClientV22 , self ) . test_create_keypair ( ) self . assertIn ( '' , keypair ) def test_create_keypair_x509 ( self ) : key_name = self . _create_keypair ( key_type = '' ) keypair = self . _show_keypair ( key_name ) self . assertIn ( key_name , keypair ) self . assertIn ( '' , keypair ) def test_import_keypair ( self ) : pub_key , fingerprint = fake_crypto . get_ssh_pub_key_and_fingerprint ( ) pub_key_file = self . _create_public_key_file ( pub_key ) keypair = self . _test_import_keypair ( fingerprint , pub_key = pub_key_file ) self . assertIn ( '' , keypair ) def test_import_keypair_x509 ( self ) : certif , fingerprint = fake_crypto . get_x509_cert_and_fingerprint ( ) pub_key_file = self . _create_public_key_file ( certif ) keypair = self . _test_import_keypair ( fingerprint , key_type = '' , pub_key = pub_key_file ) self . assertIn ( '' , keypair ) class TestKeypairsNovaClientV210 ( base . TenantTestBase ) : \"\"\"\"\"\" COMPUTE_API_VERSION = \"\" def test_create_and_list_keypair ( self ) : name = self . name_generate ( \"\" ) self . nova ( \"\" % ( name , self . user_id ) ) self . addCleanup ( self . another_nova , \"\" % name ) output = self . nova ( \"\" ) self . assertRaises ( ValueError , self . _get_value_from_the_table , output , name ) output_1 = self . another_nova ( \"\" ) output_2 = self . nova ( \"\" % self . user_id ) self . assertEqual ( output_1 , output_2 ) self . assertEqual ( name , self . _get_column_value_from_single_row_table ( output_1 , \"\" ) ) output_1 = self . another_nova ( \"\" % name ) output_2 = self . nova ( \"\" % ( self . user_id , name ) ) self . assertEqual ( output_1 , output_2 ) self . assertEqual ( self . user_id , self . _get_value_from_the_table ( output_1 , \"\" ) ) def test_create_and_delete ( self ) : name = self . name_generate ( \"\" ) def cleanup ( ) : o = self . another_nova ( \"\" ) if name in o : ", "answer": "self . another_nova ( \"\" % name )"}, {"prompt": " import pyinotify wm = pyinotify . WatchManager ( ) r = wm . add_watch ( [ '' , '' ] , pyinotify . ALL_EVENTS ) print r try : wm . add_watch ( [ '' , '' ] , pyinotify . ALL_EVENTS , quiet = False ) except pyinotify . WatchManagerError , err : print err , err . wmd try : wm . update_watch ( , mask = , quiet = False ) except pyinotify . WatchManagerError , err : print err , err . wmd ", "answer": "try :"}, {"prompt": " import random def generate_code ( referral_class ) : def _generate_code ( ) : t = \"\" return \"\" . join ( [ random . choice ( t ) for i in range ( ) ] ) code = _generate_code ( ) while referral_class . objects . filter ( code = code ) . exists ( ) : ", "answer": "code = _generate_code ( )"}, {"prompt": " \"\"\"\"\"\" import yaki . Engine , yaki . Store , yaki . Locale from BeautifulSoup import * from yaki . Utils import * import urllib class ReferrersWikiPlugin ( yaki . Plugins . WikiPlugin ) : def __init__ ( self , registry , webapp ) : registry . register ( '' , self , '' , '' ) self . ac = webapp . getContext ( ) self . i18n = yaki . Locale . i18n [ self . ac . locale ] def run ( self , serial , tag , tagname , pagename , soup , request , response ) : ", "answer": "buffer = [ u'' % ( self . i18n [ '' ] , self . i18n [ '' ] , self . i18n [ '' ] , self . i18n [ '' ] ) ]"}, {"prompt": " __author__ = '' from time import sleep , time import datetime from openduty . serializers import NoneSerializer from openduty . models import Incident from rest_framework . response import Response from rest_framework import status from rest_framework import viewsets from . celery import add from random import randint class HealthCheckViewSet ( viewsets . ModelViewSet ) : ", "answer": "queryset = Incident . objects . all ( )"}, {"prompt": " '''''' from arelle import PythonUtil import os , sys , subprocess , pickle , time , locale , re from tkinter import ( Tk , TclError , Toplevel , Menu , PhotoImage , StringVar , BooleanVar , N , S , E , W , EW , HORIZONTAL , VERTICAL , END , font as tkFont ) try : from tkinter . ttk import Frame , Button , Label , Combobox , Separator , PanedWindow , Notebook except ImportError : from ttk import Frame , Button , Label , Combobox , Separator , PanedWindow , Notebook import tkinter . tix import tkinter . filedialog import tkinter . messagebox , traceback from arelle . Locale import format_string from arelle . CntlrWinTooltip import ToolTip from arelle import XbrlConst from arelle . PluginManager import pluginClassMethods from arelle . UrlUtil import isHttpUrl import logging import threading , queue from arelle import Cntlr from arelle import ( DialogURL , DialogLanguage , DialogPluginManager , DialogPackageManager , ModelDocument , ModelManager , PackageManager , RenderingEvaluator , TableStructure , ViewWinDTS , ViewWinProperties , ViewWinConcepts , ViewWinRelationshipSet , ViewWinFormulae , ViewWinFactList , ViewFileFactList , ViewWinFactTable , ViewWinRenderedGrid , ViewWinXml , ViewWinRoleTypes , ViewFileRoleTypes , ViewFileConcepts , ViewWinTests , ViewWinTree , ViewWinVersReport , ViewWinRssFeed , ViewFileTests , ViewFileRenderedGrid , ViewFileRelationshipSet , Updater ) from arelle . ModelFormulaObject import FormulaOptions from arelle . FileSource import openFileSource restartMain = True class CntlrWinMain ( Cntlr . Cntlr ) : def __init__ ( self , parent ) : super ( CntlrWinMain , self ) . __init__ ( hasGui = True ) self . parent = parent self . filename = None self . dirty = False overrideLang = self . config . get ( \"\" ) self . labelLang = overrideLang if overrideLang else self . modelManager . defaultLang self . data = { } if self . isMac : _defaultFont = tkFont . nametofont ( \"\" ) _defaultFont . configure ( size = ) _textFont = tkFont . nametofont ( \"\" ) _textFont . configure ( size = ) toolbarButtonPadding = else : toolbarButtonPadding = tkinter . CallWrapper = TkinterCallWrapper imgpath = self . imagesDir + os . sep if self . isMSW : icon = imgpath + \"\" parent . iconbitmap ( icon , default = icon ) else : parent . iconbitmap ( \"\" + imgpath + \"\" ) self . menubar = Menu ( self . parent ) self . parent [ \"\" ] = self . menubar self . fileMenu = Menu ( self . menubar , tearoff = ) self . fileMenuLength = for label , command , shortcut_text , shortcut in ( ( _ ( \"\" ) , self . fileOpen , \"\" , \"\" ) , ( _ ( \"\" ) , self . webOpen , \"\" , \"\" ) , ( _ ( \"\" ) , self . importFileOpen , None , None ) , ( _ ( \"\" ) , self . importWebOpen , None , None ) , ( \"\" , \"\" , None , None ) , ( _ ( \"\" ) , self . fileSaveExistingFile , \"\" , \"\" ) , ( _ ( \"\" ) , self . fileSave , None , None ) , ( _ ( \"\" ) , self . saveDTSpackage , None , None ) , ( \"\" , \"\" , None , None ) , ( _ ( \"\" ) , self . fileClose , \"\" , \"\" ) , ( None , None , None , None ) , ( _ ( \"\" ) , self . quit , \"\" , \"\" ) , ( None , None , None , None ) , ( \"\" , None , None , None ) ) : if label is None : self . fileMenu . add_separator ( ) elif label == \"\" : for pluginMenuExtender in pluginClassMethods ( command ) : pluginMenuExtender ( self , self . fileMenu ) self . fileMenuLength += else : self . fileMenu . add_command ( label = label , underline = , command = command , accelerator = shortcut_text ) self . parent . bind ( shortcut , command ) self . fileMenuLength += self . loadFileMenuHistory ( ) self . menubar . add_cascade ( label = _ ( \"\" ) , menu = self . fileMenu , underline = ) toolsMenu = Menu ( self . menubar , tearoff = ) validateMenu = Menu ( self . menubar , tearoff = ) toolsMenu . add_cascade ( label = _ ( \"\" ) , menu = validateMenu , underline = ) validateMenu . add_command ( label = _ ( \"\" ) , underline = , command = self . validate ) self . modelManager . validateDisclosureSystem = self . config . setdefault ( \"\" , False ) self . validateDisclosureSystem = BooleanVar ( value = self . modelManager . validateDisclosureSystem ) self . validateDisclosureSystem . trace ( \"\" , self . setValidateDisclosureSystem ) validateMenu . add_checkbutton ( label = _ ( \"\" ) , underline = , variable = self . validateDisclosureSystem , onvalue = True , offvalue = False ) validateMenu . add_command ( label = _ ( \"\" ) , underline = , command = self . selectDisclosureSystem ) self . modelManager . validateCalcLB = self . config . setdefault ( \"\" , False ) self . validateCalcLB = BooleanVar ( value = self . modelManager . validateCalcLB ) self . validateCalcLB . trace ( \"\" , self . setValidateCalcLB ) validateMenu . add_checkbutton ( label = _ ( \"\" ) , underline = , variable = self . validateCalcLB , onvalue = True , offvalue = False ) self . modelManager . validateInferDecimals = self . config . setdefault ( \"\" , False ) self . validateInferDecimals = BooleanVar ( value = self . modelManager . validateInferDecimals ) self . validateInferDecimals . trace ( \"\" , self . setValidateInferDecimals ) validateMenu . add_checkbutton ( label = _ ( \"\" ) , underline = , variable = self . validateInferDecimals , onvalue = True , offvalue = False ) self . modelManager . validateUtr = self . config . setdefault ( \"\" , True ) self . validateUtr = BooleanVar ( value = self . modelManager . validateUtr ) self . validateUtr . trace ( \"\" , self . setValidateUtr ) validateMenu . add_checkbutton ( label = _ ( \"\" ) , underline = , variable = self . validateUtr , onvalue = True , offvalue = False ) for pluginMenuExtender in pluginClassMethods ( \"\" ) : pluginMenuExtender ( self , validateMenu ) formulaMenu = Menu ( self . menubar , tearoff = ) formulaMenu . add_command ( label = _ ( \"\" ) , underline = , command = self . formulaParametersDialog ) toolsMenu . add_cascade ( label = _ ( \"\" ) , menu = formulaMenu , underline = ) self . modelManager . formulaOptions = FormulaOptions ( self . config . get ( \"\" ) ) toolsMenu . add_command ( label = _ ( \"\" ) , underline = , command = self . compareDTSes ) cacheMenu = Menu ( self . menubar , tearoff = ) rssWatchMenu = Menu ( self . menubar , tearoff = ) rssWatchMenu . add_command ( label = _ ( \"\" ) , underline = , command = self . rssWatchOptionsDialog ) rssWatchMenu . add_command ( label = _ ( \"\" ) , underline = , command = lambda : self . rssWatchControl ( start = True ) ) rssWatchMenu . add_command ( label = _ ( \"\" ) , underline = , command = lambda : self . rssWatchControl ( stop = True ) ) toolsMenu . add_cascade ( label = _ ( \"\" ) , menu = rssWatchMenu , underline = ) self . modelManager . rssWatchOptions = self . config . setdefault ( \"\" , { } ) toolsMenu . add_cascade ( label = _ ( \"\" ) , menu = cacheMenu , underline = ) self . webCache . workOffline = self . config . setdefault ( \"\" , False ) self . workOffline = BooleanVar ( value = self . webCache . workOffline ) self . workOffline . trace ( \"\" , self . setWorkOffline ) cacheMenu . add_checkbutton ( label = _ ( \"\" ) , underline = , variable = self . workOffline , onvalue = True , offvalue = False ) '''''' cacheMenu . add_command ( label = _ ( \"\" ) , underline = , command = self . confirmClearWebCache ) cacheMenu . add_command ( label = _ ( \"\" ) , underline = , command = self . manageWebCache ) cacheMenu . add_command ( label = _ ( \"\" ) , underline = , command = self . setupProxy ) logmsgMenu = Menu ( self . menubar , tearoff = ) toolsMenu . add_cascade ( label = _ ( \"\" ) , menu = logmsgMenu , underline = ) logmsgMenu . add_command ( label = _ ( \"\" ) , underline = , command = self . logClear ) logmsgMenu . add_command ( label = _ ( \"\" ) , underline = , command = self . logSaveToFile ) self . modelManager . collectProfileStats = self . config . setdefault ( \"\" , False ) self . collectProfileStats = BooleanVar ( value = self . modelManager . collectProfileStats ) self . collectProfileStats . trace ( \"\" , self . setCollectProfileStats ) logmsgMenu . add_checkbutton ( label = _ ( \"\" ) , underline = , variable = self . collectProfileStats , onvalue = True , offvalue = False ) logmsgMenu . add_command ( label = _ ( \"\" ) , underline = , command = self . showProfileStats ) logmsgMenu . add_command ( label = _ ( \"\" ) , underline = , command = self . clearProfileStats ) self . showDebugMessages = BooleanVar ( value = self . config . setdefault ( \"\" , False ) ) self . showDebugMessages . trace ( \"\" , self . setShowDebugMessages ) logmsgMenu . add_checkbutton ( label = _ ( \"\" ) , underline = , variable = self . showDebugMessages , onvalue = True , offvalue = False ) toolsMenu . add_command ( label = _ ( \"\" ) , underline = , command = lambda : DialogLanguage . askLanguage ( self ) ) for pluginMenuExtender in pluginClassMethods ( \"\" ) : pluginMenuExtender ( self , toolsMenu ) self . menubar . add_cascade ( label = _ ( \"\" ) , menu = toolsMenu , underline = ) if any ( pluginClassMethods ( \"\" ) ) : viewMenu = Menu ( self . menubar , tearoff = ) for pluginMenuExtender in pluginClassMethods ( \"\" ) : pluginMenuExtender ( self , viewMenu ) self . menubar . add_cascade ( label = _ ( \"\" ) , menu = viewMenu , underline = ) helpMenu = Menu ( self . menubar , tearoff = ) for label , command , shortcut_text , shortcut in ( ( _ ( \"\" ) , lambda : Updater . checkForUpdates ( self ) , None , None ) , ( _ ( \"\" ) , lambda : DialogPluginManager . dialogPluginManager ( self ) , None , None ) , ( _ ( \"\" ) , lambda : DialogPackageManager . dialogPackageManager ( self ) , None , None ) , ( \"\" , \"\" , None , None ) , ( None , None , None , None ) , ( _ ( \"\" ) , self . helpAbout , None , None ) , ( \"\" , \"\" , None , None ) , ) : if label is None : helpMenu . add_separator ( ) elif label == \"\" : for pluginMenuExtender in pluginClassMethods ( command ) : pluginMenuExtender ( self , helpMenu ) else : helpMenu . add_command ( label = label , underline = , command = command , accelerator = shortcut_text ) self . parent . bind ( shortcut , command ) for pluginMenuExtender in pluginClassMethods ( \"\" ) : pluginMenuExtender ( self , toolsMenu ) self . menubar . add_cascade ( label = _ ( \"\" ) , menu = helpMenu , underline = ) windowFrame = Frame ( self . parent ) self . statusbar = Label ( windowFrame , text = _ ( \"\" ) , anchor = W ) self . statusbarTimerId = self . statusbar . after ( , self . uiClearStatusTimerEvent ) self . statusbar . grid ( row = , column = , columnspan = , sticky = EW ) self . toolbar_images = [ ] toolbar = Frame ( windowFrame ) menubarColumn = self . validateTooltipText = StringVar ( ) for image , command , toolTip , statusMsg in ( ( \"\" , self . fileOpen , _ ( \"\" ) , _ ( \"\" ) ) , ( \"\" , self . webOpen , _ ( \"\" ) , _ ( \"\" ) ) , ( \"\" , self . fileSaveExistingFile , _ ( \"\" ) , _ ( \"\" ) ) , ( \"\" , self . fileClose , _ ( \"\" ) , _ ( \"\" ) ) , ( None , None , None , None ) , ( \"\" , self . find , _ ( \"\" ) , _ ( \"\" ) ) , ( None , None , None , None ) , ( \"\" , self . validate , self . validateTooltipText , _ ( \"\" ) ) , ( \"\" , self . compareDTSes , _ ( \"\" ) , _ ( \"\" ) ) , ( None , None , None , None ) , ( \"\" , self . logClear , _ ( \"\" ) , _ ( \"\" ) ) , ) : if command is None : tbControl = Separator ( toolbar , orient = VERTICAL ) tbControl . grid ( row = , column = menubarColumn , padx = ) elif isinstance ( image , Combobox ) : tbControl = image tbControl . grid ( row = , column = menubarColumn ) else : image = os . path . join ( self . imagesDir , image ) try : image = PhotoImage ( file = image ) self . toolbar_images . append ( image ) tbControl = Button ( toolbar , image = image , command = command , style = \"\" , padding = toolbarButtonPadding ) tbControl . grid ( row = , column = menubarColumn ) except TclError as err : print ( err ) if isinstance ( toolTip , StringVar ) : ToolTip ( tbControl , textvariable = toolTip , wraplength = ) else : ToolTip ( tbControl , text = toolTip ) menubarColumn += for toolbarExtender in pluginClassMethods ( \"\" ) : toolbarExtender ( self , toolbar ) toolbar . grid ( row = , column = , sticky = ( N , W ) ) paneWinTopBtm = PanedWindow ( windowFrame , orient = VERTICAL ) paneWinTopBtm . grid ( row = , column = , sticky = ( N , S , E , W ) ) paneWinLeftRt = tkinter . PanedWindow ( paneWinTopBtm , orient = HORIZONTAL ) paneWinLeftRt . grid ( row = , column = , sticky = ( N , S , E , W ) ) paneWinLeftRt . bind ( \"\" , self . onTabChanged ) paneWinTopBtm . add ( paneWinLeftRt ) self . tabWinTopLeft = Notebook ( paneWinLeftRt , width = , height = ) self . tabWinTopLeft . grid ( row = , column = , sticky = ( N , S , E , W ) ) paneWinLeftRt . add ( self . tabWinTopLeft ) self . tabWinTopRt = Notebook ( paneWinLeftRt ) self . tabWinTopRt . grid ( row = , column = , sticky = ( N , S , E , W ) ) self . tabWinTopRt . bind ( \"\" , self . onTabChanged ) paneWinLeftRt . add ( self . tabWinTopRt ) self . tabWinBtm = Notebook ( paneWinTopBtm ) self . tabWinBtm . grid ( row = , column = , sticky = ( N , S , E , W ) ) self . tabWinBtm . bind ( \"\" , self . onTabChanged ) paneWinTopBtm . add ( self . tabWinBtm ) from arelle import ViewWinList self . logView = ViewWinList . ViewList ( None , self . tabWinBtm , _ ( \"\" ) , True ) self . startLogging ( logHandler = WinMainLogHandler ( self ) ) logViewMenu = self . logView . contextMenu ( contextMenuClick = self . contextMenuClick ) logViewMenu . add_command ( label = _ ( \"\" ) , underline = , command = self . logClear ) logViewMenu . add_command ( label = _ ( \"\" ) , underline = , command = self . logSaveToFile ) if self . hasClipboard : logViewMenu . add_command ( label = _ ( \"\" ) , underline = , command = lambda : self . logView . copyToClipboard ( cntlr = self ) ) windowFrame . grid ( row = , column = , sticky = ( N , S , E , W ) ) windowFrame . columnconfigure ( , weight = ) windowFrame . columnconfigure ( , weight = ) windowFrame . rowconfigure ( , weight = ) windowFrame . rowconfigure ( , weight = ) windowFrame . rowconfigure ( , weight = ) paneWinTopBtm . columnconfigure ( , weight = ) paneWinTopBtm . rowconfigure ( , weight = ) paneWinLeftRt . columnconfigure ( , weight = ) paneWinLeftRt . rowconfigure ( , weight = ) self . tabWinTopLeft . columnconfigure ( , weight = ) self . tabWinTopLeft . rowconfigure ( , weight = ) self . tabWinTopRt . columnconfigure ( , weight = ) self . tabWinTopRt . rowconfigure ( , weight = ) self . tabWinBtm . columnconfigure ( , weight = ) self . tabWinBtm . rowconfigure ( , weight = ) window = self . parent . winfo_toplevel ( ) window . columnconfigure ( , weight = ) window . rowconfigure ( , weight = ) priorState = self . config . get ( '' ) screenW = self . parent . winfo_screenwidth ( ) - screenH = self . parent . winfo_screenheight ( ) - if priorState == \"\" : self . parent . state ( \"\" ) w = screenW h = screenH else : priorGeometry = re . match ( \"\" , self . config . get ( '' ) ) if priorGeometry and priorGeometry . lastindex >= : try : w = int ( priorGeometry . group ( ) ) h = int ( priorGeometry . group ( ) ) x = int ( priorGeometry . group ( ) ) y = int ( priorGeometry . group ( ) ) if x + w > screenW : if w < screenW : x = screenW - w else : x = w = screenW elif x < : x = if w > screenW : w = screenW if y + h > screenH : if y < screenH : y = screenH - h else : y = h = screenH elif y < : y = if h > screenH : h = screenH self . parent . geometry ( \"\" . format ( w , h , x , y ) ) except : pass topLeftW , topLeftH = self . config . get ( '' , ( , ) ) if < topLeftW < w - : self . tabWinTopLeft . config ( width = topLeftW ) if < topLeftH < h - : self . tabWinTopLeft . config ( height = topLeftH ) self . parent . title ( _ ( \"\" ) ) self . logFile = None self . uiThreadQueue = queue . Queue ( ) self . uiThreadChecker ( self . statusbar ) self . modelManager . loadCustomTransforms ( ) if not self . modelManager . disclosureSystem . select ( self . config . setdefault ( \"\" , None ) ) : self . validateDisclosureSystem . set ( False ) self . modelManager . validateDisclosureSystem = False self . setValidateTooltipText ( ) def onTabChanged ( self , event , * args ) : try : widgetIndex = event . widget . index ( \"\" ) tabId = event . widget . tabs ( ) [ widgetIndex ] for widget in event . widget . winfo_children ( ) : if str ( widget ) == tabId : self . currentView = widget . view break except ( AttributeError , TypeError , TclError ) : pass def loadFileMenuHistory ( self ) : self . fileMenu . delete ( self . fileMenuLength , self . fileMenuLength + ) fileHistory = self . config . setdefault ( \"\" , [ ] ) self . recentFilesMenu = Menu ( self . menubar , tearoff = ) for i in range ( min ( len ( fileHistory ) , ) ) : self . recentFilesMenu . add_command ( label = fileHistory [ i ] , command = lambda j = i : self . fileOpenFile ( self . config [ \"\" ] [ j ] ) ) self . fileMenu . add_cascade ( label = _ ( \"\" ) , menu = self . recentFilesMenu , underline = ) importHistory = self . config . setdefault ( \"\" , [ ] ) self . recentAttachMenu = Menu ( self . menubar , tearoff = ) for i in range ( min ( len ( importHistory ) , ) ) : self . recentAttachMenu . add_command ( label = importHistory [ i ] , command = lambda j = i : self . fileOpenFile ( self . config [ \"\" ] [ j ] , importToDTS = True ) ) self . fileMenu . add_cascade ( label = _ ( \"\" ) , menu = self . recentAttachMenu , underline = ) self . packagesMenu = Menu ( self . menubar , tearoff = ) hasPackages = False for i , packageInfo in enumerate ( sorted ( PackageManager . packagesConfig . get ( \"\" , [ ] ) , key = lambda packageInfo : packageInfo . get ( \"\" ) ) , start = ) : name = packageInfo . get ( \"\" , \"\" . format ( i ) ) URL = packageInfo . get ( \"\" ) if name and URL and packageInfo . get ( \"\" ) == \"\" : self . packagesMenu . add_command ( label = name , command = lambda url = URL : self . fileOpenFile ( url ) ) hasPackages = True if hasPackages : self . fileMenu . add_cascade ( label = _ ( \"\" ) , menu = self . packagesMenu , underline = ) def onPackageEnablementChanged ( self ) : self . loadFileMenuHistory ( ) def fileNew ( self , * ignore ) : if not self . okayToContinue ( ) : return self . logClear ( ) self . dirty = False self . filename = None self . data = { } self . parent . title ( _ ( \"\" ) ) ; self . modelManager . load ( None ) ; def getViewAndModelXbrl ( self ) : view = getattr ( self , \"\" , None ) if view : modelXbrl = None try : modelXbrl = view . modelXbrl return ( view , modelXbrl ) except AttributeError : return ( view , None ) return ( None , None ) def okayToContinue ( self ) : view , modelXbrl = self . getViewAndModelXbrl ( ) documentIsModified = False if view is not None : try : view . updateInstanceFromFactPrototypes ( ) except AttributeError : pass if modelXbrl is not None : documentIsModified = modelXbrl . isModified ( ) if not self . dirty and ( not documentIsModified ) : return True reply = tkinter . messagebox . askokcancel ( _ ( \"\" ) , _ ( \"\" ) , parent = self . parent ) if reply is None : return False else : return reply def fileSave ( self , event = None , view = None , fileType = None , filenameFromInstance = False , * ignore ) : if view is None : view = getattr ( self , \"\" , None ) if view is not None : filename = None modelXbrl = None try : modelXbrl = view . modelXbrl except AttributeError : pass if filenameFromInstance : try : modelXbrl = view . modelXbrl filename = modelXbrl . modelDocument . filepath if filename . endswith ( '' ) : filename = None except AttributeError : pass if isinstance ( view , ViewWinRenderedGrid . ViewRenderedGrid ) : initialdir = os . path . dirname ( modelXbrl . modelDocument . uri ) if fileType in ( \"\" , \"\" , None ) : if fileType == \"\" and filename is None : filename = self . uiFileDialog ( \"\" , title = _ ( \"\" ) , initialdir = initialdir , filetypes = [ ( _ ( \"\" ) , \"\" ) , ( _ ( \"\" ) , \"\" ) ] , defaultextension = \"\" ) elif fileType == \"\" and filename is None : filename = self . uiFileDialog ( \"\" , title = _ ( \"\" ) , initialdir = initialdir , filetypes = [ ( _ ( \"\" ) , \"\" ) ] , defaultextension = \"\" ) else : if filename is None : filename = self . uiFileDialog ( \"\" , title = _ ( \"\" ) , initialdir = initialdir , filetypes = [ ( _ ( \"\" ) , \"\" ) , ( _ ( \"\" ) , \"\" ) , ( _ ( \"\" ) , \"\" ) , ( _ ( \"\" ) , \"\" ) ] , defaultextension = \"\" ) if filename and ( filename . endswith ( \"\" ) or filename . endswith ( \"\" ) ) : view . saveInstance ( filename ) return True if not filename : return False try : ViewFileRenderedGrid . viewRenderedGrid ( modelXbrl , filename , lang = self . labelLang , sourceView = view ) except ( IOError , EnvironmentError ) as err : tkinter . messagebox . showwarning ( _ ( \"\" ) , _ ( \"\" ) . format ( filename , err ) , parent = self . parent ) return True elif fileType == \"\" : return self . uiFileDialog ( \"\" , title = _ ( \"\" ) , initialdir = initialdir , filetypes = [ ( _ ( \"\" ) , \"\" ) , ( _ ( \"\" ) , \"\" ) ] , defaultextension = \"\" ) elif isinstance ( view , ViewWinTests . ViewTests ) and modelXbrl . modelDocument . type in ( ModelDocument . Type . TESTCASESINDEX , ModelDocument . Type . TESTCASE ) : ", "answer": "filename = self . uiFileDialog ( \"\" ,"}, {"prompt": " \"\"\"\"\"\" from django . conf import settings from django . core import signals from django . core . cache . backends . base import ( InvalidCacheBackendError , CacheKeyWarning , BaseCache ) from django . core . exceptions import ImproperlyConfigured from django . utils import importlib try : from mod_python . util import parse_qsl except ImportError : try : from urlparse import parse_qsl except ImportError : from cgi import parse_qsl __all__ = [ '' , '' , '' ] BACKENDS = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , } DEFAULT_CACHE_ALIAS = '' def parse_backend_uri ( backend_uri ) : \"\"\"\"\"\" if backend_uri . find ( '' ) == - : raise InvalidCacheBackendError ( \"\" ) scheme , rest = backend_uri . split ( '' , ) if not rest . startswith ( '' ) : raise InvalidCacheBackendError ( \"\" ) host = rest [ : ] qpos = rest . find ( '' ) if qpos != - : params = dict ( parse_qsl ( rest [ qpos + : ] ) ) host = rest [ : qpos ] else : params = { } ", "answer": "if host . endswith ( '' ) :"}, {"prompt": " import re from wlauto import AndroidUiAutoBenchmark , Parameter class RealLinpack ( AndroidUiAutoBenchmark ) : name = '' description = \"\"\"\"\"\" package = '' activity = '' parameters = [ ", "answer": "Parameter ( '' , kind = int , default = , constraint = lambda x : x > ,"}, {"prompt": " '''''' import numpy as np from copy import deepcopy from matrix_builder import * from genetics import * from parameters_sanity import * from scipy . stats import gamma from scipy . special import gammainc import warnings ZERO = MOLECULES = Genetics ( ) class Model ( ) : '''''' def __init__ ( self , model_type , parameters = None , ** kwargs ) : '''''' self . model_type = model_type . lower ( ) if parameters is None : self . params = { } else : self . params = parameters self . name = kwargs . get ( '' , None ) self . rate_probs = kwargs . get ( '' , None ) self . rate_factors = kwargs . get ( '' , np . ones ( ) ) self . alpha = kwargs . get ( '' , None ) self . k_gamma = kwargs . get ( '' , ) self . pinv = kwargs . get ( '' , ) self . _save_custom_matrix_freqs = kwargs . get ( '' , \"\" ) self . code = None self . aa_models = [ '' , '' , '' , '' , '' , '' , '' ] self . _check_acceptable_model ( ) self . _check_hetcodon_model ( ) self . _construct_model ( ) def _assign_code ( self ) : '''''' if \"\" in self . params : self . code = self . params [ \"\" ] else : dim = len ( self . params [ '' ] ) if dim == : self . code = MOLECULES . nucleotides elif dim == : self . code = MOLECULES . amino_acids elif dim == : self . code = MOLECULES . codons else : raise ValueError ( \"\" ) def _check_acceptable_model ( self ) : '''''' self . model_type = self . model_type . replace ( \"\" , \"\" ) accepted_models = [ '' , '' , '' , '' , '' , '' , '' , '' , '' ] + self . aa_models assert ( self . model_type in accepted_models ) , \"\" assert ( type ( self . params ) is dict ) , \"\" if self . model_type == '' : self . model_type = '' print ( \"\" ) if self . model_type == '' : self . model_type = '' print ( \"\" ) if self . model_type == '' : assert ( \"\" in self . params ) , \"\" if \"\" in self . params : warn ( \"\" , self . _save_custom_matrix_freqs , \"\" ) def _check_hetcodon_model ( self ) : '''''' self . hetcodon_model = False if \"\" in self . params : self . params [ \"\" ] = self . params [ \"\" ] self . params . pop ( \"\" ) try : ( x for x in self . params [ \"\" ] ) self . hetcodon_model = True except : self . hetcodon_model = False def _construct_model ( self ) : '''''' if self . hetcodon_model : self . _assign_rate_probs ( ) else : self . _assign_rates ( ) self . _assign_matrix ( ) self . _assign_code ( ) def _assign_matrix ( self ) : '''''' if self . model_type == '' : self . params = Nucleotide_Sanity ( self . model_type , self . params , size = ) ( ) self . matrix = Nucleotide_Matrix ( self . model_type , self . params ) ( ) elif self . model_type in self . aa_models : self . params = AminoAcid_Sanity ( self . model_type , self . params , size = ) ( ) self . matrix = AminoAcid_Matrix ( self . model_type , self . params ) ( ) elif self . model_type == '' or self . model_type == '' : self . params = MechCodon_Sanity ( self . model_type , self . params , size = , hetcodon_model = self . hetcodon_model ) ( ) if self . hetcodon_model : self . _assign_hetcodon_model_matrices ( ) else : self . matrix = MechCodon_Matrix ( self . model_type , self . params ) ( ) elif '' in self . model_type : self . params = ECM_Sanity ( self . model_type , self . params , size = ) ( ) self . matrix = ECM_Matrix ( self . model_type , self . params ) ( ) elif self . model_type == '' : self . params = MutSel_Sanity ( self . model_type , self . params ) ( ) self . matrix = MutSel_Matrix ( self . model_type , self . params ) ( ) if not self . params [ \"\" ] : self . _calculate_state_freqs_from_matrix ( ) elif self . model_type == '' : self . _assign_custom_matrix ( ) self . _calculate_state_freqs_from_matrix ( ) np . savetxt ( self . _save_custom_matrix_freqs , self . params [ \"\" ] ) else : raise ValueError ( \"\" ) assert ( \"\" in self . params ) , \"\" def _assign_custom_matrix ( self ) : '''''' custom_matrix = np . array ( self . params [ '' ] ) if \"\" in self . params : assert ( type ( self . params [ \"\" ] ) is list ) , \"\" for item in self . params [ \"\" ] : assert ( type ( item ) is str ) , \"\" dim = len ( self . params [ \"\" ] ) assert ( custom_matrix . shape == ( dim , dim ) ) , \"\" else : assert ( custom_matrix . shape == ( , ) or custom_matrix . shape == ( , ) or custom_matrix . shape == ( , ) ) , \"\" dim = custom_matrix . shape [ ] assert ( np . allclose ( np . zeros ( dim ) , np . sum ( custom_matrix , ) , rtol = ) ) , \"\" for s in range ( dim ) : temp_sum = np . sum ( custom_matrix [ s ] ) - np . sum ( custom_matrix [ s ] [ s ] ) custom_matrix [ s ] [ s ] = - * temp_sum assert ( abs ( np . sum ( custom_matrix [ s ] ) ) <= ZERO ) , \"\" self . matrix = custom_matrix def _assign_hetcodon_model_matrices ( self ) : '''''' dnds_values = np . array ( self . params [ \"\" ] ) / np . array ( self . params [ \"\" ] ) self . params [ \"\" ] = np . average ( dnds_values , weights = self . rate_probs ) self . matrix = [ ] for i in range ( len ( self . params [ '' ] ) ) : temp_params = deepcopy ( self . params ) temp_params [ '' ] = self . params [ '' ] [ i ] temp_params [ '' ] = self . params [ '' ] [ i ] mb = MechCodon_Matrix ( self . model_type , temp_params ) self . matrix . append ( mb ( ) ) assert ( len ( self . matrix ) > ) , \"\" def _calculate_state_freqs_from_matrix ( self ) : '''''' size = self . matrix . shape [ ] ( w , v ) = linalg . eig ( self . matrix , left = True , right = False ) max_i = np . argmax ( w ) max_w = w [ max_i ] assert ( abs ( max_w ) <= ZERO ) , \"\" max_v = v [ : , max_i ] max_v /= np . sum ( max_v ) eq_freqs = max_v . real eq_freqs [ eq_freqs == ] = ZERO assert ( abs ( - np . sum ( eq_freqs ) ) <= ZERO ) , \"\" assert np . allclose ( np . zeros ( size ) , np . dot ( eq_freqs , self . matrix ) ) , \"\" pi_inv = np . diag ( / eq_freqs ) s = np . dot ( self . matrix , pi_inv ) assert np . allclose ( self . matrix , np . dot ( s , np . diag ( eq_freqs ) ) , atol = ZERO , rtol = ) , \"\" assert ( not np . allclose ( eq_freqs , np . zeros ( size ) ) ) , \"\" self . params [ \"\" ] = eq_freqs def _assign_rates ( self ) : '''''' if \"\" in self . model_type : self . rate_probs = np . ones ( ) else : if self . alpha is not None : assert ( self . pinv >= and self . pinv <= ) , \"\" self . _draw_gamma_rates ( ) else : self . _assign_rate_probs ( ) self . _sanity_rate_factors ( ) def _draw_gamma_rates ( self ) : '''''' if self . rate_probs is not None : warn ( \"\" ) if type ( self . k_gamma ) is not int : raise TypeError ( \"\" ) rv = gamma ( self . alpha , scale = / self . alpha ) freqK = np . zeros ( self . k_gamma ) rK = np . zeros ( self . k_gamma ) for i in range ( self . k_gamma - ) : raw = rv . ppf ( ( i + ) / self . k_gamma ) freqK [ i ] = gammainc ( self . alpha + , raw * self . alpha ) rK [ ] = freqK [ ] * self . k_gamma rK [ self . k_gamma - ] = ( - freqK [ self . k_gamma - ] ) * self . k_gamma for i in range ( , self . k_gamma - ) : rK [ i ] = self . k_gamma * ( freqK [ i ] - freqK [ i - ] ) if self . pinv <= ZERO : self . rate_probs = np . repeat ( / self . k_gamma , self . k_gamma ) self . rate_factors = deepcopy ( rK ) else : freqK *= ( - self . pinv ) freqK = list ( freqK ) freqK . append ( self . pinv ) self . rate_probs = np . array ( freqK ) rK = list ( rK ) rK . append ( ) self . rate_factors = np . array ( rK ) def _assign_rate_probs ( self ) : '''''' if self . hetcodon_model : num_probs = len ( self . params [ \"\" ] ) else : num_probs = len ( self . rate_factors ) if self . rate_probs is None : self . rate_probs = np . repeat ( / num_probs , num_probs ) assert ( abs ( - np . sum ( self . rate_probs ) ) <= ZERO ) , \"\" try : self . rate_probs = np . array ( self . rate_probs ) except : raise TypeError ( \"\" ) assert ( len ( self . rate_probs ) == num_probs ) , \"\" def _sanity_rate_factors ( self ) : '''''' try : self . rate_factors = np . array ( self . rate_factors ) except : raise TypeError ( \"\" ) ", "answer": "if abs ( - np . sum ( self . rate_probs * self . rate_factors ) ) > ZERO :"}, {"prompt": " \"\"\"\"\"\" from __future__ import division , absolute_import __metaclass__ = type from zope . interface import implementer from twisted . python . compat import networkString from twisted . python . filepath import FilePath from twisted . internet . test . reactormixins import ReactorBuilder from twisted . internet . protocol import ServerFactory , ClientFactory , Protocol from twisted . internet . interfaces import ( IReactorSSL , ITLSTransport , IStreamClientEndpoint ) from twisted . internet . defer import Deferred , DeferredList from twisted . internet . endpoints import ( SSL4ServerEndpoint , SSL4ClientEndpoint , TCP4ClientEndpoint ) from twisted . internet . error import ConnectionClosed from twisted . internet . task import Cooperator from twisted . trial . unittest import SkipTest from twisted . python . runtime import platform from twisted . internet . test . test_core import ObjectModelIntegrationMixin from twisted . internet . test . test_tcp import ( StreamTransportTestsMixin , AbortConnectionMixin ) from twisted . internet . test . connectionmixins import ( EndpointCreator , ConnectionTestsMixin , BrokenContextFactory ) try : from OpenSSL . crypto import FILETYPE_PEM except ImportError : FILETYPE_PEM = None else : from twisted . internet . ssl import PrivateCertificate , KeyPair from twisted . internet . ssl import ClientContextFactory class TLSMixin : requiredInterfaces = [ IReactorSSL ] if platform . isWindows ( ) : msg = ( \"\" \"\" ) skippedReactors = { \"\" : msg , \"\" : msg } class ContextGeneratingMixin ( object ) : import twisted _pem = FilePath ( networkString ( twisted . __file__ ) ) . sibling ( b\"\" ) . child ( b\"\" ) del twisted def getServerContext ( self ) : \"\"\"\"\"\" pem = self . _pem . getContent ( ) cert = PrivateCertificate . load ( pem , KeyPair . load ( pem , FILETYPE_PEM ) , FILETYPE_PEM ) return cert . options ( ) def getClientContext ( self ) : return ClientContextFactory ( ) @ implementer ( IStreamClientEndpoint ) class StartTLSClientEndpoint ( object ) : \"\"\"\"\"\" def __init__ ( self , wrapped , contextFactory ) : self . wrapped = wrapped self . contextFactory = contextFactory def connect ( self , factory ) : \"\"\"\"\"\" class WrapperFactory ( ServerFactory ) : def buildProtocol ( wrapperSelf , addr ) : protocol = factory . buildProtocol ( addr ) def connectionMade ( orig = protocol . connectionMade ) : protocol . transport . startTLS ( self . contextFactory ) orig ( ) protocol . connectionMade = connectionMade return protocol return self . wrapped . connect ( WrapperFactory ( ) ) class StartTLSClientCreator ( EndpointCreator , ContextGeneratingMixin ) : \"\"\"\"\"\" def server ( self , reactor ) : \"\"\"\"\"\" return SSL4ServerEndpoint ( reactor , , self . getServerContext ( ) ) def client ( self , reactor , serverAddress ) : \"\"\"\"\"\" return StartTLSClientEndpoint ( TCP4ClientEndpoint ( reactor , '' , serverAddress . port ) , ClientContextFactory ( ) ) class BadContextTestsMixin ( object ) : \"\"\"\"\"\" def _testBadContext ( self , useIt ) : \"\"\"\"\"\" reactor = self . buildReactor ( ) exc = self . assertRaises ( ValueError , useIt , reactor , BrokenContextFactory ( ) ) self . assertEqual ( BrokenContextFactory . message , str ( exc ) ) class StartTLSClientTestsMixin ( TLSMixin , ReactorBuilder , ConnectionTestsMixin ) : \"\"\"\"\"\" endpoints = StartTLSClientCreator ( ) class SSLCreator ( EndpointCreator , ContextGeneratingMixin ) : \"\"\"\"\"\" def server ( self , reactor ) : \"\"\"\"\"\" return SSL4ServerEndpoint ( reactor , , self . getServerContext ( ) ) def client ( self , reactor , serverAddress ) : \"\"\"\"\"\" return SSL4ClientEndpoint ( reactor , '' , serverAddress . port , ClientContextFactory ( ) ) class SSLClientTestsMixin ( TLSMixin , ReactorBuilder , ContextGeneratingMixin , ConnectionTestsMixin , BadContextTestsMixin ) : \"\"\"\"\"\" endpoints = SSLCreator ( ) def test_badContext ( self ) : \"\"\"\"\"\" def useIt ( reactor , contextFactory ) : return reactor . connectSSL ( \"\" , , ClientFactory ( ) , contextFactory ) self . _testBadContext ( useIt ) def test_disconnectAfterWriteAfterStartTLS ( self ) : \"\"\"\"\"\" class ShortProtocol ( Protocol ) : def connectionMade ( self ) : if not ITLSTransport . providedBy ( self . transport ) : finished = self . factory . finished self . factory . finished = None finished . errback ( SkipTest ( \"\" ) ) return self . transport . startTLS ( self . factory . context ) self . transport . write ( b\"\" ) def dataReceived ( self , data ) : self . transport . write ( b\"\" ) self . transport . loseConnection ( ) def connectionLost ( self , reason ) : finished = self . factory . finished ", "answer": "if finished is not None :"}, {"prompt": " \"\"\"\"\"\" import sys from twisted . names import client , error from twisted . internet . task import react from twisted . python import usage class Options ( usage . Options ) : synopsis = '' def parseArgs ( self , service , proto , domainname ) : self [ '' ] = service self [ '' ] = proto self [ '' ] = domainname def printResult ( records , domainname ) : \"\"\"\"\"\" answers , authority , additional = records if answers : sys . stdout . write ( domainname + '' + '' . join ( str ( x . payload ) for x in answers ) + '' ) else : sys . stderr . write ( '' % ( domainname , ) ) def printError ( failure , domainname ) : \"\"\"\"\"\" failure . trap ( error . DNSNameError ) sys . stderr . write ( '' % ( domainname , ) ) def main ( reactor , * argv ) : options = Options ( ) try : options . parseOptions ( argv ) except usage . UsageError as errortext : sys . stderr . write ( str ( options ) + '' ) sys . stderr . write ( '' % ( errortext , ) ) raise SystemExit ( ) resolver = client . Resolver ( '' ) domainname = '' % options d = resolver . lookupService ( domainname ) d . addCallback ( printResult , domainname ) d . addErrback ( printError , domainname ) ", "answer": "return d"}, {"prompt": " import datetime import dateutil . parser import logging import re import time import uuid from django . conf import settings as django_settings from django . core . exceptions import ObjectDoesNotExist , MultipleObjectsReturned from django . db import transaction from django . utils import six , dateparse , timezone from requests import ConnectionError from keystoneclient . auth . identity import v2 from keystoneclient . service_catalog import ServiceCatalog from keystoneclient import session as keystone_session from ceilometerclient import client as ceilometer_client from cinderclient . v1 import client as cinder_client from glanceclient . v1 import client as glance_client from keystoneclient . v2_0 import client as keystone_client from neutronclient . v2_0 import client as neutron_client from novaclient . v1_1 import client as nova_client from cinderclient import exceptions as cinder_exceptions from glanceclient import exc as glance_exceptions from keystoneclient import exceptions as keystone_exceptions from neutronclient . client import exceptions as neutron_exceptions from novaclient import exceptions as nova_exceptions from nodeconductor . core . models import StateMixin from nodeconductor . core . tasks import send_task from nodeconductor . structure import ServiceBackend , ServiceBackendError , log_backend_action from nodeconductor . structure . log import event_logger from nodeconductor . openstack import models logger = logging . getLogger ( __name__ ) class OpenStackBackendError ( ServiceBackendError ) : pass class OpenStackSession ( dict ) : \"\"\"\"\"\" def __init__ ( self , ks_session = None , verify_ssl = False , ** credentials ) : self . keystone_session = ks_session if not self . keystone_session : auth_plugin = v2 . Password ( ** credentials ) self . keystone_session = keystone_session . Session ( auth = auth_plugin , verify = verify_ssl ) try : self . keystone_session . get_token ( ) except ( keystone_exceptions . AuthorizationFailure , keystone_exceptions . ConnectionRefused ) as e : six . reraise ( OpenStackBackendError , e ) for opt in ( '' , '' , '' , '' ) : self [ opt ] = getattr ( self . auth , opt ) def __getattr__ ( self , name ) : return getattr ( self . keystone_session , name ) @ classmethod def recover ( cls , session , verify_ssl = False ) : if not isinstance ( session , dict ) or not session . get ( '' ) : raise OpenStackBackendError ( '' ) args = { '' : session [ '' ] , '' : session [ '' ] [ '' ] [ '' ] } if session [ '' ] : args [ '' ] = session [ '' ] elif session [ '' ] : args [ '' ] = session [ '' ] ks_session = keystone_session . Session ( auth = v2 . Token ( ** args ) , verify = verify_ssl ) return cls ( ks_session = ks_session , tenant_id = session [ '' ] , tenant_name = session [ '' ] ) def validate ( self ) : expiresat = dateutil . parser . parse ( self . auth . auth_ref [ '' ] [ '' ] ) if expiresat > timezone . now ( ) + datetime . timedelta ( minutes = ) : return True raise OpenStackBackendError ( '' ) def __str__ ( self ) : return str ( { k : v if k != '' else '' for k , v in self } ) class OpenStackClient ( object ) : \"\"\"\"\"\" def __init__ ( self , session = None , verify_ssl = False , ** credentials ) : self . verify_ssl = verify_ssl if session : if isinstance ( session , dict ) : logger . info ( '' ) self . session = OpenStackSession . recover ( session , verify_ssl = verify_ssl ) self . session . validate ( ) else : self . session = session else : try : self . session = OpenStackSession ( verify_ssl = verify_ssl , ** credentials ) except AttributeError as e : logger . error ( '' ) six . reraise ( OpenStackBackendError , e ) @ property def keystone ( self ) : return keystone_client . Client ( session = self . session . keystone_session ) @ property def nova ( self ) : try : return nova_client . Client ( session = self . session . keystone_session ) except ( nova_exceptions . ClientException , keystone_exceptions . ClientException ) as e : logger . exception ( '' , e ) six . reraise ( OpenStackBackendError , e ) @ property def neutron ( self ) : try : return neutron_client . Client ( session = self . session . keystone_session ) except ( neutron_exceptions . NeutronClientException , keystone_exceptions . ClientException ) as e : logger . exception ( '' , e ) six . reraise ( OpenStackBackendError , e ) @ property def cinder ( self ) : try : return cinder_client . Client ( session = self . session . keystone_session ) except ( cinder_exceptions . ClientException , keystone_exceptions . ClientException ) as e : logger . exception ( '' , e ) six . reraise ( OpenStackBackendError , e ) @ property def glance ( self ) : catalog = ServiceCatalog . factory ( self . session . auth . auth_ref ) endpoint = catalog . url_for ( service_type = '' ) kwargs = { '' : self . session . get_token ( ) , '' : not self . verify_ssl , '' : , '' : True , } return glance_client . Client ( endpoint , ** kwargs ) @ property def ceilometer ( self ) : catalog = ServiceCatalog . factory ( self . session . auth . auth_ref ) endpoint = catalog . url_for ( service_type = '' ) kwargs = { '' : lambda : self . session . get_token ( ) , '' : endpoint , '' : not self . verify_ssl , '' : , '' : True , } return ceilometer_client . Client ( '' , ** kwargs ) class OpenStackBackend ( ServiceBackend ) : DEFAULT_TENANT = '' def __init__ ( self , settings , tenant_id = None ) : self . settings = settings self . tenant_id = tenant_id def get_client ( self , name = None , admin = False ) : credentials = { '' : self . settings . backend_url , '' : self . settings . username , '' : self . settings . password , } if not admin : if not self . tenant_id : raise OpenStackBackendError ( \"\" ) credentials [ '' ] = self . tenant_id elif self . settings . options : credentials [ '' ] = self . settings . options . get ( '' , self . DEFAULT_TENANT ) else : credentials [ '' ] = self . DEFAULT_TENANT attr_name = '' if admin else '' client = getattr ( self , attr_name , None ) if hasattr ( self , attr_name ) : client = getattr ( self , attr_name ) else : client = OpenStackClient ( ** credentials ) setattr ( self , attr_name , client ) if name : return getattr ( client , name ) else : return client def __getattr__ ( self , name ) : clients = '' , '' , '' , '' , '' , '' for client in clients : if name == '' . format ( client ) : return self . get_client ( client , admin = False ) if name == '' . format ( client ) : return self . get_client ( client , admin = True ) raise AttributeError ( \"\" % ( self . __class__ . __name__ , name ) ) def ping ( self , raise_exception = False ) : return True def ping_resource ( self , instance ) : try : self . nova_client . servers . get ( instance . backend_id ) except ( ConnectionError , nova_exceptions . ClientException ) : return False else : return True def sync ( self ) : try : self . pull_flavors ( ) self . pull_images ( ) except ( nova_exceptions . ClientException , glance_exceptions . ClientException ) as e : logger . exception ( '' , self . settings . backend_url ) six . reraise ( OpenStackBackendError , e ) else : logger . info ( '' , self . settings . backend_url ) def provision ( self , instance , flavor = None , image = None , ssh_key = None , ** kwargs ) : if ssh_key : instance . key_name = self . get_key_name ( ssh_key ) instance . key_fingerprint = ssh_key . fingerprint kwargs [ '' ] = ssh_key . public_key instance . flavor_name = flavor . name instance . cores = flavor . cores instance . ram = flavor . ram instance . flavor_disk = flavor . disk instance . disk = instance . system_volume_size + instance . data_volume_size if image : instance . image_name = image . name instance . min_disk = image . min_disk instance . min_ram = image . min_ram instance . save ( ) kwargs [ '' ] = flavor . backend_id if image : kwargs [ '' ] = image . backend_id send_task ( '' , '' ) ( instance . uuid . hex , ** kwargs ) def destroy ( self , instance , force = False ) : instance . schedule_deletion ( ) instance . save ( ) send_task ( '' , '' ) ( instance . uuid . hex , force = force ) def start ( self , instance ) : instance . schedule_starting ( ) instance . save ( ) send_task ( '' , '' ) ( instance . uuid . hex ) def stop ( self , instance ) : instance . schedule_stopping ( ) instance . save ( ) send_task ( '' , '' ) ( instance . uuid . hex ) def restart ( self , instance ) : instance . schedule_restarting ( ) instance . save ( ) send_task ( '' , '' ) ( instance . uuid . hex ) def get_key_name ( self , public_key ) : safe_name = self . sanitize_key_name ( public_key . name ) key_name = '' . format ( public_key . uuid . hex , safe_name ) return key_name def sanitize_key_name ( self , key_name ) : return re . sub ( r'' , '' , key_name ) [ : ] def add_ssh_key ( self , ssh_key , service_project_link ) : if service_project_link . tenant is not None : key_name = self . get_key_name ( ssh_key ) self . get_or_create_ssh_key_for_tenant ( service_project_link . tenant , key_name , ssh_key . fingerprint , ssh_key . public_key ) def get_or_create_ssh_key_for_tenant ( self , tenant , key_name , fingerprint , public_key ) : nova = self . nova_client try : return nova . keypairs . find ( fingerprint = fingerprint ) except nova_exceptions . NotFound : try : return nova . keypairs . create ( name = key_name , public_key = public_key ) except ( nova_exceptions . ClientException , keystone_exceptions . ClientException ) as e : six . reraise ( OpenStackBackendError , e ) else : logger . info ( '' , key_name ) except ( nova_exceptions . ClientException , keystone_exceptions . ClientException ) as e : six . reraise ( OpenStackBackendError , e ) else : logger . info ( '' , key_name ) def remove_ssh_key ( self , ssh_key , service_project_link ) : if service_project_link . tenant is not None : self . remove_ssh_key_from_tenant ( service_project_link . tenant , ssh_key ) @ log_backend_action ( ) def remove_ssh_key_from_tenant ( self , tenant , key_name , fingerprint ) : nova = self . nova_client keys = nova . keypairs . findall ( fingerprint = fingerprint ) for key in keys : if key . name == key_name : nova . keypairs . delete ( key ) logger . info ( '' , key_name ) def _get_instance_state ( self , instance ) : nova_to_nodeconductor = { '' : models . Instance . States . ONLINE , '' : models . Instance . States . PROVISIONING , '' : models . Instance . States . ERRED , '' : models . Instance . States . ERRED , '' : models . Instance . States . STOPPING , '' : models . Instance . States . STOPPING , '' : models . Instance . States . STARTING , '' : models . Instance . States . ONLINE , '' : models . Instance . States . OFFLINE , '' : models . Instance . States . ONLINE , '' : models . Instance . States . OFFLINE , '' : models . Instance . States . STOPPING , '' : models . Instance . States . OFFLINE , '' : models . Instance . States . OFFLINE , '' : models . Instance . States . OFFLINE , '' : models . Instance . States . OFFLINE , } return nova_to_nodeconductor . get ( instance . status , models . Instance . States . ERRED ) def _get_current_properties ( self , model ) : return { p . backend_id : p for p in model . objects . filter ( settings = self . settings ) } def _are_rules_equal ( self , backend_rule , nc_rule ) : if backend_rule [ '' ] != nc_rule . from_port : return False if backend_rule [ '' ] != nc_rule . to_port : return False if backend_rule [ '' ] != nc_rule . protocol : return False if backend_rule [ '' ] . get ( '' , '' ) != nc_rule . cidr : return False return True def _are_security_groups_equal ( self , backend_security_group , nc_security_group ) : if backend_security_group . name != nc_security_group . name : return False if len ( backend_security_group . rules ) != nc_security_group . rules . count ( ) : return False for backend_rule , nc_rule in zip ( backend_security_group . rules , nc_security_group . rules . all ( ) ) : if not self . _are_rules_equal ( backend_rule , nc_rule ) : return False return True def _normalize_security_group_rule ( self , rule ) : if rule [ '' ] is None : rule [ '' ] = '' if '' not in rule [ '' ] : rule [ '' ] [ '' ] = '' return rule def _wait_for_instance_status ( self , server_id , nova , complete_status , error_status = None , retries = , poll_interval = ) : return self . _wait_for_object_status ( server_id , nova . servers . get , complete_status , error_status , retries , poll_interval ) def _wait_for_volume_status ( self , volume_id , cinder , complete_status , error_status = None , retries = , poll_interval = ) : return self . _wait_for_object_status ( volume_id , cinder . volumes . get , complete_status , error_status , retries , poll_interval ) def _wait_for_snapshot_status ( self , snapshot_id , cinder , complete_status , error_status , retries = , poll_interval = ) : return self . _wait_for_object_status ( snapshot_id , cinder . volume_snapshots . get , complete_status , error_status , retries , poll_interval ) def _wait_for_backup_status ( self , backup , cinder , complete_status , error_status , retries = , poll_interval = ) : return self . _wait_for_object_status ( backup , cinder . backups . get , complete_status , error_status , retries , poll_interval ) def _wait_for_object_status ( self , obj_id , client_get_method , complete_status , error_status = None , retries = , poll_interval = ) : complete_state_predicate = lambda o : o . status == complete_status if error_status is not None : error_state_predicate = lambda o : o . status == error_status else : error_state_predicate = lambda _ : False for _ in range ( retries ) : obj = client_get_method ( obj_id ) if complete_state_predicate ( obj ) : return True if error_state_predicate ( obj ) : return False time . sleep ( poll_interval ) else : return False def _wait_for_volume_deletion ( self , volume_id , cinder , retries = , poll_interval = ) : try : for _ in range ( retries ) : cinder . volumes . get ( volume_id ) time . sleep ( poll_interval ) return False except cinder_exceptions . NotFound : return True def _wait_for_snapshot_deletion ( self , snapshot_id , cinder , retries = , poll_interval = ) : try : for _ in range ( retries ) : cinder . volume_snapshots . get ( snapshot_id ) time . sleep ( poll_interval ) return False except ( cinder_exceptions . NotFound , keystone_exceptions . NotFound ) : return True def _wait_for_instance_deletion ( self , backend_instance_id , retries = , poll_interval = ) : nova = self . nova_client try : for _ in range ( retries ) : nova . servers . get ( backend_instance_id ) time . sleep ( poll_interval ) return False except nova_exceptions . NotFound : return True def pull_flavors ( self ) : nova = self . nova_admin_client with transaction . atomic ( ) : cur_flavors = self . _get_current_properties ( models . Flavor ) for backend_flavor in nova . flavors . findall ( is_public = True ) : cur_flavors . pop ( backend_flavor . id , None ) models . Flavor . objects . update_or_create ( settings = self . settings , backend_id = backend_flavor . id , defaults = { '' : backend_flavor . name , '' : backend_flavor . vcpus , '' : backend_flavor . ram , '' : self . gb2mb ( backend_flavor . disk ) , } ) models . Flavor . objects . filter ( backend_id__in = cur_flavors . keys ( ) ) . delete ( ) def pull_images ( self ) : glance = self . glance_admin_client with transaction . atomic ( ) : cur_images = self . _get_current_properties ( models . Image ) for backend_image in glance . images . list ( ) : if backend_image . is_public and not backend_image . deleted : cur_images . pop ( backend_image . id , None ) models . Image . objects . update_or_create ( settings = self . settings , backend_id = backend_image . id , defaults = { '' : backend_image . name , '' : backend_image . min_ram , '' : self . gb2mb ( backend_image . min_disk ) , } ) models . Image . objects . filter ( backend_id__in = cur_images . keys ( ) ) . delete ( ) @ log_backend_action ( '' ) def push_tenant_quotas ( self , tenant , quotas ) : if '' in quotas : quotas_ratios = django_settings . NODECONDUCTOR . get ( '' , { } ) volume_ratio = quotas_ratios . get ( '' , ) snapshots_ratio = quotas_ratios . get ( '' , ) quotas [ '' ] = volume_ratio * quotas [ '' ] quotas [ '' ] = snapshots_ratio * quotas [ '' ] cinder_quotas = { '' : self . mb2gb ( quotas . get ( '' ) ) if '' in quotas else None , '' : quotas . get ( '' ) , '' : quotas . get ( '' ) , } cinder_quotas = { k : v for k , v in cinder_quotas . items ( ) if v is not None } nova_quotas = { '' : quotas . get ( '' ) , '' : quotas . get ( '' ) , } nova_quotas = { k : v for k , v in nova_quotas . items ( ) if v is not None } neutron_quotas = { '' : quotas . get ( '' ) , '' : quotas . get ( '' ) , } neutron_quotas = { k : v for k , v in neutron_quotas . items ( ) if v is not None } try : if cinder_quotas : self . cinder_client . quotas . update ( tenant . backend_id , ** cinder_quotas ) if nova_quotas : self . nova_client . quotas . update ( tenant . backend_id , ** nova_quotas ) if neutron_quotas : self . neutron_client . update_quota ( tenant . backend_id , { '' : neutron_quotas } ) except Exception as e : six . reraise ( OpenStackBackendError , e ) @ log_backend_action ( '' ) def pull_tenant_quotas ( self , tenant ) : nova = self . nova_client neutron = self . neutron_client cinder = self . cinder_client service_project_link = tenant . service_project_link try : nova_quotas = nova . quotas . get ( tenant_id = tenant . backend_id ) cinder_quotas = cinder . quotas . get ( tenant_id = tenant . backend_id ) neutron_quotas = neutron . show_quota ( tenant_id = tenant . backend_id ) [ '' ] except ( nova_exceptions . ClientException , cinder_exceptions . ClientException , neutron_exceptions . NeutronClientException ) as e : six . reraise ( OpenStackBackendError , e ) service_project_link . set_quota_limit ( '' , nova_quotas . ram ) service_project_link . set_quota_limit ( '' , nova_quotas . cores ) service_project_link . set_quota_limit ( '' , self . gb2mb ( cinder_quotas . gigabytes ) ) service_project_link . set_quota_limit ( '' , nova_quotas . instances ) service_project_link . set_quota_limit ( '' , neutron_quotas [ '' ] ) service_project_link . set_quota_limit ( '' , neutron_quotas [ '' ] ) service_project_link . set_quota_limit ( '' , neutron_quotas [ '' ] ) try : volumes = cinder . volumes . list ( ) snapshots = cinder . volume_snapshots . list ( ) instances = nova . servers . list ( ) security_groups = nova . security_groups . list ( ) floating_ips = neutron . list_floatingips ( tenant_id = tenant . backend_id ) [ '' ] flavors = { flavor . id : flavor for flavor in nova . flavors . list ( ) } ram , vcpu = , for flavor_id in ( instance . flavor [ '' ] for instance in instances ) : try : flavor = flavors . get ( flavor_id , nova . flavors . get ( flavor_id ) ) except nova_exceptions . NotFound : logger . warning ( '' , flavor_id ) continue ram += getattr ( flavor , '' , ) vcpu += getattr ( flavor , '' , ) except ( nova_exceptions . ClientException , cinder_exceptions . ClientException , neutron_exceptions . NeutronClientException ) as e : six . reraise ( OpenStackBackendError , e ) service_project_link . set_quota_usage ( '' , ram ) service_project_link . set_quota_usage ( '' , vcpu ) service_project_link . set_quota_usage ( '' , sum ( self . gb2mb ( v . size ) for v in volumes + snapshots ) ) service_project_link . set_quota_usage ( '' , len ( instances ) , fail_silently = True ) service_project_link . set_quota_usage ( '' , len ( security_groups ) ) service_project_link . set_quota_usage ( '' , len ( sum ( [ sg . rules for sg in security_groups ] , [ ] ) ) ) service_project_link . set_quota_usage ( '' , len ( floating_ips ) ) @ log_backend_action ( '' ) def pull_tenant_floating_ips ( self , tenant ) : service_project_link = tenant . service_project_link neutron = self . neutron_client try : nc_floating_ips = { ip . backend_id : ip for ip in service_project_link . floating_ips . all ( ) } try : backend_floating_ips = { ip [ '' ] : ip for ip in neutron . list_floatingips ( tenant_id = self . tenant_id ) [ '' ] if ip . get ( '' ) and ip . get ( '' ) } except neutron_exceptions . NeutronClientException as e : six . reraise ( OpenStackBackendError , e ) backend_ids = set ( backend_floating_ips . keys ( ) ) nc_ids = set ( nc_floating_ips . keys ( ) ) with transaction . atomic ( ) : for ip_id in nc_ids - backend_ids : ip = nc_floating_ips [ ip_id ] ip . delete ( ) logger . info ( '' , ip . uuid ) for ip_id in backend_ids - nc_ids : ip = backend_floating_ips [ ip_id ] created_ip = service_project_link . floating_ips . create ( status = ip [ '' ] , backend_id = ip [ '' ] , address = ip [ '' ] , backend_network_id = ip [ '' ] ) logger . info ( '' , created_ip . uuid ) for ip_id in nc_ids & backend_ids : nc_ip = nc_floating_ips [ ip_id ] backend_ip = backend_floating_ips [ ip_id ] if nc_ip . status != backend_ip [ '' ] or nc_ip . address != backend_ip [ '' ] or nc_ip . backend_network_id != backend_ip [ '' ] : if not ( nc_ip . status == '' and backend_ip [ '' ] == '' ) : nc_ip . status = backend_ip [ '' ] nc_ip . address = backend_ip [ '' ] nc_ip . backend_network_id = backend_ip [ '' ] nc_ip . save ( ) logger . info ( '' , nc_ip . uuid ) except Exception as e : six . reraise ( OpenStackBackendError , e ) @ log_backend_action ( '' ) def pull_tenant_security_groups ( self , tenant ) : nova = self . nova_client service_project_link = tenant . service_project_link try : try : backend_security_groups = nova . security_groups . list ( ) except nova_exceptions . ClientException as e : six . reraise ( OpenStackBackendError , e ) nonexistent_groups = [ ] unsynchronized_groups = [ ] extra_groups = service_project_link . security_groups . exclude ( backend_id__in = [ g . id for g in backend_security_groups ] , ) with transaction . atomic ( ) : for backend_group in backend_security_groups : try : nc_group = service_project_link . security_groups . get ( backend_id = backend_group . id ) if not self . _are_security_groups_equal ( backend_group , nc_group ) : unsynchronized_groups . append ( backend_group ) except models . SecurityGroup . DoesNotExist : nonexistent_groups . append ( backend_group ) extra_groups . delete ( ) if extra_groups : logger . debug ( '' , '' . join ( '' % ( sg . name , sg . pk ) for sg in extra_groups ) ) for backend_group in unsynchronized_groups : nc_security_group = service_project_link . security_groups . get ( backend_id = backend_group . id ) if backend_group . name != nc_security_group . name : nc_security_group . name = backend_group . name nc_security_group . state = StateMixin . States . OK nc_security_group . save ( ) self . pull_security_group_rules ( nc_security_group ) logger . debug ( '' , nc_security_group . name , nc_security_group . pk ) for backend_group in nonexistent_groups : nc_security_group = service_project_link . security_groups . create ( backend_id = backend_group . id , name = backend_group . name , state = StateMixin . States . OK ) self . pull_security_group_rules ( nc_security_group ) logger . debug ( '' , nc_security_group . name , nc_security_group . pk ) except Exception as e : six . reraise ( OpenStackBackendError , e ) def pull_security_group_rules ( self , security_group ) : nova = self . nova_client backend_security_group = nova . security_groups . get ( group_id = security_group . backend_id ) backend_rules = [ self . _normalize_security_group_rule ( r ) for r in backend_security_group . rules ] nonexistent_rules = [ ] unsynchronized_rules = [ ] extra_rules = security_group . rules . exclude ( backend_id__in = [ r [ '' ] for r in backend_rules ] ) with transaction . atomic ( ) : for backend_rule in backend_rules : try : nc_rule = security_group . rules . get ( backend_id = backend_rule [ '' ] ) if not self . _are_rules_equal ( backend_rule , nc_rule ) : unsynchronized_rules . append ( backend_rule ) except security_group . rules . model . DoesNotExist : nonexistent_rules . append ( backend_rule ) extra_rules . delete ( ) logger . info ( '' ) for backend_rule in unsynchronized_rules : security_group . rules . filter ( backend_id = backend_rule [ '' ] ) . update ( from_port = backend_rule [ '' ] , to_port = backend_rule [ '' ] , protocol = backend_rule [ '' ] , cidr = backend_rule [ '' ] [ '' ] , ) logger . debug ( '' ) for backend_rule in nonexistent_rules : rule = security_group . rules . create ( from_port = backend_rule [ '' ] , to_port = backend_rule [ '' ] , protocol = backend_rule [ '' ] , cidr = backend_rule [ '' ] [ '' ] , backend_id = backend_rule [ '' ] , ) logger . info ( '' , rule . id ) def sync_instance_security_groups ( self , instance ) : nova = self . nova_client server_id = instance . backend_id backend_ids = set ( g . id for g in nova . servers . list_security_group ( server_id ) ) nc_ids = set ( models . SecurityGroup . objects . filter ( instance_groups__instance__backend_id = server_id ) . exclude ( backend_id = '' ) . values_list ( '' , flat = True ) ) for group_id in backend_ids - nc_ids : try : nova . servers . remove_security_group ( server_id , group_id ) except nova_exceptions . ClientException : logger . exception ( '' , group_id , server_id ) else : logger . info ( '' , group_id , server_id ) for group_id in nc_ids - backend_ids : try : nova . servers . add_security_group ( server_id , group_id ) except nova_exceptions . ClientException : logger . exception ( '' , group_id , server_id ) else : logger . info ( '' , group_id , server_id ) @ log_backend_action ( ) ", "answer": "def create_tenant ( self , tenant ) :"}, {"prompt": " import json import socket from . . urllib3 import * from . dropbox_util import * class DropboxConnection ( ) : def request ( self , method , url , params = None , body = None , headers = None , raw_response = False ) : try : import ssl pool_manager = PoolManager ( num_pools = , maxsize = , block = False , timeout = , cert_reqs = ssl . CERT_REQUIRED , ca_certs = DropboxUtil . get_cert_file ( ) , ssl_version = ssl . PROTOCOL_TLSv1 , ) except ( ImportError ) : pool_manager = PoolManager ( num_pools = , maxsize = , block = False , timeout = , ) params = params or { } headers = headers or { } headers [ \"\" ] = \"\" if params : if body : raise ValueError ( \"\" ) body = urllib . parse . urlencode ( params ) headers [ \"\" ] = \"\" if hasattr ( body , \"\" ) : body = str ( body . getvalue ( ) ) headers [ \"\" ] = len ( body ) for key , value in headers . items ( ) : if type ( value ) == str and \"\" in value : raise ValueError ( \"\" + key + \"\" + value + \"\" ) try : response = pool_manager . urlopen ( method = method , url = url , body = body , headers = headers , preload_content = False ) except socket . error as e : raise SocketError ( url , e ) except exceptions . SSLError as e : raise SocketError ( url , \"\" % e ) if response . status != : raise ErrorResponse ( response , response . read ( ) ) return self . process_response ( response , raw_response ) def process_response ( self , r , raw_response ) : if raw_response : return r else : resp = json . loads ( r . read ( ) . decode ( \"\" ) ) r . close ( ) return resp def get ( self , url , headers = None , raw_response = False ) : return self . request ( \"\" , url , headers = headers , raw_response = raw_response ) def post ( self , url , params = None , headers = None , raw_response = False ) : if params is None : params = { } return self . request ( \"\" , url , params = params , headers = headers , raw_response = raw_response ) def put ( self , url , body , headers = None , raw_response = False ) : return self . request ( \"\" , url , body = body , headers = headers , raw_response = raw_response ) class SocketError ( socket . error ) : def __init__ ( self , host , e ) : msg = \"\" % ( host , str ( e ) ) socket . error . __init__ ( self , msg ) class ErrorResponse ( Exception ) : def __init__ ( self , http_resp , body ) : self . status = http_resp . status self . reason = http_resp . reason self . body = body self . headers = http_resp . getheaders ( ) http_resp . close ( ) try : self . body = json . loads ( self . body . decode ( \"\" ) ) self . error_msg = self . body . get ( '' ) self . user_error_msg = self . body . get ( '' ) except ValueError : self . error_msg = None self . user_error_msg = None def __str__ ( self ) : if self . user_error_msg and self . user_error_msg != self . error_msg : msg = \"\" % ( self . user_error_msg , self . error_msg ) elif self . error_msg : msg = repr ( self . error_msg ) elif not self . body : msg = repr ( self . reason ) else : ", "answer": "msg = \"\" + \"\" % ( self . body , self . headers )"}, {"prompt": " import unittest ", "answer": "from app import db , app"}, {"prompt": " import sys from pypy . rpython . lltypesystem import lltype , llmemory , rclass , rstr from pypy . rpython . ootypesystem import ootype from pypy . rpython . annlowlevel import llhelper , MixLevelHelperAnnotator , cast_base_ptr_to_instance , hlstr from pypy . annotation import model as annmodel from pypy . rpython . llinterp import LLException from pypy . rpython . test . test_llinterp import get_interpreter , clear_tcache from pypy . objspace . flow . model import SpaceOperation , Variable , Constant from pypy . objspace . flow . model import checkgraph , Link , copygraph from pypy . rlib . objectmodel import we_are_translated from pypy . rlib . unroll import unrolling_iterable from pypy . rlib . rarithmetic import r_uint , intmask from pypy . rlib . debug import debug_print from pypy . rpython . lltypesystem . lloperation import llop from pypy . translator . simplify import get_funcobj , get_functype from pypy . translator . unsimplify import call_final_function from pypy . jit . metainterp import codewriter from pypy . jit . metainterp import support , history , pyjitpl , gc from pypy . jit . metainterp . pyjitpl import MetaInterpStaticData , MetaInterp from pypy . jit . metainterp . policy import JitPolicy from pypy . jit . metainterp . typesystem import LLTypeHelper , OOTypeHelper from pypy . jit . metainterp . jitprof import Profiler , EmptyProfiler from pypy . rlib . jit import DEBUG_STEPS , DEBUG_DETAILED , DEBUG_OFF , DEBUG_PROFILE def apply_jit ( translator , backend_name = \"\" , debug_level = DEBUG_STEPS , inline = False , ** kwds ) : if '' not in kwds : from pypy . jit . backend . detect_cpu import getcpuclass kwds [ '' ] = getcpuclass ( backend_name ) if debug_level > DEBUG_OFF : ProfilerClass = Profiler else : ProfilerClass = EmptyProfiler warmrunnerdesc = WarmRunnerDesc ( translator , translate_support_code = True , listops = True , no_stats = True , ProfilerClass = ProfilerClass , ** kwds ) warmrunnerdesc . state . set_param_inlining ( inline ) warmrunnerdesc . state . set_param_debug ( debug_level ) warmrunnerdesc . finish ( ) translator . warmrunnerdesc = warmrunnerdesc def ll_meta_interp ( function , args , backendopt = False , type_system = '' , listcomp = False , ** kwds ) : if listcomp : extraconfigopts = { '' : True } else : extraconfigopts = { } interp , graph = get_interpreter ( function , args , backendopt = False , type_system = type_system , ** extraconfigopts ) clear_tcache ( ) return jittify_and_run ( interp , graph , args , backendopt = backendopt , ** kwds ) def jittify_and_run ( interp , graph , args , repeat = , backendopt = False , trace_limit = sys . maxint , debug_level = DEBUG_STEPS , inline = False , ** kwds ) : translator = interp . typer . annotator . translator translator . config . translation . gc = \"\" warmrunnerdesc = WarmRunnerDesc ( translator , backendopt = backendopt , ** kwds ) warmrunnerdesc . state . set_param_threshold ( ) warmrunnerdesc . state . set_param_trace_eagerness ( ) warmrunnerdesc . state . set_param_trace_limit ( trace_limit ) warmrunnerdesc . state . set_param_inlining ( inline ) warmrunnerdesc . state . set_param_debug ( debug_level ) warmrunnerdesc . finish ( ) res = interp . eval_graph ( graph , args ) if not kwds . get ( '' , False ) : warmrunnerdesc . metainterp_sd . profiler . finish ( ) print '' , res while repeat > : print '' * res1 = interp . eval_graph ( graph , args ) if isinstance ( res , int ) : assert res1 == res repeat -= return res def rpython_ll_meta_interp ( function , args , backendopt = True , loops = '' , ** kwds ) : return ll_meta_interp ( function , args , backendopt = backendopt , translate_support_code = True , ** kwds ) def _find_jit_marker ( graphs , marker_name ) : results = [ ] for graph in graphs : for block in graph . iterblocks ( ) : for i in range ( len ( block . operations ) ) : op = block . operations [ i ] if ( op . opname == '' and op . args [ ] . value == marker_name ) : results . append ( ( graph , block , i ) ) return results def find_can_enter_jit ( graphs ) : results = _find_jit_marker ( graphs , '' ) if not results : raise Exception ( \"\" ) return results def find_jit_merge_point ( graphs ) : results = _find_jit_marker ( graphs , '' ) if len ( results ) != : raise Exception ( \"\" % ( len ( results ) , ) ) return results [ ] def find_set_param ( graphs ) : return _find_jit_marker ( graphs , '' ) def get_stats ( ) : return pyjitpl . _warmrunnerdesc . stats def get_translator ( ) : return pyjitpl . _warmrunnerdesc . translator def debug_checks ( ) : stats = get_stats ( ) stats . maybe_view ( ) stats . check_consistency ( ) class JitException ( Exception ) : _go_through_llinterp_uncaught_ = True class ContinueRunningNormallyBase ( JitException ) : pass class CannotInlineCanEnterJit ( JitException ) : pass class WarmRunnerDesc : def __init__ ( self , translator , policy = None , backendopt = True , CPUClass = None , optimizer = None , ** kwds ) : pyjitpl . _warmrunnerdesc = self if policy is None : policy = JitPolicy ( ) self . set_translator ( translator ) self . find_portal ( ) self . make_leave_jit_graph ( ) self . codewriter = codewriter . CodeWriter ( self . rtyper ) graphs = self . codewriter . find_all_graphs ( self . portal_graph , self . leave_graph , policy , CPUClass . supports_floats ) policy . dump_unsafe_loops ( ) self . check_access_directly_sanity ( graphs ) if backendopt : self . prejit_optimizations ( policy , graphs ) self . build_meta_interp ( CPUClass , ** kwds ) self . make_args_specification ( ) self . rewrite_jit_merge_point ( policy ) self . make_driverhook_graphs ( ) if self . jitdriver . virtualizables : from pypy . jit . metainterp . virtualizable import VirtualizableInfo self . metainterp_sd . virtualizable_info = VirtualizableInfo ( self ) self . codewriter . generate_bytecode ( self . metainterp_sd , self . portal_graph , self . leave_graph , self . portal_runner_ptr ) self . make_enter_function ( ) self . rewrite_can_enter_jit ( ) self . rewrite_set_param ( ) self . add_profiler_finish ( ) self . metainterp_sd . finish_setup ( optimizer = optimizer ) def finish ( self ) : vinfo = self . metainterp_sd . virtualizable_info if vinfo is not None : vinfo . finish ( ) if self . cpu . translate_support_code : self . annhelper . finish ( ) def _freeze_ ( self ) : return True def set_translator ( self , translator ) : self . translator = translator self . rtyper = translator . rtyper self . gcdescr = gc . get_description ( translator . config ) def find_portal ( self ) : graphs = self . translator . graphs self . jit_merge_point_pos = find_jit_merge_point ( graphs ) graph , block , pos = self . jit_merge_point_pos op = block . operations [ pos ] args = op . args [ : ] s_binding = self . translator . annotator . binding self . portal_args_s = [ s_binding ( v ) for v in args ] graph = copygraph ( graph ) graph . startblock . isstartblock = False graph . startblock = support . split_before_jit_merge_point ( * find_jit_merge_point ( [ graph ] ) ) graph . startblock . isstartblock = True checkgraph ( graph ) for v in graph . getargs ( ) : assert isinstance ( v , Variable ) assert len ( dict . fromkeys ( graph . getargs ( ) ) ) == len ( graph . getargs ( ) ) self . translator . graphs . append ( graph ) self . portal_graph = graph assert hasattr ( graph , \"\" ) graph . func . _dont_inline_ = True graph . func . _jit_unroll_safe_ = True self . jitdriver = block . operations [ pos ] . args [ ] . value def check_access_directly_sanity ( self , graphs ) : from pypy . translator . backendopt . inline import collect_called_graphs jit_graphs = set ( graphs ) for graph in collect_called_graphs ( self . translator . graphs [ ] , self . translator ) : if graph in jit_graphs : continue assert not getattr ( graph , '' , False ) def prejit_optimizations ( self , policy , graphs ) : from pypy . translator . backendopt . all import backend_optimizations backend_optimizations ( self . translator , graphs = graphs , merge_if_blocks = True , constfold = True , raisingop2direct_call = False , remove_asserts = True , really_remove_asserts = True ) def build_meta_interp ( self , CPUClass , translate_support_code = False , view = \"\" , no_stats = False , ProfilerClass = EmptyProfiler , ** kwds ) : assert CPUClass is not None opt = history . Options ( ** kwds ) if no_stats : stats = history . NoStats ( ) else : stats = history . Stats ( ) self . stats = stats if translate_support_code : self . annhelper = MixLevelHelperAnnotator ( self . translator . rtyper ) annhelper = self . annhelper else : annhelper = None cpu = CPUClass ( self . translator . rtyper , self . stats , translate_support_code , gcdescr = self . gcdescr ) self . cpu = cpu self . metainterp_sd = MetaInterpStaticData ( self . portal_graph , cpu , self . stats , opt , ProfilerClass = ProfilerClass , warmrunnerdesc = self ) def make_enter_function ( self ) : from pypy . jit . metainterp . warmstate import WarmEnterState state = WarmEnterState ( self ) maybe_compile_and_run = state . make_entry_point ( ) self . state = state def crash_in_jit ( e ) : if not we_are_translated ( ) : print \"\" print '' % ( e . __class__ , e ) if sys . stdout == sys . __stdout__ : import pdb ; pdb . post_mortem ( sys . exc_info ( ) [ ] ) raise debug_print ( '' ) debug_print ( '' % ( e , ) ) raise history . CrashInJIT ( \"\" ) crash_in_jit . _dont_inline_ = True if self . translator . rtyper . type_system . name == '' : def maybe_enter_jit ( * args ) : try : maybe_compile_and_run ( * args ) except JitException : raise except Exception , e : crash_in_jit ( e ) maybe_enter_jit . _always_inline_ = True else : def maybe_enter_jit ( * args ) : maybe_compile_and_run ( * args ) maybe_enter_jit . _always_inline_ = True self . maybe_enter_jit_fn = maybe_enter_jit def make_leave_jit_graph ( self ) : self . leave_graph = None if self . jitdriver . leave : args_s = self . portal_args_s from pypy . annotation import model as annmodel annhelper = MixLevelHelperAnnotator ( self . translator . rtyper ) s_result = annmodel . s_None self . leave_graph = annhelper . getgraph ( self . jitdriver . leave , args_s , s_result ) annhelper . finish ( ) def make_driverhook_graphs ( self ) : from pypy . rlib . jit import BaseJitCell bk = self . rtyper . annotator . bookkeeper classdef = bk . getuniqueclassdef ( BaseJitCell ) s_BaseJitCell_or_None = annmodel . SomeInstance ( classdef , can_be_None = True ) s_BaseJitCell_not_None = annmodel . SomeInstance ( classdef ) s_Str = annmodel . SomeString ( ) annhelper = MixLevelHelperAnnotator ( self . translator . rtyper ) self . set_jitcell_at_ptr = self . _make_hook_graph ( annhelper , self . jitdriver . set_jitcell_at , annmodel . s_None , s_BaseJitCell_not_None ) self . get_jitcell_at_ptr = self . _make_hook_graph ( annhelper , self . jitdriver . get_jitcell_at , s_BaseJitCell_or_None ) self . can_inline_ptr = self . _make_hook_graph ( annhelper , self . jitdriver . can_inline , annmodel . s_Bool ) self . get_printable_location_ptr = self . _make_hook_graph ( annhelper , self . jitdriver . get_printable_location , s_Str ) annhelper . finish ( ) def _make_hook_graph ( self , annhelper , func , s_result , s_first_arg = None ) : if func is None : return None extra_args_s = [ ] if s_first_arg is not None : extra_args_s . append ( s_first_arg ) args_s = self . portal_args_s [ : len ( self . green_args_spec ) ] graph = annhelper . getgraph ( func , extra_args_s + args_s , s_result ) funcptr = annhelper . graph2delayed ( graph ) return funcptr def make_args_specification ( self ) : graph , block , index = self . jit_merge_point_pos op = block . operations [ index ] args = op . args [ : ] ALLARGS = [ ] self . green_args_spec = [ ] self . red_args_types = [ ] for i , v in enumerate ( args ) : TYPE = v . concretetype ALLARGS . append ( TYPE ) if i < len ( self . jitdriver . greens ) : self . green_args_spec . append ( TYPE ) else : self . red_args_types . append ( history . getkind ( TYPE ) ) self . num_green_args = len ( self . green_args_spec ) RESTYPE = graph . getreturnvar ( ) . concretetype ( self . JIT_ENTER_FUNCTYPE , self . PTR_JIT_ENTER_FUNCTYPE ) = self . cpu . ts . get_FuncType ( ALLARGS , lltype . Void ) ( self . PORTAL_FUNCTYPE , self . PTR_PORTAL_FUNCTYPE ) = self . cpu . ts . get_FuncType ( ALLARGS , RESTYPE ) def rewrite_can_enter_jit ( self ) : FUNC = self . JIT_ENTER_FUNCTYPE FUNCPTR = self . PTR_JIT_ENTER_FUNCTYPE jit_enter_fnptr = self . helper_func ( FUNCPTR , self . maybe_enter_jit_fn ) graphs = self . translator . graphs can_enter_jits = find_can_enter_jit ( graphs ) for graph , block , index in can_enter_jits : if graph is self . jit_merge_point_pos [ ] : continue op = block . operations [ index ] greens_v , reds_v = decode_hp_hint_args ( op ) args_v = greens_v + reds_v vlist = [ Constant ( jit_enter_fnptr , FUNCPTR ) ] + args_v v_result = Variable ( ) v_result . concretetype = lltype . Void newop = SpaceOperation ( '' , vlist , v_result ) block . operations [ index ] = newop def helper_func ( self , FUNCPTR , func ) : if not self . cpu . translate_support_code : return llhelper ( FUNCPTR , func ) FUNC = get_functype ( FUNCPTR ) args_s = [ annmodel . lltype_to_annotation ( ARG ) for ARG in FUNC . ARGS ] s_result = annmodel . lltype_to_annotation ( FUNC . RESULT ) graph = self . annhelper . getgraph ( func , args_s , s_result ) return self . annhelper . graph2delayed ( graph , FUNC ) def rewrite_jit_merge_point ( self , policy ) : origportalgraph = self . jit_merge_point_pos [ ] portalgraph = self . portal_graph PORTALFUNC = self . PORTAL_FUNCTYPE portal_ptr = self . cpu . ts . functionptr ( PORTALFUNC , '' , graph = portalgraph ) self . portal_ptr = portal_ptr portalfunc_ARGS = unrolling_iterable ( [ ( i , '' % i , ARG ) for i , ARG in enumerate ( PORTALFUNC . ARGS ) ] ) class DoneWithThisFrameVoid ( JitException ) : def __str__ ( self ) : return '' class DoneWithThisFrameInt ( JitException ) : def __init__ ( self , result ) : assert lltype . typeOf ( result ) is lltype . Signed self . result = result def __str__ ( self ) : return '' % ( self . result , ) class DoneWithThisFrameRef ( JitException ) : def __init__ ( self , cpu , result ) : assert lltype . typeOf ( result ) == cpu . ts . BASETYPE self . result = result def __str__ ( self ) : return '' % ( self . result , ) class DoneWithThisFrameFloat ( JitException ) : def __init__ ( self , result ) : assert lltype . typeOf ( result ) is lltype . Float self . result = result def __str__ ( self ) : return '' % ( self . result , ) class ExitFrameWithExceptionRef ( JitException ) : def __init__ ( self , cpu , value ) : assert lltype . typeOf ( value ) == cpu . ts . BASETYPE self . value = value def __str__ ( self ) : return '' % ( self . value , ) class ContinueRunningNormally ( ContinueRunningNormallyBase ) : def __init__ ( self , argboxes ) : from pypy . jit . metainterp . warmstate import unwrap for i , name , ARG in portalfunc_ARGS : v = unwrap ( ARG , argboxes [ i ] ) setattr ( self , name , v ) def __str__ ( self ) : return '' % ( '' . join ( map ( str , self . args ) ) , ) self . DoneWithThisFrameVoid = DoneWithThisFrameVoid self . DoneWithThisFrameInt = DoneWithThisFrameInt self . DoneWithThisFrameRef = DoneWithThisFrameRef self . DoneWithThisFrameFloat = DoneWithThisFrameFloat self . ExitFrameWithExceptionRef = ExitFrameWithExceptionRef self . ContinueRunningNormally = ContinueRunningNormally self . metainterp_sd . DoneWithThisFrameVoid = DoneWithThisFrameVoid self . metainterp_sd . DoneWithThisFrameInt = DoneWithThisFrameInt self . metainterp_sd . DoneWithThisFrameRef = DoneWithThisFrameRef self . metainterp_sd . DoneWithThisFrameFloat = DoneWithThisFrameFloat self . metainterp_sd . ExitFrameWithExceptionRef = ExitFrameWithExceptionRef self . metainterp_sd . ContinueRunningNormally = ContinueRunningNormally rtyper = self . translator . rtyper RESULT = PORTALFUNC . RESULT result_kind = history . getkind ( RESULT ) ts = self . cpu . ts def ll_portal_runner ( * args ) : while : try : return support . maybe_on_top_of_llinterp ( rtyper , portal_ptr ) ( * args ) except ContinueRunningNormally , e : args = ( ) for _ , name , _ in portalfunc_ARGS : v = getattr ( e , name ) args = args + ( v , ) except DoneWithThisFrameVoid : assert result_kind == '' return ", "answer": "except DoneWithThisFrameInt , e :"}, {"prompt": " import flask ", "answer": "import traceback"}, {"prompt": " \"\"\"\"\"\" from __future__ import unicode_literals import random NOUNS = ( \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , ", "answer": "\"\" , \"\" , \"\" , \"\" , \"\" ,"}, {"prompt": " import os ", "answer": "import sys"}, {"prompt": " from __future__ import print_function import os import os . path as op from nose . tools import assert_true , assert_raises from nose . plugins . skip import SkipTest import numpy as np from numpy . testing import assert_array_equal , assert_allclose , assert_equal import warnings from mne . datasets import testing from mne import ( read_source_spaces , vertex_to_mni , write_source_spaces , setup_source_space , setup_volume_source_space , add_source_space_distances , read_bem_surfaces , morph_source_spaces , SourceEstimate ) from mne . utils import ( _TempDir , requires_fs_or_nibabel , requires_nibabel , requires_freesurfer , run_subprocess , slow_test , requires_mne , requires_version , run_tests_if_main ) from mne . surface import _accumulate_normals , _triangle_neighbors from mne . source_space import _get_mri_header , _get_mgz_header from mne . externals . six . moves import zip from mne . source_space import ( get_volume_labels_from_aseg , SourceSpaces , _compare_source_spaces ) from mne . tests . common import assert_naming from mne . io . constants import FIFF warnings . simplefilter ( '' ) data_path = testing . data_path ( download = False ) subjects_dir = op . join ( data_path , '' ) fname_mri = op . join ( data_path , '' , '' , '' , '' ) fname = op . join ( subjects_dir , '' , '' , '' ) fname_vol = op . join ( subjects_dir , '' , '' , '' ) fname_bem = op . join ( data_path , '' , '' , '' , '' ) fname_fs = op . join ( subjects_dir , '' , '' , '' ) fname_morph = op . join ( subjects_dir , '' , '' , '' ) base_dir = op . join ( op . dirname ( __file__ ) , '' , '' , '' , '' ) fname_small = op . join ( base_dir , '' ) rng = np . random . RandomState ( ) @ testing . requires_testing_data @ requires_nibabel ( vox2ras_tkr = True ) def test_mgz_header ( ) : \"\"\"\"\"\" header = _get_mgz_header ( fname_mri ) mri_hdr = _get_mri_header ( fname_mri ) assert_allclose ( mri_hdr . get_data_shape ( ) , header [ '' ] ) assert_allclose ( mri_hdr . get_vox2ras_tkr ( ) , header [ '' ] ) assert_allclose ( mri_hdr . get_ras2vox ( ) , header [ '' ] ) @ requires_version ( '' , '' ) def test_add_patch_info ( ) : \"\"\"\"\"\" src = read_source_spaces ( fname_small ) src_new = read_source_spaces ( fname_small ) for s in src_new : s [ '' ] = None s [ '' ] = None ", "answer": "s [ '' ] = None"}, {"prompt": " from threading import Timer def delayed ( seconds ) : def decorator ( f ) : ", "answer": "def wrapper ( * args , ** kargs ) :"}, {"prompt": " \"\"\"\"\"\" __author__ = '' from functools import reduce import networkx as nx from networkx . utils import not_implemented_for __all__ = [ '' , '' ] @ not_implemented_for ( '' ) def immediate_dominators ( G , start ) : \"\"\"\"\"\" if start not in G : raise nx . NetworkXError ( '' ) idom = { start : start } order = list ( nx . dfs_postorder_nodes ( G , start ) ) dfn = { u : i for i , u in enumerate ( order ) } order . pop ( ) order . reverse ( ) def intersect ( u , v ) : while u != v : ", "answer": "while dfn [ u ] < dfn [ v ] :"}, {"prompt": " import re import jsondate as json import six from quandl . model . dataset import Dataset from quandl . model . data import Data from quandl . model . data_list import DataList from test . factories . dataset import DatasetFactory from test . factories . dataset_data import DatasetDataFactory def setupDatasetsTest ( unit_test , httpretty ) : httpretty . reset ( ) httpretty . enable ( ) unit_test . dataset_data = { '' : DatasetDataFactory . build ( ) } single_col_data = DatasetDataFactory . build ( column_names = [ six . u ( '' ) , six . u ( '' ) ] , data = [ [ '' , ] , [ '' , ] , [ '' , ] , [ '' , ] ] ) unit_test . single_dataset_data = { '' : single_col_data } dataset_data = DatasetDataFactory . build ( ) d_values = dataset_data . pop ( '' ) d_metadata = dataset_data unit_test . data_list_obj = DataList ( Data , d_values , d_metadata ) unit_test . nse_oil = { '' : DatasetFactory . build ( database_code = '' , dataset_code = '' ) } unit_test . goog_aapl = { '' : DatasetFactory . build ( database_code = '' , dataset_code = '' ) } unit_test . goog_msft = { '' : DatasetFactory . build ( database_code = '' , dataset_code = '' , newest_available_date = '' , oldest_available_date = '' ) } unit_test . single_col = { '' : DatasetFactory . build ( database_code = '' , dataset_code = '' , newest_available_date = '' , oldest_available_date = '' ) } unit_test . oil_obj = Dataset ( '' , unit_test . nse_oil [ '' ] ) ", "answer": "unit_test . aapl_obj = Dataset ( '' , unit_test . goog_aapl [ '' ] )"}, {"prompt": " from calvin . utilities import certificate import os print \"\" testconfig = certificate . Config ( domain = \"\" ) print \"\" print \"\" certificate . new_domain ( testconfig ) print \"\" for i in range ( , ) : for j in range ( , ) : name = \"\" . format ( i , j ) certreq = certificate . new_runtime ( testconfig , name ) certificate . sign_req ( testconfig , os . path . basename ( certreq ) , name ) certreq = certificate . new_runtime ( testconfig , \"\" ) ", "answer": "certificate . sign_req ( testconfig , os . path . basename ( certreq ) , \"\" ) "}, {"prompt": " import gzip import os import re import shutil from logic import url_factory try : from io import BytesIO except ImportError : from cStringIO import StringIO as BytesIO EXTENSION = '' def get_full_filename ( handler , url = None ) : if not url : url = handler . prefix + handler . breadcrumbs [ '' ] elif not url . startswith ( handler . prefix ) : url = handler . prefix + url filename = url_factory . clean_filename ( url ) path = os . path . join ( handler . application . settings [ \"\" ] , filename + '' + EXTENSION ) parent_directory = os . path . dirname ( path ) if not os . path . isdir ( parent_directory ) : os . makedirs ( parent_directory ) return path def add ( handler , content , rendered_content ) : if not rendered_content : return try : rendered_content += '' full_path = get_full_filename ( handler , handler . content_url ( content ) ) f = open ( full_path , '' ) f . write ( rendered_content ) f . close ( ) except Exception as ex : pass def remove ( handler , url = None ) : ", "answer": "try :"}, {"prompt": " import wtforms_json from wtforms import Form from wtforms . fields import BooleanField , StringField wtforms_json . init ( ) class LocationForm ( Form ) : name = StringField ( ) address = StringField ( ) class EventForm ( Form ) : name = StringField ( ) ", "answer": "is_public = BooleanField ( )"}, {"prompt": " \"\"\"\"\"\" import logging from nova import compute from occi_os_api . nova_glue import vm NETWORK_API = compute . API ( ) . network_api LOG = logging . getLogger ( __name__ ) def get_network_details ( uid , context ) : \"\"\"\"\"\" vm_instance = vm . get_vm ( uid , context ) result = { '' : [ ] , '' : [ ] } try : net_info = NETWORK_API . get_instance_nw_info ( context , vm_instance ) [ ] except IndexError : LOG . warn ( '' '' ) return result gw = net_info [ '' ] [ '' ] [ ] [ '' ] [ '' ] mac = net_info [ '' ] if len ( net_info [ '' ] [ '' ] [ ] [ '' ] ) == : tmp = { '' : [ ] , '' : '' } else : tmp = net_info [ '' ] [ '' ] [ ] [ '' ] [ ] for item in tmp [ '' ] : result [ '' ] . append ( { '' : '' , '' : '' , '' : '' , '' : item [ '' ] , '' : '' , '' : '' } ) result [ '' ] . append ( { '' : '' , '' : mac , '' : '' , '' : tmp [ '' ] , '' : gw , '' : '' } ) return result def add_floating_ip ( uid , pool_name , context ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " import pytest from pupa . scrape import Person , Organization , Membership , Post from pupa . utils import get_pseudo_id from validictory import ValidationError import datetime def test_basic_post ( ) : post = Post ( label = '' , role = '' , organization_id = '' ) assert '' in str ( post ) post . validate ( ) def test_basic_invalid_post ( ) : post = Post ( label = , role = '' , organization_id = '' ) with pytest . raises ( ValueError ) : post . validate ( ) def test_basic_membership ( ) : m = Membership ( person_id = '' , organization_id = '' ) assert '' in str ( m ) and '' in str ( m ) def test_basic_invalid_membership ( ) : membership = Membership ( person_id = , organization_id = \"\" ) with pytest . raises ( ValueError ) : membership . validate ( ) def test_basic_invalid_person ( ) : bob = Person ( \"\" ) bob . add_source ( url = '' ) bob . validate ( ) bob . name = None with pytest . raises ( ValidationError ) : bob . validate ( ) def test_basic_person ( ) : p = Person ( '' ) p . add_source ( '' ) assert p . name in str ( p ) p . validate ( ) def test_person_add_membership_org ( ) : p = Person ( '' ) p . add_source ( '' ) o = Organization ( '' , classification = '' ) p . add_membership ( o , role = '' , start_date = '' , end_date = datetime . date ( , , ) ) assert len ( p . _related ) == p . _related [ ] . validate ( ) assert p . _related [ ] . person_id == p . _id assert p . _related [ ] . organization_id == o . _id assert p . _related [ ] . start_date == '' assert p . _related [ ] . end_date == datetime . date ( , , ) def test_basic_organization ( ) : org = Organization ( '' , classification = '' ) org . add_source ( '' ) assert org . name in str ( org ) org . validate ( ) def test_no_source_on_party_org ( ) : org = Organization ( '' , classification = '' ) org . validate ( ) def test_basic_invalid_organization ( ) : orga = Organization ( \"\" ) with pytest . raises ( ValidationError ) : orga . validate ( ) def test_org_add_post ( ) : \"\"\"\"\"\" ", "answer": "orga = Organization ( \"\" , classification = \"\" )"}, {"prompt": " import functools import operator import os import shutil import sys import py import pytest import rasterio if sys . version_info > ( , ) : reduce = functools . reduce test_files = [ os . path . join ( os . path . dirname ( __file__ ) , p ) for p in [ '' ] ] def pytest_cmdline_main ( config ) : if reduce ( operator . and_ , map ( os . path . exists , test_files ) ) : print ( \"\" ) else : print ( \"\" ) sys . exit ( ) @ pytest . fixture ( scope = '' ) def data ( ) : \"\"\"\"\"\" tmpdir = py . test . ensuretemp ( '' ) ", "answer": "for filename in test_files :"}, {"prompt": " from pysb import * Model ( ) Monomer ( '' ) ", "answer": "Parameter ( '' , )"}, {"prompt": " \"\"\"\"\"\" import diamond . collector import re from urlparse import urljoin from urllib import quote import urllib2 from base64 import b64encode try : import json except ImportError : import simplejson as json class RabbitMQClient ( object ) : \"\"\"\"\"\" def __init__ ( self , host , user , password , timeout = , scheme = \"\" ) : self . base_url = '' % ( scheme , host ) self . timeout = timeout self . _authorization = '' + b64encode ( '' % ( user , password ) ) def do_call ( self , path ) : url = urljoin ( self . base_url , path ) req = urllib2 . Request ( url ) req . add_header ( '' , self . _authorization ) return json . load ( urllib2 . urlopen ( req , timeout = self . timeout ) ) def get_all_vhosts ( self ) : return self . do_call ( '' ) def get_vhost_names ( self ) : return [ i [ '' ] for i in self . get_all_vhosts ( ) ] def get_queues ( self , vhost = None ) : path = '' if vhost : vhost = quote ( vhost , '' ) path += '' % vhost queues = self . do_call ( path ) return queues or [ ] def get_overview ( self ) : return self . do_call ( '' ) def get_nodes ( self ) : return self . do_call ( '' ) def get_node ( self , node ) : return self . do_call ( '' % node ) class RabbitMQCollector ( diamond . collector . Collector ) : def get_default_config_help ( self ) : config_help = super ( RabbitMQCollector , self ) . get_default_config_help ( ) config_help . update ( { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' '' } ) return config_help def get_default_config ( self ) : \"\"\"\"\"\" config = super ( RabbitMQCollector , self ) . get_default_config ( ) config . update ( { '' : '' , '' : '' , '' : '' , '' : '' , '' : False , '' : False , '' : '' , '' : False , '' : '' , } ) return config def collect_health ( self ) : health_metrics = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , ] try : client = RabbitMQClient ( self . config [ '' ] , self . config [ '' ] , self . config [ '' ] , scheme = self . config [ '' ] ) node_name = client . get_overview ( ) [ '' ] node_data = client . get_node ( node_name ) for metric in health_metrics : self . publish ( '' . format ( metric ) , node_data [ metric ] ) if self . config [ '' ] : self . publish ( '' , len ( node_data [ '' ] ) ) content = client . get_nodes ( ) self . publish ( '' , len ( content ) ) except Exception , e : self . log . error ( '' , e ) return { } def collect ( self ) : self . collect_health ( ) matchers = [ ] if self . config [ '' ] : for reg in self . config [ '' ] . split ( ) : matchers . append ( re . compile ( reg ) ) try : client = RabbitMQClient ( self . config [ '' ] , self . config [ '' ] , self . config [ '' ] , scheme = self . config [ '' ] ) legacy = False if '' not in self . config : legacy = True if '' in self . config : vhost_conf = { \"\" : self . config [ '' ] } else : ", "answer": "vhost_conf = { \"\" : \"\" }"}, {"prompt": " import functools from taskflow . engines . action_engine . actions import base from taskflow import logging from taskflow import states from taskflow import task as task_atom from taskflow . types import failure LOG = logging . getLogger ( __name__ ) class TaskAction ( base . Action ) : \"\"\"\"\"\" def __init__ ( self , storage , notifier , task_executor ) : super ( TaskAction , self ) . __init__ ( storage , notifier ) self . _task_executor = task_executor def _is_identity_transition ( self , old_state , state , task , progress = None ) : if state in self . SAVE_RESULT_STATES : return False if state != old_state : return False if progress is None : return False old_progress = self . _storage . get_task_progress ( task . name ) if old_progress != progress : return False return True def change_state ( self , task , state , progress = None , result = base . Action . NO_RESULT ) : old_state = self . _storage . get_atom_state ( task . name ) if self . _is_identity_transition ( old_state , state , task , progress = progress ) : return if state in self . SAVE_RESULT_STATES : save_result = None if result is not self . NO_RESULT : save_result = result self . _storage . save ( task . name , save_result , state ) else : self . _storage . set_atom_state ( task . name , state ) if progress is not None : self . _storage . set_task_progress ( task . name , progress ) task_uuid = self . _storage . get_atom_uuid ( task . name ) details = { ", "answer": "'' : task . name ,"}, {"prompt": " from __future__ import division from WC_net import * from PyDSTool . Toolbox . phaseplane import * builder = rate_network ( ) S = thresh_Naka_Rushton_fndef ( , , , with_if = False ) ", "answer": "builder . add_neuron ( '' , tau = , ic = , thresh_fn = S )"}, {"prompt": " \"\"\"\"\"\" from __future__ import print_function from sys import argv from zope . interface import implementer from twisted . internet . endpoints import UNIXClientEndpoint from twisted . internet . task import react from twisted . web . iweb import IAgentEndpointFactory from twisted . web . client import Agent , readBody @ implementer ( IAgentEndpointFactory ) class DockerEndpointFactory ( object ) : \"\"\"\"\"\" def __init__ ( self , reactor ) : self . reactor = reactor ", "answer": "def endpointForURI ( self , uri ) :"}, {"prompt": " import sys import os sys . path . insert ( , os . path . abspath ( '' ) ) from updater4pyi import upd_version extensions = [ '' , ", "answer": "'' ,"}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import , division , print_function , with_statement , unicode_literals from . helper import unittest , db , Named , get_tree_details from . Named import NamedTestCase class DeletionTestCase ( NamedTestCase ) : def _delete_helper ( self , name , result ) : node = db . session . query ( Named ) . filter_by ( name = name ) . one ( ) db . session . delete ( node ) db . session . commit ( ) self . assertEqual ( get_tree_details ( ) , result ) def test_del_root1 ( self ) : name = u\"\" result = [ ( u\"\" , { '' : , '' : , '' : , '' : } , [ ] ) , ( u\"\" , { '' : , '' : , '' : , '' : } , [ ] ) , ( u\"\" , { '' : , '' : , '' : , '' : } , [ ] ) , ( u\"\" , { '' : , '' : , '' : , '' : } , [ ( u\"\" , { '' : , '' : , '' : , '' : } , [ ( u\"\" , { '' : , '' : , '' : , '' : } , [ ] ) , ( u\"\" , { '' : , '' : , '' : , '' : } , [ ( u\"\" , { '' : , '' : , '' : , '' : } , [ ] ) , ( u\"\" , { '' : , '' : , '' : , '' : } , [ ( u\"\" , { '' : , '' : , '' : , '' : } , [ ] ) , ( u\"\" , { '' : , '' : , '' : , '' : } , [ ] ) , ] ) , ] ) , ] ) , ( u\"\" , { '' : , '' : , '' : , '' : } , [ ] ) , ( u\"\" , { '' : , '' : , '' : , '' : } , [ ] ) , ] ) , ( u\"\" , { '' : , '' : , '' : , '' : } , [ ] ) , ] self . _delete_helper ( name , result ) def test_del_child11 ( self ) : name = u\"\" result = [ ( u\"\" , { '' : , '' : , '' : , '' : } , [ ( u\"\" , { '' : , '' : , '' : , '' : } , [ ] ) , ( u\"\" , { '' : , '' : , '' : , '' : } , [ ] ) , ] ) , ( u\"\" , { '' : , '' : , '' : , '' : } , [ ( u\"\" , { '' : , '' : , '' : , '' : } , [ ( u\"\" , { '' : , '' : , '' : , '' : } , [ ] ) , ( u\"\" , { '' : , '' : , '' : , '' : } , [ ( u\"\" , { '' : , '' : , '' : , '' : } , [ ] ) , ( u\"\" , { '' : , '' : , '' : , '' : } , [ ( u\"\" , { '' : , '' : , '' : , '' : } , [ ] ) , ( u\"\" , { '' : , '' : , '' : , '' : } , [ ] ) , ] ) , ] ) , ] ) , ( u\"\" , { '' : , '' : , '' : , '' : } , [ ] ) , ( u\"\" , { '' : , '' : , '' : , '' : } , [ ] ) , ] ) , ( u\"\" , { '' : , '' : , '' : , '' : } , [ ] ) , ] ", "answer": "self . _delete_helper ( name , result )"}, {"prompt": " class Driver ( object ) : def get_config ( self ) : return { } class SyncDriverError ( Exception ) : def __init__ ( self , message , errorno ) : Exception . __init__ ( self , message ) self . errorno = errorno def __str__ ( self ) : return self . message class SyncDriver ( Driver ) : def sync ( self , args ) : raise NotImplementedError class LockDriverError ( Exception ) : def __init__ ( self , message , errorno ) : Exception . __init__ ( self , message ) self . errorno = errorno def __str__ ( self ) : return self . message class LockDriver ( Driver ) : def check_lock ( self , args ) : raise NotImplementedError def add_lock ( self , args ) : raise NotImplementedError def remove_lock ( self , args ) : raise NotImplementedError class ServiceDriverError ( Exception ) : def __init__ ( self , message , errorno ) : Exception . __init__ ( self , message ) self . errorno = errorno def __str__ ( self ) : return self . message ", "answer": "class ServiceDriver ( Driver ) :"}, {"prompt": " '''''' import logging ; _L = logging . getLogger ( '' ) from datetime import timedelta import multiprocessing import signal import traceback import time import os import os . path import json from . import process_one , compat JOB_TIMEOUT = timedelta ( hours = ) class JobTimeoutException ( Exception ) : '''''' def __init__ ( self , jobstack = [ ] ) : super ( JobTimeoutException , self ) . __init__ ( ) self . jobstack = jobstack def timeout ( timeout ) : '''''' def decorate ( f ) : def timeout_handler ( signum , frame ) : raise JobTimeoutException ( traceback . format_stack ( ) ) def new_f ( * args , ** kwargs ) : old_handler = signal . signal ( signal . SIGALRM , timeout_handler ) signal . alarm ( timeout ) result = f ( * args , ** kwargs ) signal . signal ( signal . SIGALRM , old_handler ) signal . alarm ( ) return result if compat . PY2 : new_f . func_name = f . func_name else : new_f . __name__ = f . __name__ return new_f return decorate def setup_logger ( logfile = None , log_level = logging . DEBUG , log_stderr = True , log_config_file = \"\" ) : '''''' openaddr_logger = logging . getLogger ( '' ) log_format = '' openaddr_logger . setLevel ( logging . DEBUG ) for old_handler in openaddr_logger . handlers : openaddr_logger . removeHandler ( old_handler ) mp_logger = multiprocessing . get_logger ( ) mp_logger . propagate = True ", "answer": "log_config_file = os . path . expanduser ( log_config_file )"}, {"prompt": " \"\"\"\"\"\" import cortex_m ", "answer": "import target_kinetis"}, {"prompt": " from django . conf . urls . defaults import * from django . core . urlresolvers import reverse from django . shortcuts import redirect from oncall . views import getoncall , oncall from models import ServerModel from misc . generic_views import create_object , gen_mod_dict urlpatterns = patterns ( '' , ( r'' , '' ) , ( r'' , '' ) , ( r'' , '' ) , ", "answer": "( r'' , '' ) ,"}, {"prompt": " import os import sys from datetime import datetime sys . path . insert ( , os . path . abspath ( '' ) ) sys . path . insert ( , os . path . abspath ( '' ) ) from yql import __version__ as VERSION extensions = [ '' , '' , '' , '' ] templates_path = [ '' ] source_suffix = '' source_encoding = '' master_doc = '' project = u'' copyright = u'' '' '' % datetime . now ( ) . year version = VERSION release = VERSION exclude_trees = [ ] pygments_style = '' html_theme = '' html_theme_path = [ '' ] html_logo = \"\" html_favicon = \"\" html_static_path = [ '' ] html_last_updated_fmt = '' html_use_smartypants = True html_use_modindex = True html_use_index = True html_show_sourcelink = True html_use_opensearch = '' htmlhelp_basename = '' latex_documents = [ ", "answer": "( '' , '' , u'' ,"}, {"prompt": " \"\"\"\"\"\" import collections import logging import os import platform import re import subprocess import time import ipaddr import netifaces import pyping from common import detector from pi import scanning_proxy LINUX_RE = ( r'' r'' r'' ) LINUX_RE = re . compile ( LINUX_RE ) MAC_RE = ( r'' r'' r'' ) MAC_RE = re . compile ( MAC_RE ) class NetworkMonitor ( scanning_proxy . ScanningProxy ) : \"\"\"\"\"\" def __init__ ( self , callback , scan_period_sec , timeout_secs ) : assert os . geteuid ( ) == , '' self . _callback = callback self . _timeout_secs = timeout_secs self . _ping_frequency_secs = self . _hosts = collections . defaultdict ( lambda : False ) self . _last_ping = collections . defaultdict ( float ) self . _detectors = collections . defaultdict ( detector . AccrualFailureDetector ) self . _level_event_frequency_secs = * self . _last_level_event = super ( NetworkMonitor , self ) . __init__ ( scan_period_sec ) def _ping ( self , ip_address , now ) : \"\"\"\"\"\" if self . _last_ping [ ip_address ] + self . _ping_frequency_secs > now : return pyping . ping ( ip_address , timeout = , count = ) self . _last_ping [ ip_address ] = now def ping_subnet ( self , now ) : \"\"\"\"\"\" if self . _last_ping [ '' ] + self . _ping_frequency_secs > now : return self . _last_ping [ '' ] = now for interface in netifaces . interfaces ( ) : if interface . startswith ( '' ) : continue details = netifaces . ifaddresses ( interface ) if netifaces . AF_INET not in details : continue for detail in details [ netifaces . AF_INET ] : address = detail . get ( '' , None ) netmask = detail . get ( '' , None ) if address is None or netmask is None : continue parsed = ipaddr . IPv4Network ( '' % ( address , netmask ) ) logging . debug ( '' , parsed . broadcast ) pyping . ping ( str ( parsed . broadcast ) , timeout = , count = ) def _arp ( self ) : ", "answer": "system = platform . system ( )"}, {"prompt": " from django import template from django . template import defaultfilters as filters from django . utils . translation import pgettext_lazy from django . utils . translation import ugettext_lazy as _ from horizon import tables from horizon . utils import filters as utils_filters SERVICE_ENABLED = \"\" SERVICE_DISABLED = \"\" SERVICE_STATUS_DISPLAY_CHOICES = ( ( SERVICE_ENABLED , _ ( \"\" ) ) , ( SERVICE_DISABLED , _ ( \"\" ) ) , ) SERVICE_STATE_DISPLAY_CHOICES = ( ( '' , _ ( \"\" ) ) , ( '' , _ ( \"\" ) ) , ) class ServiceFilterAction ( tables . FilterAction ) : filter_field = '' def filter ( self , table , services , filter_string ) : q = filter_string . lower ( ) def comp ( service ) : attr = getattr ( service , self . filter_field , '' ) if attr is not None and q in attr . lower ( ) : return True return False return filter ( comp , services ) class SubServiceFilterAction ( ServiceFilterAction ) : filter_field = '' def get_status ( service ) : if service . host : return SERVICE_ENABLED if not service . disabled else SERVICE_DISABLED return None class ServicesTable ( tables . DataTable ) : id = tables . Column ( '' , hidden = True ) name = tables . Column ( \"\" , verbose_name = _ ( '' ) ) service_type = tables . Column ( '' , verbose_name = _ ( '' ) ) host = tables . Column ( '' , verbose_name = _ ( '' ) ) status = tables . Column ( get_status , verbose_name = _ ( '' ) , status = True , display_choices = SERVICE_STATUS_DISPLAY_CHOICES ) class Meta ( object ) : name = \"\" verbose_name = _ ( \"\" ) table_actions = ( ServiceFilterAction , ) multi_select = False status_columns = [ \"\" ] def get_available ( zone ) : return zone . zoneState [ '' ] def get_agent_status ( agent ) : template_name = '' context = { '' : agent . status , '' : agent . disabled_reason } return template . loader . render_to_string ( template_name , context ) class NovaServicesTable ( tables . DataTable ) : binary = tables . Column ( \"\" , verbose_name = _ ( '' ) ) host = tables . Column ( '' , verbose_name = _ ( '' ) ) zone = tables . Column ( '' , verbose_name = _ ( '' ) ) status = tables . Column ( get_agent_status , verbose_name = _ ( '' ) ) state = tables . Column ( '' , verbose_name = _ ( '' ) , display_choices = SERVICE_STATE_DISPLAY_CHOICES ) updated_at = tables . Column ( '' , verbose_name = pgettext_lazy ( ", "answer": "'' ,"}, {"prompt": " \"\"\"\"\"\" from django . db import models class Category ( models . Model ) : name = models . CharField ( maxlength = ) class Meta : ordering = ( '' , ) def __str__ ( self ) : return self . name class Author ( models . Model ) : name = models . CharField ( maxlength = ) class Meta : ordering = ( '' , ) def __str__ ( self ) : ", "answer": "return self . name"}, {"prompt": " import copy import mock from nose . tools import * from website . models import User , ApiOAuth2PersonalToken from website . util import api_v2_url from tests . base import ApiTestCase from tests . factories import ApiOAuth2PersonalTokenFactory , AuthUserFactory TOKEN_LIST_URL = api_v2_url ( '' , base_route = '' ) def _get_token_detail_route ( token ) : path = \"\" . format ( token . _id ) return api_v2_url ( path , base_route = '' ) class TestTokenDetail ( ApiTestCase ) : def setUp ( self ) : super ( TestTokenDetail , self ) . setUp ( ) self . user1 = AuthUserFactory ( ) self . user2 = AuthUserFactory ( ) self . user1_token = ApiOAuth2PersonalTokenFactory ( owner = self . user1 , user_id = self . user1 . _id ) self . user1_token_url = _get_token_detail_route ( self . user1_token ) self . missing_type = { '' : { '' : { '' : '' , '' : '' , } } } self . incorrect_type = { '' : { '' : '' , '' : { '' : '' , '' : '' , } } } self . injected_scope = { '' : { '' : '' , '' : { '' : '' , '' : '' , } } } self . nonsense_scope = { '' : { '' : '' , '' : { '' : '' , '' : '' , } } } self . correct = { '' : { '' : '' , '' : { '' : '' , '' : '' , } } } def test_owner_can_view ( self ) : res = self . app . get ( self . user1_token_url , auth = self . user1 . auth ) assert_equal ( res . status_code , ) assert_equal ( res . json [ '' ] [ '' ] , self . user1_token . _id ) def test_non_owner_cant_view ( self ) : res = self . app . get ( self . user1_token_url , auth = self . user2 . auth , expect_errors = True ) assert_equal ( res . status_code , ) def test_returns_401_when_not_logged_in ( self ) : res = self . app . get ( self . user1_token_url , expect_errors = True ) assert_equal ( res . status_code , ) @ mock . patch ( '' ) def test_owner_can_delete ( self , mock_method ) : mock_method . return_value ( True ) res = self . app . delete ( self . user1_token_url , auth = self . user1 . auth ) assert_equal ( res . status_code , ) def test_non_owner_cant_delete ( self ) : res = self . app . delete ( self . user1_token_url , auth = self . user2 . auth , expect_errors = True ) assert_equal ( res . status_code , ) @ mock . patch ( '' ) def test_deleting_tokens_makes_api_view_inaccessible ( self , mock_method ) : mock_method . return_value ( True ) res = self . app . delete ( self . user1_token_url , auth = self . user1 . auth ) res = self . app . get ( self . user1_token_url , auth = self . user1 . auth , expect_errors = True ) assert_equal ( res . status_code , ) @ mock . patch ( '' ) def test_updating_one_field_should_not_blank_others_on_patch_update ( self , mock_revoke ) : mock_revoke . return_value = True user1_token = self . user1_token new_name = \"\" res = self . app . patch_json_api ( self . user1_token_url , { '' : { '' : { '' : new_name , '' : '' } , '' : self . user1_token . _id , '' : '' } } , auth = self . user1 . auth ) user1_token . reload ( ) assert_equal ( res . status_code , ) assert_dict_contains_subset ( { '' : user1_token . owner . _id , '' : new_name , '' : '' . format ( user1_token . scopes ) , } , res . json [ '' ] [ '' ] ) assert_equal ( res . json [ '' ] [ '' ] , user1_token . _id ) @ mock . patch ( '' ) def test_updating_an_instance_does_not_change_the_number_of_instances ( self , mock_revoke ) : mock_revoke . return_value = True new_name = \"\" res = self . app . patch_json_api ( self . user1_token_url , { '' : { '' : { \"\" : new_name , '' : '' } , '' : self . user1_token . _id , '' : '' } } , auth = self . user1 . auth ) assert_equal ( res . status_code , ) list_url = TOKEN_LIST_URL res = self . app . get ( list_url , auth = self . user1 . auth ) assert_equal ( res . status_code , ) assert_equal ( len ( res . json [ '' ] ) , ) @ mock . patch ( '' ) def test_deleting_token_flags_instance_inactive ( self , mock_method ) : mock_method . return_value ( True ) res = self . app . delete ( self . user1_token_url , auth = self . user1 . auth ) self . user1_token . reload ( ) assert_false ( self . user1_token . is_active ) def test_read_does_not_return_token_id ( self ) : res = self . app . get ( self . user1_token_url , auth = self . user1 . auth ) assert_equal ( res . status_code , ) assert_false ( res . json [ '' ] [ '' ] . has_key ( '' ) ) def test_create_with_admin_scope_fails ( self ) : res = self . app . post_json_api ( TOKEN_LIST_URL , self . injected_scope , auth = self . user1 . auth , expect_errors = True ) assert_equal ( res . status_code , ) def test_create_with_fake_scope_fails ( self ) : res = self . app . post_json_api ( TOKEN_LIST_URL , self . nonsense_scope , auth = self . user1 . auth , expect_errors = True ) assert_equal ( res . status_code , ) def test_update_with_admin_scope_fails ( self ) : res = self . app . put_json_api ( self . user1_token_url , self . injected_scope , auth = self . user1 . auth , expect_errors = True ) assert_equal ( res . status_code , ) def test_update_with_fake_scope_fails ( self ) : res = self . app . put_json_api ( self . user1_token_url , self . nonsense_scope , auth = self . user1 . auth , expect_errors = True ) assert_equal ( res . status_code , ) @ mock . patch ( '' ) def test_update_token_does_not_return_token_id ( self , mock_revoke ) : mock_revoke . return_value = True res = self . app . put_json_api ( self . user1_token_url , self . correct , auth = self . user1 . auth , expect_errors = True ) assert_equal ( res . status_code , ) assert_false ( res . json [ '' ] [ '' ] . has_key ( '' ) ) @ mock . patch ( '' ) def test_update_token ( self , mock_revoke ) : mock_revoke . return_value = True res = self . app . put_json_api ( self . user1_token_url , self . correct , auth = self . user1 . auth , expect_errors = True ) assert_equal ( res . status_code , ) def test_update_token_incorrect_type ( self ) : res = self . app . put_json_api ( self . user1_token_url , self . incorrect_type , auth = self . user1 . auth , expect_errors = True ) assert_equal ( res . status_code , ) def test_update_token_no_type ( self ) : res = self . app . put_json_api ( self . user1_token_url , self . missing_type , auth = self . user1 . auth , expect_errors = True ) assert_equal ( res . status_code , ) def test_update_token_no_attributes ( self ) : payload = { '' : self . user1_token . _id , '' : '' , '' : '' } res = self . app . put_json_api ( self . user1_token_url , payload , auth = self . user1 . auth , expect_errors = True ) assert_equal ( res . status_code , ) def test_partial_update_token_incorrect_type ( self ) : res = self . app . patch_json_api ( self . user1_token_url , self . incorrect_type , auth = self . user1 . auth , expect_errors = True ) assert_equal ( res . status_code , ) def test_partial_update_token_no_type ( self ) : res = self . app . patch_json_api ( self . user1_token_url , self . missing_type , auth = self . user1 . auth , expect_errors = True ) assert_equal ( res . status_code , ) ", "answer": "def test_partial_update_token_no_attributes ( self ) :"}, {"prompt": " \"\"\"\"\"\" from Bcfg2 . Options import Option ", "answer": "class Two ( object ) :"}, {"prompt": " \"\"\"\"\"\" from imaginary . creation import CreationPluginHelper , createCreator ", "answer": "thingPlugin = CreationPluginHelper ( \"\" , createCreator ( ) ) "}, {"prompt": " \"\"\"\"\"\" import logging import urllib2 from hashlib import md5 from urllib import urlencode from os . path import join as path_join from platform import system as platform_system import simplejson as json from yaml import load as yaml_load from paste . deploy . converters import asbool , asint from pylons import request from turbulenz_local import SDK_VERSION , CONFIG_PATH from turbulenz_local . models . gamelist import get_game_by_slug from turbulenz_local . tools import slugify as slugify_fn LOG = logging . getLogger ( __name__ ) def turbulenz_api ( endpoint , timeout = ) : try : f = urllib2 . urlopen ( endpoint , None , timeout ) try : data = json . load ( f ) finally : f . close ( ) except urllib2 . URLError as e : LOG . error ( '' , endpoint ) LOG . error ( '' , str ( e ) ) data = { } return data def turbulenz_sdk_version ( sdk_version ) : query = turbulenz_api ( sdk_version ) if query . get ( '' , False ) : data = query . get ( '' , None ) if data : os_mapping = { '' : '' , '' : '' , '' : '' } sysname = platform_system ( ) os = os_mapping [ sysname ] this_os = data [ os ] latest_version = this_os [ '' ] all_versions = this_os [ '' ] if all_versions : latest_link = '' % all_versions [ latest_version ] [ '' ] else : latest_link = '' latest_version = '' return { '' : latest_version , '' : SDK_VERSION , '' : latest_link } return { '' : '' , '' : SDK_VERSION , '' : '' } def turbulenz_engine_version ( engine_version ) : query = turbulenz_api ( engine_version ) plugin_data = { } if query . get ( '' , False ) : data = query . get ( '' , None ) if data : os_list = [ '' , '' , '' ] for o in os_list : this_os = data [ o ] latest_plugin_version = this_os [ '' ] all_versions = this_os [ '' ] if all_versions : latest_plugin_link = all_versions [ latest_plugin_version ] [ '' ] else : latest_plugin_link = '' latest_plugin_version = '' os_data = { '' : latest_plugin_version , '' : latest_plugin_link } plugin_data [ o ] = os_data return plugin_data def _load_yaml_mapping ( filename ) : try : f = open ( filename ) try : yaml_versions = yaml_load ( f ) finally : f . close ( ) except IOError : yaml_versions = { } return yaml_versions class Helpers ( object ) : def __init__ ( self , config ) : self . sdk_data = turbulenz_sdk_version ( config [ '' ] ) self . plugin_data = turbulenz_engine_version ( config [ '' ] ) self . gravatars_style = config . get ( '' , '' ) if asbool ( config . get ( '' , False ) ) : self . js_mapping = { } self . css_mapping = { } self . html_mapping = { } else : self . js_mapping = _load_yaml_mapping ( path_join ( CONFIG_PATH , '' ) ) self . css_mapping = _load_yaml_mapping ( path_join ( CONFIG_PATH , '' ) ) self . html_mapping = _load_yaml_mapping ( path_join ( CONFIG_PATH , '' ) ) self . deploy_enable = asbool ( config . get ( '' , False ) ) self . deploy_host = config . get ( '' , '' ) self . deploy_port = asint ( config . get ( '' , ) ) self . viewer_app = config . get ( '' , '' ) ", "answer": "def javascript_link ( self , url ) :"}, {"prompt": " def main ( ) : delete_submissions = raw_input ( \"\" ) == \"\" delete_assignments = delete_submissions and raw_input ( \"\" ) == \"\" delete_users = delete_assignments and raw_input ( \"\" ) == \"\" delete_classes = delete_users and raw_input ( \"\" ) == \"\" import mongoengine mongoengine . connect ( \"\" ) from galah . base . config import load_config ", "answer": "config = load_config ( \"\" )"}, {"prompt": " import shutil import sys import os , os . path import imp import blogofile . main from blogofile import argparse def setup ( parent_parser , parser_template ) : from . import __dist__ cmd_subparsers = parent_parser . add_subparsers ( ) command1 = cmd_subparsers . add_parser ( ", "answer": "\"\" , help = \"\" , parents = [ parser_template ] )"}, {"prompt": " import os import pdb import sys import tempfile sys . path . append ( \"\" ) from translator . toscalib . tosca_template import ToscaTemplate from core . models import User , Deployment , DeploymentRole from xosresource import XOSResource class XOSDeploymentRole ( XOSResource ) : provides = \"\" xos_model = DeploymentRole name_field = \"\" ", "answer": "def get_xos_args ( self ) :"}, {"prompt": " \"\"\"\"\"\" import tempfile from shade import exc from shade import openstack_cloud from shade . tests import base simple_template = '''''' root_template = '''''' environment = '''''' validate_template = '''''' class TestStack ( base . TestCase ) : def setUp ( self ) : super ( TestStack , self ) . setUp ( ) self . cloud = openstack_cloud ( cloud = '' ) if not self . cloud . has_service ( '' ) : self . skipTest ( '' ) def _cleanup_stack ( self ) : self . cloud . delete_stack ( self . stack_name , wait = True ) self . assertIsNone ( self . cloud . get_stack ( self . stack_name ) ) def test_stack_validation ( self ) : test_template = tempfile . NamedTemporaryFile ( delete = False ) test_template . write ( validate_template ) test_template . close ( ) stack_name = self . getUniqueString ( '' ) self . assertRaises ( exc . OpenStackCloudException , self . cloud . create_stack , name = stack_name , template_file = test_template . name ) def test_stack_simple ( self ) : test_template = tempfile . NamedTemporaryFile ( delete = False ) test_template . write ( simple_template ) test_template . close ( ) self . stack_name = self . getUniqueString ( '' ) self . addCleanup ( self . _cleanup_stack ) stack = self . cloud . create_stack ( name = self . stack_name , template_file = test_template . name , wait = True ) self . assertEqual ( '' , stack [ '' ] ) rand = stack [ '' ] [ ] [ '' ] self . assertEqual ( , len ( rand ) ) ", "answer": "stack = self . cloud . get_stack ( self . stack_name )"}, {"prompt": " \"\"\"\"\"\" class Command ( object ) : \"\"\"\"\"\" def __init__ ( self , args ) : self . args = args def execute_command ( self ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " import numpy as np import scipy . sparse as sp from sklearn . utils . testing import assert_array_almost_equal ", "answer": "from sklearn . utils . testing import assert_almost_equal"}, {"prompt": " from builtins import str import os import sys try : from importlib import import_module except ImportError : from django . utils . importlib import import_module import django from . exceptions import InvalidSettingsFactory , SettingsFactoryDoesNotExist from . decorators import callable_setting from . importers import SettingsImporter from . settings import DjangoDefaults , AppSettings , PrefixedSettings from . switching import switcher from cbsettings . pkgmeta import * ENVIRONMENT_VARIABLE = '' DJANGO_SETTINGS_MODULE = django . conf . ENVIRONMENT_VARIABLE def configure ( factory = None , ** kwargs ) : if not factory : factory = os . environ . get ( ENVIRONMENT_VARIABLE ) if not factory : raise ImportError ( '' '' '' % ENVIRONMENT_VARIABLE ) if '' in factory : factory_module , factory_name = factory . rsplit ( '' , ) try : mod = import_module ( factory_module ) ", "answer": "factory_obj = getattr ( mod , factory_name )"}, {"prompt": " \"\"\"\"\"\" import urllib2 from urlparse import urlparse ", "answer": "from urllib2 import HTTPError"}, {"prompt": " import datetime import pickle from decimal import Decimal from operator import attrgetter from django . conf import settings from django . core . exceptions import FieldError from django . db import DEFAULT_DB_ALIAS from django . db . models import Count , Max , Avg , Sum , StdDev , Variance , F , Q from django . test import TestCase , Approximate from models import Author , Book , Publisher , Clues , Entries , HardbackBook def run_stddev_tests ( ) : \"\"\"\"\"\" if settings . DATABASES [ DEFAULT_DB_ALIAS ] [ '' ] == '' : return False class StdDevPop ( object ) : sql_function = '' try : connection . ops . check_aggregate_support ( StdDevPop ( ) ) except : return False return True class AggregationTests ( TestCase ) : def assertObjectAttrs ( self , obj , ** kwargs ) : for attr , value in kwargs . iteritems ( ) : self . assertEqual ( getattr ( obj , attr ) , value ) def test_aggregates_in_where_clause ( self ) : \"\"\"\"\"\" qs = Book . objects . values ( '' ) . annotate ( Max ( '' ) ) qs = qs . order_by ( '' ) . values_list ( '' , flat = True ) books = Book . objects . order_by ( '' ) qs1 = books . filter ( id__in = qs ) qs2 = books . filter ( id__in = list ( qs ) ) self . assertEqual ( list ( qs1 ) , list ( qs2 ) ) def test_aggregates_in_where_clause_pre_eval ( self ) : \"\"\"\"\"\" qs = Book . objects . values ( '' ) . annotate ( Max ( '' ) ) qs = qs . order_by ( '' ) . values_list ( '' , flat = True ) list ( qs ) books = Book . objects . order_by ( '' ) qs1 = books . filter ( id__in = qs ) qs2 = books . filter ( id__in = list ( qs ) ) self . assertEqual ( list ( qs1 ) , list ( qs2 ) ) if settings . DATABASES [ DEFAULT_DB_ALIAS ] [ '' ] != '' : def test_annotate_with_extra ( self ) : \"\"\"\"\"\" shortest_book_sql = \"\"\"\"\"\" qs = Publisher . objects . extra ( select = { '' : shortest_book_sql , } ) . annotate ( total_books = Count ( '' ) ) list ( qs ) def test_aggregate ( self ) : self . assertEqual ( Author . objects . order_by ( \"\" ) . aggregate ( Avg ( \"\" ) ) , { \"\" : Approximate ( , places = ) } ) self . assertEqual ( Book . objects . aggregate ( Sum ( \"\" ) ) , { \"\" : } , ) self . assertEqual ( Book . objects . aggregate ( Sum ( '' ) , Avg ( '' ) ) , { '' : , '' : Approximate ( , places = ) } ) self . assertEqual ( Book . objects . values ( ) . aggregate ( Sum ( '' ) , Avg ( '' ) ) , { '' : , '' : Approximate ( , places = ) } ) self . assertEqual ( Book . objects . extra ( select = { '' : '' } ) . aggregate ( Sum ( '' ) ) , { '' : } ) def test_annotation ( self ) : obj = Book . objects . annotate ( mean_auth_age = Avg ( \"\" ) ) . extra ( select = { \"\" : \"\" } ) . get ( pk = ) self . assertObjectAttrs ( obj , contact_id = , id = , isbn = u'' , mean_auth_age = , name = '' , pages = , price = Decimal ( \"\" ) , pubdate = datetime . date ( , , ) , publisher_id = , rating = ) self . assertTrue ( obj . manufacture_cost == or obj . manufacture_cost == Decimal ( '' ) ) obj = Book . objects . extra ( select = { '' : '' } ) . annotate ( mean_auth_age = Avg ( '' ) ) . get ( pk = ) self . assertObjectAttrs ( obj , contact_id = , id = , isbn = u'' , mean_auth_age = , name = u'' , pages = , price = Decimal ( \"\" ) , pubdate = datetime . date ( , , ) , publisher_id = , rating = ) self . assertTrue ( obj . manufacture_cost == or obj . manufacture_cost == Decimal ( '' ) ) obj = Book . objects . annotate ( mean_auth_age = Avg ( '' ) ) . extra ( select = { '' : '' } ) . values ( ) . get ( pk = ) manufacture_cost = obj [ '' ] self . assertTrue ( manufacture_cost == or manufacture_cost == Decimal ( '' ) ) del obj [ '' ] self . assertEqual ( obj , { \"\" : , \"\" : , \"\" : u\"\" , \"\" : , \"\" : u\"\" , \"\" : , \"\" : Decimal ( \"\" ) , \"\" : datetime . date ( , , ) , \"\" : , \"\" : , } ) obj = Book . objects . values ( ) . annotate ( mean_auth_age = Avg ( '' ) ) . extra ( select = { '' : '' } ) . get ( pk = ) manufacture_cost = obj [ '' ] self . assertTrue ( manufacture_cost == or manufacture_cost == Decimal ( '' ) ) del obj [ '' ] self . assertEqual ( obj , { '' : , '' : , '' : u'' , '' : , '' : u'' , '' : , '' : Decimal ( \"\" ) , '' : datetime . date ( , , ) , '' : , '' : } ) obj = Book . objects . annotate ( mean_auth_age = Avg ( '' ) ) . extra ( select = { '' : '' } ) . values ( '' ) . get ( pk = ) self . assertEqual ( obj , { \"\" : u'' , } ) obj = Book . objects . annotate ( mean_auth_age = Avg ( '' ) ) . extra ( select = { '' : '' } ) . values ( '' , '' ) . get ( pk = ) self . assertEqual ( obj , { '' : , '' : u'' , } ) qs = Book . objects . annotate ( n_authors = Count ( '' ) ) . values ( '' ) . filter ( n_authors__gt = ) self . assertQuerysetEqual ( qs , [ { \"\" : u'' } ] , lambda b : b , ) obj = Book . objects . values ( '' ) . annotate ( mean_auth_age = Avg ( '' ) ) . extra ( select = { '' : '' } ) . get ( pk = ) self . assertEqual ( obj , { '' : , '' : u'' , } ) self . assertEqual ( len ( Author . objects . annotate ( Avg ( '' ) ) . values ( ) ) , ) qs = Book . objects . values ( '' ) . annotate ( oldest = Max ( '' ) ) . order_by ( '' , '' ) . annotate ( Max ( '' ) ) self . assertQuerysetEqual ( qs , [ { '' : Decimal ( \"\" ) , '' : , '' : } , { '' : Decimal ( \"\" ) , '' : , '' : } , { '' : Decimal ( \"\" ) , '' : , '' : } , { '' : Decimal ( \"\" ) , '' : , '' : } , { '' : Decimal ( \"\" ) , '' : , '' : } ] , lambda b : b , ) def test_aggrate_annotation ( self ) : vals = Book . objects . all ( ) . annotate ( num_authors = Count ( '' ) ) . aggregate ( Max ( '' ) , Max ( '' ) , Sum ( '' ) , Avg ( '' ) ) self . assertEqual ( vals , { '' : , '' : Approximate ( , places = ) , '' : , '' : Decimal ( \"\" ) } ) def test_field_error ( self ) : self . assertRaises ( FieldError , lambda : Book . objects . all ( ) . aggregate ( num_authors = Count ( '' ) ) ) self . assertRaises ( FieldError , lambda : Book . objects . all ( ) . annotate ( num_authors = Count ( '' ) ) ) self . assertRaises ( FieldError , lambda : Book . objects . all ( ) . annotate ( num_authors = Count ( '' ) ) . aggregate ( Max ( '' ) ) ) def test_more ( self ) : self . assertEqual ( Book . objects . annotate ( num_authors = Count ( '' ) ) . count ( ) , ) vals = Book . objects . annotate ( num_authors = Count ( '' ) ) . aggregate ( Max ( '' ) ) self . assertEqual ( vals , { '' : } ) vals = Publisher . objects . annotate ( avg_price = Avg ( '' ) ) . aggregate ( Max ( '' ) ) self . assertEqual ( vals , { '' : } ) vals = Book . objects . aggregate ( number = Max ( '' ) , select = Max ( '' ) ) self . assertEqual ( vals , { '' : , '' : } ) obj = Book . objects . select_related ( '' ) . annotate ( num_authors = Count ( '' ) ) . values ( ) [ ] self . assertEqual ( obj , { '' : , '' : , '' : u'' , '' : u'' , '' : , '' : , '' : Decimal ( \"\" ) , '' : datetime . date ( , , ) , '' : , '' : , } ) self . assertEqual ( len ( Book . objects . annotate ( num_authors = Count ( '' ) ) ) , ) self . assertEqual ( len ( Book . objects . annotate ( num_authors = Count ( '' ) ) . filter ( num_authors__gt = ) ) , ) self . assertEqual ( len ( Book . objects . annotate ( num_authors = Count ( '' ) ) . exclude ( num_authors__gt = ) ) , ) self . assertEqual ( len ( Book . objects . annotate ( num_authors = Count ( '' ) ) . filter ( num_authors__lt = ) . exclude ( num_authors__lt = ) ) , ) self . assertEqual ( len ( Book . objects . annotate ( num_authors = Count ( '' ) ) . exclude ( num_authors__lt = ) . filter ( num_authors__lt = ) ) , ) def test_aggregate_fexpr ( self ) : qs = Publisher . objects . annotate ( num_books = Count ( '' ) ) . filter ( num_books__lt = F ( '' ) / ) . order_by ( '' ) . values ( '' , '' , '' ) self . assertQuerysetEqual ( qs , [ { '' : , '' : u'' , '' : } , { '' : , '' : u'' , '' : } ] , lambda p : p , ) qs = Publisher . objects . annotate ( num_books = Count ( '' ) ) . exclude ( num_books__lt = F ( '' ) / ) . order_by ( '' ) . values ( '' , '' , '' ) self . assertQuerysetEqual ( qs , [ { '' : , '' : u'' , '' : } , { '' : , '' : u\"\" , '' : } , { '' : , '' : u'' , '' : } ] , lambda p : p , ) qs = Publisher . objects . annotate ( num_books = Count ( '' ) ) . filter ( num_awards__gt = * F ( '' ) ) . order_by ( '' ) . values ( '' , '' , '' ) self . assertQuerysetEqual ( qs , [ { '' : , '' : u'' , '' : } , { '' : , '' : u'' , '' : } ] , lambda p : p , ) qs = Publisher . objects . annotate ( num_books = Count ( '' ) ) . exclude ( num_books__lt = F ( '' ) / ) . order_by ( '' ) . values ( '' , '' , '' ) self . assertQuerysetEqual ( qs , [ { '' : , '' : u'' , '' : } , { '' : , '' : u\"\" , '' : } , { '' : , '' : u'' , '' : } ] , lambda p : p , ) def test_db_col_table ( self ) : qs = Clues . objects . values ( '' ) . annotate ( Appearances = Count ( '' ) , Distinct_Clues = Count ( '' , distinct = True ) ) self . assertQuerysetEqual ( qs , [ ] ) qs = Entries . objects . annotate ( clue_count = Count ( '' ) ) self . assertQuerysetEqual ( qs , [ ] ) def test_empty ( self ) : self . assertEqual ( Book . objects . filter ( id__in = [ ] ) . count ( ) , ) vals = Book . objects . filter ( id__in = [ ] ) . aggregate ( num_authors = Count ( '' ) , avg_authors = Avg ( '' ) , max_authors = Max ( '' ) , max_price = Max ( '' ) , max_rating = Max ( '' ) ) self . assertEqual ( vals , { '' : None , '' : None , '' : , '' : None , '' : None } ) qs = Publisher . objects . filter ( pk = ) . annotate ( num_authors = Count ( '' ) , avg_authors = Avg ( '' ) , max_authors = Max ( '' ) , max_price = Max ( '' ) , max_rating = Max ( '' ) ) . values ( ) self . assertQuerysetEqual ( qs , [ { '' : None , '' : u\"\" , '' : , '' : None , '' : , '' : None , '' : , '' : None } ] , lambda p : p ) def test_more_more ( self ) : self . assertQuerysetEqual ( Book . objects . annotate ( num_authors = Count ( '' ) ) . order_by ( '' , '' ) , [ \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , ] , lambda b : b . name ) qs = Book . objects . filter ( rating__lt = ) . select_related ( ) . annotate ( Avg ( '' ) ) self . assertQuerysetEqual ( qs , [ ( u'' , , u'' , u'' ) , ( u'' , , u'' , u'' ) , ( u'' , Approximate ( , places = ) , u'' , u'' ) , ( u'' , , u'' , u'' ) ] , lambda b : ( b . name , b . authors__age__avg , b . publisher . name , b . contact . name ) ) qs = Book . objects . extra ( select = { '' : '' } ) . values ( '' ) . annotate ( Count ( '' ) ) . order_by ( '' ) self . assertQuerysetEqual ( qs , [ { '' : , '' : } , { '' : , '' : } , { '' : , '' : } , { '' : , '' : } ] , lambda b : b ) qs = Book . objects . extra ( select = { '' : '' , '' : '' } ) . values ( '' ) . annotate ( Count ( '' ) ) . order_by ( '' ) self . assertQuerysetEqual ( qs , [ { '' : , '' : } , { '' : , '' : } , { '' : , '' : } , { '' : , '' : } ] , lambda b : b ) ids = Book . objects . filter ( pages__gt = ) . annotate ( n_authors = Count ( '' ) ) . filter ( n_authors__gt = ) . order_by ( '' ) self . assertQuerysetEqual ( Book . objects . filter ( id__in = ids ) , [ \"\" , ] , lambda b : b . name ) def test_duplicate_alias ( self ) : self . assertRaises ( ValueError , Book . objects . all ( ) . annotate , Avg ( '' ) , authors__age__avg = Avg ( '' ) ) def test_field_name_conflict ( self ) : self . assertRaises ( ValueError , Author . objects . annotate , age = Avg ( '' ) ) def test_m2m_name_conflict ( self ) : self . assertRaises ( ValueError , Author . objects . annotate , friends = Count ( '' ) ) def test_values_queryset_non_conflict ( self ) : results = Author . objects . values ( '' ) . annotate ( age = Count ( '' ) ) . order_by ( '' ) self . assertEquals ( len ( results ) , ) self . assertEquals ( results [ ] [ '' ] , u'' ) self . assertEquals ( results [ ] [ '' ] , ) results = Author . objects . values ( '' ) . annotate ( age = Avg ( '' ) ) . order_by ( '' ) self . assertEquals ( len ( results ) , ) self . assertEquals ( results [ ] [ '' ] , u'' ) self . assertEquals ( results [ ] [ '' ] , ) results = Author . objects . values ( '' ) . annotate ( friends = Count ( '' ) ) . order_by ( '' ) self . assertEquals ( len ( results ) , ) self . assertEquals ( results [ ] [ '' ] , u'' ) self . assertEquals ( results [ ] [ '' ] , ) def test_reverse_relation_name_conflict ( self ) : self . assertRaises ( ValueError , Author . objects . annotate , book_contact_set = Avg ( '' ) ) def test_pickle ( self ) : qs = Book . objects . annotate ( num_authors = Count ( '' ) ) pickle . dumps ( qs ) query = qs . query . get_compiler ( qs . db ) . as_sql ( ) [ ] qs2 = pickle . loads ( pickle . dumps ( qs ) ) self . assertEqual ( qs2 . query . get_compiler ( qs2 . db ) . as_sql ( ) [ ] , query , ) def test_more_more_more ( self ) : books = Book . objects . all ( ) books . aggregate ( Avg ( \"\" ) ) self . assertQuerysetEqual ( books . all ( ) , [ u'' , u'' , u'' , u'' , u'' , u'' ] , lambda b : b . name ) qs = Book . objects . annotate ( num_authors = Count ( '' ) ) . filter ( num_authors = ) . dates ( '' , '' ) self . assertQuerysetEqual ( qs , [ datetime . datetime ( , , , , ) , datetime . datetime ( , , , , ) ] , lambda b : b ) qs = Book . objects . annotate ( mean_auth_age = Avg ( '' ) ) . extra ( select = { '' : '' } , select_params = [ , ] ) . order_by ( '' ) . values ( '' ) self . assertQuerysetEqual ( qs , [ , , , , , ] , lambda b : int ( b [ \"\" ] ) ) self . assertEqual ( Book . objects . values ( '' ) . annotate ( Count ( '' ) ) . count ( ) , ) self . assertEqual ( Book . objects . annotate ( Count ( '' ) ) . values ( '' ) . count ( ) , ) publishers = Publisher . objects . filter ( id__in = [ , ] ) self . assertQuerysetEqual ( publishers , [ \"\" , \"\" ] , lambda p : p . name ) publishers = publishers . annotate ( n_books = Count ( \"\" ) ) self . assertEqual ( publishers [ ] . n_books , ) self . assertQuerysetEqual ( publishers , [ \"\" , \"\" , ] , lambda p : p . name ) books = Book . objects . filter ( publisher__in = publishers ) self . assertQuerysetEqual ( books , [ \"\" , \"\" , \"\" , ] , lambda b : b . name ) self . assertQuerysetEqual ( publishers , [ \"\" , \"\" , ] , lambda p : p . name ) self . assertEqual ( HardbackBook . objects . aggregate ( n_pages = Sum ( '' ) ) , { '' : } ) self . assertEqual ( HardbackBook . objects . aggregate ( n_pages = Sum ( '' ) ) , { '' : } , ) qs = HardbackBook . objects . annotate ( n_authors = Count ( '' ) ) . values ( '' , '' ) self . assertQuerysetEqual ( qs , [ { '' : , '' : u'' } , { '' : , '' : u'' } ] , lambda h : h ) qs = HardbackBook . objects . annotate ( n_authors = Count ( '' ) ) . values ( '' , '' ) self . assertQuerysetEqual ( qs , [ { '' : , '' : u'' } , { '' : , '' : u'' } ] , lambda h : h , ) self . assertRaises ( FieldError , lambda : Book . objects . annotate ( mean_age = Avg ( '' ) ) . annotate ( Avg ( '' ) ) ) def test_empty_filter_count ( self ) : self . assertEqual ( Author . objects . filter ( id__in = [ ] ) . annotate ( Count ( \"\" ) ) . count ( ) , ) def test_empty_filter_aggregate ( self ) : self . assertEqual ( Author . objects . filter ( id__in = [ ] ) . annotate ( Count ( \"\" ) ) . aggregate ( Count ( \"\" ) ) , { \"\" : None } ) def test_annotate_and_join ( self ) : self . assertEqual ( Author . objects . annotate ( c = Count ( \"\" ) ) . exclude ( friends__name = \"\" ) . count ( ) , Author . objects . count ( ) ) def test_f_expression_annotation ( self ) : qs = Book . objects . values ( \"\" ) . annotate ( n_authors = Count ( \"\" ) ) . filter ( pages__lt = F ( \"\" ) * ) . values_list ( \"\" ) self . assertQuerysetEqual ( Book . objects . filter ( pk__in = qs ) , [ \"\" ] , attrgetter ( \"\" ) ) def test_values_annotate_values ( self ) : qs = Book . objects . values ( \"\" ) . annotate ( n_authors = Count ( \"\" ) ) . values_list ( \"\" , flat = True ) self . assertEqual ( list ( qs ) , list ( Book . objects . values_list ( \"\" , flat = True ) ) ) def test_having_group_by ( self ) : qs = Book . objects . values_list ( \"\" ) . annotate ( n_authors = Count ( \"\" ) ) . filter ( pages__gt = F ( \"\" ) ) . values_list ( \"\" , flat = True ) self . assertEqual ( list ( qs ) , list ( Book . objects . values_list ( \"\" , flat = True ) ) ) def test_annotation_disjunction ( self ) : qs = Book . objects . annotate ( n_authors = Count ( \"\" ) ) . filter ( Q ( n_authors = ) | Q ( name = \"\" ) ) self . assertQuerysetEqual ( qs , [ ", "answer": "\"\" ,"}, {"prompt": " import sys , os sys . path . append ( os . path . dirname ( os . path . abspath ( __file__ ) ) ) try : from django . conf import settings from tests import settings as test_settings settings . configure ( default_settings = test_settings ) try : import django setup = django . setup except AttributeError : pass else : setup ( ) from django_nose import NoseTestSuiteRunner except ImportError : import traceback traceback . print_exc ( ) raise ImportError ( \"\" ) import logging logging . disable ( logging . WARNING ) logging . captureWarnings ( True ) def run_tests ( * test_args ) : ", "answer": "if not test_args :"}, {"prompt": " from __future__ import absolute_import , unicode_literals \"\"\"\"\"\" from . base import Client ", "answer": "from . . parameters import prepare_grant_uri"}, {"prompt": " \"\"\"\"\"\" from sqlalchemy import ( MetaData , Table , Column , Integer , String , ForeignKey , Unicode , and_ , create_engine ) from sqlalchemy . orm import mapper , relationship , Session , lazyload import sys , os , io , re from xml . etree import ElementTree e = create_engine ( '' ) meta = MetaData ( ) documents = Table ( '' , meta , Column ( '' , Integer , primary_key = True ) , Column ( '' , String ( ) , unique = True ) , Column ( '' , Integer , ForeignKey ( '' ) ) ) elements = Table ( '' , meta , Column ( '' , Integer , primary_key = True ) , Column ( '' , Integer , ForeignKey ( '' ) ) , Column ( '' , Unicode ( ) , nullable = False ) , Column ( '' , Unicode ) , Column ( '' , Unicode ) ) attributes = Table ( '' , meta , Column ( '' , Integer , ForeignKey ( '' ) , primary_key = True ) , Column ( '' , Unicode ( ) , nullable = False , primary_key = True ) , Column ( '' , Unicode ( ) ) ) meta . create_all ( e ) class Document ( object ) : def __init__ ( self , name , element ) : ", "answer": "self . filename = name"}, {"prompt": " from django . conf import settings ", "answer": "from django . contrib import messages"}, {"prompt": " from . . base import BaseTopazTest class TestRegexpObject ( BaseTopazTest ) : def test_source ( self , space ) : w_res = space . execute ( \"\" ) assert space . str_w ( w_res ) == \"\" def test_compile_regexps ( self , space ) : space . execute ( \"\"\"\"\"\" ) def test_regexp_syntax_errors ( self , space ) : with self . raises ( space , \"\" ) : space . execute ( \"\" ) with self . raises ( space , \"\" ) : space . execute ( \"\"\"\"\"\" ) with self . raises ( space , \"\" ) : space . execute ( \"\"\"\"\"\" ) def test_regexp_compile_errors ( self , space ) : with self . raises ( space , \"\" ) : space . execute ( \"\" ) with self . raises ( space , \"\" ) : space . execute ( \"\"\"\"\"\" ) def test_regexp_new_errors ( self , space ) : with self . raises ( space , \"\" ) : space . execute ( \"\" ) with self . raises ( space , \"\" ) : space . execute ( \"\"\"\"\"\" ) def test_to_s ( self , space ) : w_res = space . execute ( \"\" ) assert space . str_w ( w_res ) == \"\" w_res = space . execute ( \"\" ) assert space . str_w ( w_res ) == \"\" def test_match_operator ( self , space ) : w_res = space . execute ( \"\"\"\"\"\" ) assert self . unwrap ( space , w_res ) == [ , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ] def test_match_method ( self , space ) : w_res = space . execute ( \"\" ) assert space . int_w ( w_res ) == def test_match_begin ( self , space ) : w_res = space . execute ( \"\" ) assert space . int_w ( w_res ) == w_res = space . execute ( \"\" ) assert space . int_w ( w_res ) == w_res = space . execute ( \"\" ) assert space . int_w ( w_res ) == with self . raises ( space , \"\" , \"\" ) : space . execute ( \"\" ) def test_match_end ( self , space ) : w_res = space . execute ( \"\" ) assert space . int_w ( w_res ) == w_res = space . execute ( \"\" ) assert space . int_w ( w_res ) == w_res = space . execute ( \"\" ) assert space . int_w ( w_res ) == with self . raises ( space , \"\" , \"\" ) : space . execute ( \"\" ) def test_new_regexp ( self , space ) : w_res = space . execute ( \"\" ) assert w_res is space . w_true w_res = space . execute ( \"\" ) assert space . str_w ( w_res ) == \"\" def test_allocate ( self , space ) : with self . raises ( space , \"\" , \"\" ) : space . execute ( \"\" ) with self . raises ( space , \"\" , \"\" ) : space . execute ( \"\" ) def test_size ( self , space ) : w_res = space . execute ( \"\"\"\"\"\" ) assert space . int_w ( w_res ) == def test_set_match_data_wrong_type ( self , space ) : with self . raises ( space , \"\" ) : space . execute ( \"\" ) space . execute ( \"\" ) def test_atomic_grouping ( self , space ) : w_res = space . execute ( '' ) assert w_res is space . w_nil w_res = space . execute ( '' ) assert space . int_w ( w_res ) == w_res = space . execute ( '' ) assert self . unwrap ( space , w_res ) == [ \"\" ] def test_set_intersection ( self , space ) : w_res = space . execute ( \"\" ) assert space . int_w ( w_res ) == def test_to_a ( self , space ) : w_res = space . execute ( \"\"\"\"\"\" ) assert self . unwrap ( space , w_res ) == [ \"\" , \"\" , \"\" , \"\" ] def test_values_at ( self , space ) : w_res = space . execute ( \"\"\"\"\"\" ) assert self . unwrap ( space , w_res ) == [ \"\" , \"\" , \"\" ] def test_branch ( self , space ) : w_res = space . execute ( \"\" ) assert space . int_w ( w_res ) == def test_dot ( self , space ) : w_res = space . execute ( '' ) assert w_res is space . w_nil w_res = space . execute ( '' ) assert space . int_w ( w_res ) == def test_non_capturing_group ( self , space ) : w_res = space . execute ( \"\" ) assert self . unwrap ( space , w_res ) == [ \"\" , \"\" ] def test_optional_group ( self , space ) : w_res = space . execute ( \"\" ) assert self . unwrap ( space , w_res ) == \"\" w_res = space . execute ( \"\" ) assert self . unwrap ( space , w_res ) == \"\" w_res = space . execute ( \"\" ) assert self . unwrap ( space , w_res ) is None def test_quantify_set ( self , space ) : w_res = space . execute ( \"\" ) assert space . int_w ( w_res ) == def test_posix_class ( self , space ) : w_res = space . execute ( \"\" ) assert space . int_w ( w_res ) == def test_quantify ( self , space ) : w_res = space . execute ( \"\" ) assert self . unwrap ( space , w_res ) == [ \"\" ] def test_repeated_quantification ( self , space ) : w_res = space . execute ( \"\" ) assert self . unwrap ( space , w_res ) == [ \"\" , \"\" ] ", "answer": "def test_casefoldp ( self , space ) :"}, {"prompt": " from openstack . network import network_service from openstack import resource ", "answer": "class AddressScope ( resource . Resource ) :"}, {"prompt": " \"\"\"\"\"\" import click import SoftLayer from SoftLayer . CLI import environment from SoftLayer . CLI import exceptions @ click . command ( ) @ click . option ( '' , help = '' ) @ click . option ( '' , help = '' ) @ click . option ( '' , help = '' ) @ click . option ( '' , help = '' ) @ click . option ( '' , help = '' ) @ click . option ( '' , help = '' ) @ click . option ( '' , help = '' ) @ click . option ( '' , help = '' ) @ click . option ( '' , help = '' ) @ click . option ( '' , default = None , help = '' ) @ click . option ( '' , help = '' ) @ environment . pass_env def cli ( env , abuse , address1 , address2 , city , company , country , firstname , lastname , postal , public , state ) : \"\"\"\"\"\" mgr = SoftLayer . NetworkManager ( env . client ) update = { '' : abuse , '' : address1 , '' : address2 , '' : company , '' : city , '' : country , '' : firstname , '' : lastname , '' : postal , '' : state , '' : public , } if public is True : update [ '' ] = False elif public is False : update [ '' ] = True ", "answer": "check = [ x for x in update . values ( ) if x is not None ]"}, {"prompt": " from flask import render_template , redirect , flash , current_app , url_for , session , jsonify , request , Response from flask . ext . babel import gettext from werkzeug . contrib . cache import SimpleCache import os import urllib import gzip import requests import StringIO import re import xmlrpclib from os_util import OSFile from . import mod cache = SimpleCache ( ) OST_API = '' OST_USERAGENT = '' @ mod . route ( '' ) def index ( ) : if not os . path . isdir ( current_app . config [ '' ] ) : flash ( gettext ( \"\" , directory = directory ) ) return redirect ( \"\" ) return render_template ( '' , movies = get_movies ( ) ) @ mod . route ( '' ) def refresh ( ) : cache . set ( '' , None , timeout = * * * ) return redirect ( url_for ( '' ) ) @ mod . route ( '' ) def player ( ) : return render_template ( '' ) @ mod . route ( '' ) def control ( ) : return render_template ( '' , movies = get_movies ( ) ) @ mod . route ( '' ) def find_subtitles ( ) : rel_path = request . args . get ( '' ) [ len ( current_app . config [ \"\" ] ) + : ] json = cache . get ( rel_path ) if json == None : path = os . path . join ( current_app . config [ '' ] , urllib . unquote ( rel_path ) . decode ( '' ) ) subtitles = [ ] results = os_search ( path ) try : for sub in results : if sub [ '' ] == '' : subtitles . append ( { '' : sub [ '' ] , ", "answer": "'' : sub [ '' ] ,"}, {"prompt": " import time ", "answer": "import unittest"}, {"prompt": " '''''' ", "answer": "import logging"}, {"prompt": " from sympy import Symbol , symbols from sympy . physics . vector import Point , ReferenceFrame from sympy . physics . mechanics import inertia , Body from sympy . utilities . pytest import raises def test_default ( ) : body = Body ( '' ) assert body . name == '' assert body . loads == [ ] point = Point ( '' ) point . set_vel ( body . frame , ) com = body . masscenter frame = body . frame assert com . vel ( frame ) == point . vel ( frame ) assert body . mass == Symbol ( '' ) ixx , iyy , izz = symbols ( '' ) ixy , iyz , izx = symbols ( '' ) assert body . inertia == ( inertia ( body . frame , ixx , iyy , izz , ixy , iyz , izx ) , body . masscenter ) def test_custom_rigid_body ( ) : rigidbody_masscenter = Point ( '' ) rigidbody_mass = Symbol ( '' ) rigidbody_frame = ReferenceFrame ( '' ) body_inertia = inertia ( rigidbody_frame , , , ) rigid_body = Body ( '' , rigidbody_masscenter , rigidbody_mass , rigidbody_frame , body_inertia ) com = rigid_body . masscenter frame = rigid_body . frame rigidbody_masscenter . set_vel ( rigidbody_frame , ) assert com . vel ( frame ) == rigidbody_masscenter . vel ( frame ) assert com . pos_from ( com ) == rigidbody_masscenter . pos_from ( com ) assert rigid_body . mass == rigidbody_mass assert rigid_body . inertia == ( body_inertia , rigidbody_masscenter ) assert hasattr ( rigid_body , '' ) assert hasattr ( rigid_body , '' ) assert hasattr ( rigid_body , '' ) assert hasattr ( rigid_body , '' ) def test_particle_body ( ) : particle_masscenter = Point ( '' ) particle_mass = Symbol ( '' ) particle_frame = ReferenceFrame ( '' ) particle_body = Body ( '' , particle_masscenter , particle_mass , particle_frame ) com = particle_body . masscenter frame = particle_body . frame particle_masscenter . set_vel ( particle_frame , ) assert com . vel ( frame ) == particle_masscenter . vel ( frame ) ", "answer": "assert com . pos_from ( com ) == particle_masscenter . pos_from ( com )"}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import from django . contrib . localflavor . py . py_department import DEPARTMENT_CHOICES , DEPARTMENT_ROMAN_CHOICES ", "answer": "from django . forms . fields import Select"}, {"prompt": " from django . contrib import admin from django . utils . translation import ugettext_lazy as _ from django import forms from django . contrib . auth import get_user_model from django . contrib . sites . models import Site from django . conf import settings from opps . core . widgets import OppsEditor from opps . channels . models import Channel from . models import FlatPage from opps . core . admin import apply_opps_rules from opps . contrib . multisite . admin import AdminViewPermission from opps . images . generate import image_url class FlatPageAdminForm ( forms . ModelForm ) : def __init__ ( self , * args , ** kwargs ) : super ( FlatPageAdminForm , self ) . __init__ ( * args , ** kwargs ) self . fields [ '' ] . required = False def clean_channel ( self ) : if self . cleaned_data [ '' ] : return self . cleaned_data [ \"\" ] return Channel . objects . get_homepage ( site = self . cleaned_data [ '' ] ) class Meta : model = FlatPage widgets = { '' : OppsEditor ( ) } @ apply_opps_rules ( '' ) class FlatPageAdmin ( AdminViewPermission ) : form = FlatPageAdminForm prepopulated_fields = { \"\" : [ \"\" ] } readonly_fields = [ '' , '' , '' ] list_display = [ '' , '' , '' , '' , '' ] raw_id_fields = [ '' , '' ] fieldsets = ( ( _ ( u'' ) , { '' : ( '' , '' , '' , '' , '' ) } ) , ( _ ( u'' ) , { '' : ( '' , '' , ( '' , '' ) ) } ) , ( _ ( u'' ) , { '' : ( '' ) , '' : ( '' , '' , '' , '' ) } ) , ) def image_thumb ( self , obj ) : if obj . main_image : return u'' . format ( image_url ( obj . main_image . archive . url , width = , height = ) ) return _ ( u'' ) image_thumb . short_description = _ ( u'' ) image_thumb . allow_tags = True def save_model ( self , request , obj , form , change ) : if getattr ( obj , '' , None ) is None : obj . user = get_user_model ( ) . objects . get ( pk = request . user . pk ) obj . site = Site . objects . get ( pk = settings . SITE_ID ) ", "answer": "if not obj . channel :"}, {"prompt": " '''''' import sys , traceback import arcpy from arcpy import env try : domTable = arcpy . GetParameterAsText ( ) codeField = arcpy . GetParameterAsText ( ) descField = arcpy . GetParameterAsText ( ) ", "answer": "dWorkspace = arcpy . GetParameterAsText ( )"}, {"prompt": " VM_INFO = UPDATE_IP_RULE = UPLINK_NAME = DFA_AGENT_QUEUE = '' DFA_SERVER_QUEUE = '' DFA_EXCHANGE = '' RESULT_FAIL = '' RESULT_SUCCESS = '' CREATE_FAIL = '' DELETE_FAIL = '' UPDATE_FAIL = '' ", "answer": "IP_DHCP_WAIT = \"\""}, {"prompt": " from babelfish import LanguageReverseConverter from subliminal . exceptions import ConfigurationError ", "answer": "class TheSubDBConverter ( LanguageReverseConverter ) :"}, {"prompt": " \"\"\"\"\"\" from __future__ import division , print_function , absolute_import import warnings import numpy from numpy import ( atleast_1d , poly , polyval , roots , real , asarray , allclose , resize , pi , absolute , logspace , r_ , sqrt , tan , log10 , arctan , arcsinh , sin , exp , cosh , arccosh , ceil , conjugate , zeros , sinh , append , concatenate , prod , ones , array ) from numpy import mintypecode import numpy as np from scipy import special , optimize from scipy . special import comb from scipy . misc import factorial from numpy . polynomial . polynomial import polyval as npp_polyval import math __all__ = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ] class BadCoefficients ( UserWarning ) : \"\"\"\"\"\" pass abs = absolute def findfreqs ( num , den , N ) : \"\"\"\"\"\" ep = atleast_1d ( roots ( den ) ) + tz = atleast_1d ( roots ( num ) ) + if len ( ep ) == : ep = atleast_1d ( - ) + ez = r_ [ '' , numpy . compress ( ep . imag >= , ep , axis = - ) , numpy . compress ( ( abs ( tz ) < ) & ( tz . imag >= ) , tz , axis = - ) ] integ = abs ( ez ) < hfreq = numpy . around ( numpy . log10 ( numpy . max ( * abs ( ez . real + integ ) + * ez . imag ) ) + ) lfreq = numpy . around ( numpy . log10 ( * numpy . min ( abs ( real ( ez + integ ) ) + * ez . imag ) ) - ) w = logspace ( lfreq , hfreq , N ) return w def freqs ( b , a , worN = None , plot = None ) : \"\"\"\"\"\" if worN is None : w = findfreqs ( b , a , ) elif isinstance ( worN , int ) : N = worN w = findfreqs ( b , a , N ) else : w = worN w = atleast_1d ( w ) s = * w h = polyval ( b , s ) / polyval ( a , s ) if plot is not None : plot ( w , h ) return w , h def freqz ( b , a = , worN = None , whole = False , plot = None ) : \"\"\"\"\"\" b , a = map ( atleast_1d , ( b , a ) ) if whole : lastpoint = * pi else : lastpoint = pi if worN is None : N = w = numpy . linspace ( , lastpoint , N , endpoint = False ) elif isinstance ( worN , int ) : N = worN w = numpy . linspace ( , lastpoint , N , endpoint = False ) else : w = worN w = atleast_1d ( w ) zm1 = exp ( - * w ) h = polyval ( b [ : : - ] , zm1 ) / polyval ( a [ : : - ] , zm1 ) if plot is not None : plot ( w , h ) return w , h def group_delay ( system , w = None , whole = False ) : r\"\"\"\"\"\" if w is None : w = if isinstance ( w , int ) : if whole : w = np . linspace ( , * pi , w , endpoint = False ) else : w = np . linspace ( , pi , w , endpoint = False ) w = np . atleast_1d ( w ) b , a = map ( np . atleast_1d , system ) c = np . convolve ( b , a [ : : - ] ) cr = c * np . arange ( c . size ) z = np . exp ( - * w ) num = np . polyval ( cr [ : : - ] , z ) den = np . polyval ( c [ : : - ] , z ) singular = np . absolute ( den ) < * EPSILON if np . any ( singular ) : warnings . warn ( \"\" . format ( \"\" . join ( \"\" . format ( ws ) for ws in w [ singular ] ) ) ) gd = np . zeros_like ( w ) gd [ ~ singular ] = np . real ( num [ ~ singular ] / den [ ~ singular ] ) - a . size + return w , gd def _cplxreal ( z , tol = None ) : \"\"\"\"\"\" z = atleast_1d ( z ) if z . size == : return z , z elif z . ndim != : raise ValueError ( '' ) if tol is None : tol = * np . finfo ( ( * z ) . dtype ) . eps z = z [ np . lexsort ( ( abs ( z . imag ) , z . real ) ) ] real_indices = abs ( z . imag ) <= tol * abs ( z ) zr = z [ real_indices ] . real if len ( zr ) == len ( z ) : return array ( [ ] ) , zr z = z [ ~ real_indices ] zp = z [ z . imag > ] zn = z [ z . imag < ] if len ( zp ) != len ( zn ) : raise ValueError ( '' '' ) same_real = np . diff ( zp . real ) <= tol * abs ( zp [ : - ] ) diffs = numpy . diff ( concatenate ( ( [ ] , same_real , [ ] ) ) ) run_starts = numpy . where ( diffs > ) [ ] run_stops = numpy . where ( diffs < ) [ ] for i in range ( len ( run_starts ) ) : start = run_starts [ i ] stop = run_stops [ i ] + for chunk in ( zp [ start : stop ] , zn [ start : stop ] ) : chunk [ ... ] = chunk [ np . lexsort ( [ abs ( chunk . imag ) ] ) ] if any ( abs ( zp - zn . conj ( ) ) > tol * abs ( zn ) ) : raise ValueError ( '' '' ) zc = ( zp + zn . conj ( ) ) / return zc , zr def _cplxpair ( z , tol = None ) : \"\"\"\"\"\" z = atleast_1d ( z ) if z . size == or np . isrealobj ( z ) : return np . sort ( z ) if z . ndim != : raise ValueError ( '' ) zc , zr = _cplxreal ( z , tol ) zc = np . dstack ( ( zc . conj ( ) , zc ) ) . flatten ( ) z = np . append ( zc , zr ) return z def tf2zpk ( b , a ) : r\"\"\"\"\"\" b , a = normalize ( b , a ) b = ( b + ) / a [ ] a = ( a + ) / a [ ] k = b [ ] b /= b [ ] z = roots ( b ) p = roots ( a ) return z , p , k def zpk2tf ( z , p , k ) : \"\"\"\"\"\" z = atleast_1d ( z ) k = atleast_1d ( k ) if len ( z . shape ) > : temp = poly ( z [ ] ) b = zeros ( ( z . shape [ ] , z . shape [ ] + ) , temp . dtype . char ) if len ( k ) == : k = [ k [ ] ] * z . shape [ ] for i in range ( z . shape [ ] ) : b [ i ] = k [ i ] * poly ( z [ i ] ) else : b = k * poly ( z ) a = atleast_1d ( poly ( p ) ) if issubclass ( b . dtype . type , numpy . complexfloating ) : roots = numpy . asarray ( z , complex ) pos_roots = numpy . compress ( roots . imag > , roots ) neg_roots = numpy . conjugate ( numpy . compress ( roots . imag < , roots ) ) if len ( pos_roots ) == len ( neg_roots ) : if numpy . all ( numpy . sort_complex ( neg_roots ) == numpy . sort_complex ( pos_roots ) ) : b = b . real . copy ( ) if issubclass ( a . dtype . type , numpy . complexfloating ) : roots = numpy . asarray ( p , complex ) pos_roots = numpy . compress ( roots . imag > , roots ) neg_roots = numpy . conjugate ( numpy . compress ( roots . imag < , roots ) ) if len ( pos_roots ) == len ( neg_roots ) : if numpy . all ( numpy . sort_complex ( neg_roots ) == numpy . sort_complex ( pos_roots ) ) : a = a . real . copy ( ) return b , a def tf2sos ( b , a , pairing = '' ) : \"\"\"\"\"\" return zpk2sos ( * tf2zpk ( b , a ) , pairing = pairing ) def sos2tf ( sos ) : \"\"\"\"\"\" sos = np . asarray ( sos ) b = [ ] a = [ ] n_sections = sos . shape [ ] for section in range ( n_sections ) : b = np . polymul ( b , sos [ section , : ] ) a = np . polymul ( a , sos [ section , : ] ) return b , a def sos2zpk ( sos ) : \"\"\"\"\"\" sos = np . asarray ( sos ) n_sections = sos . shape [ ] z = np . empty ( n_sections * , np . complex128 ) p = np . empty ( n_sections * , np . complex128 ) k = for section in range ( n_sections ) : zpk = tf2zpk ( sos [ section , : ] , sos [ section , : ] ) z [ * section : * ( section + ) ] = zpk [ ] p [ * section : * ( section + ) ] = zpk [ ] k *= zpk [ ] return z , p , k def _nearest_real_complex_idx ( fro , to , which ) : \"\"\"\"\"\" assert which in ( '' , '' ) order = np . argsort ( np . abs ( fro - to ) ) mask = np . isreal ( fro [ order ] ) if which == '' : mask = ~ mask return order [ np . where ( mask ) [ ] [ ] ] def zpk2sos ( z , p , k , pairing = '' ) : \"\"\"\"\"\" valid_pairings = [ '' , '' ] if pairing not in valid_pairings : raise ValueError ( '' % ( valid_pairings , pairing ) ) if len ( z ) == len ( p ) == : return array ( [ [ k , , , , , ] ] ) p = np . concatenate ( ( p , np . zeros ( max ( len ( z ) - len ( p ) , ) ) ) ) z = np . concatenate ( ( z , np . zeros ( max ( len ( p ) - len ( z ) , ) ) ) ) n_sections = ( max ( len ( p ) , len ( z ) ) + ) // sos = zeros ( ( n_sections , ) ) if len ( p ) % == and pairing == '' : p = np . concatenate ( ( p , [ ] ) ) z = np . concatenate ( ( z , [ ] ) ) assert len ( p ) == len ( z ) z = np . concatenate ( _cplxreal ( z ) ) p = np . concatenate ( _cplxreal ( p ) ) p_sos = np . zeros ( ( n_sections , ) , np . complex128 ) z_sos = np . zeros_like ( p_sos ) for si in range ( n_sections ) : p1_idx = np . argmin ( np . abs ( - np . abs ( p ) ) ) p1 = p [ p1_idx ] p = np . delete ( p , p1_idx ) if np . isreal ( p1 ) and np . isreal ( p ) . sum ( ) == : z1_idx = _nearest_real_complex_idx ( z , p1 , '' ) z1 = z [ z1_idx ] z = np . delete ( z , z1_idx ) p2 = z2 = else : if not np . isreal ( p1 ) and np . isreal ( z ) . sum ( ) == : z1_idx = _nearest_real_complex_idx ( z , p1 , '' ) assert not np . isreal ( z [ z1_idx ] ) else : z1_idx = np . argmin ( np . abs ( p1 - z ) ) z1 = z [ z1_idx ] z = np . delete ( z , z1_idx ) if not np . isreal ( p1 ) : if not np . isreal ( z1 ) : p2 = p1 . conj ( ) z2 = z1 . conj ( ) else : p2 = p1 . conj ( ) z2_idx = _nearest_real_complex_idx ( z , p1 , '' ) z2 = z [ z2_idx ] assert np . isreal ( z2 ) z = np . delete ( z , z2_idx ) else : if not np . isreal ( z1 ) : z2 = z1 . conj ( ) p2_idx = _nearest_real_complex_idx ( p , z1 , '' ) p2 = p [ p2_idx ] assert np . isreal ( p2 ) else : idx = np . where ( np . isreal ( p ) ) [ ] assert len ( idx ) > p2_idx = idx [ np . argmin ( np . abs ( np . abs ( p [ idx ] ) - ) ) ] p2 = p [ p2_idx ] assert np . isreal ( p2 ) z2_idx = _nearest_real_complex_idx ( z , p2 , '' ) z2 = z [ z2_idx ] assert np . isreal ( z2 ) z = np . delete ( z , z2_idx ) p = np . delete ( p , p2_idx ) p_sos [ si ] = [ p1 , p2 ] z_sos [ si ] = [ z1 , z2 ] assert len ( p ) == len ( z ) == del p , z p_sos = np . reshape ( p_sos [ : : - ] , ( n_sections , ) ) z_sos = np . reshape ( z_sos [ : : - ] , ( n_sections , ) ) gains = np . ones ( n_sections ) gains [ ] = k for si in range ( n_sections ) : x = zpk2tf ( z_sos [ si ] , p_sos [ si ] , gains [ si ] ) sos [ si ] = np . concatenate ( x ) return sos def _align_nums ( nums ) : \"\"\"\"\"\" try : nums = asarray ( nums ) if not np . issubdtype ( nums . dtype , np . number ) : raise ValueError ( \"\" ) return nums except ValueError : nums = list ( nums ) maxwidth = len ( max ( nums , key = lambda num : atleast_1d ( num ) . size ) ) for index , num in enumerate ( nums ) : num = atleast_1d ( num ) . tolist ( ) nums [ index ] = [ ] * ( maxwidth - len ( num ) ) + num return atleast_1d ( nums ) def normalize ( b , a ) : \"\"\"\"\"\" b = _align_nums ( b ) b , a = map ( atleast_1d , ( b , a ) ) if len ( a . shape ) != : raise ValueError ( \"\" ) if len ( b . shape ) > : raise ValueError ( \"\" \"\" ) if len ( b . shape ) == : b = asarray ( [ b ] , b . dtype . char ) while a [ ] == and len ( a ) > : a = a [ : ] outb = b * ( ) / a [ ] outa = a * ( ) / a [ ] if allclose ( , outb [ : , ] , atol = ) : warnings . warn ( \"\" \"\" , BadCoefficients ) while allclose ( , outb [ : , ] , atol = ) and ( outb . shape [ - ] > ) : outb = outb [ : , : ] if outb . shape [ ] == : outb = outb [ ] return outb , outa def lp2lp ( b , a , wo = ) : \"\"\"\"\"\" ", "answer": "a , b = map ( atleast_1d , ( a , b ) )"}, {"prompt": " from msrest . serialization import Model class HttpRequest ( Model ) : \"\"\"\"\"\" ", "answer": "_attribute_map = {"}, {"prompt": " \"\"\"\"\"\" class ListSet ( list ) : \"\"\"\"\"\" def __init__ ( self , * args ) : self . _itemSet = None self . _duplicates = dict ( ) nargs = len ( args ) if nargs == : super ( ListSet , self ) . __init__ ( ) self . _itemSet = set ( ) elif nargs == : if isinstance ( args [ ] , int ) : initialCapacity , = args ", "answer": "super ( ListSet , self ) . __init__ ( )"}, {"prompt": " import os import io import unittest import json from . import medication from . fhirdate import FHIRDate class MedicationTests ( unittest . TestCase ) : def instantiate_from ( self , filename ) : datadir = os . environ . get ( '' ) or '' with io . open ( os . path . join ( datadir , filename ) , '' , encoding = '' ) as handle : js = json . load ( handle ) self . assertEqual ( \"\" , js [ \"\" ] ) return medication . Medication ( js ) def testMedication1 ( self ) : inst = self . instantiate_from ( \"\" ) self . assertIsNotNone ( inst , \"\" ) self . implMedication1 ( inst ) js = inst . as_json ( ) self . assertEqual ( \"\" , js [ \"\" ] ) inst2 = medication . Medication ( js ) self . implMedication1 ( inst2 ) def implMedication1 ( self , inst ) : self . assertEqual ( inst . code . coding [ ] . code , \"\" ) self . assertEqual ( inst . code . coding [ ] . display , \"\" ) self . assertEqual ( inst . code . coding [ ] . system , \"\" ) self . assertEqual ( inst . id , \"\" ) self . assertTrue ( inst . isBrand ) self . assertEqual ( inst . product . form . coding [ ] . code , \"\" ) self . assertEqual ( inst . product . form . coding [ ] . display , \"\" ) self . assertEqual ( inst . product . form . coding [ ] . system , \"\" ) self . assertEqual ( inst . product . ingredient [ ] . amount . denominator . value , ) self . assertEqual ( inst . product . ingredient [ ] . amount . numerator . code , \"\" ) self . assertEqual ( inst . product . ingredient [ ] . amount . numerator . system , \"\" ) self . assertEqual ( inst . product . ingredient [ ] . amount . numerator . unit , \"\" ) self . assertEqual ( inst . product . ingredient [ ] . amount . numerator . value , ) ", "answer": "self . assertEqual ( inst . text . status , \"\" )"}, {"prompt": " from __future__ import unicode_literals , print_function import itertools as it , operator as op , functools as ft import os , sys , io , errno , tempfile , stat , re from os . path import dirname , basename import logging log = logging . getLogger ( __name__ ) class ConfigMixin ( object ) : conf_path_default = b'' conf_save = False conf_raise_structure_errors = False conf_update_keys = dict ( client = { '' , '' } , auth = { '' , '' , '' , '' } , request = { '' , '' , '' } ) def __init__ ( self , ** kwz ) : raise NotImplementedError ( '' ) @ classmethod def from_conf ( cls , path = None , ** overrides ) : '''''' from onedrive import portalocker import yaml if path is None : path = cls . conf_path_default log . debug ( '' , path ) path = os . path . expanduser ( path ) with open ( path , '' ) as src : portalocker . lock ( src , portalocker . LOCK_SH ) yaml_str = src . read ( ) portalocker . unlock ( src ) conf = yaml . safe_load ( yaml_str ) conf . setdefault ( '' , path ) conf_cls = dict ( ) for ns , keys in cls . conf_update_keys . viewitems ( ) : for k in keys : try : v = conf . get ( ns , dict ( ) ) . get ( k ) except AttributeError : if not cls . conf_raise_structure_errors : raise raise KeyError ( ( '' '' '' ) . format ( ns = ns , k = k , path = path ) ) if v is not None : conf_cls [ '' . format ( ns , k ) ] = conf [ ns ] [ k ] conf_cls . update ( overrides ) if isinstance ( conf . get ( '' , dict ( ) ) . get ( '' ) , ( int , long ) ) : log . warn ( '' '' '' , path ) cid = conf [ '' ] [ '' ] if not re . search ( r'' . format ( cid ) , yaml_str ) and re . search ( r'' . format ( cid ) , yaml_str ) : cid = int ( '' . format ( cid ) ) conf [ '' ] [ '' ] = '' . format ( cid ) self = cls ( ** conf_cls ) self . conf_save = conf [ '' ] return self def sync ( self ) : if not self . conf_save : return from onedrive import portalocker import yaml retry = False with open ( self . conf_save , '' ) as src : portalocker . lock ( src , portalocker . LOCK_SH ) conf_raw = src . read ( ) conf = yaml . safe_load ( io . BytesIO ( conf_raw ) ) if conf_raw else dict ( ) portalocker . unlock ( src ) conf_updated = False ", "answer": "for ns , keys in self . conf_update_keys . viewitems ( ) :"}, {"prompt": " import sys , os , re import sphinx if sphinx . __version__ < \"\" : raise RuntimeError ( \"\" ) needs_sphinx = '' sys . path . insert ( , os . path . abspath ( '' ) ) sys . path . insert ( , os . path . abspath ( os . path . dirname ( __file__ ) ) ) extensions = [ '' , '' , '' , '' , '' , '' , '' ] try : from matplotlib . sphinxext import plot_directive except ImportError : use_matplotlib_plot_directive = False else : try : use_matplotlib_plot_directive = ( plot_directive . __version__ >= ) except AttributeError : use_matplotlib_plot_directive = False if use_matplotlib_plot_directive : extensions . append ( '' ) else : raise RuntimeError ( \"\" ) templates_path = [ '' ] source_suffix = '' master_doc = '' project = '' copyright = '' import scipy version = re . sub ( r'' , r'' , scipy . __version__ ) release = scipy . __version__ print \"\" % ( version , ) today_fmt = '' default_role = \"\" exclude_dirs = [ ] add_function_parentheses = False show_authors = False pygments_style = '' themedir = os . path . join ( os . pardir , '' , '' ) if os . path . isdir ( themedir ) : html_theme = '' html_theme_path = [ themedir ] if '' in tags : html_theme_options = { \"\" : True , \"\" : \"\" , \"\" : True , \"\" : [ ( \"\" , \"\" ) , ( \"\" , \"\" ) ] } else : html_theme_options = { \"\" : False , \"\" : \"\" , \"\" : False , \"\" : [ ] } html_logo = '' html_sidebars = { '' : '' } else : if '' in tags : raise RuntimeError ( \"\" \"\" ) else : html_style = '' html_logo = '' html_sidebars = { '' : '' } html_title = \"\" % ( project , version ) html_static_path = [ '' ] html_last_updated_fmt = '' html_additional_pages = { } html_use_modindex = True html_copy_source = False html_file_suffix = '' htmlhelp_basename = '' mathjax_path = \"\" _stdauthor = '' latex_documents = [ ( '' , '' , '' , _stdauthor , '' ) , ] latex_preamble = r'''''' latex_use_modindex = False intersphinx_mapping = { '' : None , '' : None , } phantom_import_file = '' numpydoc_use_plots = True if sphinx . __version__ >= \"\" : import glob autosummary_generate = glob . glob ( \"\" ) coverage_ignore_modules = r\"\"\"\"\"\" . split ( ) coverage_ignore_functions = r\"\"\"\"\"\" . split ( ) coverage_ignore_classes = r\"\"\"\"\"\" . split ( ) coverage_c_path = [ ] coverage_c_regexes = { } coverage_ignore_c_items = { } plot_pre_code = \"\"\"\"\"\" plot_include_source = True ", "answer": "plot_formats = [ ( '' , ) , '' ]"}, {"prompt": " from django . core . exceptions import ValidationError from django . shortcuts import get_object_or_404 from django . shortcuts import render from django . http import HttpResponse from core . utils import int_to_ip , resolve_ip_type from core . range . forms import RangeForm from core . range . utils import range_usage from core . range . ip_choosing_utils import ( calculate_filters , label_value_maker , calc_template_ranges , integrate_real_ranges , UN ", "answer": ")"}, {"prompt": " from django . core . urlresolvers import reverse from django import http from mox3 . mox import IgnoreArg from mox3 . mox import IsA from openstack_dashboard import api from openstack_dashboard . test import helpers as test IDPS_INDEX_URL = reverse ( '' ) ", "answer": "IDPS_REGISTER_URL = reverse ( '' )"}, {"prompt": " import sys if sys . version_info [ ] == : from urlparse import urlparse if urlparse ( '' ) . netloc != '' : ", "answer": "from urlparse import uses_netloc"}, {"prompt": " \"\"\"\"\"\" __all__ = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , ] import collections import copy import functools import logging import os from google . appengine . datastore import entity_pb from google . appengine . api import api_base_pb from google . appengine . api import apiproxy_rpc from google . appengine . api import apiproxy_stub_map from google . appengine . api import datastore_errors from google . appengine . api import datastore_types from google . appengine . api . app_identity import app_identity from google . appengine . datastore import datastore_pb from google . appengine . datastore import datastore_pbs from google . appengine . datastore import datastore_v4_pb from google . appengine . runtime import apiproxy_errors _CLOUD_DATASTORE_ENABLED = datastore_pbs . _CLOUD_DATASTORE_ENABLED if _CLOUD_DATASTORE_ENABLED : from google . appengine . datastore . datastore_pbs import googledatastore _MAX_ID_BATCH_SIZE = * * _DATASTORE_V3 = '' _DATASTORE_V4 = '' _CLOUD_DATASTORE_V1 = '' def _positional ( max_pos_args ) : \"\"\"\"\"\" def positional_decorator ( wrapped ) : @ functools . wraps ( wrapped ) def positional_wrapper ( * args , ** kwds ) : if len ( args ) > max_pos_args : plural_s = '' if max_pos_args != : plural_s = '' raise TypeError ( '' % ( wrapped . __name__ , max_pos_args , plural_s , len ( args ) ) ) return wrapped ( * args , ** kwds ) return positional_wrapper return positional_decorator def _GetDatastoreType ( app = None ) : \"\"\"\"\"\" current_app = datastore_types . ResolveAppId ( None ) if app not in ( current_app , None ) : return BaseConnection . UNKNOWN_DATASTORE partition , _ , _ = app_identity . _ParseFullAppId ( current_app ) if partition : return BaseConnection . HIGH_REPLICATION_DATASTORE return BaseConnection . MASTER_SLAVE_DATASTORE class AbstractAdapter ( object ) : \"\"\"\"\"\" _entity_converter = datastore_pbs . get_entity_converter ( ) _query_converter = datastore_pbs . _QueryConverter ( _entity_converter ) def __init__ ( self , id_resolver = None ) : if id_resolver : self . _entity_converter = datastore_pbs . get_entity_converter ( id_resolver ) self . _query_converter = datastore_pbs . _QueryConverter ( self . _entity_converter ) def get_entity_converter ( self ) : return self . _entity_converter def get_query_converter ( self ) : return self . _query_converter def pb_to_key ( self , pb ) : \"\"\"\"\"\" raise NotImplementedError def pb_v1_to_key ( self , pb ) : \"\"\"\"\"\" v3_ref = entity_pb . Reference ( ) self . _entity_converter . v1_to_v3_reference ( pb , v3_ref ) return self . pb_to_key ( v3_ref ) def pb_to_entity ( self , pb ) : \"\"\"\"\"\" raise NotImplementedError def pb_v1_to_entity ( self , pb , is_projection ) : \"\"\"\"\"\" v3_entity = entity_pb . EntityProto ( ) self . _entity_converter . v1_to_v3_entity ( pb , v3_entity , is_projection ) return self . pb_to_entity ( v3_entity ) def pb_v1_to_query_result ( self , pb , query_options ) : \"\"\"\"\"\" if query_options . keys_only : return self . pb_v1_to_key ( pb . key ) else : return self . pb_v1_to_entity ( pb , bool ( query_options . projection ) ) def pb_to_index ( self , pb ) : \"\"\"\"\"\" raise NotImplementedError def pb_to_query_result ( self , pb , query_options ) : \"\"\"\"\"\" if query_options . keys_only : return self . pb_to_key ( pb . key ( ) ) else : return self . pb_to_entity ( pb ) def key_to_pb ( self , key ) : \"\"\"\"\"\" raise NotImplementedError def key_to_pb_v1 ( self , key ) : \"\"\"\"\"\" v3_ref = self . key_to_pb ( key ) v1_key = googledatastore . Key ( ) self . _entity_converter . v3_to_v1_key ( v3_ref , v1_key ) return v1_key def entity_to_pb ( self , entity ) : \"\"\"\"\"\" raise NotImplementedError def entity_to_pb_v1 ( self , entity ) : \"\"\"\"\"\" v3_entity = self . entity_to_pb ( entity ) v1_entity = googledatastore . Entity ( ) self . _entity_converter . v3_to_v1_entity ( v3_entity , v1_entity ) return v1_entity def new_key_pb ( self ) : \"\"\"\"\"\" return entity_pb . Reference ( ) def new_entity_pb ( self ) : \"\"\"\"\"\" return entity_pb . EntityProto ( ) class IdentityAdapter ( AbstractAdapter ) : \"\"\"\"\"\" def __init__ ( self , id_resolver = None ) : super ( IdentityAdapter , self ) . __init__ ( id_resolver ) def pb_to_key ( self , pb ) : return pb def pb_to_entity ( self , pb ) : return pb def key_to_pb ( self , key ) : return key def entity_to_pb ( self , entity ) : return entity def pb_to_index ( self , pb ) : return pb class ConfigOption ( object ) : \"\"\"\"\"\" def __init__ ( self , validator ) : self . validator = validator def __get__ ( self , obj , objtype ) : if obj is None : return self return obj . _values . get ( self . validator . __name__ , None ) def __set__ ( self , obj , value ) : raise AttributeError ( '' % ( self . validator . __name__ , ) ) def __call__ ( self , * args ) : \"\"\"\"\"\" name = self . validator . __name__ for config in args : if isinstance ( config , ( type ( None ) , apiproxy_stub_map . UserRPC ) ) : pass elif not isinstance ( config , BaseConfiguration ) : raise datastore_errors . BadArgumentError ( '' % ( config , ) ) elif name in config . _values and self is config . _options [ name ] : return config . _values [ name ] return None class _ConfigurationMetaClass ( type ) : \"\"\"\"\"\" def __new__ ( metaclass , classname , bases , classDict ) : if classname == '' : return type . __new__ ( metaclass , classname , bases , classDict ) if object in bases : classDict [ '' ] = [ '' ] else : classDict [ '' ] = [ ] cls = type . __new__ ( metaclass , classname , bases , classDict ) if object not in bases : options = { } for c in reversed ( cls . __mro__ ) : if '' in c . __dict__ : options . update ( c . __dict__ [ '' ] ) cls . _options = options for option , value in cls . __dict__ . iteritems ( ) : if isinstance ( value , ConfigOption ) : if cls . _options . has_key ( option ) : raise TypeError ( '' % ( option , cls . __name__ ) ) cls . _options [ option ] = value value . _cls = cls return cls class BaseConfiguration ( object ) : \"\"\"\"\"\" __metaclass__ = _ConfigurationMetaClass _options = { } def __new__ ( cls , config = None , ** kwargs ) : \"\"\"\"\"\" if config is None : pass elif isinstance ( config , BaseConfiguration ) : if cls is config . __class__ and config . __is_stronger ( ** kwargs ) : return config for key , value in config . _values . iteritems ( ) : if issubclass ( cls , config . _options [ key ] . _cls ) : kwargs . setdefault ( key , value ) else : raise datastore_errors . BadArgumentError ( '' % ( config , ) ) obj = super ( BaseConfiguration , cls ) . __new__ ( cls ) obj . _values = { } for key , value in kwargs . iteritems ( ) : if value is not None : try : config_option = obj . _options [ key ] except KeyError , err : raise TypeError ( '' % err ) value = config_option . validator ( value ) if value is not None : obj . _values [ key ] = value return obj def __eq__ ( self , other ) : if self is other : return True if not isinstance ( other , BaseConfiguration ) : return NotImplemented return self . _options == other . _options and self . _values == other . _values def __ne__ ( self , other ) : equal = self . __eq__ ( other ) if equal is NotImplemented : return equal return not equal def __hash__ ( self ) : return ( hash ( frozenset ( self . _values . iteritems ( ) ) ) ^ hash ( frozenset ( self . _options . iteritems ( ) ) ) ) def __repr__ ( self ) : args = [ ] for key_value in sorted ( self . _values . iteritems ( ) ) : args . append ( '' % key_value ) return '' % ( self . __class__ . __name__ , '' . join ( args ) ) def __is_stronger ( self , ** kwargs ) : \"\"\"\"\"\" for key , value in kwargs . iteritems ( ) : if key not in self . _values or value != self . _values [ key ] : return False return True @ classmethod def is_configuration ( cls , obj ) : \"\"\"\"\"\" return isinstance ( obj , BaseConfiguration ) and obj . _is_configuration ( cls ) def _is_configuration ( self , cls ) : return isinstance ( self , cls ) def merge ( self , config ) : \"\"\"\"\"\" if config is None or config is self : return self if not ( isinstance ( config , _MergedConfiguration ) or isinstance ( self , _MergedConfiguration ) ) : if isinstance ( config , self . __class__ ) : for key in self . _values : if key not in config . _values : break else : return config if isinstance ( self , config . __class__ ) : if self . __is_stronger ( ** config . _values ) : return self def _quick_merge ( obj ) : obj . _values = self . _values . copy ( ) obj . _values . update ( config . _values ) return obj if isinstance ( config , self . __class__ ) : return _quick_merge ( type ( config ) ( ) ) if isinstance ( self , config . __class__ ) : return _quick_merge ( type ( self ) ( ) ) return _MergedConfiguration ( config , self ) def __getstate__ ( self ) : return { '' : self . _values } def __setstate__ ( self , state ) : obj = self . __class__ ( ** state [ '' ] ) self . _values = obj . _values class _MergedConfiguration ( BaseConfiguration ) : \"\"\"\"\"\" __slots__ = [ '' , '' , '' , '' ] def __new__ ( cls , * configs ) : obj = super ( BaseConfiguration , cls ) . __new__ ( cls ) obj . _configs = configs obj . _options = { } for config in configs : for name , option in config . _options . iteritems ( ) : if name in obj . _options : if option is not obj . _options [ name ] : error = ( \"\" % ( name , option . _cls . __name__ , obj . _options [ name ] . _cls . __name__ ) ) raise datastore_errors . BadArgumentError ( error ) obj . _options [ name ] = option obj . _values = { } for config in reversed ( configs ) : for name , value in config . _values . iteritems ( ) : obj . _values [ name ] = value return obj def __repr__ ( self ) : return '' % ( self . __class__ . __name__ , tuple ( self . _configs ) ) def _is_configuration ( self , cls ) : for config in self . _configs : if config . _is_configuration ( cls ) : return True return False def __getattr__ ( self , name ) : if name in self . _options : if name in self . _values : return self . _values [ name ] else : return None raise AttributeError ( \"\" % ( name , ) ) def __getstate__ ( self ) : return { '' : self . _configs } def __setstate__ ( self , state ) : obj = _MergedConfiguration ( * state [ '' ] ) self . _values = obj . _values self . _configs = obj . _configs self . _options = obj . _options class Configuration ( BaseConfiguration ) : \"\"\"\"\"\" STRONG_CONSISTENCY = \"\"\"\"\"\" EVENTUAL_CONSISTENCY = \"\"\"\"\"\" APPLY_ALL_JOBS_CONSISTENCY = \"\"\"\"\"\" ALL_READ_POLICIES = frozenset ( ( STRONG_CONSISTENCY , EVENTUAL_CONSISTENCY , APPLY_ALL_JOBS_CONSISTENCY , ) ) @ ConfigOption def deadline ( value ) : \"\"\"\"\"\" if not isinstance ( value , ( int , long , float ) ) : raise datastore_errors . BadArgumentError ( '' % ( value , ) ) if value <= : raise datastore_errors . BadArgumentError ( '' % ( value , ) ) return value @ ConfigOption def on_completion ( value ) : \"\"\"\"\"\" return value @ ConfigOption def read_policy ( value ) : \"\"\"\"\"\" if value not in Configuration . ALL_READ_POLICIES : raise datastore_errors . BadArgumentError ( '' % ( value , ) ) return value @ ConfigOption def force_writes ( value ) : \"\"\"\"\"\" if not isinstance ( value , bool ) : raise datastore_errors . BadArgumentError ( '' % ( value , ) ) return value @ ConfigOption def max_entity_groups_per_rpc ( value ) : \"\"\"\"\"\" if not ( isinstance ( value , ( int , long ) ) and value > ) : raise datastore_errors . BadArgumentError ( '' ) return value @ ConfigOption def max_allocate_ids_keys ( value ) : \"\"\"\"\"\" if not ( isinstance ( value , ( int , long ) ) and value > ) : raise datastore_errors . BadArgumentError ( '' ) return value @ ConfigOption def max_rpc_bytes ( value ) : \"\"\"\"\"\" if not ( isinstance ( value , ( int , long ) ) and value > ) : raise datastore_errors . BadArgumentError ( '' ) return value @ ConfigOption def max_get_keys ( value ) : \"\"\"\"\"\" if not ( isinstance ( value , ( int , long ) ) and value > ) : raise datastore_errors . BadArgumentError ( '' ) return value @ ConfigOption def max_put_entities ( value ) : \"\"\"\"\"\" if not ( isinstance ( value , ( int , long ) ) and value > ) : raise datastore_errors . BadArgumentError ( '' ) return value @ ConfigOption def max_delete_keys ( value ) : \"\"\"\"\"\" if not ( isinstance ( value , ( int , long ) ) and value > ) : raise datastore_errors . BadArgumentError ( '' ) return value _NOOP_SERVICE = '' class _NoopRPC ( apiproxy_rpc . RPC ) : \"\"\"\"\"\" def __init__ ( self ) : super ( _NoopRPC , self ) . __init__ ( ) def _WaitImpl ( self ) : return True def _MakeCallImpl ( self ) : self . _state = apiproxy_rpc . RPC . FINISHING class _NoopRPCStub ( object ) : \"\"\"\"\"\" def CreateRPC ( self ) : return _NoopRPC ( ) class MultiRpc ( object ) : \"\"\"\"\"\" def __init__ ( self , rpcs , extra_hook = None ) : \"\"\"\"\"\" self . __rpcs = self . flatten ( rpcs ) self . __extra_hook = extra_hook @ property def rpcs ( self ) : \"\"\"\"\"\" return list ( self . __rpcs ) @ property def state ( self ) : \"\"\"\"\"\" lo = apiproxy_rpc . RPC . FINISHING hi = apiproxy_rpc . RPC . IDLE for rpc in self . __rpcs : lo = min ( lo , rpc . state ) hi = max ( hi , rpc . state ) if lo == hi : return lo return apiproxy_rpc . RPC . RUNNING def wait ( self ) : \"\"\"\"\"\" apiproxy_stub_map . UserRPC . wait_all ( self . __rpcs ) def check_success ( self ) : \"\"\"\"\"\" self . wait ( ) for rpc in self . __rpcs : rpc . check_success ( ) def get_result ( self ) : \"\"\"\"\"\" if len ( self . __rpcs ) == : results = self . __rpcs [ ] . get_result ( ) else : results = [ ] for rpc in self . __rpcs : result = rpc . get_result ( ) if isinstance ( result , list ) : results . extend ( result ) elif result is not None : results . append ( result ) if self . __extra_hook is not None : results = self . __extra_hook ( results ) return results @ classmethod def flatten ( cls , rpcs ) : \"\"\"\"\"\" flat = [ ] for rpc in rpcs : if isinstance ( rpc , MultiRpc ) : flat . extend ( rpc . __rpcs ) else : if not isinstance ( rpc , apiproxy_stub_map . UserRPC ) : raise datastore_errors . BadArgumentError ( '' % ( rpc , ) ) flat . append ( rpc ) return flat @ classmethod def wait_any ( cls , rpcs ) : \"\"\"\"\"\" return apiproxy_stub_map . UserRPC . wait_any ( cls . flatten ( rpcs ) ) @ classmethod def wait_all ( cls , rpcs ) : \"\"\"\"\"\" apiproxy_stub_map . UserRPC . wait_all ( cls . flatten ( rpcs ) ) class BaseConnection ( object ) : \"\"\"\"\"\" UNKNOWN_DATASTORE = MASTER_SLAVE_DATASTORE = HIGH_REPLICATION_DATASTORE = __SUPPORTED_VERSIONS = frozenset ( ( _DATASTORE_V3 , _CLOUD_DATASTORE_V1 ) ) @ _positional ( ) def __init__ ( self , adapter = None , config = None , _api_version = _DATASTORE_V3 ) : \"\"\"\"\"\" if adapter is None : adapter = IdentityAdapter ( ) if not isinstance ( adapter , AbstractAdapter ) : raise datastore_errors . BadArgumentError ( '' % ( adapter , ) ) self . __adapter = adapter if config is None : config = Configuration ( ) elif not Configuration . is_configuration ( config ) : raise datastore_errors . BadArgumentError ( '' % ( config , ) ) self . __config = config if _api_version not in self . __SUPPORTED_VERSIONS : raise datastore_errors . BadArgumentError ( '' % ( _api_version , ) ) if _api_version == _CLOUD_DATASTORE_V1 : if not _CLOUD_DATASTORE_ENABLED : raise datastore_errors . BadArgumentError ( datastore_pbs . MISSING_CLOUD_DATASTORE_MESSAGE ) apiproxy_stub_map . apiproxy . ReplaceStub ( _NOOP_SERVICE , _NoopRPCStub ( ) ) self . _api_version = _api_version self . __pending_rpcs = set ( ) @ property def adapter ( self ) : \"\"\"\"\"\" return self . __adapter @ property def config ( self ) : \"\"\"\"\"\" return self . __config def _add_pending ( self , rpc ) : \"\"\"\"\"\" assert not isinstance ( rpc , MultiRpc ) self . __pending_rpcs . add ( rpc ) def _remove_pending ( self , rpc ) : \"\"\"\"\"\" if isinstance ( rpc , MultiRpc ) : for wrapped_rpc in rpc . _MultiRpc__rpcs : self . _remove_pending ( wrapped_rpc ) else : try : self . __pending_rpcs . remove ( rpc ) except KeyError : pass def is_pending ( self , rpc ) : \"\"\"\"\"\" if isinstance ( rpc , MultiRpc ) : for wrapped_rpc in rpc . _MultiRpc__rpcs : if self . is_pending ( wrapped_rpc ) : return True return False else : return rpc in self . __pending_rpcs def get_pending_rpcs ( self ) : \"\"\"\"\"\" return set ( self . __pending_rpcs ) def get_datastore_type ( self , app = None ) : \"\"\"\"\"\" return _GetDatastoreType ( app ) def wait_for_all_pending_rpcs ( self ) : \"\"\"\"\"\" while self . __pending_rpcs : try : rpc = apiproxy_stub_map . UserRPC . wait_any ( self . __pending_rpcs ) except Exception : logging . info ( '' , exc_info = True ) continue if rpc is None : logging . debug ( '' ) continue assert rpc . state == apiproxy_rpc . RPC . FINISHING if rpc in self . __pending_rpcs : try : self . check_rpc_success ( rpc ) except Exception : logging . info ( '' '' , exc_info = True ) def _create_rpc ( self , config = None , service_name = None ) : \"\"\"\"\"\" deadline = Configuration . deadline ( config , self . __config ) on_completion = Configuration . on_completion ( config , self . __config ) callback = None if service_name is None : service_name = self . _api_version if on_completion is not None : def callback ( ) : return on_completion ( rpc ) rpc = apiproxy_stub_map . UserRPC ( service_name , deadline , callback ) return rpc create_rpc = _create_rpc def _set_request_read_policy ( self , request , config = None ) : \"\"\"\"\"\" if isinstance ( config , apiproxy_stub_map . UserRPC ) : read_policy = getattr ( config , '' , None ) else : read_policy = Configuration . read_policy ( config ) if read_policy is None : read_policy = self . __config . read_policy if hasattr ( request , '' ) and hasattr ( request , '' ) : if read_policy == Configuration . APPLY_ALL_JOBS_CONSISTENCY : request . set_strong ( True ) return True elif read_policy == Configuration . EVENTUAL_CONSISTENCY : request . set_strong ( False ) request . set_failover_ms ( - ) return False else : return None elif hasattr ( request , '' ) : if read_policy == Configuration . EVENTUAL_CONSISTENCY : request . read_options . read_consistency = ( googledatastore . ReadOptions . EVENTUAL ) return False else : return None else : raise datastore_errors . BadRequestError ( '' ) def _set_request_transaction ( self , request ) : \"\"\"\"\"\" return None def _make_rpc_call ( self , config , method , request , response , get_result_hook = None , user_data = None , service_name = None ) : \"\"\"\"\"\" if isinstance ( config , apiproxy_stub_map . UserRPC ) : rpc = config else : rpc = self . _create_rpc ( config , service_name ) rpc . make_call ( method , request , response , get_result_hook , user_data ) self . _add_pending ( rpc ) return rpc make_rpc_call = _make_rpc_call def check_rpc_success ( self , rpc ) : \"\"\"\"\"\" try : rpc . wait ( ) finally : self . _remove_pending ( rpc ) try : rpc . check_success ( ) except apiproxy_errors . ApplicationError , err : raise _ToDatastoreError ( err ) MAX_RPC_BYTES = * MAX_GET_KEYS = MAX_PUT_ENTITIES = MAX_DELETE_KEYS = MAX_ALLOCATE_IDS_KEYS = DEFAULT_MAX_ENTITY_GROUPS_PER_RPC = def __get_max_entity_groups_per_rpc ( self , config ) : \"\"\"\"\"\" return Configuration . max_entity_groups_per_rpc ( config , self . __config ) or self . DEFAULT_MAX_ENTITY_GROUPS_PER_RPC def _extract_entity_group ( self , value ) : \"\"\"\"\"\" if _CLOUD_DATASTORE_ENABLED and isinstance ( value , googledatastore . Entity ) : value = value . key if isinstance ( value , entity_pb . EntityProto ) : value = value . key ( ) if _CLOUD_DATASTORE_ENABLED and isinstance ( value , googledatastore . Key ) : elem = value . path [ ] elem_id = elem . id elem_name = elem . name kind = elem . kind else : elem = value . path ( ) . element ( ) kind = elem . type ( ) elem_id = elem . id ( ) elem_name = elem . name ( ) return ( kind , elem_id or elem_name or ( '' , id ( elem ) ) ) def _map_and_group ( self , values , map_fn , group_fn ) : \"\"\"\"\"\" indexed_key_groups = collections . defaultdict ( list ) for index , value in enumerate ( values ) : key = map_fn ( value ) indexed_key_groups [ group_fn ( key ) ] . append ( ( key , index ) ) return indexed_key_groups . values ( ) def __create_result_index_pairs ( self , indexes ) : \"\"\"\"\"\" def create_result_index_pairs ( results ) : return zip ( results , indexes ) return create_result_index_pairs def __sort_result_index_pairs ( self , extra_hook ) : \"\"\"\"\"\" def sort_result_index_pairs ( result_index_pairs ) : results = [ None ] * len ( result_index_pairs ) for result , index in result_index_pairs : results [ index ] = result if extra_hook is not None : results = extra_hook ( results ) return results return sort_result_index_pairs def _generate_pb_lists ( self , grouped_values , base_size , max_count , max_groups , config ) : \"\"\"\"\"\" max_size = ( Configuration . max_rpc_bytes ( config , self . __config ) or self . MAX_RPC_BYTES ) pbs = [ ] pb_indexes = [ ] size = base_size num_groups = for indexed_pbs in grouped_values : num_groups += if max_groups is not None and num_groups > max_groups : yield ( pbs , pb_indexes ) pbs = [ ] pb_indexes = [ ] size = base_size num_groups = for indexed_pb in indexed_pbs : ( pb , index ) = indexed_pb incr_size = pb . ByteSize ( ) + if ( not isinstance ( config , apiproxy_stub_map . UserRPC ) and ( len ( pbs ) >= max_count or ( pbs and size + incr_size > max_size ) ) ) : yield ( pbs , pb_indexes ) pbs = [ ] pb_indexes = [ ] size = base_size num_groups = pbs . append ( pb ) pb_indexes . append ( index ) size += incr_size yield ( pbs , pb_indexes ) def __force ( self , req ) : \"\"\"\"\"\" if isinstance ( req , ( datastore_pb . PutRequest , datastore_pb . TouchRequest , datastore_pb . DeleteRequest ) ) : req . set_force ( True ) def get ( self , keys ) : \"\"\"\"\"\" return self . async_get ( None , keys ) . get_result ( ) def async_get ( self , config , keys , extra_hook = None ) : \"\"\"\"\"\" def make_get_call ( base_req , pbs , extra_hook = None ) : req = copy . deepcopy ( base_req ) if self . _api_version == _CLOUD_DATASTORE_V1 : method = '' req . keys . extend ( pbs ) resp = googledatastore . LookupResponse ( ) else : method = '' req . key_list ( ) . extend ( pbs ) resp = datastore_pb . GetResponse ( ) user_data = config , pbs , extra_hook return self . _make_rpc_call ( config , method , req , resp , get_result_hook = self . __get_hook , user_data = user_data , service_name = self . _api_version ) if self . _api_version == _CLOUD_DATASTORE_V1 : base_req = googledatastore . LookupRequest ( ) key_to_pb = self . __adapter . key_to_pb_v1 else : base_req = datastore_pb . GetRequest ( ) base_req . set_allow_deferred ( True ) key_to_pb = self . __adapter . key_to_pb is_read_current = self . _set_request_read_policy ( base_req , config ) txn = self . _set_request_transaction ( base_req ) if isinstance ( config , apiproxy_stub_map . UserRPC ) or len ( keys ) <= : pbs = [ key_to_pb ( key ) for key in keys ] return make_get_call ( base_req , pbs , extra_hook ) max_count = ( Configuration . max_get_keys ( config , self . __config ) or self . MAX_GET_KEYS ) indexed_keys_by_entity_group = self . _map_and_group ( keys , key_to_pb , self . _extract_entity_group ) if is_read_current is None : is_read_current = ( self . get_datastore_type ( ) == BaseConnection . HIGH_REPLICATION_DATASTORE ) if is_read_current and txn is None : max_egs_per_rpc = self . __get_max_entity_groups_per_rpc ( config ) else : max_egs_per_rpc = None pbsgen = self . _generate_pb_lists ( indexed_keys_by_entity_group , base_req . ByteSize ( ) , max_count , max_egs_per_rpc , config ) rpcs = [ ] for pbs , indexes in pbsgen : rpcs . append ( make_get_call ( base_req , pbs , self . __create_result_index_pairs ( indexes ) ) ) return MultiRpc ( rpcs , self . __sort_result_index_pairs ( extra_hook ) ) def __get_hook ( self , rpc ) : \"\"\"\"\"\" self . check_rpc_success ( rpc ) config , keys_from_request , extra_hook = rpc . user_data if self . _api_version == _DATASTORE_V3 and rpc . response . in_order ( ) : entities = [ ] for entity_result in rpc . response . entity_list ( ) : if entity_result . has_entity ( ) : entity = self . __adapter . pb_to_entity ( entity_result . entity ( ) ) else : entity = None entities . append ( entity ) else : current_get_response = rpc . response result_dict = { } self . __add_get_response_entities_to_dict ( current_get_response , result_dict ) deferred_req = copy . deepcopy ( rpc . request ) if self . _api_version == _CLOUD_DATASTORE_V1 : method = '' deferred_resp = googledatastore . LookupResponse ( ) while current_get_response . deferred : deferred_req . ClearField ( '' ) deferred_req . keys . extend ( current_get_response . deferred ) deferred_resp . Clear ( ) deferred_rpc = self . _make_rpc_call ( config , method , deferred_req , deferred_resp , service_name = self . _api_version ) deferred_rpc . get_result ( ) current_get_response = deferred_rpc . response self . __add_get_response_entities_to_dict ( current_get_response , result_dict ) else : method = '' deferred_resp = datastore_pb . GetResponse ( ) while current_get_response . deferred_list ( ) : deferred_req . clear_key ( ) deferred_req . key_list ( ) . extend ( current_get_response . deferred_list ( ) ) deferred_resp . Clear ( ) deferred_rpc = self . _make_rpc_call ( config , method , deferred_req , deferred_resp , service_name = self . _api_version ) deferred_rpc . get_result ( ) current_get_response = deferred_rpc . response self . __add_get_response_entities_to_dict ( current_get_response , result_dict ) entities = [ result_dict . get ( datastore_types . ReferenceToKeyValue ( pb ) ) for pb in keys_from_request ] if extra_hook is not None : entities = extra_hook ( entities ) return entities def __add_get_response_entities_to_dict ( self , get_response , result_dict ) : \"\"\"\"\"\" if ( _CLOUD_DATASTORE_ENABLED and isinstance ( get_response , googledatastore . LookupResponse ) ) : for result in get_response . found : v1_key = result . entity . key entity = self . __adapter . pb_v1_to_entity ( result . entity , False ) result_dict [ datastore_types . ReferenceToKeyValue ( v1_key ) ] = entity else : for entity_result in get_response . entity_list ( ) : if entity_result . has_entity ( ) : reference_pb = entity_result . entity ( ) . key ( ) hashable_key = datastore_types . ReferenceToKeyValue ( reference_pb ) entity = self . __adapter . pb_to_entity ( entity_result . entity ( ) ) result_dict [ hashable_key ] = entity def get_indexes ( self ) : \"\"\"\"\"\" return self . async_get_indexes ( None ) . get_result ( ) def async_get_indexes ( self , config , extra_hook = None , _app = None ) : \"\"\"\"\"\" req = datastore_pb . GetIndicesRequest ( ) req . set_app_id ( datastore_types . ResolveAppId ( _app ) ) resp = datastore_pb . CompositeIndices ( ) return self . _make_rpc_call ( config , '' , req , resp , get_result_hook = self . __get_indexes_hook , user_data = extra_hook , service_name = _DATASTORE_V3 ) def __get_indexes_hook ( self , rpc ) : \"\"\"\"\"\" self . check_rpc_success ( rpc ) indexes = [ self . __adapter . pb_to_index ( index ) for index in rpc . response . index_list ( ) ] if rpc . user_data : indexes = rpc . user_data ( indexes ) return indexes def put ( self , entities ) : \"\"\"\"\"\" return self . async_put ( None , entities ) . get_result ( ) def async_put ( self , config , entities , extra_hook = None ) : \"\"\"\"\"\" def make_put_call ( base_req , pbs , user_data = None ) : req = copy . deepcopy ( base_req ) if self . _api_version == _CLOUD_DATASTORE_V1 : for entity in pbs : mutation = req . mutations . add ( ) mutation . upsert . CopyFrom ( entity ) method = '' resp = googledatastore . CommitResponse ( ) else : req . entity_list ( ) . extend ( pbs ) method = '' resp = datastore_pb . PutResponse ( ) user_data = pbs , user_data return self . _make_rpc_call ( config , method , req , resp , get_result_hook = self . __put_hook , user_data = user_data , service_name = self . _api_version ) if self . _api_version == _CLOUD_DATASTORE_V1 : base_req = googledatastore . CommitRequest ( ) base_req . mode = googledatastore . CommitRequest . NON_TRANSACTIONAL entity_to_pb = self . __adapter . entity_to_pb_v1 else : base_req = datastore_pb . PutRequest ( ) entity_to_pb = self . __adapter . entity_to_pb self . _set_request_transaction ( base_req ) if Configuration . force_writes ( config , self . __config ) : self . __force ( base_req ) if isinstance ( config , apiproxy_stub_map . UserRPC ) or len ( entities ) <= : pbs = [ entity_to_pb ( entity ) for entity in entities ] return make_put_call ( base_req , pbs , extra_hook ) max_count = ( Configuration . max_put_entities ( config , self . __config ) or self . MAX_PUT_ENTITIES ) if ( ( self . _api_version == _CLOUD_DATASTORE_V1 and not base_req . transaction ) or not base_req . has_transaction ( ) ) : max_egs_per_rpc = self . __get_max_entity_groups_per_rpc ( config ) else : max_egs_per_rpc = None indexed_entities_by_entity_group = self . _map_and_group ( entities , entity_to_pb , self . _extract_entity_group ) pbsgen = self . _generate_pb_lists ( indexed_entities_by_entity_group , base_req . ByteSize ( ) , max_count , max_egs_per_rpc , config ) rpcs = [ ] for pbs , indexes in pbsgen : rpcs . append ( make_put_call ( base_req , pbs , self . __create_result_index_pairs ( indexes ) ) ) return MultiRpc ( rpcs , self . __sort_result_index_pairs ( extra_hook ) ) def __put_hook ( self , rpc ) : \"\"\"\"\"\" self . check_rpc_success ( rpc ) entities_from_request , extra_hook = rpc . user_data if ( _CLOUD_DATASTORE_ENABLED and isinstance ( rpc . response , googledatastore . CommitResponse ) ) : keys = [ ] i = for entity in entities_from_request : if datastore_pbs . is_complete_v1_key ( entity . key ) : keys . append ( entity . key ) else : keys . append ( rpc . response . mutation_results [ i ] . key ) i += keys = [ self . __adapter . pb_v1_to_key ( key ) for key in keys ] else : keys = [ self . __adapter . pb_to_key ( key ) for key in rpc . response . key_list ( ) ] if extra_hook is not None : keys = extra_hook ( keys ) return keys def delete ( self , keys ) : \"\"\"\"\"\" return self . async_delete ( None , keys ) . get_result ( ) def async_delete ( self , config , keys , extra_hook = None ) : \"\"\"\"\"\" def make_delete_call ( base_req , pbs , user_data = None ) : req = copy . deepcopy ( base_req ) if self . _api_version == _CLOUD_DATASTORE_V1 : for pb in pbs : mutation = req . mutations . add ( ) mutation . delete . CopyFrom ( pb ) method = '' resp = googledatastore . CommitResponse ( ) else : req . key_list ( ) . extend ( pbs ) method = '' resp = datastore_pb . DeleteResponse ( ) return self . _make_rpc_call ( config , method , req , resp , get_result_hook = self . __delete_hook , user_data = user_data , service_name = self . _api_version ) if self . _api_version == _CLOUD_DATASTORE_V1 : base_req = googledatastore . CommitRequest ( ) base_req . mode = googledatastore . CommitRequest . NON_TRANSACTIONAL key_to_pb = self . __adapter . key_to_pb_v1 else : base_req = datastore_pb . DeleteRequest ( ) key_to_pb = self . __adapter . key_to_pb self . _set_request_transaction ( base_req ) if Configuration . force_writes ( config , self . __config ) : self . __force ( base_req ) if isinstance ( config , apiproxy_stub_map . UserRPC ) or len ( keys ) <= : pbs = [ key_to_pb ( key ) for key in keys ] return make_delete_call ( base_req , pbs , extra_hook ) max_count = ( Configuration . max_delete_keys ( config , self . __config ) or self . MAX_DELETE_KEYS ) if ( ( self . _api_version == _CLOUD_DATASTORE_V1 and not base_req . transaction ) or not base_req . has_transaction ( ) ) : max_egs_per_rpc = self . __get_max_entity_groups_per_rpc ( config ) else : max_egs_per_rpc = None indexed_keys_by_entity_group = self . _map_and_group ( keys , key_to_pb , self . _extract_entity_group ) pbsgen = self . _generate_pb_lists ( indexed_keys_by_entity_group , base_req . ByteSize ( ) , max_count , max_egs_per_rpc , config ) rpcs = [ ] for pbs , _ in pbsgen : rpcs . append ( make_delete_call ( base_req , pbs ) ) return MultiRpc ( rpcs , extra_hook ) def __delete_hook ( self , rpc ) : \"\"\"\"\"\" self . check_rpc_success ( rpc ) if rpc . user_data is not None : rpc . user_data ( None ) def begin_transaction ( self , app ) : \"\"\"\"\"\" return self . async_begin_transaction ( None , app ) . get_result ( ) def async_begin_transaction ( self , config , app ) : \"\"\"\"\"\" if not isinstance ( app , basestring ) or not app : raise datastore_errors . BadArgumentError ( '' % ( app , ) ) if self . _api_version == _CLOUD_DATASTORE_V1 : req = googledatastore . BeginTransactionRequest ( ) resp = googledatastore . BeginTransactionResponse ( ) else : req = datastore_pb . BeginTransactionRequest ( ) req . set_app ( app ) if ( TransactionOptions . xg ( config , self . __config ) ) : req . set_allow_multiple_eg ( True ) resp = datastore_pb . Transaction ( ) return self . _make_rpc_call ( config , '' , req , resp , get_result_hook = self . __begin_transaction_hook , service_name = self . _api_version ) def __begin_transaction_hook ( self , rpc ) : \"\"\"\"\"\" self . check_rpc_success ( rpc ) if self . _api_version == _CLOUD_DATASTORE_V1 : return rpc . response . transaction else : return rpc . response class Connection ( BaseConnection ) : \"\"\"\"\"\" @ _positional ( ) def __init__ ( self , adapter = None , config = None , _api_version = _DATASTORE_V3 ) : \"\"\"\"\"\" super ( Connection , self ) . __init__ ( adapter = adapter , config = config , _api_version = _api_version ) self . __adapter = self . adapter self . __config = self . config def new_transaction ( self , config = None ) : \"\"\"\"\"\" config = self . __config . merge ( config ) return TransactionalConnection ( adapter = self . __adapter , config = config , _api_version = self . _api_version ) def allocate_ids ( self , key , size = None , max = None ) : \"\"\"\"\"\" return self . async_allocate_ids ( None , key , size , max ) . get_result ( ) def async_allocate_ids ( self , config , key , size = None , max = None , extra_hook = None ) : \"\"\"\"\"\" if size is not None : if max is not None : raise datastore_errors . BadArgumentError ( '' ) if not isinstance ( size , ( int , long ) ) : raise datastore_errors . BadArgumentError ( '' % ( size , ) ) if size > _MAX_ID_BATCH_SIZE : raise datastore_errors . BadArgumentError ( '' % ( _MAX_ID_BATCH_SIZE , size ) ) if size <= : raise datastore_errors . BadArgumentError ( '' % size ) if max is not None : if not isinstance ( max , ( int , long ) ) : raise datastore_errors . BadArgumentError ( '' % ( max , ) ) if max < : raise datastore_errors . BadArgumentError ( '' % size ) req = datastore_pb . AllocateIdsRequest ( ) req . mutable_model_key ( ) . CopyFrom ( self . __adapter . key_to_pb ( key ) ) if size is not None : req . set_size ( size ) if max is not None : req . set_max ( max ) resp = datastore_pb . AllocateIdsResponse ( ) rpc = self . _make_rpc_call ( config , '' , req , resp , get_result_hook = self . __allocate_ids_hook , user_data = extra_hook , service_name = _DATASTORE_V3 ) return rpc def __allocate_ids_hook ( self , rpc ) : \"\"\"\"\"\" self . check_rpc_success ( rpc ) pair = rpc . response . start ( ) , rpc . response . end ( ) if rpc . user_data is not None : pair = rpc . user_data ( pair ) return pair def _reserve_keys ( self , keys ) : \"\"\"\"\"\" self . _async_reserve_keys ( None , keys ) . get_result ( ) def _async_reserve_keys ( self , config , keys , extra_hook = None ) : \"\"\"\"\"\" def to_id_key ( key ) : if key . path ( ) . element_size ( ) == : return '' else : return self . _extract_entity_group ( key ) keys_by_idkey = self . _map_and_group ( keys , self . __adapter . key_to_pb , to_id_key ) max_count = ( Configuration . max_allocate_ids_keys ( config , self . __config ) or self . MAX_ALLOCATE_IDS_KEYS ) rpcs = [ ] pbsgen = self . _generate_pb_lists ( keys_by_idkey , , max_count , None , config ) for pbs , _ in pbsgen : req = datastore_v4_pb . AllocateIdsRequest ( ) for key in pbs : datastore_pbs . get_entity_converter ( ) . v3_to_v4_key ( key , req . add_reserve ( ) ) resp = datastore_v4_pb . AllocateIdsResponse ( ) rpcs . append ( self . _make_rpc_call ( config , '' , req , resp , get_result_hook = self . __reserve_keys_hook , user_data = extra_hook , service_name = _DATASTORE_V4 ) ) return MultiRpc ( rpcs ) def __reserve_keys_hook ( self , rpc ) : \"\"\"\"\"\" self . check_rpc_success ( rpc ) if rpc . user_data is not None : return rpc . user_data ( rpc . response ) class TransactionOptions ( Configuration ) : \"\"\"\"\"\" NESTED = \"\"\"\"\"\" MANDATORY = \"\"\"\"\"\" ALLOWED = \"\"\"\"\"\" INDEPENDENT = \"\"\"\"\"\" _PROPAGATION = frozenset ( ( NESTED , MANDATORY , ALLOWED , INDEPENDENT ) ) @ ConfigOption def propagation ( value ) : \"\"\"\"\"\" if value not in TransactionOptions . _PROPAGATION : raise datastore_errors . BadArgumentError ( '' % ( value , ) ) return value @ ConfigOption def xg ( value ) : \"\"\"\"\"\" if not isinstance ( value , bool ) : raise datastore_errors . BadArgumentError ( '' % ( value , ) ) return value @ ConfigOption def retries ( value ) : \"\"\"\"\"\" datastore_types . ValidateInteger ( value , '' , datastore_errors . BadArgumentError , ", "answer": "zero_ok = True )"}, {"prompt": " import os . path import unittest def get_tests ( ) : return full_suite ( ) def full_suite ( ) : ", "answer": "from . resource import ResourceTestCase"}, {"prompt": " from django . middleware . csrf import get_token ", "answer": "class CsrfCookieUsedMiddleware ( object ) :"}, {"prompt": " from django . contrib import admin from datatrans . models import KeyValue class KeyValueAdmin ( admin . ModelAdmin ) : list_display = ( '' , '' , '' , '' , '' , '' , '' ) ordering = ( '' , '' ) search_fields = ( '' , '' , '' , ) ", "answer": "list_filter = ( '' , '' , '' , '' )"}, {"prompt": " import struct \"\"\"\"\"\" __all__ = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ] class EndOfFile ( Exception ) : pass def get_ui32 ( f ) : try : ret = struct . unpack ( \"\" , f . read ( ) ) [ ] except struct . error : raise EndOfFile return ret def make_ui32 ( num ) : return struct . pack ( \"\" , num ) def get_si32_extended ( f ) : low_high = f . read ( ) if len ( low_high ) < : raise EndOfFile combined = low_high [ ] + low_high [ : ] ", "answer": "return struct . unpack ( \"\" , combined ) [ ]"}, {"prompt": " from PySide . QtCore import * from PySide . QtGui import * import csv from progressbar import ProgressBar import codecs from pandas import merge , read_csv from database import * class ExportFileDialog ( QFileDialog ) : \"\"\"\"\"\" def __init__ ( self , * args , ** kwargs ) : super ( ExportFileDialog , self ) . __init__ ( * args , ** kwargs ) self . mainWindow = self . parent ( ) self . setWindowTitle ( \"\" ) self . setAcceptMode ( QFileDialog . AcceptSave ) self . setFilter ( \"\" ) self . setDefaultSuffix ( \"\" ) self . optionBOM = QCheckBox ( \"\" , self ) self . optionBOM . setCheckState ( Qt . CheckState . Checked ) self . optionWide = QCheckBox ( \"\" , self ) self . optionWide . setCheckState ( Qt . CheckState . Unchecked ) self . optionAll = QComboBox ( self ) self . optionAll . insertItems ( , [ '' , '' ] ) if self . mainWindow . tree . noneOrAllSelected ( ) : self . optionAll . setCurrentIndex ( ) ", "answer": "else :"}, {"prompt": " import sys , os import imp from optparse import make_option from django . conf import settings from django . utils . importlib import import_module from django . core . management import call_command from django . core . management import BaseCommand from django . db import connections def import_app ( app_label , verbosity ) : try : app_path = __import__ ( app_label , { } , { } , [ app_label . split ( '' ) [ - ] ] ) . __path__ except AttributeError : return except ImportError : print \"\" % app_label print \"\" sys . exit ( ) try : ", "answer": "imp . find_module ( '' , app_path )"}, {"prompt": " \"\"\"\"\"\" from __future__ import print_function from collections import defaultdict import sys import traceback from . thrift_message import ThriftMessage class StreamContext ( object ) : def __init__ ( self ) : self . bytes = '' class StreamHandler ( object ) : def __init__ ( self , outqueue , protocol = None , finagle_thrift = False , max_message_size = * , read_values = False , debug = False ) : self . _contexts_by_streams = defaultdict ( StreamContext ) self . _pop_size = self . _outqueue = outqueue self . _protocol = protocol self . _finagle_thrift = finagle_thrift self . _max_message_size = max_message_size self . _debug = debug self . _read_values = read_values self . _seen_messages = self . _recognized_streams = set ( ) ", "answer": "def __call__ ( self , * args , ** kwargs ) :"}, {"prompt": " import sys from pubnub import Pubnub pubnub = Pubnub ( publish_key = '' , subscribe_key = '' ) channel = '' username = '' message = '' data = { '' : username , ", "answer": "'' : message"}, {"prompt": " '''''' ", "answer": "def handle_matrix_test_class ( ) :"}, {"prompt": " from __future__ import print_function __author__ = '' from . capturetask import CaptureGameTask from pybrain . rl . environments . twoplayergames . capturegameplayers import ModuleDecidingPlayer from pybrain . rl . environments . twoplayergames import CaptureGame from pybrain . rl . environments . twoplayergames . capturegameplayers . captureplayer import CapturePlayer from pybrain . structure . networks . custom . capturegame import CaptureGameNetwork class RelativeCaptureTask ( CaptureGameTask ) : \"\"\"\"\"\" useNetworks = False maxGames = presetGamesProportion = minTemperature = maxTemperature = verbose = False numMovesCoeff = def __init__ ( self , size , ** args ) : self . setArgs ( ** args ) self . size = size self . task = CaptureGameTask ( self . size ) ", "answer": "self . env = self . task . env"}, {"prompt": " import turnstile . checks as checks import turnstile . common . output as output import turnstile . models . specifications as specifications @ checks . Check ( '' ) def check ( user_configuration , repository_configuration , commit_message ) : \"\"\"\"\"\" logger = output . get_sub_logger ( '' , '' ) logger . debug ( '' ) logger . debug ( '' , commit_message . message ) if commit_message . message . startswith ( '' ) : logger . debug ( \"\" ) raise checks . CheckIgnore check_options = repository_configuration . get ( '' , { } ) allowed_schemes = check_options . get ( '' , [ '' , '' ] ) allowed_formats = check_options . get ( '' , { '' } ) logger . debug ( \"\" , allowed_schemes ) ", "answer": "result = checks . CheckResult ( )"}, {"prompt": " \"\"\"\"\"\" ", "answer": "from . import TestCase"}, {"prompt": " import datetime from django . core . management . base import BaseCommand , CommandError from formdata . db_worker_settings import FIELDDIR_LOCATION from formdata . models import * def list_db_fields_from_model ( this_model ) : \"\"\"\"\"\" field_list = [ ] for field in this_model . _meta . fields : if not field . auto_created : ", "answer": "field_list . append ( field . column )"}, {"prompt": " import sys import numpy as np from numpy import linalg as LA from theano import tensor as T import theano from deepy . utils . functions import FLOATX from deepy . trainers import CustomizeTrainer from deepy . trainers . optimize import optimize_function class FirstGlimpseTrainer ( CustomizeTrainer ) : def __init__ ( self , network , attention_layer , config ) : \"\"\"\"\"\" super ( FirstGlimpseTrainer , self ) . __init__ ( network , config ) self . large_cov_mode = False self . batch_size = config . get ( \"\" , ) self . disable_backprop = config . get ( \"\" , False ) self . disable_reinforce = config . get ( \"\" , False ) self . last_average_reward = ", "answer": "self . turn = "}, {"prompt": " import sublime import sublime_plugin import os . path from ... core import Settings , StateProperty from ... utils import ( ActionHistory , Constant ) REPORT_TEMPLATE = '''''' ", "answer": "class JavatarActionHistoryCommand ( sublime_plugin . WindowCommand ) :"}, {"prompt": " from __future__ import absolute_import , division , print_function import os import importlib import logging logger = logging . getLogger ( __name__ ) filetypes = [ '' , '' , '' ] ", "answer": "blacklisted = [ '' , '' , '' , '' ]"}, {"prompt": " from mapy . reader import user_setattr from mapy . model . properties import Properties class Prop2D ( Properties ) : def __init__ ( self ) : super ( Prop2D , self ) . __init__ ( ) class PropShell ( Prop2D ) : ", "answer": "def __init__ ( self , inputs ) :"}, {"prompt": " from django . db import models from datetime import datetime , date from decimal import Decimal import six from six . moves import xrange from django_dynamic_fixture . django_helper import django_greater_than class DataFixtureTestCase ( object ) : def setUp ( self ) : self . fixture = None def test_numbers ( self ) : self . assertTrue ( isinstance ( self . fixture . generate_data ( models . IntegerField ( ) ) , int ) ) self . assertTrue ( isinstance ( self . fixture . generate_data ( models . SmallIntegerField ( ) ) , int ) ) self . assertTrue ( isinstance ( self . fixture . generate_data ( models . PositiveIntegerField ( ) ) , int ) ) self . assertTrue ( isinstance ( self . fixture . generate_data ( models . PositiveSmallIntegerField ( ) ) , int ) ) self . assertTrue ( isinstance ( self . fixture . generate_data ( models . BigIntegerField ( ) ) , int ) ) self . assertTrue ( isinstance ( self . fixture . generate_data ( models . FloatField ( ) ) , float ) ) self . assertTrue ( isinstance ( self . fixture . generate_data ( models . DecimalField ( max_digits = , decimal_places = ) ) , Decimal ) ) def test_it_must_deal_with_decimal_max_digits ( self ) : for _ in xrange ( ) : self . assertTrue ( isinstance ( self . fixture . generate_data ( models . DecimalField ( max_digits = , decimal_places = ) ) , Decimal ) ) self . assertTrue ( isinstance ( self . fixture . generate_data ( models . DecimalField ( max_digits = , decimal_places = ) ) , Decimal ) ) def test_strings ( self ) : self . assertTrue ( isinstance ( self . fixture . generate_data ( models . CharField ( max_length = ) ) , six . text_type ) ) self . assertTrue ( isinstance ( self . fixture . generate_data ( models . TextField ( ) ) , six . text_type ) ) self . assertTrue ( isinstance ( self . fixture . generate_data ( models . SlugField ( max_length = ) ) , six . text_type ) ) self . assertTrue ( isinstance ( self . fixture . generate_data ( models . CommaSeparatedIntegerField ( max_length = ) ) , six . text_type ) ) def test_new_truncate_strings_to_max_length ( self ) : for _ in range ( ) : self . assertTrue ( isinstance ( self . fixture . generate_data ( models . CharField ( max_length = ) ) , six . text_type ) ) def test_boolean ( self ) : self . assertTrue ( isinstance ( self . fixture . generate_data ( models . BooleanField ( ) ) , bool ) ) value = self . fixture . generate_data ( models . NullBooleanField ( ) ) self . assertTrue ( isinstance ( value , bool ) or value == None ) def test_date_time_related ( self ) : self . assertTrue ( isinstance ( self . fixture . generate_data ( models . DateField ( ) ) , date ) ) self . assertTrue ( isinstance ( self . fixture . generate_data ( models . TimeField ( ) ) , datetime ) ) self . assertTrue ( isinstance ( self . fixture . generate_data ( models . DateTimeField ( ) ) , datetime ) ) def test_formatted_strings ( self ) : self . assertTrue ( isinstance ( self . fixture . generate_data ( models . EmailField ( max_length = ) ) , six . text_type ) ) self . assertTrue ( isinstance ( self . fixture . generate_data ( models . URLField ( max_length = ) ) , six . text_type ) ) self . assertTrue ( isinstance ( self . fixture . generate_data ( models . IPAddressField ( max_length = ) ) , six . text_type ) ) ", "answer": "if django_greater_than ( '' ) :"}, {"prompt": " from django . utils import timezone from openduty . models import Service , ServiceTokens , Token , SchedulePolicy , Incident from rest_framework . reverse import reverse from rest_framework . test import APIRequestFactory , APIClient from . shared import BaseTestCase , random_string class TestAPI ( BaseTestCase ) : def setUp ( self ) : super ( TestAPI , self ) . setUp ( ) self . sp = SchedulePolicy ( name = random_string ( ) , repeat_times = ) self . sp . save ( ) self . service = Service ( name = random_string ( ) , policy = self . sp ) self . service . save ( ) self . token = Token ( key = \"\" ) self . token . save ( ) self . servicetoken = ServiceTokens ( name = \"\" , service_id = self . service , token_id = self . token ) self . servicetoken . save ( ) self . service2 = Service ( name = random_string ( ) , policy = self . sp ) self . service2 . save ( ) self . token2 = Token ( key = \"\" ) self . token2 . save ( ) self . servicetoken2 = ServiceTokens ( name = \"\" , service_id = self . service2 , token_id = self . token2 ) self . servicetoken2 . save ( ) def tearDown ( self ) : super ( TestAPI , self ) . tearDown ( ) try : self . servicetoken . delete ( ) self . servicetoken2 . delete ( ) self . token2 . delete ( ) self . token . delete ( ) self . service2 . delete ( ) self . service . delete ( ) self . sp . delete ( ) except : pass def test_create_event ( self ) : try : client = APIClient ( ) response = client . post ( '' , data = { \"\" : \"\" , \"\" : self . token . key , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" } , ) self . assertEqual ( , response . status_code ) new_instance = Incident . objects . get ( incident_key = '' ) self . assertEqual ( \"\" , new_instance . incident_key ) self . assertEqual ( Incident . TRIGGER , new_instance . event_type ) self . assertEqual ( self . service , new_instance . service_key ) finally : pass def test_create_event_fails_with_invalid_key ( self ) : try : client = APIClient ( ) response = client . post ( '' , data = { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" } , ) self . assertEqual ( , response . status_code ) finally : pass def inject_incident ( self ) : incident = Incident ( ) incident . service_key = self . service incident . event_type = Incident . TRIGGER ", "answer": "incident . incident_key = \"\""}, {"prompt": " \"\"\"\"\"\" from __future__ import division from . component import VisualComponent from . . shaders import Varying class GridContourComponent ( VisualComponent ) : \"\"\"\"\"\" SHADERS = dict ( frag_color = \"\"\"\"\"\" , vert_post_hook = \"\"\"\"\"\" ) def __init__ ( self , spacing ) : super ( GridContourComponent , self ) . __init__ ( ) self . spacing = spacing var = Varying ( '' , dtype = '' ) self . _funcs [ '' ] [ '' ] = var self . _funcs [ '' ] [ '' ] = var @ property def color ( self ) : return self . _color @ color . setter def color ( self , c ) : self . _color = c def activate ( self , program , mode ) : ff = self . _funcs [ '' ] ff [ '' ] = self . spacing class ShadingComponent ( VisualComponent ) : \"\"\"\"\"\" SHADERS = dict ( frag_color = \"\"\"\"\"\" ) def __init__ ( self , normal_comp , lights , ambient = ) : super ( ShadingComponent , self ) . __init__ ( ) self . normal_comp = normal_comp self . _deps = [ normal_comp ] self . lights = lights self . ambient = ambient def activate ( self , program , mode ) : ff = self . _funcs [ '' ] ff [ '' ] = self . normal_comp . normal_shader ( ) ff [ '' ] = tuple ( self . lights [ ] [ ] [ : ] ) + ( , ) ", "answer": "ff [ '' ] = tuple ( self . lights [ ] [ ] [ : ] ) + ( , )"}, {"prompt": " \"\"\"\"\"\" from django . conf . urls import url from zinnia . urls import _ from zinnia . views . tags import TagList from zinnia . views . tags import TagDetail urlpatterns = [ url ( r'' , TagList . as_view ( ) , name = '' ) , ", "answer": "url ( r'' ,"}, {"prompt": " import copy import mock from sahara . service . api import v10 as api from sahara . service . validations import cluster_template_schema as ct_schema from sahara . tests . unit . service . validation import utils as u SAMPLE_DATA = { '' : '' , '' : '' , '' : '' , '' : False , '' : False } class TestClusterTemplateUpdateValidation ( u . ValidationTestCase ) : def setUp ( self ) : super ( TestClusterTemplateUpdateValidation , self ) . setUp ( ) self . _create_object_fun = mock . Mock ( ) self . scheme = ct_schema . CLUSTER_TEMPLATE_UPDATE_SCHEMA api . plugin_base . setup_plugins ( ) def test_cluster_template_update_nothing_required ( self ) : self . _assert_create_object_validation ( data = { } ) def test_cluster_template_update_schema ( self ) : create = copy . copy ( ct_schema . CLUSTER_TEMPLATE_SCHEMA ) update = copy . copy ( ct_schema . CLUSTER_TEMPLATE_UPDATE_SCHEMA ) self . assertEqual ( [ ] , update [ \"\" ] ) del update [ \"\" ] del create [ \"\" ] self . assertEqual ( create , update ) def test_cluster_template_update ( self ) : self . _assert_create_object_validation ( data = SAMPLE_DATA ) extra = copy . copy ( SAMPLE_DATA ) extra [ '' ] = '' self . _assert_create_object_validation ( data = extra , ", "answer": "bad_req_i = ( , \"\" ,"}, {"prompt": " \"\"\"\"\"\" from __future__ import unicode_literals , absolute_import import bson from . . common import * from . . types import BaseType from . . exceptions import ConversionError class ObjectIdType ( BaseType ) : \"\"\"\"\"\" MESSAGES = { '' : \"\" , } def __init__ ( self , auto_fill = False , ** kwargs ) : self . auto_fill = auto_fill super ( ObjectIdType , self ) . __init__ ( ** kwargs ) def to_native ( self , value , context = None ) : if not isinstance ( value , bson . objectid . ObjectId ) : try : value = bson . objectid . ObjectId ( str ( value ) ) except bson . objectid . InvalidId : raise ConversionError ( self . messages [ '' ] ) return value ", "answer": "def to_primitive ( self , value , context = None ) :"}, {"prompt": " import time from appium_helper import OperaAppiumDriver from selenium . webdriver . common . by import By from selenium . webdriver . support . ui import WebDriverWait from selenium . webdriver . support import expected_conditions as ExpectedConditions desired_caps = { '' : '' , '' : '' , } driver = OperaAppiumDriver ( '' , desired_caps ) driver . skip_introduction_guide ( ) driver . open_page_in_native_context ( \"\" ) ", "answer": "driver . switch_to . context ( '' )"}, {"prompt": " from nose . tools import eq_ from nose . tools import raises import unittest def test_cache_control_object_max_age_None ( ) : from webob . cachecontrol import CacheControl cc = CacheControl ( { } , '' ) cc . properties [ '' ] = None eq_ ( cc . max_age , - ) class TestUpdateDict ( unittest . TestCase ) : def setUp ( self ) : self . call_queue = [ ] def callback ( args ) : self . call_queue . append ( \"\" % repr ( args ) ) self . callback = callback def make_one ( self , callback ) : from webob . cachecontrol import UpdateDict ud = UpdateDict ( ) ud . updated = callback return ud def test_clear ( self ) : newone = self . make_one ( self . callback ) newone [ '' ] = assert len ( newone ) == newone . clear ( ) assert len ( newone ) == def test_update ( self ) : newone = self . make_one ( self . callback ) d = { '' : } newone . update ( d ) assert newone == d def test_set_delete ( self ) : newone = self . make_one ( self . callback ) newone [ '' ] = assert len ( self . call_queue ) == assert self . call_queue [ - ] == \"\" del newone [ '' ] assert len ( self . call_queue ) == assert self . call_queue [ - ] == '' def test_setdefault ( self ) : newone = self . make_one ( self . callback ) assert newone . setdefault ( '' , '' ) == '' assert len ( self . call_queue ) == assert self . call_queue [ - ] == \"\" , self . call_queue [ - ] assert newone . setdefault ( '' , '' ) == '' assert len ( self . call_queue ) == def test_pop ( self ) : newone = self . make_one ( self . callback ) newone [ '' ] = newone . pop ( '' ) assert len ( self . call_queue ) == assert self . call_queue [ - ] == '' , self . call_queue [ - ] def test_popitem ( self ) : newone = self . make_one ( self . callback ) newone [ '' ] = assert newone . popitem ( ) == ( '' , ) assert len ( self . call_queue ) == assert self . call_queue [ - ] == '' , self . call_queue [ - ] def test_callback_args ( self ) : assert True class TestExistProp ( unittest . TestCase ) : \"\"\"\"\"\" def setUp ( self ) : pass def make_one ( self ) : from webob . cachecontrol import exists_property class Dummy ( object ) : properties = dict ( prop = ) type = '' prop = exists_property ( '' , '' ) badprop = exists_property ( '' , '' ) return Dummy def test_get_on_class ( self ) : from webob . cachecontrol import exists_property Dummy = self . make_one ( ) assert isinstance ( Dummy . prop , exists_property ) , Dummy . prop def test_get_on_instance ( self ) : obj = self . make_one ( ) ( ) ", "answer": "assert obj . prop is True"}, {"prompt": " \"\"\"\"\"\" from __future__ import print_function , division from sympy . utilities import public @ public class DomainElement ( object ) : \"\"\"\"\"\" ", "answer": "def parent ( self ) :"}, {"prompt": " from __future__ import print_function from __future__ import unicode_literals from __future__ import absolute_import from __future__ import generators import os , sys , inspect , copy if - != sys . path [ ] . find ( '' ) : raise Exception ( '' ) exampleFileDirectory = sys . path [ ] [ : sys . path [ ] . rfind ( os . sep ) ] pyeq2IimportDirectory = os . path . join ( os . path . join ( exampleFileDirectory , '' ) , '' ) if pyeq2IimportDirectory not in sys . path : sys . path . append ( pyeq2IimportDirectory ) import pyeq2 def UniqueCombinations ( items , n ) : if n == : yield [ ] else : for i in xrange ( len ( items ) ) : for cc in UniqueCombinations ( items [ i + : ] , n - ) : yield [ items [ i ] ] + cc def UniqueCombinations2 ( items2 , n2 ) : if n2 == : yield [ ] else : for i2 in xrange ( len ( items2 ) ) : for cc2 in UniqueCombinations2 ( items2 [ i2 + : ] , n2 - ) : yield [ items2 [ i2 ] ] + cc2 def SetParametersAndFit ( inEquation , resultList , inPrintStatus ) : try : if len ( inEquation . GetCoefficientDesignators ( ) ) > len ( inEquation . dataCache . allDataCacheDictionary [ '' ] ) : return if inEquation . ShouldDataBeRejected ( inEquation ) : return if inPrintStatus : print ( '' , inEquation . __module__ , \"\" + inEquation . GetDisplayName ( ) + \"\" ) inEquation . Solve ( ) target = inEquation . CalculateAllDataFittingTarget ( inEquation . solvedCoefficients ) if target > : ", "answer": "return"}, {"prompt": " from plumbum . commands . processes import CommandNotFound from plumbum . commands . processes import ProcessExecutionError from plumbum . commands . processes import ProcessTimedOut class PopenAddons ( object ) : \"\"\"\"\"\" def verify ( self , retcode , timeout , stdout , stderr ) : \"\"\"\"\"\" if getattr ( self , \"\" , False ) : raise ProcessTimedOut ( \"\" % ( timeout , ) , getattr ( self , \"\" , None ) ) if retcode is not None : if hasattr ( retcode , \"\" ) : if self . returncode not in retcode : raise ProcessExecutionError ( getattr ( self , \"\" , None ) , self . returncode , stdout , stderr ) elif self . returncode != retcode : raise ProcessExecutionError ( getattr ( self , \"\" , None ) , self . returncode , stdout , stderr ) class BaseMachine ( object ) : \"\"\"\"\"\" def get ( self , cmd , * othercommands ) : \"\"\"\"\"\" try : command = self [ cmd ] if not command . executable . exists ( ) : raise CommandNotFound ( cmd , command . executable ) else : return command except CommandNotFound : if othercommands : return self . get ( othercommands [ ] , * othercommands [ : ] ) else : raise def __contains__ ( self , cmd ) : \"\"\"\"\"\" try : self [ cmd ] except CommandNotFound : ", "answer": "return False"}, {"prompt": " from solum . objects import registry from solum . objects . sqlalchemy import app from solum . tests import base from solum . tests import utils class TestApp ( base . BaseTestCase ) : def setUp ( self ) : super ( TestApp , self ) . setUp ( ) self . db = self . useFixture ( utils . Database ( ) ) self . ctx = utils . dummy_context ( ) self . data = [ { '' : '' , '' : self . ctx . tenant , '' : '' , '' : '' , '' : '' , } ] utils . create_models_from_data ( app . App , self . data , self . ctx ) def test_objects_registered ( self ) : self . assertTrue ( registry . App ) self . assertTrue ( registry . AppList ) def test_get_all ( self ) : lst = app . AppList ( ) self . assertEqual ( , len ( lst . get_all ( self . ctx ) ) ) ", "answer": "def test_check_data_by_id ( self ) :"}, {"prompt": " import os from os import walk import sys import thread import gzip from multiprocessing import Pool , Process , Queue PROCESS_COUNT = class Utils : @ staticmethod def rename ( file , to ) : call_rename = \"\" % ( file , to ) print call_rename os . system ( call_rename ) return to @ staticmethod def archive ( file ) : if \"\" in file : return file file_archive = \"\" % file Utils . rename ( file , file_archive ) return file_archive @ staticmethod def unarchive ( file ) : if \"\" not in file : return file file2 = file [ : - ] Utils . rename ( file , file2 ) return file2 @ staticmethod def gzip ( file ) : if \"\" in file : return file call_zip = \"\" % ( file ) print call_zip os . system ( call_zip ) return \"\" % file @ staticmethod def gunzip ( file ) : if \"\" not in file : return file call_unzip = \"\" % ( file ) print call_unzip os . system ( call_unzip ) return file [ : - ] ", "answer": "@ staticmethod"}, {"prompt": " \"\"\"\"\"\" import os import sys import pytest import flask ", "answer": "from flask . _compat import PY2"}, {"prompt": " '''''' import csv import hashlib import logging import os import sys import numpy as np logger = logging . getLogger ( __name__ ) try : from cStringIO import StringIO except : from StringIO import StringIO import matplotlib . mlab import cellprofiler . cpmodule as cpm import cellprofiler . objects as cpo import cellprofiler . measurements as cpmeas import cellprofiler . settings as cps from cellprofiler . settings import YES , NO import cellprofiler . preferences as cpprefs import identify as I from cellprofiler . modules . loadimages import LoadImagesImageProvider from cellprofiler . modules . loadimages import C_FILE_NAME , C_PATH_NAME , C_URL from cellprofiler . modules . loadimages import C_SERIES , C_FRAME from cellprofiler . modules . loadimages import C_OBJECTS_FILE_NAME from cellprofiler . modules . loadimages import C_OBJECTS_PATH_NAME from cellprofiler . modules . loadimages import C_OBJECTS_URL from cellprofiler . measurements import C_OBJECTS_SERIES , C_OBJECTS_FRAME from cellprofiler . modules . loadimages import C_MD5_DIGEST , C_SCALING from cellprofiler . modules . loadimages import C_HEIGHT , C_WIDTH from cellprofiler . modules . loadimages import bad_sizes_warning from cellprofiler . modules . loadimages import convert_image_to_objects from cellprofiler . modules . loadimages import pathname2url , url2pathname from cellprofiler . preferences import standardize_default_folder_names , DEFAULT_INPUT_FOLDER_NAME , DEFAULT_OUTPUT_FOLDER_NAME , NO_FOLDER_NAME , ABSOLUTE_FOLDER_NAME , IO_FOLDER_CHOICE_HELP_TEXT IMAGE_CATEGORIES = ( C_URL , C_FILE_NAME , C_PATH_NAME ) OBJECTS_CATEGORIES = ( C_OBJECTS_URL , C_OBJECTS_FILE_NAME , C_OBJECTS_PATH_NAME ) DIR_NONE = '' DIR_OTHER = '' DIR_ALL = [ DEFAULT_INPUT_FOLDER_NAME , DEFAULT_OUTPUT_FOLDER_NAME , NO_FOLDER_NAME , ABSOLUTE_FOLDER_NAME ] '''''' PATH_PADDING = '''''' header_cache = { } def header_to_column ( field ) : '''''' for name in ( C_PATH_NAME , C_FILE_NAME , C_URL , C_OBJECTS_FILE_NAME , C_OBJECTS_PATH_NAME , C_OBJECTS_URL ) : if field . startswith ( cpmeas . IMAGE + '' + name + '' ) : return field [ len ( cpmeas . IMAGE ) + : ] return field def is_path_name_feature ( feature ) : '''''' return feature . startswith ( C_PATH_NAME + '' ) def is_file_name_feature ( feature ) : '''''' return feature . startswith ( C_FILE_NAME + '' ) def is_url_name_feature ( feature ) : return feature . startswith ( C_URL + \"\" ) def is_objects_path_name_feature ( feature ) : '''''' return feature . startswith ( C_OBJECTS_PATH_NAME + \"\" ) def is_objects_file_name_feature ( feature ) : '''''' return feature . startswith ( C_OBJECTS_FILE_NAME + \"\" ) def is_objects_url_name_feature ( feature ) : return feature . startswith ( C_OBJECTS_URL + \"\" ) def get_image_name ( feature ) : '''''' if is_path_name_feature ( feature ) : return feature [ len ( C_PATH_NAME + '' ) : ] if is_file_name_feature ( feature ) : return feature [ len ( C_FILE_NAME + '' ) : ] if is_url_name_feature ( feature ) : return feature [ len ( C_URL + '' ) : ] raise ValueError ( '' % feature ) def get_objects_name ( feature ) : '''''' if is_objects_path_name_feature ( feature ) : return feature [ len ( C_OBJECTS_PATH_NAME + \"\" ) : ] if is_objects_file_name_feature ( feature ) : return feature [ len ( C_OBJECTS_FILE_NAME + \"\" ) : ] if is_objects_url_name_feature ( feature ) : return feature [ len ( C_OBJECTS_URL + \"\" ) : ] raise ValueError ( '' % feature ) def make_path_name_feature ( image ) : '''''' return C_PATH_NAME + '' + image def make_file_name_feature ( image ) : '''''' return C_FILE_NAME + '' + image def make_objects_path_name_feature ( objects_name ) : '''''' return C_OBJECTS_PATH_NAME + '' + objects_name def make_objects_file_name_feature ( objects_name ) : '''''' return C_OBJECTS_FILE_NAME + '' + objects_name class LoadData ( cpm . CPModule ) : module_name = \"\" category = '' variable_revision_number = def create_settings ( self ) : self . csv_directory = cps . DirectoryPath ( \"\" , allow_metadata = False , support_urls = True , doc = \"\"\"\"\"\" % globals ( ) ) def get_directory_fn ( ) : '''''' return self . csv_directory . get_absolute_path ( ) def set_directory_fn ( path ) : dir_choice , custom_path = self . csv_directory . get_parts_from_path ( path ) self . csv_directory . join_parts ( dir_choice , custom_path ) self . csv_file_name = cps . FilenameText ( \"\" , cps . NONE , doc = \"\"\"\"\"\" , get_directory_fn = get_directory_fn , set_directory_fn = set_directory_fn , browse_msg = \"\" , exts = [ ( \"\" , \"\" ) , ( \"\" , \"\" ) ] ) self . browse_csv_button = cps . DoSomething ( \"\" , \"\" , self . browse_csv ) self . wants_images = cps . Binary ( \"\" , True , doc = \"\"\"\"\"\" % globals ( ) ) self . rescale = cps . Binary ( \"\" , True , doc = \"\"\"\"\"\" % globals ( ) ) self . image_directory = cps . DirectoryPath ( \"\" , dir_choices = DIR_ALL , allow_metadata = False , doc = \"\"\"\"\"\" ) self . wants_image_groupings = cps . Binary ( \"\" , False , doc = \"\"\"\"\"\" % globals ( ) ) self . metadata_fields = cps . MultiChoice ( \"\" , None , doc = \"\"\"\"\"\" ) self . wants_rows = cps . Binary ( \"\" , False , doc = \"\"\"\"\"\" % globals ( ) ) self . row_range = cps . IntegerRange ( \"\" , ( , ) , , doc = \"\"\"\"\"\" ) def do_reload ( ) : global header_cache header_cache = { } try : self . open_csv ( ) except : pass self . clear_cache_button = cps . DoSomething ( \"\" , \"\" , do_reload , doc = \"\"\"\"\"\" ) def settings ( self ) : return [ self . csv_directory , self . csv_file_name , self . wants_images , self . image_directory , self . wants_rows , self . row_range , self . wants_image_groupings , self . metadata_fields , self . rescale ] def validate_module ( self , pipeline ) : csv_path = self . csv_path if self . csv_directory . dir_choice != cps . URL_FOLDER_NAME : if not os . path . isfile ( csv_path ) : raise cps . ValidationError ( \"\" % csv_path , self . csv_file_name ) try : self . open_csv ( ) except IOError , e : import errno if e . errno == errno . EWOULDBLOCK : raise cps . ValidationError ( \"\" % self . csv_path , self . csv_file_name ) else : raise cps . ValidationError ( \"\" % ( self . csv_path , e ) , self . csv_file_name ) try : self . get_header ( ) except Exception , e : raise cps . ValidationError ( \"\" % ( self . csv_path , e ) , self . csv_file_name ) def validate_module_warnings ( self , pipeline ) : '''''' from cellprofiler . modules . loadimages import LoadImages for module in pipeline . modules ( ) : if id ( module ) == id ( self ) : return if isinstance ( module , LoadData ) : raise cps . ValidationError ( \"\" \"\" \"\" \"\" \"\" , self . csv_file_name ) if isinstance ( module , LoadImages ) : raise cps . ValidationError ( \"\" \"\" \"\" \"\" \"\" \"\" \"\" , self . csv_file_name ) if self . wants_image_groupings . value and ( len ( self . metadata_fields . selections ) == ) : raise cps . ValidationError ( \"\" \"\" , self . metadata_fields ) def visible_settings ( self ) : result = [ self . csv_directory , self . csv_file_name , self . browse_csv_button ] if self . csv_directory . dir_choice == cps . URL_FOLDER_NAME : result += [ self . clear_cache_button ] self . csv_file_name . text = \"\" self . csv_file_name . set_browsable ( False ) else : self . csv_file_name . text = \"\" self . csv_file_name . set_browsable ( True ) result += [ self . wants_images ] if self . wants_images . value : result += [ self . rescale , self . image_directory , self . wants_image_groupings ] if self . wants_image_groupings . value : result += [ self . metadata_fields ] try : fields = [ field [ len ( \"\" ) : ] for field in self . get_header ( ) if field . startswith ( \"\" ) ] if self . has_synthetic_well_metadata ( ) : fields += [ cpmeas . FTR_WELL ] self . metadata_fields . choices = fields except : self . metadata_fields . choices = [ \"\" ] result += [ self . wants_rows ] if self . wants_rows . value : result += [ self . row_range ] return result def convert ( self ) : data = matplotlib . mlab . csv2rec ( self . csv_path ) src_dsc = data [ '' ] def uniquewaves ( seq ) : output = [ ] for x in seq : if x not in output : output . append ( x ) return output waves = uniquewaves ( src_dsc ) pathname = [ ] filename = [ ] wave_pnames = [ ] wave_fnames = [ ] for i in range ( len ( waves ) ) : mask = data [ '' ] == waves [ i ] pathname . append ( data [ mask ] [ '' ] ) filename . append ( data [ mask ] [ '' ] ) wave_pnames . append ( '' % ( waves [ i ] . strip ( '' ) ) ) wave_fnames . append ( '' % ( waves [ i ] . strip ( '' ) ) ) for i in range ( len ( waves ) ) : if len ( filename [ i ] ) != len ( filename [ ] ) : raise RuntimeError ( \"\" % ( wave_fnames [ i ] , len ( filename [ i ] ) , wave_fnames [ ] , len ( filename [ ] ) ) ) def metadatacols ( header ) : output = [ ] for h in header : if not h . startswith ( '' ) : if isinstance ( h , unicode ) : output . append ( h . encode ( \"\" ) ) else : output . append ( h ) return output def data_for_one_wave ( data ) : mask = data [ '' ] == waves [ ] data_onewave = data [ mask ] return data_onewave header = data . dtype . names metadata_names = metadatacols ( header ) data_onewave = data_for_one_wave ( data ) strdate = [ ] for date in data_onewave [ '' ] : strdate += [ str ( date ) ] metadata_names . remove ( '' ) metadata_names . remove ( '' ) data_onewave_nofilepaths = matplotlib . mlab . rec_keep_fields ( data_onewave , metadata_names ) metadata_names = [ '' + m for m in metadata_names ] data_onewave_nofilepaths . dtype . names = metadata_names final_data = data_onewave_nofilepaths final_data = matplotlib . mlab . rec_append_fields ( final_data , '' , strdate ) for i in range ( len ( waves ) ) : final_data = matplotlib . mlab . rec_append_fields ( final_data , wave_pnames [ i ] , pathname [ i ] ) final_data = matplotlib . mlab . rec_append_fields ( final_data , wave_fnames [ i ] , filename [ i ] ) return final_data @ property def csv_path ( self ) : '''''' if cpprefs . get_data_file ( ) is not None : return cpprefs . get_data_file ( ) if self . csv_directory . dir_choice == cps . URL_FOLDER_NAME : return self . csv_file_name . value path = self . csv_directory . get_absolute_path ( ) return os . path . join ( path , self . csv_file_name . value ) @ property def image_path ( self ) : return self . image_directory . get_absolute_path ( ) @ property def legacy_field_key ( self ) : '''''' return '' % self . module_num def get_cache_info ( self ) : '''''' global header_cache entry = header_cache . get ( self . csv_path , dict ( ctime = ) ) if cpprefs . is_url_path ( self . csv_path ) : if not header_cache . has_key ( self . csv_path ) : header_cache [ self . csv_path ] = entry return entry ctime = os . stat ( self . csv_path ) . st_ctime if ctime > entry [ \"\" ] : entry = header_cache [ self . csv_path ] = { } entry [ \"\" ] = ctime return entry def open_csv ( self , do_not_cache = False ) : '''''' global header_cache if cpprefs . is_url_path ( self . csv_path ) : if not header_cache . has_key ( self . csv_path ) : header_cache [ self . csv_path ] = { } entry = header_cache [ self . csv_path ] if entry . has_key ( \"\" ) : raise entry [ \"\" ] if entry . has_key ( \"\" ) : fd = StringIO ( entry [ \"\" ] ) else : if do_not_cache : raise RuntimeError ( '' ) import urllib2 try : url_fd = urllib2 . urlopen ( self . csv_path ) except Exception , e : entry [ \"\" ] = e raise e fd = StringIO ( ) while True : text = url_fd . read ( ) if len ( text ) == : break fd . write ( text ) fd . seek ( ) entry [ \"\" ] = fd . getvalue ( ) return fd else : return open ( self . csv_path , '' ) def browse_csv ( self ) : import wx from cellprofiler . gui import get_cp_icon try : fd = self . open_csv ( ) except : wx . MessageBox ( \"\" % self . csv_path ) return reader = csv . reader ( fd ) header = reader . next ( ) frame = wx . Frame ( wx . GetApp ( ) . frame , title = self . csv_path ) sizer = wx . BoxSizer ( wx . VERTICAL ) frame . SetSizer ( sizer ) list_ctl = wx . ListCtrl ( frame , style = wx . LC_REPORT ) sizer . Add ( list_ctl , , wx . EXPAND ) for i , field in enumerate ( header ) : list_ctl . InsertColumn ( i , field ) for line in reader : list_ctl . Append ( [ unicode ( s , '' ) if isinstance ( s , str ) else s for s in line [ : len ( header ) ] ] ) frame . SetMinSize ( ( , ) ) frame . SetIcon ( get_cp_icon ( ) ) frame . Fit ( ) frame . Show ( ) def get_header ( self , do_not_cache = False ) : '''''' entry = self . get_cache_info ( ) if entry . has_key ( \"\" ) : return entry [ \"\" ] fd = self . open_csv ( do_not_cache = do_not_cache ) reader = csv . reader ( fd ) header = reader . next ( ) fd . close ( ) if header [ ] . startswith ( '' ) : try : data = self . convert ( ) except Exception , e : raise RuntimeError ( \"\" % e ) header = data . dtype . names entry [ \"\" ] = [ header_to_column ( column ) for column in header ] return entry [ \"\" ] def get_image_names ( self , do_not_cache = False ) : header = self . get_header ( do_not_cache = do_not_cache ) image_names = set ( [ get_image_name ( field ) for field in header if is_file_name_feature ( field ) or is_url_name_feature ( field ) ] ) return list ( image_names ) def get_object_names ( self , do_not_cache = False ) : header = self . get_header ( do_not_cache = do_not_cache ) object_names = set ( [ get_objects_name ( field ) for field in header if is_objects_file_name_feature ( field ) or is_objects_url_name_feature ( field ) ] ) return list ( object_names ) def other_providers ( self , group ) : '''''' if group == '' and self . wants_images . value : try : return self . get_image_names ( do_not_cache = True ) except Exception , e : return [ ] elif group == '' and self . wants_images : try : return self . get_object_names ( do_not_cache = True ) except Exception , e : return [ ] return [ ] def is_image_from_file ( self , image_name ) : '''''' providers = self . other_providers ( '' ) return image_name in providers def is_load_module ( self ) : '''''' return True def prepare_run ( self , workspace ) : pipeline = workspace . pipeline m = workspace . measurements assert isinstance ( m , cpmeas . Measurements ) '''''' if pipeline . in_batch_mode ( ) : return True fd = self . open_csv ( ) reader = csv . reader ( fd ) header = [ header_to_column ( column ) for column in reader . next ( ) ] if header [ ] . startswith ( '' ) : reader = self . convert ( ) header = list ( reader . dtype . names ) if self . wants_rows . value : rows = [ ] for idx , row in enumerate ( reader ) : if idx + < self . row_range . min : continue if idx + > self . row_range . max : break if len ( row ) == : continue row = [ unicode ( s , '' ) if isinstance ( s , str ) else s for s in row ] if len ( row ) != len ( header ) : raise ValueError ( \"\" % ( i , len ( row ) , len ( header ) ) ) rows . append ( row ) else : rows = [ [ unicode ( s , '' ) if isinstance ( s , str ) else s for s in row ] for row in reader if len ( row ) > ] fd . close ( ) n_fields = len ( header ) for i , row in enumerate ( rows ) : if len ( row ) < n_fields : text = ( '' '' '' ) % ( i + , self . csv_file_name . value , '' . join ( row ) , len ( row ) , n_fields ) raise ValueError ( text ) elif len ( row ) > n_fields : del row [ n_fields : ] metadata_columns = { } object_columns = { } image_columns = { } well_row_column = well_column_column = well_well_column = None for i , column in enumerate ( header ) : if column . find ( \"\" ) == - : category = \"\" feature = column else : category , feature = column . split ( \"\" , ) if category in IMAGE_CATEGORIES : if not image_columns . has_key ( feature ) : image_columns [ feature ] = [ ] image_columns [ feature ] . append ( i ) elif category in OBJECTS_CATEGORIES : if not object_columns . has_key ( feature ) : object_columns [ feature ] = [ ] object_columns [ feature ] . append ( i ) else : metadata_columns [ column ] = i if category == cpmeas . C_METADATA : if feature . lower ( ) == cpmeas . FTR_WELL . lower ( ) : well_well_column = i elif cpmeas . is_well_row_token ( feature ) : well_row_column = i elif cpmeas . is_well_column_token ( feature ) : well_column_column = i if ( well_row_column is not None and well_column_column is not None and well_well_column is None ) : metadata_columns [ cpmeas . M_WELL ] = len ( header ) header . append ( cpmeas . M_WELL ) for row in rows : row . append ( row [ well_row_column ] + row [ well_column_column ] ) if self . wants_images : if self . image_directory . dir_choice == cps . NO_FOLDER_NAME : path_base = \"\" else : path_base = self . image_path for d , url_category , file_name_category , path_name_category in ( ( image_columns , C_URL , C_FILE_NAME , C_PATH_NAME ) , ( object_columns , C_OBJECTS_URL , C_OBJECTS_FILE_NAME , C_OBJECTS_PATH_NAME ) ) : for name in d . keys ( ) : url_column = file_name_column = path_name_column = None for k in d [ name ] : if header [ k ] . startswith ( url_category ) : url_column = k elif header [ k ] . startswith ( file_name_category ) : file_name_column = k elif header [ k ] . startswith ( path_name_category ) : path_name_column = k if url_column is None : if file_name_column is None : raise ValueError ( ( \"\" \"\" ) % ( file_name_category , name , path_name_category , name ) ) d [ name ] . append ( len ( header ) ) url_feature = \"\" . join ( ( url_category , name ) ) header . append ( url_feature ) for row in rows : if path_name_column is None : fullname = os . path . join ( path_base , row [ file_name_column ] ) else : row_path_name = os . path . join ( path_base , row [ path_name_column ] ) fullname = os . path . join ( row_path_name , row [ file_name_column ] ) row [ path_name_column ] = row_path_name url = pathname2url ( fullname ) row . append ( url ) if path_name_column is None : d [ name ] . append ( len ( header ) ) path_feature = \"\" . join ( ( path_name_category , name ) ) header . append ( path_feature ) for row in rows : row . append ( path_base ) elif path_name_column is None and file_name_column is None : path_feature = \"\" . join ( ( path_name_category , name ) ) path_name_column = len ( header ) header . append ( path_feature ) file_name_feature = \"\" . join ( ( file_name_category , name ) ) file_name_column = len ( header ) header . append ( file_name_feature ) for row in rows : url = row [ url_column ] idx = url . rfind ( \"\" ) if idx == - : idx = url . rfind ( \"\" ) if idx == - : row += [ \"\" , url ] else : row += [ url [ : ( idx + ) ] , url [ ( idx + ) : ] ] else : row += [ url [ : idx ] , url [ ( idx + ) : ] ] column_type = { } for column in self . get_measurement_columns ( pipeline ) : column_type [ column [ ] ] = column [ ] previous_column_types = dict ( [ ( c [ ] , c [ ] ) for c in pipeline . get_measurement_columns ( self ) if c [ ] == cpmeas . IMAGE ] ) columns = { } for index , feature in enumerate ( header ) : c = [ ] columns [ feature ] = c for row in rows : value = row [ index ] if column_type . has_key ( feature ) : datatype = column_type [ feature ] else : datatype = previous_column_types [ feature ] if datatype == cpmeas . COLTYPE_INTEGER : value = int ( value ) elif datatype == cpmeas . COLTYPE_FLOAT : value = float ( value ) c . append ( value ) if len ( metadata_columns ) > : image_numbers = m . match_metadata ( metadata_columns . keys ( ) , [ columns [ k ] for k in metadata_columns . keys ( ) ] ) image_numbers = np . array ( image_numbers , int ) . flatten ( ) max_image_number = np . max ( image_numbers ) new_columns = { } for key , values in columns . iteritems ( ) : new_values = [ None ] * max_image_number for image_number , value in zip ( image_numbers , values ) : new_values [ image_number - ] = value new_columns [ key ] = new_values columns = new_columns for feature , values in columns . iteritems ( ) : m . add_all_measurements ( cpmeas . IMAGE , feature , values ) if self . wants_image_groupings and len ( self . metadata_fields . selections ) > : keys = [ \"\" . join ( ( cpmeas . C_METADATA , k ) ) for k in self . metadata_fields . selections ] m . set_grouping_tags ( keys ) return True def prepare_to_create_batch ( self , workspace , fn_alter_path ) : '''''' if self . wants_images : m = workspace . measurements assert isinstance ( m , cpmeas . Measurements ) image_numbers = m . get_image_numbers ( ) all_image_features = m . get_feature_names ( cpmeas . IMAGE ) for url_category , file_category , path_category , names in ( ( C_URL , C_FILE_NAME , C_PATH_NAME , self . get_image_names ( ) ) , ( C_OBJECTS_URL , C_OBJECTS_FILE_NAME , C_OBJECTS_PATH_NAME , self . get_object_names ( ) ) ) : for name in names : url_feature = \"\" . join ( ( url_category , name ) ) path_feature = \"\" . join ( ( path_category , name ) ) ", "answer": "if path_feature not in all_image_features :"}, {"prompt": " import datetime from django . test import TestCase from panda import solr as solrjson ", "answer": "class TestSolrJSONEncoder ( TestCase ) :"}, {"prompt": " from south . utils import datetime_utils as datetime from south . db import db from south . v2 import SchemaMigration from django . db import models class Migration ( SchemaMigration ) : def forwards ( self , orm ) : db . add_column ( u'' , '' , self . gf ( '' ) ( default = ) , keep_default = False ) db . add_column ( u'' , '' , self . gf ( '' ) ( default = ) , keep_default = False ) def backwards ( self , orm ) : db . delete_column ( u'' , '' ) db . delete_column ( u'' , '' ) models = { u'' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : u\"\" } ) , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : u\"\" , '' : u\"\" , '' : '' } ) } , u'' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : \"\" , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : \"\" , '' : u\"\" } ) , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , u'' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : \"\" , '' : u\"\" } ) , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , u'' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : \"\" , '' : u\"\" } ) , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : u\"\" } ) } , u'' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , u'' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : \"\" , '' : u\"\" } ) , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : \"\" , '' : u\"\" } ) } , u'' : { '' : { '' : '' } , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : u\"\" , '' : '' , '' : '' } ) } , u'' : { '' : { '' : \"\" , '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : u\"\" } ) , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , u'' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : u\"\" , '' : '' , '' : '' } ) , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : u\"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) } , u'' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) } , u'' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : \"\" , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : u\"\" } ) } , u'' : { '' : { '' : \"\" , '' : \"\" , '' : '' , '' : \"\" } , '' : ( '' , [ ] , { '' : '' } ) , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , u'' : { '' : { '' : '' } , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { } ) , '' : ( '' , [ ] , { } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : u\"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , u'' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : '' , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : '' , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : '' , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : '' , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : '' , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : '' , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , u'' : { '' : { '' : '' } , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : '' } ) } , u'' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : u\"\" , '' : u\"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) } , u'' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , u'' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : u\"\" } ) , ", "answer": "'' : ( '' , [ ] , { '' : '' } ) ,"}, {"prompt": " from will . plugin import WillPlugin from will . decorators import respond_to , require_settings from will import settings import datetime import pygerduty class PagerDutyPlugin ( WillPlugin ) : @ staticmethod def _associate_pd_user ( email_address , pager ) : try : user = next ( pager . users . list ( query = email_address , limit = ) ) return user except StopIteration : return None def _get_user_email_from_mention_name ( self , mention_name ) : try : u = self . get_user_by_nick ( mention_name [ : ] ) email_address = self . get_hipchat_user ( u [ '' ] ) [ '' ] return email_address except TypeError : return None def _update_incident ( self , message , incidents , action , assign_to_email = None ) : pager = pygerduty . PagerDuty ( settings . PAGERDUTY_SUBDOMAIN , settings . PAGERDUTY_API_KEY ) email_address = self . get_hipchat_user ( message . sender [ '' ] ) [ '' ] user = self . _associate_pd_user ( email_address , pager ) if user is None : self . reply ( message , \"\" ) return if incidents : for i in incidents : try : incident = pager . incidents . show ( entity_id = i ) except pygerduty . BadRequest as e : if e . code == : self . reply ( message , \"\" % i , color = \"\" ) continue if action == '' : try : incident . acknowledge ( requester_id = user . id ) except pygerduty . BadRequest as e : if e . code == : self . reply ( message , \"\" % i , color = \"\" ) continue elif action == '' : try : incident . resolve ( requester_id = user . id ) except pygerduty . BadRequest as e : if e . code == : self . reply ( message , \"\" % i , color = \"\" ) continue elif action == '' : try : if assign_to_email is not None : assign_to = self . _associate_pd_user ( assign_to_email , pager ) if assign_to is None : ", "answer": "self . reply ( message , \"\" % assign_to_email )"}, {"prompt": " \"\"\"\"\"\" __all__ = [ '' , '' , '' , '' , '' , '' , '' ] from zope . interface import Interface from twisted . python . deprecate import deprecatedModuleAttribute from twisted . python . versions import Version from twisted . words . protocols . jabber . ijabber import IXMPPHandler from twisted . words . protocols . jabber . ijabber import IXMPPHandlerCollection deprecatedModuleAttribute ( Version ( \"\" , , , ) , \"\" , __name__ , \"\" ) deprecatedModuleAttribute ( Version ( \"\" , , , ) , \"\" \"\" , __name__ , \"\" ) class IDisco ( Interface ) : \"\"\"\"\"\" def getDiscoInfo ( requestor , target , nodeIdentifier = '' ) : \"\"\"\"\"\" def getDiscoItems ( requestor , target , nodeIdentifier = '' ) : \"\"\"\"\"\" class IPubSubClient ( Interface ) : def itemsReceived ( event ) : \"\"\"\"\"\" def deleteReceived ( event ) : \"\"\"\"\"\" def purgeReceived ( event ) : \"\"\"\"\"\" def createNode ( service , nodeIdentifier = None ) : \"\"\"\"\"\" def deleteNode ( service , nodeIdentifier ) : \"\"\"\"\"\" def subscribe ( service , nodeIdentifier , subscriber ) : \"\"\"\"\"\" def unsubscribe ( service , nodeIdentifier , subscriber ) : \"\"\"\"\"\" def publish ( service , nodeIdentifier , items = [ ] ) : \"\"\"\"\"\" class IPubSubService ( Interface ) : \"\"\"\"\"\" def notifyPublish ( service , nodeIdentifier , notifications ) : \"\"\"\"\"\" def notifyDelete ( service , nodeIdentifier , subscribers , redirectURI = None ) : \"\"\"\"\"\" def publish ( requestor , service , nodeIdentifier , items ) : \"\"\"\"\"\" def subscribe ( requestor , service , nodeIdentifier , subscriber ) : \"\"\"\"\"\" def unsubscribe ( requestor , service , nodeIdentifier , subscriber ) : \"\"\"\"\"\" def subscriptions ( requestor , service ) : \"\"\"\"\"\" def affiliations ( requestor , service ) : \"\"\"\"\"\" def create ( requestor , service , nodeIdentifier ) : \"\"\"\"\"\" def getConfigurationOptions ( ) : \"\"\"\"\"\" def getDefaultConfiguration ( requestor , service , nodeType ) : \"\"\"\"\"\" def getConfiguration ( requestor , service , nodeIdentifier ) : \"\"\"\"\"\" def setConfiguration ( requestor , service , nodeIdentifier , options ) : \"\"\"\"\"\" def items ( requestor , service , nodeIdentifier , maxItems , itemIdentifiers ) : \"\"\"\"\"\" def retract ( requestor , service , nodeIdentifier , itemIdentifiers ) : \"\"\"\"\"\" def purge ( requestor , service , nodeIdentifier ) : \"\"\"\"\"\" def delete ( requestor , service , nodeIdentifier ) : \"\"\"\"\"\" class IPubSubResource ( Interface ) : def locateResource ( request ) : \"\"\"\"\"\" def getInfo ( requestor , service , nodeIdentifier ) : \"\"\"\"\"\" def getNodes ( requestor , service , nodeIdentifier ) : \"\"\"\"\"\" def getConfigurationOptions ( ) : \"\"\"\"\"\" def publish ( request ) : \"\"\"\"\"\" def subscribe ( request ) : \"\"\"\"\"\" def unsubscribe ( request ) : \"\"\"\"\"\" def subscriptions ( request ) : \"\"\"\"\"\" def affiliations ( request ) : \"\"\"\"\"\" def create ( request ) : \"\"\"\"\"\" def default ( request ) : \"\"\"\"\"\" def configureGet ( request ) : \"\"\"\"\"\" def configureSet ( request ) : \"\"\"\"\"\" def items ( request ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " from __future__ import unicode_literals from datetime import datetime import uuid from moto . core . utils import unix_time from . . exceptions import SWFWorkflowExecutionClosedError from . timeout import Timeout class DecisionTask ( object ) : def __init__ ( self , workflow_execution , scheduled_event_id ) : self . workflow_execution = workflow_execution self . workflow_type = workflow_execution . workflow_type self . task_token = str ( uuid . uuid4 ( ) ) self . scheduled_event_id = scheduled_event_id self . previous_started_event_id = self . started_event_id = None self . started_timestamp = None self . start_to_close_timeout = self . workflow_execution . task_start_to_close_timeout self . state = \"\" self . scheduled_at = datetime . utcnow ( ) self . timeout_type = None @ property def started ( self ) : return self . state == \"\" def _check_workflow_execution_open ( self ) : if not self . workflow_execution . open : raise SWFWorkflowExecutionClosedError ( ) def to_full_dict ( self , reverse_order = False ) : events = self . workflow_execution . events ( reverse_order = reverse_order ) hsh = { \"\" : [ evt . to_dict ( ) for evt in events ] , \"\" : self . task_token , \"\" : self . previous_started_event_id , \"\" : self . workflow_execution . to_short_dict ( ) , \"\" : self . workflow_type . to_short_dict ( ) , } if self . started_event_id : hsh [ \"\" ] = self . started_event_id return hsh def start ( self , started_event_id ) : self . state = \"\" self . started_timestamp = unix_time ( ) self . started_event_id = started_event_id def complete ( self ) : self . _check_workflow_execution_open ( ) ", "answer": "self . state = \"\""}, {"prompt": " from nose . tools import * from exercise48 . parser import * def test_parse_sentence ( ) : ", "answer": "sentence = parse_sentence ( [ ( '' , '' ) , ( '' , '' ) ] )"}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import import datetime import re import pytz from pytz import UTC from . util import if_none def ensure_date ( date ) : \"\"\"\"\"\" if isinstance ( date , datetime . datetime ) : if date . tzinfo is None : raise TypeError ( \"\" ) else : return date . date ( ) if isinstance ( date , datetime . date ) : return date if isinstance ( date , int ) and <= date <= : return datetime . date ( date // , ( date % ) // , date % ) if date == \"\" : return datetime . date . today ( ) if date == \"\" : return datetime . datetime . utcnow ( ) . date ( ) def from_ymd ( y , m , d ) : try : return datetime . date ( y , m , d ) except ValueError : raise TypeError ( \"\" . format ( date ) ) if isinstance ( date , str ) : match = re . match ( r\"\" , date ) if match is None : match = re . match ( r\"\" , date ) if match is not None : return from_ymd ( * [ int ( g ) for g in match . groups ( ) ] ) raise TypeError ( \"\" . format ( date ) ) def ensure_time ( time ) : \"\"\"\"\"\" if isinstance ( time , datetime . datetime ) : return date . time ( ) if isinstance ( time , datetime . time ) : return time if time == \"\" : return datetime . datetime . now ( ) . time ( ) if time == \"\" : return datetime . datetime . utcnow ( ) . time ( ) def from_parts ( h , m , s = ) : try : return datetime . time ( h , m , s ) except ValueError : raise TypeError ( \"\" . format ( time ) ) if isinstance ( time , str ) : match = re . match ( r\"\" , time ) if match is None : match = re . match ( r\"\" , time ) if match is not None : return from_parts ( * [ int ( g ) for g in match . groups ( ) ] ) raise TypeError ( \"\" . format ( time ) ) _DATETIME_REGEXES = [ re . compile ( r ) for r in ( r\"\" , r\"\" , ) ] def ensure_datetime ( dt ) : \"\"\"\"\"\" if isinstance ( dt , datetime . datetime ) : return dt try : item = dt . item ( ) except : pass else : if isinstance ( item , datetime . datetime ) : return item . replace ( tzinfo = UTC ) if dt == \"\" : return datetime . datetime . utcnow ( ) . replace ( tzinfo = UTC ) def from_parts ( ye , mo , da , ho = , mi = , se = ) : try : return datetime . datetime ( ye , mo , da , ho , mi , se , tzinfo = UTC ) except ValueError : raise TypeError ( \"\" . format ( dt ) ) if isinstance ( dt , str ) : for regex in _DATETIME_REGEXES : match = regex . match ( dt ) if match is not None : ye = int ( match . group ( \"\" ) ) mo = int ( match . group ( \"\" ) ) da = int ( match . group ( \"\" ) ) ho = int ( if_none ( match . group ( \"\" ) , ) ) mi = int ( if_none ( match . group ( \"\" ) , ) ) se = int ( if_none ( match . group ( \"\" ) , ) ) return from_parts ( ye , mo , da , ho , mi , se ) raise TypeError ( \"\" . format ( dt ) ) def ensure_timedelta ( delta ) : \"\"\"\"\"\" if isinstance ( delta , datetime . timedelta ) : return delta if isinstance ( delta , str ) : match = re . match ( r\"\" , delta ) if match is not None : num , unit = match . groups ( ) if unit == \"\" : ", "answer": "return datetime . timedelta ( int ( num ) , )"}, {"prompt": " import os import time import hashlib import collections import sublime_plugin try : from . common import msg , shared as G , utils from . sublime_utils import get_buf , get_text assert G and G and utils and msg and get_buf and get_text except ImportError : from common import msg , shared as G , utils from sublime_utils import get_buf , get_text def if_connected ( f ) : def wrapped ( * args ) : if not G . AGENT or not G . AGENT . is_ready ( ) : return args = list ( args ) args . append ( G . AGENT ) return f ( * args ) ", "answer": "return wrapped"}, {"prompt": " from collections import namedtuple import numpy as np class VolumeBreakpoint ( namedtuple ( '' , [ '' , '' , '' ] ) ) : def __new__ ( cls , time , volume , fade_type = \"\" ) : return super ( VolumeBreakpoint , cls ) . __new__ ( cls , time , volume , fade_type ) class VolumeBreakpoints ( object ) : def __init__ ( self , volume_breakpoints ) : self . breakpoints = volume_breakpoints def add_breakpoint ( self , bp ) : self . breakpoints . append ( bp ) def add_breakpoints ( self , bps ) : self . breakpoints . extend ( bps ) def to_array ( self , samplerate ) : sorted_bps = sorted ( self . breakpoints , key = lambda x : x . time ) arr = np . ones ( int ( sorted_bps [ - ] [ ] * samplerate ) ) for i , bp in enumerate ( sorted_bps [ : - ] ) : t = int ( bp . time * samplerate ) v = bp . volume next_t = int ( sorted_bps [ i + ] . time * samplerate ) next_v = sorted_bps [ i + ] . volume if bp . fade_type == \"\" and v != next_v : if v < next_v : arr [ t : next_t ] = np . logspace ( , , num = next_t - t , base = ) * ( next_v - v ) / + v else : arr [ t : next_t ] = np . logspace ( , , num = next_t - t , base = ) * ( v - next_v ) / + next_v ", "answer": "else :"}, {"prompt": " from django . conf import urls ", "answer": "import openstack_dashboard . urls"}, {"prompt": " import logging import requests from pyembed . core import parse from pyembed . core . error import PyEmbedError try : from urlparse import parse_qsl , urljoin , urlsplit , urlunsplit from urllib import urlencode except ImportError : from urllib . parse import parse_qsl , urljoin , urlsplit , urlunsplit , urlencode class PyEmbedConsumerError ( PyEmbedError ) : \"\"\"\"\"\" def get_first_oembed_response ( oembed_urls , max_width = None , max_height = None ) : \"\"\"\"\"\" for oembed_url in oembed_urls : try : return get_oembed_response ( oembed_url , max_width = max_width , max_height = max_height ) except PyEmbedError : logging . warn ( '' % oembed_url , exc_info = True ) raise PyEmbedConsumerError ( '' % oembed_urls ) def get_oembed_response ( oembed_url , max_width = None , max_height = None ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " from kaa import bot from urllib import quote import json import requests LINE_LIMIT = @ bot . command ( '' ) @ bot . command def urbandict ( context ) : url = '' url = url . format ( quote ( context . args ) ) r = requests . get ( url ) data = json . loads ( r . content ) if not data [ '' ] [ ] . get ( '' ) : return '' data = data [ '' ] [ ] [ '' ] . splitlines ( ) data = '' . join ( data ) ", "answer": "return data [ : LINE_LIMIT ] "}, {"prompt": " import datetime from south . db import db from south . v2 import SchemaMigration from django . db import models from django . db import connection class Migration ( SchemaMigration ) : def forwards ( self , orm ) : db . start_transaction ( ) cursor = connection . cursor ( ) cursor . execute ( '' ) qs = cursor . fetchall ( ) db . create_table ( '' , ( ( '' , self . gf ( '' ) ( primary_key = True ) ) , ( '' , self . gf ( '' ) ( to = orm [ '' ] , null = True ) ) , ( '' , self . gf ( '' ) ( max_length = ) ) , ) ) db . send_create_signal ( '' , [ '' ] ) db . create_table ( '' , ( ( '' , self . gf ( '' ) ( primary_key = True ) ) , ( '' , self . gf ( '' ) ( to = orm [ '' ] , null = True ) ) , ( '' , self . gf ( '' ) ( to = orm [ '' ] ) ) , ( '' , self . gf ( '' ) ( ) ) , ) ) db . send_create_signal ( '' , [ '' ] ) db . create_table ( '' , ( ( '' , self . gf ( '' ) ( primary_key = True ) ) , ( '' , self . gf ( '' ) ( to = orm [ '' ] , null = True ) ) , ( '' , self . gf ( '' ) ( ) ) , ) ) db . send_create_signal ( '' , [ '' ] ) db . delete_column ( '' , '' ) from django . contrib . contenttypes . management import update_contenttypes from django . db . models import get_app , get_models update_contenttypes ( get_app ( '' ) , get_models ( ) ) if not db . dry_run : db . commit_transaction ( ) db . start_transaction ( ) ct = orm [ '' ] . objects . get ( app_label = \"\" , model = \"\" ) for form in qs : rep = orm . FormsFormActionMessage ( message = form [ ] , form_id = form [ ] ) rep . save ( ) orm . FormsFormAction . objects . create ( form_id = form [ ] , object_id = rep . pk , content_type = ct ) db . commit_transaction ( ) def backwards ( self , orm ) : db . delete_table ( '' ) db . delete_table ( '' ) db . delete_table ( '' ) db . add_column ( '' , '' , self . gf ( '' ) ( default = '' ) , keep_default = False ) models = { '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) } , '' : { '' : { '' : \"\" , '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) } , '' : { '' : { '' : \"\" , '' : \"\" , '' : '' , '' : \"\" } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : '' , '' : \"\" } , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : \"\" , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : '' , '' : \"\" } , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" } ) } , '' : { '' : { '' : '' , '' : \"\" } , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { } ) } , '' : { '' : { '' : '' , '' : \"\" } , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , ", "answer": "'' : ( '' , [ ] , { } )"}, {"prompt": " from calvin . actor . actor import Actor , ActionResult , condition class Environmental ( Actor ) : \"\"\"\"\"\" def init ( self ) : self . setup ( ) def setup ( self ) : ", "answer": "self . use ( \"\" , shorthand = \"\" )"}, {"prompt": " from __future__ import absolute_import , division , print_function , unicode_literals import logging import sys import unittest sys . dont_write_bytecode = True from benchexec . util import ProcessExitCode from benchexec . model import Run from benchexec . result import * from benchexec . tools . template import BaseTool normal_result = ProcessExitCode ( raw = , value = , signal = None ) class TestResult ( unittest . TestCase ) : @ classmethod def setUpClass ( cls ) : cls . longMessage = True logging . disable ( logging . CRITICAL ) def create_run ( self , info_result = RESULT_UNKNOWN ) : runSet = lambda : None runSet . log_folder = '' runSet . options = [ ] runSet . real_name = None runSet . propertyfile = None runSet . benchmark = lambda : None runSet . benchmark . base_dir = '' runSet . benchmark . benchmark_file = '' runSet . benchmark . columns = [ ] runSet . benchmark . name = '' runSet . benchmark . instance = '' runSet . benchmark . rlimits = { } runSet . benchmark . tool = BaseTool ( ) def determine_result ( self , returncode , returnsignal , output , isTimeout = False ) : return info_result runSet . benchmark . tool . determine_result = determine_result return Run ( sourcefiles = [ '' ] , fileOptions = [ ] , runSet = runSet ) def test_simple ( self ) : run = self . create_run ( info_result = RESULT_UNKNOWN ) self . assertEqual ( RESULT_UNKNOWN , run . _analyse_result ( normal_result , '' , False , None ) ) run = self . create_run ( info_result = RESULT_TRUE_PROP ) self . assertEqual ( RESULT_TRUE_PROP , run . _analyse_result ( normal_result , '' , False , None ) ) run = self . create_run ( info_result = RESULT_FALSE_REACH ) self . assertEqual ( RESULT_FALSE_REACH , run . _analyse_result ( normal_result , '' , False , None ) ) def test_timeout ( self ) : run = self . create_run ( info_result = RESULT_UNKNOWN ) self . assertEqual ( '' , run . _analyse_result ( normal_result , '' , True , None ) ) run = self . create_run ( info_result = RESULT_TRUE_PROP ) self . assertEqual ( '' , run . _analyse_result ( normal_result , '' , True , None ) ) run = self . create_run ( info_result = RESULT_FALSE_REACH ) self . assertEqual ( '' , run . _analyse_result ( normal_result , '' , True , None ) ) run = self . create_run ( info_result = '' ) self . assertEqual ( '' , run . _analyse_result ( normal_result , '' , True , None ) ) def test_out_of_memory ( self ) : run = self . create_run ( info_result = RESULT_UNKNOWN ) self . assertEqual ( '' , run . _analyse_result ( normal_result , '' , False , '' ) ) run = self . create_run ( info_result = RESULT_TRUE_PROP ) self . assertEqual ( '' , run . _analyse_result ( normal_result , '' , False , '' ) ) run = self . create_run ( info_result = RESULT_FALSE_REACH ) self . assertEqual ( '' , run . _analyse_result ( normal_result , '' , False , '' ) ) run = self . create_run ( info_result = '' ) self . assertEqual ( '' , run . _analyse_result ( normal_result , '' , False , '' ) ) def test_timeout_and_out_of_memory ( self ) : run = self . create_run ( info_result = RESULT_UNKNOWN ) self . assertEqual ( '' , run . _analyse_result ( normal_result , '' , True , '' ) ) run = self . create_run ( info_result = RESULT_TRUE_PROP ) self . assertEqual ( '' , run . _analyse_result ( normal_result , '' , True , '' ) ) run = self . create_run ( info_result = RESULT_FALSE_REACH ) self . assertEqual ( '' , run . _analyse_result ( normal_result , '' , True , '' ) ) run = self . create_run ( info_result = '' ) self . assertEqual ( '' , run . _analyse_result ( normal_result , '' , False , '' ) ) def test_returnsignal ( self ) : def signal ( sig ) : \"\"\"\"\"\" return ProcessExitCode ( raw = sig , value = None , signal = sig ) run = self . create_run ( info_result = RESULT_UNKNOWN ) self . assertEqual ( '' , run . _analyse_result ( signal ( ) , '' , True , None ) ) run = self . create_run ( info_result = RESULT_UNKNOWN ) self . assertEqual ( '' , run . _analyse_result ( signal ( ) , '' , False , '' ) ) run = self . create_run ( info_result = RESULT_TRUE_PROP ) self . assertEqual ( RESULT_TRUE_PROP , run . _analyse_result ( signal ( ) , '' , False , None ) ) run = self . create_run ( info_result = RESULT_FALSE_REACH ) self . assertEqual ( RESULT_FALSE_REACH , run . _analyse_result ( signal ( ) , '' , False , None ) ) run = self . create_run ( info_result = '' ) self . assertEqual ( '' , run . _analyse_result ( signal ( ) , '' , False , None ) ) ", "answer": "run = self . create_run ( info_result = RESULT_UNKNOWN )"}, {"prompt": " r\"\"\"\"\"\" __version__ = '' __all__ = [ '' , '' , '' , '' , '' , '' , '' , '' , ] __author__ = '' from decimal import Decimal from decoder import JSONDecoder , JSONDecodeError from encoder import JSONEncoder def _import_OrderedDict ( ) : import collections try : return collections . OrderedDict except AttributeError : import ordered_dict return ordered_dict . OrderedDict OrderedDict = _import_OrderedDict ( ) def _import_c_make_encoder ( ) : try : raise ImportError from simplejson . _speedups import make_encoder return make_encoder except ImportError : return None _default_encoder = JSONEncoder ( skipkeys = False , ensure_ascii = True , check_circular = True , allow_nan = True , indent = None , separators = None , encoding = '' , default = None , use_decimal = False , ) def dump ( obj , fp , skipkeys = False , ensure_ascii = True , check_circular = True , allow_nan = True , cls = None , indent = None , separators = None , encoding = '' , default = None , use_decimal = False , ** kw ) : \"\"\"\"\"\" if ( not skipkeys and ensure_ascii and check_circular and allow_nan and cls is None and indent is None and separators is None and encoding == '' and default is None and not use_decimal and not kw ) : iterable = _default_encoder . iterencode ( obj ) else : if cls is None : cls = JSONEncoder iterable = cls ( skipkeys = skipkeys , ensure_ascii = ensure_ascii , check_circular = check_circular , allow_nan = allow_nan , indent = indent , separators = separators , encoding = encoding , default = default , use_decimal = use_decimal , ** kw ) . iterencode ( obj ) for chunk in iterable : fp . write ( chunk ) def dumps ( obj , skipkeys = False , ensure_ascii = True , check_circular = True , allow_nan = True , cls = None , indent = None , separators = None , encoding = '' , default = None , use_decimal = False , ** kw ) : \"\"\"\"\"\" if ( not skipkeys and ensure_ascii and check_circular and allow_nan and cls is None and indent is None and separators is None and encoding == '' and default is None and not use_decimal and not kw ) : return _default_encoder . encode ( obj ) if cls is None : cls = JSONEncoder return cls ( skipkeys = skipkeys , ensure_ascii = ensure_ascii , check_circular = check_circular , allow_nan = allow_nan , indent = indent , separators = separators , encoding = encoding , default = default , use_decimal = use_decimal , ** kw ) . encode ( obj ) _default_decoder = JSONDecoder ( encoding = None , object_hook = None , object_pairs_hook = None ) def load ( fp , encoding = None , cls = None , object_hook = None , parse_float = None , parse_int = None , parse_constant = None , object_pairs_hook = None , use_decimal = False , ** kw ) : \"\"\"\"\"\" return loads ( fp . read ( ) , encoding = encoding , cls = cls , object_hook = object_hook , parse_float = parse_float , parse_int = parse_int , parse_constant = parse_constant , object_pairs_hook = object_pairs_hook , use_decimal = use_decimal , ** kw ) def loads ( s , encoding = None , cls = None , object_hook = None , parse_float = None , parse_int = None , parse_constant = None , object_pairs_hook = None , use_decimal = False , ** kw ) : \"\"\"\"\"\" if ( cls is None and encoding is None and object_hook is None and parse_int is None and parse_float is None and parse_constant is None and object_pairs_hook is None and not use_decimal and not kw ) : return _default_decoder . decode ( s ) if cls is None : cls = JSONDecoder if object_hook is not None : kw [ '' ] = object_hook if object_pairs_hook is not None : kw [ '' ] = object_pairs_hook if parse_float is not None : kw [ '' ] = parse_float if parse_int is not None : kw [ '' ] = parse_int if parse_constant is not None : kw [ '' ] = parse_constant if use_decimal : if parse_float is not None : raise TypeError ( \"\" ) kw [ '' ] = Decimal return cls ( encoding = encoding , ** kw ) . decode ( s ) def _toggle_speedups ( enabled ) : import decoder as dec import encoder as enc import scanner as scan c_make_encoder = _import_c_make_encoder ( ) if enabled : dec . scanstring = dec . c_scanstring or dec . py_scanstring enc . c_make_encoder = c_make_encoder enc . encode_basestring_ascii = ( enc . c_encode_basestring_ascii or enc . py_encode_basestring_ascii ) ", "answer": "scan . make_scanner = scan . c_make_scanner or scan . py_make_scanner"}, {"prompt": " from collections import Counter from hippybot . decorators import botcmd class Plugin ( object ) : \"\"\"\"\"\" global_commands = [ '' , '' ] command_aliases = { '' : '' } counts = Counter ( ) @ botcmd def wave ( self , mess , args ) : \"\"\"\"\"\" channel = unicode ( mess . getFrom ( ) ) . split ( '' ) [ ] self . bot . log . info ( \"\" % self . counts [ channel ] ) ", "answer": "if not self . bot . from_bot ( mess ) :"}, {"prompt": " \"\"\"\"\"\" from social . backends . legacy import LegacyAuth ", "answer": "class EmailAuth ( LegacyAuth ) :"}, {"prompt": " \"\"\"\"\"\" from swift import gettext_ as _ from swift . common import constraints import logging import time import socket import eventlet from eventlet . green . httplib import CONTINUE , HTTPConnection , HTTPMessage , HTTPResponse , HTTPSConnection , _UNKNOWN from six . moves . urllib . parse import quote import six httplib = eventlet . import_patched ( '' ) httplib . _MAXHEADERS = constraints . MAX_HEADER_COUNT class BufferedHTTPResponse ( HTTPResponse ) : \"\"\"\"\"\" def __init__ ( self , sock , debuglevel = , strict = , method = None ) : self . sock = sock self . _real_socket = sock . fd . _sock self . fp = sock . makefile ( '' ) self . debuglevel = debuglevel self . strict = strict self . _method = method self . msg = None self . version = _UNKNOWN self . status = _UNKNOWN self . reason = _UNKNOWN self . chunked = _UNKNOWN self . chunk_left = _UNKNOWN self . length = _UNKNOWN self . will_close = _UNKNOWN self . _readline_buffer = '' def expect_response ( self ) : if self . fp : self . fp . close ( ) self . fp = None self . fp = self . sock . makefile ( '' , ) version , status , reason = self . _read_status ( ) if status != CONTINUE : self . _read_status = lambda : ( version , status , reason ) self . begin ( ) else : self . status = status self . reason = reason . strip ( ) self . version = self . msg = HTTPMessage ( self . fp , ) self . msg . fp = None def read ( self , amt = None ) : if not self . _readline_buffer : return HTTPResponse . read ( self , amt ) if amt is None : buffered = self . _readline_buffer self . _readline_buffer = '' return buffered + HTTPResponse . read ( self , amt ) elif amt <= len ( self . _readline_buffer ) : res = self . _readline_buffer [ : amt ] self . _readline_buffer = self . _readline_buffer [ amt : ] return res else : smaller_amt = amt - len ( self . _readline_buffer ) buf = self . _readline_buffer self . _readline_buffer = '' return buf + HTTPResponse . read ( self , smaller_amt ) def readline ( self , size = ) : while ( '' not in self . _readline_buffer and len ( self . _readline_buffer ) < size ) : read_size = size - len ( self . _readline_buffer ) chunk = HTTPResponse . read ( self , read_size ) if not chunk : break self . _readline_buffer += chunk line , newline , rest = self . _readline_buffer . partition ( '' ) self . _readline_buffer = rest return line + newline def nuke_from_orbit ( self ) : \"\"\"\"\"\" if self . _real_socket : self . _real_socket . close ( ) self . _real_socket = None self . close ( ) def close ( self ) : HTTPResponse . close ( self ) self . sock = None self . _real_socket = None class BufferedHTTPConnection ( HTTPConnection ) : \"\"\"\"\"\" response_class = BufferedHTTPResponse def connect ( self ) : self . _connected_time = time . time ( ) ret = HTTPConnection . connect ( self ) self . sock . setsockopt ( socket . IPPROTO_TCP , socket . TCP_NODELAY , ) return ret def putrequest ( self , method , url , skip_host = , skip_accept_encoding = ) : self . _method = method self . _path = url return HTTPConnection . putrequest ( self , method , url , skip_host , skip_accept_encoding ) def getexpect ( self ) : response = BufferedHTTPResponse ( self . sock , strict = self . strict , method = self . _method ) response . expect_response ( ) return response def getresponse ( self ) : response = HTTPConnection . getresponse ( self ) logging . debug ( \"\" \"\" , { '' : time . time ( ) - self . _connected_time , '' : self . _method , '' : self . host , '' : self . port , '' : self . _path } ) return response def http_connect ( ipaddr , port , device , partition , method , path , headers = None , query_string = None , ssl = False ) : \"\"\"\"\"\" if isinstance ( path , six . text_type ) : try : path = path . encode ( \"\" ) except UnicodeError as e : logging . exception ( _ ( '' ) , str ( e ) ) if isinstance ( device , six . text_type ) : try : device = device . encode ( \"\" ) except UnicodeError as e : logging . exception ( _ ( '' ) , str ( e ) ) path = quote ( '' + device + '' + str ( partition ) + path ) return http_connect_raw ( ipaddr , port , method , path , headers , query_string , ssl ) ", "answer": "def http_connect_raw ( ipaddr , port , method , path , headers = None ,"}, {"prompt": " from __future__ import unicode_literals from django import forms from django . db import transaction from django . forms . models import ModelChoiceIterator , inlineformset_factory from django . utils . translation import pgettext_lazy from ... product . models import ( AttributeChoiceValue , Product , ProductAttribute , ProductImage , ProductVariant , Stock , VariantImage ) from . widgets import ImagePreviewWidget PRODUCT_CLASSES = { Product : '' } class ProductClassForm ( forms . Form ) : product_cls = forms . ChoiceField ( label = pgettext_lazy ( '' , '' ) , widget = forms . RadioSelect , choices = [ ( cls . __name__ , presentation ) for cls , presentation in PRODUCT_CLASSES . items ( ) ] ) def __init__ ( self , * args , ** kwargs ) : super ( ProductClassForm , self ) . __init__ ( * args , ** kwargs ) product_class = next ( iter ( ( PRODUCT_CLASSES ) ) ) self . fields [ '' ] . initial = product_class . __name__ class StockForm ( forms . ModelForm ) : class Meta : model = Stock exclude = [ '' ] def __init__ ( self , * args , ** kwargs ) : product = kwargs . pop ( '' ) super ( StockForm , self ) . __init__ ( * args , ** kwargs ) self . fields [ '' ] = forms . ModelChoiceField ( queryset = product . variants ) class ProductForm ( forms . ModelForm ) : class Meta : model = Product exclude = [ ] def __init__ ( self , * args , ** kwargs ) : super ( ProductForm , self ) . __init__ ( * args , ** kwargs ) field = self . fields [ '' ] field . widget . attrs [ '' ] = pgettext_lazy ( '' , '' ) field = self . fields [ '' ] field . widget . attrs [ '' ] = pgettext_lazy ( '' , '' ) field = self . fields [ '' ] field . widget . attrs [ '' ] = pgettext_lazy ( '' , '' ) ", "answer": "class ProductVariantForm ( forms . ModelForm ) :"}, {"prompt": " \"\"\"\"\"\" from . import sessions def request ( method , url , ** kwargs ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " from libmproxy . protocol . http import HTTPResponse from netlib . odict import ODictCaseless ", "answer": "\"\"\"\"\"\""}, {"prompt": " \"\"\"\"\"\" import functools from django . utils . decorators import available_attrs from django . utils . translation import ugettext_lazy as _ def _current_component ( view_func , dashboard = None , panel = None ) : \"\"\"\"\"\" @ functools . wraps ( view_func , assigned = available_attrs ( view_func ) ) def dec ( request , * args , ** kwargs ) : if dashboard : request . horizon [ '' ] = dashboard if panel : request . horizon [ '' ] = panel return view_func ( request , * args , ** kwargs ) return dec def require_auth ( view_func ) : \"\"\"\"\"\" from horizon . exceptions import NotAuthenticated @ functools . wraps ( view_func , assigned = available_attrs ( view_func ) ) def dec ( request , * args , ** kwargs ) : if request . user . is_authenticated ( ) : return view_func ( request , * args , ** kwargs ) raise NotAuthenticated ( _ ( \"\" ) ) return dec def require_perms ( view_func , required ) : \"\"\"\"\"\" from horizon . exceptions import NotAuthorized current_perms = getattr ( view_func , '' , set ( [ ] ) ) view_func . _required_perms = current_perms | set ( required ) @ functools . wraps ( view_func , assigned = available_attrs ( view_func ) ) def dec ( request , * args , ** kwargs ) : if request . user . is_authenticated ( ) : if request . user . has_perms ( view_func . _required_perms ) : return view_func ( request , * args , ** kwargs ) raise NotAuthorized ( _ ( \"\" ) % request . path ) if required : return dec ", "answer": "else :"}, {"prompt": " import threading import time import logging import httplib2 import json import re import base64 class CallbackWorker ( ) : def __init__ ( self , callback_url ) : self . log = logging . getLogger ( '' % ( __name__ , self . __class__ . __name__ ) ) self . callback_queue = [ ] self . queue_lock = threading . BoundedSemaphore ( ) self . queue_not_empty = threading . Event ( ) self . httplib = httplib2 . Http ( ) url_regex = r\"\" sr = re . search ( url_regex , callback_url ) if sr : self . callback_url = sr . group ( ) + sr . group ( ) auth = base64 . encodestring ( sr . group ( ) + '' + sr . group ( ) ) self . headers = { '' : '' , '' : '' + auth } else : self . callback_url = callback_url self . headers = { '' : '' } self . shutdown = False def start ( self ) : self . thread = threading . Thread ( target = self ) self . thread . start ( ) return self . thread def shut_down ( self , blocking = False ) : self . shutdown = True self . queue_lock . acquire ( ) if len ( self . callback_queue ) == : self . queue_not_empty . set ( ) self . queue_lock . release ( ) if blocking : self . thread . join ( ) def status_notifier ( self , notification ) : image = notification . sender _type = type ( image ) . __name__ typemap = { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" } if not _type in typemap : raise Exception ( \"\" % _type ) callback_body = { typemap [ _type ] : { '' : _type , '' : image . identifier } } for key in image . metadata ( ) : if key not in ( '' , '' , '' , '' ) : callback_body [ typemap [ _type ] ] [ key ] = getattr ( image , key , None ) self . _enqueue ( callback_body ) def _enqueue ( self , status_update ) : ", "answer": "if self . shutdown :"}, {"prompt": " from copy import copy from six . moves import filter _BOOLEAN_ATTRS = frozenset ( [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ] ) def htmlbools ( v ) : attrs = copy ( v ) for key in filter ( lambda k : k in _BOOLEAN_ATTRS , attrs . keys ( ) ) : if attrs [ key ] : ", "answer": "attrs [ key ] = key"}, {"prompt": " '''''' import logging import Queue log = logging . getLogger ( ) class DeferredIOWorker ( object ) : '''''' def __init__ ( self , io_worker ) : self . _io_worker = io_worker self . _io_worker . set_receive_handler ( self . io_worker_receive_handler ) self . _receive_queue = Queue . Queue ( ) self . _send_queue = Queue . Queue ( ) self . _receive_buf = \"\" self . _currently_blocked = False def block ( self ) : '''''' self . _currently_blocked = True ", "answer": "def unblock ( self ) :"}, {"prompt": " def pretty_tree ( x , kids , show ) : \"\"\"\"\"\" ( MID , END , CONT , LAST , ROOT ) = ( u'' , u'' , u'' , u'' , u'' ) def rec ( x , indent , sym ) : ", "answer": "line = indent + sym + show ( x )"}, {"prompt": " from __future__ import absolute_import , division , unicode_literals , print_function import sys import struct import array try : unichr = unichr except NameError : unichr = chr def unpack ( fmt , data ) : ", "answer": "fmt = str ( \">\" + fmt )"}, {"prompt": " \"\"\"\"\"\" _copyright = '''''' _copyright += \"\" _copyright += '''''' from xml . dom import Node from Namespaces import XMLNS import cStringIO as StringIO try : from xml . dom . ext import c14n except ImportError , ex : _implementation2 = None _attrs = lambda E : ( E . attributes and E . attributes . values ( ) ) or [ ] _children = lambda E : E . childNodes or [ ] else : class _implementation2 ( c14n . _implementation ) : \"\"\"\"\"\" def __init__ ( self , node , write , ** kw ) : self . unsuppressedPrefixes = kw . get ( '' ) self . _exclusive = None if node . nodeType == Node . ELEMENT_NODE : if not c14n . _inclusive ( self ) : self . _exclusive = self . _inherit_context ( node ) c14n . _implementation . __init__ ( self , node , write , ** kw ) def _do_element ( self , node , initial_other_attrs = [ ] ) : \"\"\"\"\"\" ns_parent , ns_rendered , xml_attrs = self . state [ ] , self . state [ ] . copy ( ) , self . state [ ] . copy ( ) ns_local = ns_parent . copy ( ) xml_attrs_local = { } other_attrs = [ ] sort_these_attrs = initial_other_attrs [ : ] in_subset = c14n . _in_subset ( self . subset , node ) sort_these_attrs += c14n . _attrs ( node ) for a in sort_these_attrs : if a . namespaceURI == c14n . XMLNS . BASE : n = a . nodeName if n == \"\" : n = \"\" ns_local [ n ] = a . nodeValue elif a . namespaceURI == c14n . XMLNS . XML : if c14n . _inclusive ( self ) or ( in_subset and c14n . _in_subset ( self . subset , a ) ) : xml_attrs_local [ a . nodeName ] = a else : if c14n . _in_subset ( self . subset , a ) : other_attrs . append ( a ) xml_attrs . update ( xml_attrs_local ) W , name = self . write , None if in_subset : name = node . nodeName W ( '' ) W ( name ) ns_to_render = [ ] for n , v in ns_local . items ( ) : if n == \"\" and v in [ c14n . XMLNS . BASE , '' ] and ns_rendered . get ( '' ) in [ c14n . XMLNS . BASE , '' , None ] : continue if n in [ \"\" , \"\" ] and v in [ '' ] : continue if ( n , v ) not in ns_rendered . items ( ) and ( c14n . _inclusive ( self ) or c14n . _utilized ( n , node , other_attrs , self . unsuppressedPrefixes ) ) : ns_to_render . append ( ( n , v ) ) if not c14n . _inclusive ( self ) : if node . prefix is None : look_for = [ ( '' , node . namespaceURI ) , ] else : look_for = [ ( '' % node . prefix , node . namespaceURI ) , ] for a in c14n . _attrs ( node ) : if a . namespaceURI != XMLNS . BASE : if a . prefix : look_for . append ( ( '' % a . prefix , a . namespaceURI ) ) for key , namespaceURI in look_for : if ns_rendered . has_key ( key ) : if ns_rendered [ key ] == namespaceURI : pass else : pass elif ( key , namespaceURI ) in ns_to_render : pass else : ns_local [ key ] = namespaceURI for a in self . _exclusive : if a . nodeName == key : ns_to_render += [ ( a . nodeName , a . value ) ] break elif key is None and a . nodeName == '' : ns_to_render += [ ( a . nodeName , a . value ) ] break else : raise RuntimeError , '' % ( key , namespaceURI ) ns_to_render . sort ( c14n . _sorter_ns ) for n , v in ns_to_render : if v : self . _do_attr ( n , v ) else : v = '' self . _do_attr ( n , v ) ns_rendered [ n ] = v if not c14n . _inclusive ( self ) or c14n . _in_subset ( self . subset , node . parentNode ) : other_attrs . extend ( xml_attrs_local . values ( ) ) else : other_attrs . extend ( xml_attrs . values ( ) ) other_attrs . sort ( c14n . _sorter ) for a in other_attrs : self . _do_attr ( a . nodeName , a . value ) W ( '>' ) state , self . state = self . state , ( ns_local , ns_rendered , xml_attrs ) for c in c14n . _children ( node ) : c14n . _implementation . handlers [ c . nodeType ] ( self , c ) self . state = state if name : W ( '' % name ) c14n . _implementation . handlers [ c14n . Node . ELEMENT_NODE ] = _do_element _IN_XML_NS = lambda n : n . namespaceURI == XMLNS . XML _LesserElement , _Element , _GreaterElement = range ( ) def _sorter ( n1 , n2 ) : '''''' i = cmp ( n1 . namespaceURI , n2 . namespaceURI ) if i : return i return cmp ( n1 . localName , n2 . localName ) def _sorter_ns ( n1 , n2 ) : '''''' if n1 [ ] == '' : return - if n2 [ ] == '' : return return cmp ( n1 [ ] , n2 [ ] ) def _utilized ( n , node , other_attrs , unsuppressedPrefixes ) : '''''' if n . startswith ( '' ) : n = n [ : ] elif n . startswith ( '' ) : n = n [ : ] if n == node . prefix or n in unsuppressedPrefixes : return for attr in other_attrs : if n == attr . prefix : return return _in_subset = lambda subset , node : not subset or node in subset class _implementation : '''''' handlers = { } def __init__ ( self , node , write , ** kw ) : '''''' self . write = write ", "answer": "self . subset = kw . get ( '' )"}, {"prompt": " import hashlib import os from abc import ( ABCMeta , abstractmethod ) import six from . utils import ( BytesIoContextManager , hex_sha1_of_stream ) @ six . add_metaclass ( ABCMeta ) ", "answer": "class AbstractUploadSource ( object ) :"}, {"prompt": " from __future__ import absolute_import , unicode_literals from django . contrib import admin from django . utils . translation import ugettext_lazy as _ from . import models class ContactAdmin ( admin . ModelAdmin ) : fieldsets = ( ( None , { '' : ( '' , '' , '' , '' ) } ) , ( _ ( '' ) , { '' : models . Contact . address_fields ( '' ) , } ) , ( _ ( '' ) , { '' : ( [ '' ] + models . Contact . address_fields ( '' ) ) , } ) , ( _ ( '' ) , { '' : ( '' , ) , } ) , ) list_display = ( '' , '' , '' , '' , '' ) ", "answer": "list_filter = ( '' , )"}, {"prompt": " \"\"\"\"\"\" from types import ModuleType import sys __version__ = '' all_by_module = { '' : [ '' ] , '' : [ '' , '' , '' , '' , '' ] , '' : [ '' ] , '' : [ '' ] , '' : [ '' , '' , '' , '' ] , '' : [ '' ] , '' : [ '' , '' ] , '' : [ '' , '' , '' , '' , '' , '' , '' , '' , ", "answer": "'' , '' ] ,"}, {"prompt": " import json import logging import posixpath import gevent from gevent . event import Event from gevent . queue import Queue from kazoo . client import KazooClient from kazoo . exceptions import NoNodeError from kazoo . recipe . watchers import ( ChildrenWatch , DataWatch ) ROOT_LOG = logging . getLogger ( '' ) class Endpoint ( object ) : \"\"\"\"\"\" def __init__ ( self , host , port ) : self . _host = host self . _port = port def _key ( self ) : return self . host , self . port def __eq__ ( self , other ) : return isinstance ( other , self . __class__ ) and self . _key ( ) == other . _key ( ) def __hash__ ( self ) : return hash ( self . _host ) ^ hash ( self . _port ) @ property def host ( self ) : return self . _host @ property def port ( self ) : return self . _port def __str__ ( self ) : return '' % ( self . host , self . port ) class Member ( object ) : \"\"\"\"\"\" @ classmethod def from_node ( cls , member , data ) : blob = json . loads ( data ) additional_endpoints = blob . get ( '' ) if additional_endpoints is None : raise ValueError ( \"\" ) service_endpoint = blob . get ( '' ) if service_endpoint is None : raise ValueError ( \"\" ) status = blob . get ( '' ) if status is None : raise ValueError ( \"\" ) shard = blob . get ( '' ) if shard is not None : try : shard = int ( shard ) except ValueError : ROOT_LOG . warn ( '' % shard ) shard = None return cls ( member = member , service_endpoint = Endpoint ( service_endpoint [ '' ] , service_endpoint [ '' ] ) , additional_endpoints = dict ( ( name , Endpoint ( value [ '' ] , value [ '' ] ) ) for name , value in additional_endpoints . items ( ) ) , shard = shard , status = status ) def __init__ ( self , member , service_endpoint , additional_endpoints , shard , status ) : self . _name = member self . _service_endpoint = service_endpoint self . _additional_endpoints = additional_endpoints self . _status = status self . _shard = shard @ property def name ( self ) : return self . _name @ property def service_endpoint ( self ) : return self . _service_endpoint @ property def additional_endpoints ( self ) : return self . _additional_endpoints @ property def status ( self ) : return self . _status @ property def shard ( self ) : return self . _shard def __addl_endpoints_str ( self ) : return [ '' % ( k , v ) for k , v in self . additional_endpoints . items ( ) ] def __str__ ( self ) : return '' % ( self . service_endpoint , ( '' % self . _shard ) if self . _shard is not None else '' , '' . join ( self . __addl_endpoints_str ( ) ) , self . status ) def _key ( self ) : return ( self . service_endpoint , frozenset ( sorted ( self . __addl_endpoints_str ( ) ) ) , self . status , self . _shard ) def __eq__ ( self , other ) : return isinstance ( other , self . __class__ ) and self . _key ( ) == other . _key ( ) def __hash__ ( self ) : return hash ( self . _key ( ) ) class ServerSet ( object ) : \"\"\"\"\"\" class _CallbackBlocker ( object ) : def __init__ ( self ) : self . event = Event ( ) self . event . set ( ) self . _count = def __enter__ ( self ) : if self . _count == : self . event . clear ( ) self . _count += def __exit__ ( self , exc_type , exc_val , exc_tb ) : self . _count -= if self . _count == : self . event . set ( ) def ensure_safe ( self ) : self . event . wait ( ) def is_blocking ( self ) : return self . _count != def __init__ ( self , zk , zk_path , on_join = None , on_leave = None , member_filter = None , member_factory = None ) : \"\"\"\"\"\" def noop ( * args , ** kwargs ) : pass def true ( * args , ** kwargs ) : return True self . _log = ROOT_LOG . getChild ( '' % zk_path ) self . _log . info ( '' % zk_path ) if not isinstance ( zk , KazooClient ) : raise TypeError ( '' ) if not zk . connected : raise Exception ( '' ) self . _zk_path = zk_path self . _zk = zk self . _nodes = set ( ) self . _members = { } self . _on_join = on_join or noop self . _on_leave = on_leave or noop self . _notification_queue = Queue ( ) self . _watching = False self . _cb_blocker = self . _CallbackBlocker ( ) self . _member_filter = member_filter or true self . _member_factory = member_factory or Member . from_node self . _running = True self . _worker = gevent . spawn ( self . _notification_worker ) if on_join or on_leave : self . _monitor ( ) def stop ( self ) : self . _running = False if self . _worker : self . _worker . kill ( block = False ) def __iter__ ( self ) : with self . _cb_blocker : try : nodes = self . _zk . get_children ( self . _zk_path ) except NoNodeError : nodes = ( ) members = self . _zk_nodes_to_members ( nodes ) return ( n for n in members ) ", "answer": "def get_members ( self ) :"}, {"prompt": " from __future__ import absolute_import , unicode_literals import unittest ", "answer": "from distutils . version import StrictVersion"}, {"prompt": " from django . contrib . sites . models import Site from django . contrib . contenttypes . models import ContentType ", "answer": "from django . shortcuts import render_to_response"}, {"prompt": " import os . path import hashlib import urllib class Downloader : \"\"\"\"\"\" @ staticmethod def request ( url , params = None , on_complete = None ) : \"\"\"\"\"\" params = params or { } if params : url += \"\" + urllib . parse . urlencode ( params ) return Downloader . download ( url , on_complete = on_complete ) @ staticmethod def download ( url , checksum = None , on_complete = None ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " __author__ = '' ", "answer": "from . win_soup import WinSoup "}, {"prompt": " from test import CollectorTestCase from test import get_collector_config from test import unittest from mock import Mock from mock import patch from diamond . collector import Collector from elasticsearch import ElasticSearchCollector class TestElasticSearchCollector ( CollectorTestCase ) : def setUp ( self ) : config = get_collector_config ( '' , { } ) self . collector = ElasticSearchCollector ( config , None ) def test_import ( self ) : self . assertTrue ( ElasticSearchCollector ) def test_new__instances_default ( self ) : config = get_collector_config ( '' , { } ) self . collector = ElasticSearchCollector ( config , None ) self . assertEqual ( self . collector . instances , { '' : ( '' , ) } ) def test_new__instances_single ( self ) : config = get_collector_config ( '' , { '' : '' } ) self . collector = ElasticSearchCollector ( config , None ) self . assertEqual ( self . collector . instances , { '' : ( '' , ) } ) def test_new__instances_multi ( self ) : config = get_collector_config ( '' , { '' : [ '' , '' , '' , ] } ) self . collector = ElasticSearchCollector ( config , None ) self . assertEqual ( self . collector . instances , { '' : ( '' , ) , '' : ( '' , ) , '' : ( '' , ) , } ) @ patch . object ( Collector , '' ) def test_should_work_with_real_data ( self , publish_mock ) : returns = [ self . getFixture ( '' ) , self . getFixture ( '' ) , self . getFixture ( '' ) , ] urlopen_mock = patch ( '' , Mock ( side_effect = lambda * args : returns . pop ( ) ) ) self . collector . config [ '' ] = True urlopen_mock . start ( ) self . collector . collect ( ) urlopen_mock . stop ( ) self . assertEqual ( urlopen_mock . new . call_count , ) metrics = { '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : , '' : , } self . setDocExample ( collector = self . collector . __class__ . __name__ , metrics = metrics , defaultpath = self . collector . config [ '' ] ) ", "answer": "self . assertPublishedMany ( publish_mock , metrics )"}, {"prompt": " from oslo_config import cfg from neutron . common import utils as n_utils from neutron . plugins . ml2 . drivers . mech_sriov . agent . common import config from neutron . plugins . ml2 . drivers . mech_sriov . agent import sriov_nic_agent as agent from neutron . tests import base class TestSriovAgentConfig ( base . BaseTestCase ) : EXCLUDE_DEVICES_LIST = [ '' , '' ] EXCLUDE_DEVICES_LIST_INVALID = [ '' ] EXCLUDE_DEVICES_WITH_SPACES_LIST = [ '' , '' ] EXCLUDE_DEVICES_WITH_SPACES_ERROR = [ '' , '' ] EXCLUDE_DEVICES = { '' : set ( [ '' , '' ] ) , '' : set ( [ '' ] ) } DEVICE_MAPPING_LIST = [ '' , '' ] DEVICE_MAPPING_WITH_ERROR_LIST = [ '' , '' ] DEVICE_MAPPING_WITH_SPACES_LIST = [ '' , '' ] DEVICE_MAPPING = { '' : [ '' ] , '' : [ '' ] } def test_defaults ( self ) : self . assertEqual ( config . DEFAULT_DEVICE_MAPPINGS , cfg . CONF . SRIOV_NIC . physical_device_mappings ) self . assertEqual ( config . DEFAULT_EXCLUDE_DEVICES , cfg . CONF . SRIOV_NIC . exclude_devices ) self . assertEqual ( , cfg . CONF . AGENT . polling_interval ) def test_device_mappings ( self ) : cfg . CONF . set_override ( '' , self . DEVICE_MAPPING_LIST , '' ) device_mappings = n_utils . parse_mappings ( ", "answer": "cfg . CONF . SRIOV_NIC . physical_device_mappings , unique_keys = False )"}, {"prompt": " from __future__ import print_function import site site . addsitedir ( '' ) site . addsitedir ( '' ) import sys import time from threading import Thread from mesos . interface import Executor , mesos_pb2 from mesos . native import MesosExecutorDriver class MinimalExecutor ( Executor ) : ", "answer": "def launchTask ( self , driver , task ) :"}, {"prompt": " from . . utils import TranspileTestCase import unittest class ListComprehensionTests ( TranspileTestCase ) : def test_syntax ( self ) : self . assertCodeExecution ( \"\"\"\"\"\" ) ", "answer": "@ unittest . expectedFailure"}, {"prompt": " from amdevice import * from afc import * class AFCRoot ( AFC ) : def __init__ ( self , amdevice ) : ", "answer": "s = amdevice . start_service ( u'' )"}, {"prompt": " import datastore import webtest ", "answer": "def test_datastore ( testbed ) :"}, {"prompt": " from unleash import issues , info , log PLUGIN_NAME = '' PLUGIN_DEPENDS = [ '' ] _PY2_CLASSIFIER = '' _PY3_CLASSIFIER = '' def lint_release ( ) : log . info ( '' ) cs = info [ '' ] . classifiers if not cs : issues . warn ( '' , '' '' '' ) else : ", "answer": "if not _PY2_CLASSIFIER in cs and not _PY3_CLASSIFIER in cs :"}, {"prompt": " import csv import sys def last_index ( list_ , value ) : \"\"\"\"\"\" found = None ", "answer": "for index , val in enumerate ( list_ ) :"}, {"prompt": " from flask import Flask from nose . tools import eq_ from standup . filters import format_update , gravatar_url , TAG_TMPL from standup . tests import BaseTestCase class FilterTestCase ( BaseTestCase ) : def test_tags ( self ) : \"\"\"\"\"\" with self . app . app_context ( ) : for tag in ( '' , '' , '' , '' ) : expected = '' % ( tag , TAG_TMPL . format ( '' , tag [ : ] . lower ( ) , tag [ : ] ) ) eq_ ( format_update ( tag ) , expected ) for tag in ( '' , '' , '' ) : eq_ ( format_update ( tag ) , tag ) def test_gravatar_url ( self ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " import argparse import numpy as np from PIL import Image import ocppaths import ocpcarest import zindex import anydbm import multiprocessing import pdb \"\"\"\"\"\" parser = argparse . ArgumentParser ( description = '' ) parser . add_argument ( '' , action = \"\" , help = '' ) parser . add_argument ( '' , action = \"\" , help = '' ) parser . add_argument ( '' , action = \"\" , help = '' ) parser . add_argument ( '' , action = \"\" , help = '' ) result = parser . parse_args ( ) resolution = [ db , proj , projdb ] = ocpcarest . loadDBProj ( result . token ) ( xcubedim , ycubedim , zcubedim ) = proj . datasetcfg . cubedim [ resolution ] ( startslice , endslice ) = proj . datasetcfg . slicerange batchsz = zcubedim ximagesz = yimagesz = batchsz = totalslices = range ( startslice , endslice , ) totalprocs = int ( result . process ) def parallelwrite ( slicenumber ) : [ db , proj , projdb ] = ocpcarest . loadDBProj ( result . token ) startslice = slicenumber endslice = startslice + for sl in range ( startslice , endslice + , batchsz ) : slab = np . zeros ( [ batchsz , yimagesz , ximagesz ] , dtype = np . uint32 ) for b in range ( batchsz ) : if ( sl + b <= endslice and sl + b <= ) : filenm = result . path + '' + '' . format ( sl + b ) + '' img = Image . open ( filenm , '' ) imgdata = np . asarray ( img ) anydb = anydbm . open ( '' , '' ) superpixelarray = imgdata [ : , : , ] + ( np . uint32 ( imgdata [ : , : , ] ) << ) newdata = np . zeros ( [ superpixelarray . shape [ ] , superpixelarray . shape [ ] ] , dtype = np . uint32 ) print sl + b , multiprocessing . current_process ( ) for i in range ( superpixelarray . shape [ ] ) : for j in range ( superpixelarray . shape [ ] ) : key = str ( sl ) + '' + str ( superpixelarray [ i , j ] ) ", "answer": "if ( key not in anydb ) :"}, {"prompt": " \"\"\"\"\"\" import inspect import logging from google . appengine import runtime from google . appengine . api import logservice from google . appengine . runtime import features NEWLINE_REPLACEMENT = \"\" class AppLogsHandler ( logging . Handler ) : \"\"\"\"\"\" def emit ( self , record ) : \"\"\"\"\"\" try : if features . IsEnabled ( \"\" ) : logservice . write_record ( self . _AppLogsLevel ( record . levelno ) , record . created , self . format ( record ) , self . _AppLogsLocation ( ) ) else : message = self . _AppLogsMessage ( record ) if isinstance ( message , unicode ) : message = message . encode ( \"\" ) logservice . write ( message ) except ( KeyboardInterrupt , SystemExit , runtime . DeadlineExceededError ) : raise except : self . handleError ( record ) def _AppLogsMessage ( self , record ) : \"\"\"\"\"\" message = self . format ( record ) . replace ( \"\" , NEWLINE_REPLACEMENT ) message = message . replace ( \"\" , NEWLINE_REPLACEMENT ) message = message . replace ( \"\" , NEWLINE_REPLACEMENT ) return \"\" % ( self . _AppLogsLevel ( record . levelno ) , long ( record . created * * ) , message ) ", "answer": "def _AppLogsLevel ( self , level ) :"}, {"prompt": " from itty import * from tropo import Tropo , Session @ post ( '' ) def index ( request ) : s = Session ( request . body ) t = Tropo ( ) t . say ( '' , _as = '' , voice = '' ) json = t . RenderJson ( ) print json return json ", "answer": "run_itty ( ) "}, {"prompt": " __all__ = [ '' , '' , '' , '' , '' , '' , '' , '' , '' ] ", "answer": "from version import __version__ "}, {"prompt": " from __future__ import unicode_literals from django . db import models , migrations import tethys_compute . utilities class Migration ( migrations . Migration ) : dependencies = [ ( '' , '' ) , ] operations = [ migrations . AlterField ( model_name = '' , name = '' , field = tethys_compute . utilities . DictionaryField ( default = b'' , blank = True ) , preserve_default = True , ", "answer": ") ,"}, {"prompt": " \"\"\"\"\"\" import click import SoftLayer from SoftLayer . CLI import environment from SoftLayer . CLI import exceptions from SoftLayer . CLI import formatting from SoftLayer . CLI import loadbal @ click . command ( ) @ click . argument ( '' ) @ environment . pass_env def cli ( env , identifier ) : \"\"\"\"\"\" ", "answer": "mgr = SoftLayer . LoadBalancerManager ( env . client )"}, {"prompt": " from nose . tools import * import networkx as nx from networkx . testing import * class _GenericTest ( object ) : def _test_equal ( self , a , b ) : self . _assert_func ( a , b ) def _test_not_equal ( self , a , b ) : try : self . _assert_func ( a , b ) passed = True except AssertionError : pass else : raise AssertionError ( \"\" ) class TestNodesEqual ( _GenericTest ) : def setUp ( self ) : self . _assert_func = assert_nodes_equal def test_nodes_equal ( self ) : a = [ , , , ] b = [ , , , ] self . _test_equal ( a , b ) def test_nodes_not_equal ( self ) : a = [ , , , ] b = [ , , , ] self . _test_not_equal ( a , b ) def test_nodes_with_data_equal ( self ) : G = nx . Graph ( ) G . add_nodes_from ( [ , , ] , color = '' ) H = nx . Graph ( ) H . add_nodes_from ( [ , , ] , color = '' ) self . _test_equal ( G . nodes ( data = True ) , H . nodes ( data = True ) ) def test_edges_with_data_not_equal ( self ) : G = nx . Graph ( ) G . add_nodes_from ( [ , , ] , color = '' ) H = nx . Graph ( ) H . add_nodes_from ( [ , , ] , color = '' ) self . _test_not_equal ( G . nodes ( data = True ) , H . nodes ( data = True ) ) class TestEdgesEqual ( _GenericTest ) : def setUp ( self ) : self . _assert_func = assert_edges_equal def test_edges_equal ( self ) : a = [ ( , ) , ( , ) ] b = [ ( , ) , ( , ) ] self . _test_equal ( a , b ) def test_edges_not_equal ( self ) : a = [ ( , ) , ( , ) ] b = [ ( , ) , ( , ) ] self . _test_not_equal ( a , b ) def test_edges_with_data_equal ( self ) : G = nx . MultiGraph ( ) nx . add_path ( G , [ , , ] , weight = ) H = nx . MultiGraph ( ) nx . add_path ( H , [ , , ] , weight = ) ", "answer": "self . _test_equal ( G . edges ( data = True , keys = True ) ,"}, {"prompt": " import re from tkinter import * import tkinter . messagebox as tkMessageBox def get ( root ) : if not hasattr ( root , \"\" ) : root . _searchengine = SearchEngine ( root ) return root . _searchengine class SearchEngine : def __init__ ( self , root ) : self . root = root self . patvar = StringVar ( root ) self . revar = BooleanVar ( root ) self . casevar = BooleanVar ( root ) self . wordvar = BooleanVar ( root ) self . wrapvar = BooleanVar ( root ) self . wrapvar . set ( ) self . backvar = BooleanVar ( root ) def getpat ( self ) : return self . patvar . get ( ) def setpat ( self , pat ) : self . patvar . set ( pat ) def isre ( self ) : return self . revar . get ( ) def iscase ( self ) : return self . casevar . get ( ) def isword ( self ) : return self . wordvar . get ( ) def iswrap ( self ) : return self . wrapvar . get ( ) def isback ( self ) : return self . backvar . get ( ) def getcookedpat ( self ) : pat = self . getpat ( ) if not self . isre ( ) : pat = re . escape ( pat ) if self . isword ( ) : pat = r\"\" % pat return pat def getprog ( self ) : pat = self . getpat ( ) if not pat : self . report_error ( pat , \"\" ) return None pat = self . getcookedpat ( ) flags = if not self . iscase ( ) : flags = flags | re . IGNORECASE try : prog = re . compile ( pat , flags ) except re . error as what : try : msg , col = what except : msg = str ( what ) col = - self . report_error ( pat , msg , col ) return None return prog def report_error ( self , pat , msg , col = - ) : msg = \"\" + str ( msg ) if pat : msg = msg + \"\" + str ( pat ) if col >= : msg = msg + \"\" + str ( col ) tkMessageBox . showerror ( \"\" , msg , master = self . root ) def setcookedpat ( self , pat ) : if self . isre ( ) : pat = re . escape ( pat ) self . setpat ( pat ) def search_text ( self , text , prog = None , ok = ) : \"\"\"\"\"\" if not prog : prog = self . getprog ( ) if not prog : return None wrap = self . wrapvar . get ( ) first , last = get_selection ( text ) if self . isback ( ) : if ok : start = last else : start = first line , col = get_line_col ( start ) res = self . search_backward ( text , prog , line , col , wrap , ok ) else : if ok : start = first else : start = last line , col = get_line_col ( start ) res = self . search_forward ( text , prog , line , col , wrap , ok ) return res def search_forward ( self , text , prog , line , col , wrap , ok = ) : wrapped = startline = line chars = text . get ( \"\" % line , \"\" % ( line + ) ) while chars : m = prog . search ( chars [ : - ] , col ) if m : if ok or m . end ( ) > col : return line , m line = line + if wrapped and line > startline : break col = ok = chars = text . get ( \"\" % line , \"\" % ( line + ) ) if not chars and wrap : wrapped = wrap = line = chars = text . get ( \"\" , \"\" ) return None def search_backward ( self , text , prog , line , col , wrap , ok = ) : ", "answer": "wrapped = "}, {"prompt": " from __future__ import division from __future__ import print_function ", "answer": "from datetime import datetime"}, {"prompt": " \"\"\"\"\"\" import sre_parse , sre_compile , sre_constants from sre_constants import BRANCH , SUBPATTERN from re import VERBOSE , MULTILINE , DOTALL import re __all__ = [ '' , '' ] FLAGS = ( VERBOSE | MULTILINE | DOTALL ) class Scanner ( object ) : def __init__ ( self , lexicon , flags = FLAGS ) : self . actions = [ None ] s = sre_parse . Pattern ( ) s . flags = flags p = [ ] for idx , token in enumerate ( lexicon ) : phrase = token . pattern try : subpattern = sre_parse . SubPattern ( s , [ ( SUBPATTERN , ( idx + , sre_parse . parse ( phrase , flags ) ) ) ] ) except sre_constants . error : raise p . append ( subpattern ) self . actions . append ( token ) p = sre_parse . SubPattern ( s , [ ( BRANCH , ( None , p ) ) ] ) self . scanner = sre_compile . compile ( p ) def iterscan ( self , string , idx = , context = None ) : \"\"\"\"\"\" match = self . scanner . scanner ( string , idx ) . match actions = self . actions lastend = idx end = len ( string ) while True : m = match ( ) if m is None : break matchbegin , matchend = m . span ( ) if lastend == matchend : ", "answer": "break"}, {"prompt": " import fudge import urllib from django . core . exceptions import ImproperlyConfigured from django . utils . safestring import SafeData from . . _utils import TestCase from ... templatetags import text_helpers def generate_random_request ( match = \"\" , url_template = \"\" ) : request = fudge . Fake ( ) request . has_attr ( META = { \"\" : url_template % match } ) fudge . clear_calls ( ) return request def generate_random_request_and_context ( text , match = \"\" , url_template = \"\" ) : request = generate_random_request ( match = match , url_template = url_template ) context = { \"\" : request , \"\" : text , } return request , context class HelloWorld ( TestCase ) : def test_data_returns_is_marked_as_safe ( self ) : text = \"\" request , context = generate_random_request_and_context ( text ) node = text_helpers . HighlightedSearchTermNode ( \"\" ) result = node . render ( context ) self . assertIsInstance ( result , SafeData ) def test_gracefully_returns_when_lacking_request_object ( self ) : text = \"\" node = text_helpers . HighlightedSearchTermNode ( \"\" ) result = node . render ( { \"\" : text } ) self . assertEqual ( text , result ) def test_raises_exception_when_debug_is_on ( self ) : settings = fudge . Fake ( ) settings . has_attr ( DEBUG = True ) text = \"\" node = text_helpers . HighlightedSearchTermNode ( \"\" ) with fudge . patched_context ( text_helpers , '' , settings ) : self . assertRaises ( ImproperlyConfigured , node . render , { \"\" : text } ) def test_works_with_referrers_with_no_q_get_param ( self ) : text = \"\" request , context = generate_random_request_and_context ( \"\" , url_template = \"\" , match = \"\" ) node = text_helpers . HighlightedSearchTermNode ( \"\" ) result = node . render ( { \"\" : text } ) self . assertEqual ( text , result ) def test_replaces_words_with_highlighted_word ( self ) : text = \"\" request , context = generate_random_request_and_context ( text ) node = text_helpers . HighlightedSearchTermNode ( \"\" ) result = node . render ( context ) expected = '' self . assertEqual ( expected , result ) def test_can_handle_mismatched_case ( self ) : text = \"\" ", "answer": "request , context = generate_random_request_and_context ( text )"}, {"prompt": " from __future__ import print_function from __future__ import absolute_import import numpy import sys import time import theano import theano . tensor as T import theano . sandbox from six . moves import xrange from theano . compile import module , Mode , ProfileMode from theano import gof , Op , Apply from theano . tensor import blas , opt if : class Opt ( object ) : merge = theano . gof . MergeOptimizer ( ) gemm_opt_1 = theano . gof . TopoOptimizer ( theano . tensor_opt . gemm_pattern_1 ) gemm_opt_2 = theano . gof . TopoOptimizer ( theano . gof . PatternSub ( ( T . sub_inplace , '' , ( T . mul , dict ( pattern = ( T . DimShuffle ( ( ) , [ '' , '' ] , inplace = True ) , '' ) , allow_multiple_clients = True ) , ( T . add , ( T . dot , '' , '' ) , ( T . transpose_inplace , ( T . dot , '' , '' ) ) ) ) ) , ( T . gemm , ( T . gemm , '' , ( T . neg , '' ) , ( T . transpose_inplace , '' ) , ( T . transpose_inplace , '' ) , T . constant ( ) ) , ( T . neg , '' ) , '' , '' , T . constant ( ) ) , allow_multiple_clients = False ) ) sqr = [ ] sqr . append ( theano . gof . TopoOptimizer ( theano . gof . PatternSub ( ( T . mul , '' , '' ) , ( T . sqr , '' ) , allow_multiple_clients = True ) ) ) sqr . append ( theano . gof . TopoOptimizer ( theano . gof . PatternSub ( ( T . pow , '' , ( T . DimShuffle ( ( ) , [ '' , '' ] , inplace = True ) , T . constant ( ) ) ) , ( T . sqr , '' ) , allow_multiple_clients = True ) ) ) ident_opt_list = [ ] ident_opt_list . append ( theano . gof . TopoOptimizer ( theano . gof . PatternSub ( ( T . tensor_copy , '' ) , '' , allow_multiple_clients = True ) ) ) ident_opt_list . append ( theano . gof . TopoOptimizer ( theano . gof . PatternSub ( ( T . transpose_inplace , ( T . transpose_inplace , '' ) ) , '' , allow_multiple_clients = True ) ) ) ident_opt_list . append ( theano . gof . TopoOptimizer ( theano . gof . PatternSub ( ( T . sqr , ( T . sqrt , '' ) ) , '' , allow_multiple_clients = True ) ) ) ident_opt_list . append ( theano . gof . TopoOptimizer ( theano . gof . PatternSub ( ( T . sqrt , ( T . sqr , '' ) ) , '' , allow_multiple_clients = True ) ) ) ident_opt_list . append ( theano . gof . TopoOptimizer ( theano . gof . PatternSub ( ( T . mul , '' , ( T . div , '' , '' ) ) , '' , allow_multiple_clients = True ) ) ) ident_opt_list . append ( theano . gof . TopoOptimizer ( theano . gof . PatternSub ( ( T . mul , ( T . div , '' , '' ) , '' ) , '' , allow_multiple_clients = True ) ) ) ident_opt_list . append ( ", "answer": "theano . gof . TopoOptimizer ("}, {"prompt": " import json import numpy as np import matplotlib . pyplot as plt from bubbly . extractors import RGBExtractor from bubbly . dr1 import bubble_params def hide_axes ( ) : plt . gca ( ) . get_xaxis ( ) . set_visible ( False ) plt . gca ( ) . get_yaxis ( ) . set_visible ( False ) plt . gca ( ) . axis ( '' ) def ex ( params ) : rgb = RGBExtractor ( ) rgb . shp = ( , ) p = list ( params ) p [ - ] *= return rgb . extract ( * p ) ", "answer": "def main ( ) :"}, {"prompt": " import getopt import os import rcsparse import re import string import subprocess import sys import time from hashlib import md5 from svn import core , fs , delta , repos CHANGESET_FUZZ_SEC = def usage ( ) : print >> sys . stderr , '' '' '' def main ( ) : email_domain = None do_incremental = False dump_all = False log_encoding = '' rcs = RcsKeywords ( ) ; modules = [ ] fuzzsec = CHANGESET_FUZZ_SEC try : opts , args = getopt . getopt ( sys . argv [ : ] , '' ) for opt , v in opts : if opt == '' : fuzzsec = int ( v ) elif opt == '' : email_domain = v elif opt == '' : dump_all = True elif opt == '' : log_encoding = v elif opt == '' : rcs . add_id_keyword ( v ) elif opt == '' : modules . append ( v ) elif opt == '' : usage ( ) sys . exit ( ) except Exception , msg : print >> sys . stderr , msg usage ( ) sys . exit ( ) if len ( args ) != and len ( args ) != : usage ( ) sys . exit ( ) log_encodings = log_encoding . split ( '' ) cvsroot = args [ ] while cvsroot [ - ] == '' : cvsroot = cvsroot [ : - ] if len ( args ) == : svnroot = args [ ] svnpath = args [ ] else : svnroot = None svnpath = None if svnroot is None : svn = SvnDumper ( ) else : svn = SvnDumper ( svnpath ) try : svn . load ( svnroot ) if svn . last_rev is not None : do_incremental = True print >> sys . stderr , '' % ( svn . last_rev , svn . last_author ) except : pass if do_incremental and email_domain is not None and svn . last_author . lower ( ) . endswith ( ( '' + email_domain ) . lower ( ) ) : last_author = svn . last_author [ : - * ( + len ( email_domain ) ) ] else : last_author = svn . last_author cvs = CvsConv ( cvsroot , rcs , not do_incremental , fuzzsec ) print >> sys . stderr , '' if len ( modules ) == : cvs . walk ( ) else : for module in modules : cvs . walk ( module ) svn . dump = True changesets = sorted ( cvs . changesets ) nchangesets = len ( changesets ) print >> sys . stderr , '' % ( nchangesets ) if nchangesets <= : sys . exit ( ) if not dump_all : max_time_max = changesets [ - ] . max_time - else : max_time_max = changesets [ - ] . max_time printOnce = False found_last_revision = False for i , k in enumerate ( changesets ) : if do_incremental and not found_last_revision : if k . min_time == svn . last_date and k . author == last_author : found_last_revision = True continue if k . max_time > max_time_max : break if not printOnce : print '' print '' printOnce = True finfo = k . revs [ ] rcsfile = rcsparse . rcsfile ( finfo . path ) log = rcsparse . rcsfile ( k . revs [ ] . path ) . getlog ( k . revs [ ] . rev ) for i , e in enumerate ( log_encodings ) : try : how = '' if i == len ( log_encodings ) - else '' ; log = log . decode ( e , how ) break except : pass log = log . encode ( '' , '' ) if email_domain is None : email = k . author else : email = k . author + '' + email_domain revprops = str_prop ( '' , email ) revprops += str_prop ( '' , svn_time ( k . min_time ) ) revprops += str_prop ( '' , log ) revprops += '' print '' % ( i + ) print '' % ( len ( revprops ) ) print '' % ( len ( revprops ) ) print '' print revprops for f in k . revs : rcsfile = rcsparse . rcsfile ( f . path ) fileprops = '' if os . access ( f . path , os . X_OK ) : fileprops += str_prop ( '' , '' ) fileprops += '' filecont = rcs . expand_keyword ( f . path , f . rev ) md5sum = md5 ( ) md5sum . update ( filecont ) p = node_path ( cvs . cvsroot , svnpath , f . path ) if f . state == '' : if not svn . exists ( p ) : print >> sys . stderr , \"\" \"\" % ( p ) continue print '' % ( p ) print '' print '' print '' svn . remove ( p ) continue elif not svn . exists ( p ) : svn . add ( p ) print '' % ( p ) print '' print '' else : print '' % ( p ) print '' print '' print '' % ( len ( fileprops ) ) print '' % ( len ( filecont ) ) print '' % ( md5sum . hexdigest ( ) ) print '' % ( len ( fileprops ) + len ( filecont ) ) print '' print fileprops + filecont print '' if do_incremental and not found_last_revision : raise Exception ( '' ) print >> sys . stderr , '' class FileRevision : def __init__ ( self , path , rev , state , markseq ) : self . path = path self . rev = rev self . state = state self . markseq = markseq class ChangeSetKey : def __init__ ( self , branch , author , time , log , commitid , fuzzsec ) : self . branch = branch self . author = author self . min_time = time self . max_time = time self . commitid = commitid self . fuzzsec = fuzzsec self . revs = [ ] self . tags = [ ] self . log_hash = h = for c in log : h = * h + ord ( c ) self . log_hash = h def __cmp__ ( self , anon ) : if isinstance ( anon , ChangeSetKey ) : cid = cmp ( self . commitid , anon . commitid ) if cid == and self . commitid is not None : return ma = anon . min_time - self . max_time mi = self . min_time - anon . max_time ct = self . min_time - anon . min_time if ma > self . fuzzsec or mi > self . fuzzsec : return ct if cid != : return cid if ct == else ct c = cmp ( self . log_hash , anon . log_hash ) if c == : c = cmp ( self . branch , anon . branch ) if c == : c = cmp ( self . author , anon . author ) if c == : return return ct if ct != else c return - def merge ( self , anon ) : self . max_time = max ( self . max_time , anon . max_time ) self . min_time = min ( self . min_time , anon . min_time ) self . revs . extend ( anon . revs ) def __hash__ ( self ) : return hash ( self . branch + '' + self . author ) * + self . log_hash def put_file ( self , path , rev , state , markseq ) : self . revs . append ( FileRevision ( path , rev , state , markseq ) ) class CvsConv : def __init__ ( self , cvsroot , rcs , dumpfile , fuzzsec ) : self . cvsroot = cvsroot self . rcs = rcs self . changesets = dict ( ) self . dumpfile = dumpfile self . markseq = self . tags = dict ( ) self . fuzzsec = fuzzsec def walk ( self , module = None ) : p = [ self . cvsroot ] if module is not None : p . append ( module ) path = reduce ( os . path . join , p ) for root , dirs , files in os . walk ( path ) : for f in files : if not f [ - : ] == '' : continue self . parse_file ( root + os . sep + f ) for t , c in self . tags . items ( ) : c . tags . append ( t ) def parse_file ( self , path ) : rtags = dict ( ) rcsfile = rcsparse . rcsfile ( path ) path_related = path [ len ( self . cvsroot ) + : ] [ : - ] branches = { '' : '' , '' : '' } have_111 = False for k , v in rcsfile . symbols . items ( ) : r = v . split ( '' ) if len ( r ) == : branches [ v ] = '' elif len ( r ) >= and r [ - ] == '' : z = reduce ( lambda a , b : a + '' + b , r [ : - ] + r [ - : ] ) branches [ reduce ( lambda a , b : a + '' + b , r [ : - ] + r [ - : ] ) ] = k if len ( r ) == and branches [ r [ ] ] == '' : if not rtags . has_key ( v ) : rtags [ v ] = list ( ) rtags [ v ] . append ( k ) revs = sorted ( rcsfile . revs . items ( ) , lambda a , b : cmp ( a [ ] [ ] , b [ ] [ ] ) or cmp ( b [ ] [ ] , a [ ] [ ] ) ) p = '' novendor = False have_initial_revision = False last_vendor_status = None for k , v in revs : r = k . split ( '' ) if len ( r ) == and r [ ] == '' and r [ ] == '' and r [ ] == '' and r [ ] == '' : if have_initial_revision : continue if v [ ] == '' : continue last_vendor_status = v [ ] have_initial_revision = True elif len ( r ) == and r [ ] == '' and r [ ] == '' and r [ ] == '' : if novendor : continue last_vendor_status = v [ ] elif len ( r ) == : if r [ ] == '' and r [ ] == '' : if have_initial_revision : continue if v [ ] == '' : continue have_initial_revision = True elif r [ ] == '' and r [ ] != '' : novendor = True if last_vendor_status == '' and v [ ] == '' : last_vendor_status = None continue last_vendor_status = None else : continue if self . dumpfile : self . markseq = self . markseq + b = reduce ( lambda a , b : a + '' + b , r [ : - ] ) try : a = ChangeSetKey ( branches [ b ] , v [ ] , v [ ] , rcsfile . getlog ( v [ ] ) , v [ ] , self . fuzzsec ) except Exception as e : print >> sys . stderr , '' % ( path , v [ ] ) raise e a . put_file ( path , k , v [ ] , self . markseq ) while self . changesets . has_key ( a ) : c = self . changesets [ a ] del self . changesets [ a ] c . merge ( a ) a = c self . changesets [ a ] = a p = k if rtags . has_key ( k ) : for t in rtags [ k ] : if not self . tags . has_key ( t ) or self . tags [ t ] . max_time < a . max_time : self . tags [ t ] = a def node_path ( r , n , p ) : if r . endswith ( '' ) : r = r [ : - ] path = p [ : - ] p = path . split ( '' ) if len ( p ) > and p [ - ] == '' : path = string . join ( p [ : - ] , '' ) + '' + p [ - ] if path . startswith ( r ) : path = path [ len ( r ) + : ] if n is None or len ( n ) == : return path return '' % ( n , path ) def str_prop ( k , v ) : return '' % ( len ( k ) , k , len ( v ) , v ) def svn_time ( t ) : import time return time . strftime ( \"\" , time . gmtime ( t ) ) class SvnDumper : def __init__ ( self , root = '' ) : self . root = root if self . root != '' and self . root [ - ] == '' : self . root = self . root [ : - ] self . dirs = { } self . dirs [ self . root ] = { '' : } self . dump = False def exists ( self , path ) : d = os . path . dirname ( path ) if not self . dirs . has_key ( d ) : return False return self . dirs [ d ] . has_key ( os . path . basename ( path ) ) def add ( self , path ) : d = os . path . dirname ( path ) if not self . dirs . has_key ( d ) : self . mkdir ( d ) self . dirs [ d ] [ os . path . basename ( path ) ] = def remove ( self , path ) : d = os . path . dirname ( path ) if d == path : return del self . dirs [ d ] [ os . path . basename ( path ) ] self . rmdir ( d ) def rmdir ( self , path ) : if len ( self . dirs [ path ] ) > : return for r in self . dirs . keys ( ) : if r != path and r . startswith ( path + '' ) : return if self . dump : print '' % ( path ) print '' print '' print '' del self . dirs [ path ] d = os . path . dirname ( path ) if d == path or not self . dirs . has_key ( d ) : return self . rmdir ( d ) def mkdir ( self , path ) : if not self . dirs . has_key ( path ) : d = os . path . dirname ( path ) if d == path : return self . mkdir ( d ) if self . dump : print '' % ( path ) print '' print '' print '' print '' self . dirs [ path ] = { } def load ( self , repo_path ) : repo_path = core . svn_path_canonicalize ( repo_path ) repos_ptr = repos . open ( repo_path ) fs_ptr = repos . fs ( repos_ptr ) rev = fs . youngest_rev ( fs_ptr ) base_root = fs . revision_root ( fs_ptr , ) root = fs . revision_root ( fs_ptr , rev ) hist = fs . node_history ( root , self . root ) while hist is not None : hist = fs . history_prev ( hist , ) dummy , rev = fs . history_location ( hist ) d = fs . revision_prop ( fs_ptr , rev , core . SVN_PROP_REVISION_DATE ) author = fs . revision_prop ( fs_ptr , rev , core . SVN_PROP_REVISION_AUTHOR ) if author == '' : continue self . last_author = author self . last_date = core . svn_time_from_cstring ( d ) / self . last_rev = rev def authz_cb ( root , path , pool ) : return editor = SvnDumperEditor ( self ) e_ptr , e_baton = delta . make_editor ( editor ) repos . dir_delta ( base_root , '' , '' , root , self . root , e_ptr , e_baton , authz_cb , , , , ) break class SvnDumperEditor ( delta . Editor ) : def __init__ ( self , dumper ) : self . dumper = dumper def add_file ( self , path , * args ) : self . dumper . add ( self . dumper . root + '' + path ) def add_directory ( self , path , * args ) : self . dumper . mkdir ( self . dumper . root + '' + path ) class RcsKeywords : RCS_KW_AUTHOR = ( << ) RCS_KW_DATE = ( << ) RCS_KW_LOG = ( << ) RCS_KW_NAME = ( << ) RCS_KW_RCSFILE = ( << ) RCS_KW_REVISION = ( << ) RCS_KW_SOURCE = ( << ) RCS_KW_STATE = ( << ) RCS_KW_FULLPATH = ( << ) RCS_KW_MDOCDATE = ( << ) RCS_KW_LOCKER = ( << ) RCS_KW_ID = ( RCS_KW_RCSFILE | RCS_KW_REVISION | RCS_KW_DATE | RCS_KW_AUTHOR | RCS_KW_STATE ) RCS_KW_HEADER = ( RCS_KW_ID | RCS_KW_FULLPATH ) rcs_expkw = { \"\" : RCS_KW_AUTHOR , \"\" : RCS_KW_DATE , \"\" : RCS_KW_HEADER , \"\" : RCS_KW_ID , \"\" : RCS_KW_LOG , \"\" : RCS_KW_NAME , \"\" : RCS_KW_RCSFILE , \"\" : RCS_KW_REVISION , \"\" : RCS_KW_SOURCE , \"\" : RCS_KW_STATE , \"\" : RCS_KW_MDOCDATE , \"\" : RCS_KW_LOCKER } RCS_KWEXP_NONE = ( << ) RCS_KWEXP_NAME = ( << ) RCS_KWEXP_VAL = ( << ) RCS_KWEXP_LKR = ( << ) RCS_KWEXP_OLD = ( << ) RCS_KWEXP_ERR = ( << ) RCS_KWEXP_DEFAULT = ( RCS_KWEXP_NAME | RCS_KWEXP_VAL ) RCS_KWEXP_KVL = ( RCS_KWEXP_NAME | RCS_KWEXP_VAL | RCS_KWEXP_LKR ) def __init__ ( self ) : self . rerecomple ( ) def rerecomple ( self ) : pat = '' . join ( self . rcs_expkw . keys ( ) ) self . re_kw = re . compile ( r\"\" + pat + \"\" ) def add_id_keyword ( self , keyword ) : self . rcs_expkw [ keyword ] = self . RCS_KW_ID self . rerecomple ( ) def kflag_get ( self , flags ) : if flags is None : return self . RCS_KWEXP_DEFAULT fl = for fc in flags : if fc == '' : fl |= self . RCS_KWEXP_NAME elif fc == '' : fl |= self . RCS_KWEXP_VAL elif fc == '' : fl |= self . RCS_KWEXP_LKR elif fc == '' : if len ( flags ) != : fl |= self . RCS_KWEXP_ERR fl |= self . RCS_KWEXP_OLD elif fc == '' : if len ( flags ) != : fl |= self . RCS_KWEXP_ERR fl |= self . RCS_KWEXP_NONE else : fl |= self . RCS_KWEXP_ERR return fl def expand_keyword ( self , filename , r ) : rcs = rcsparse . rcsfile ( filename ) rev = rcs . revs [ r ] mode = self . kflag_get ( rcs . expand ) if ( mode & ( self . RCS_KWEXP_NONE | self . RCS_KWEXP_OLD ) ) != : return rcs . checkout ( rev [ ] ) s = logbuf = '' for line in rcs . checkout ( rev [ ] ) . split ( '' ) : while True : m = self . re_kw . match ( line ) if m is None : break if len ( line ) > m . end ( ) and line [ m . end ( ) ] == '' : dsign = m . end ( ) else : try : dsign = string . index ( line , '' , m . end ( ) ) if dsign < : break except : break prefix = line [ : m . start ( ) - ] line = line [ dsign + : ] s += prefix expbuf = '' if ( mode & self . RCS_KWEXP_NAME ) != : expbuf += '' expbuf += m . group ( ) if ( mode & self . RCS_KWEXP_VAL ) != : expbuf += '' if ( mode & self . RCS_KWEXP_VAL ) != : expkw = self . rcs_expkw [ m . group ( ) ] if ( expkw & self . RCS_KW_RCSFILE ) != : expbuf += filename if ( expkw & self . RCS_KW_FULLPATH ) != else os . path . basename ( filename ) expbuf += \"\" if ( expkw & self . RCS_KW_REVISION ) != : expbuf += rev [ ] expbuf += \"\" if ( expkw & self . RCS_KW_DATE ) != : expbuf += time . strftime ( \"\" , time . gmtime ( rev [ ] ) ) if ( expkw & self . RCS_KW_MDOCDATE ) != : d = time . gmtime ( rev [ ] ) expbuf += time . strftime ( \"\" if ( d . tm_mday < ) else \"\" , d ) if ( expkw & self . RCS_KW_AUTHOR ) != : expbuf += rev [ ] expbuf += \"\" if ( expkw & self . RCS_KW_STATE ) != : ", "answer": "expbuf += rev [ ]"}, {"prompt": " \"\"\"\"\"\" from pyrseas . testutils import DatabaseToMapTestCase from pyrseas . testutils import InputMapToSqlTestCase , fix_indent CREATE_COMPOSITE_STMT = \"\" CREATE_ENUM_STMT = \"\" CREATE_SHELL_STMT = \"\" CREATE_FUNC_IN = \"\" \"\" CREATE_FUNC_OUT = \"\" \"\" CREATE_TYPE_STMT = \"\" DROP_STMT = \"\" COMMENT_STMT = \"\" class CompositeToMapTestCase ( DatabaseToMapTestCase ) : \"\"\"\"\"\" def test_composite ( self ) : \"\" dbmap = self . to_map ( [ CREATE_COMPOSITE_STMT ] ) assert dbmap [ '' ] [ '' ] == { '' : [ { '' : { '' : '' } } , { '' : { '' : '' } } , { '' : { '' : '' } } ] } def test_dropped_attribute ( self ) : \"\" if self . db . version < : self . skipTest ( '' ) stmts = [ CREATE_COMPOSITE_STMT , \"\" ] dbmap = self . to_map ( stmts ) assert dbmap [ '' ] [ '' ] == { '' : [ { '' : { '' : '' } } , { '' : { '' : '' } } ] } class CompositeToSqlTestCase ( InputMapToSqlTestCase ) : \"\"\"\"\"\" def test_create_composite ( self ) : \"\" inmap = self . std_map ( ) inmap [ '' ] . update ( { '' : { '' : [ { '' : { '' : '' } } , { '' : { '' : '' } } , { '' : { '' : '' } } ] } } ) sql = self . to_sql ( inmap ) assert fix_indent ( sql [ ] ) == CREATE_COMPOSITE_STMT def test_drop_composite ( self ) : \"\" sql = self . to_sql ( self . std_map ( ) , [ CREATE_COMPOSITE_STMT ] ) assert sql == [ \"\" ] def test_rename_composite ( self ) : \"\" inmap = self . std_map ( ) inmap [ '' ] . update ( { '' : { '' : '' , '' : [ { '' : { '' : '' } } , { '' : { '' : '' } } , { '' : { '' : '' } } ] } } ) sql = self . to_sql ( inmap , [ CREATE_COMPOSITE_STMT ] ) assert sql == [ \"\" ] def test_add_attribute ( self ) : \"\" if self . db . version < : self . skipTest ( '' ) inmap = self . std_map ( ) inmap [ '' ] . update ( { '' : { '' : [ { '' : { '' : '' } } , { '' : { '' : '' } } , { '' : { '' : '' } } ] } } ) sql = self . to_sql ( inmap , [ \"\" ] ) assert fix_indent ( sql [ ] ) == \"\" def test_drop_attribute ( self ) : \"\" if self . db . version < : self . skipTest ( '' ) inmap = self . std_map ( ) inmap [ '' ] . update ( { '' : { '' : [ { '' : { '' : '' } } , { '' : { '' : '' } } ] } } ) sql = self . to_sql ( inmap , [ CREATE_COMPOSITE_STMT ] ) assert fix_indent ( sql [ ] ) == \"\" def test_drop_attribute_schema ( self ) : \"\" if self . db . version < : self . skipTest ( '' ) inmap = self . std_map ( ) inmap . update ( { '' : { '' : { '' : [ { '' : { '' : '' } } , { '' : { '' : '' } } ] } } } ) sql = self . to_sql ( inmap , [ \"\" , \"\" ] ) assert fix_indent ( sql [ ] ) == \"\" def test_rename_attribute ( self ) : \"\" if self . db . version < : ", "answer": "self . skipTest ( '' )"}, {"prompt": " from ... ext . six import string_types from . shader_object import ShaderObject class Expression ( ShaderObject ) : \"\"\"\"\"\" def definition ( self , names ) : return None class TextExpression ( Expression ) : \"\"\"\"\"\" def __init__ ( self , text ) : super ( TextExpression , self ) . __init__ ( ) if not isinstance ( text , string_types ) : raise TypeError ( \"\" ) self . _text = text def __repr__ ( self ) : return '' % ( self . text , id ( self ) ) def expression ( self , names = None ) : return self . _text @ property def text ( self ) : return self . _text @ text . setter def text ( self , t ) : self . _text = t self . changed ( ) def __eq__ ( self , a ) : if isinstance ( a , TextExpression ) : return a . _text == self . _text elif isinstance ( a , string_types ) : return a == self . _text else : return False def __hash__ ( self ) : return self . _text . __hash__ ( ) class FunctionCall ( Expression ) : \"\"\"\"\"\" def __init__ ( self , function , args ) : from . function import Function super ( FunctionCall , self ) . __init__ ( ) if not isinstance ( function , Function ) : raise TypeError ( '' ) sig_len = len ( function . args ) if len ( args ) != sig_len : raise TypeError ( '' % ( function . name , sig_len , len ( args ) ) ) sig = function . args self . _function = function self . _args = [ ShaderObject . create ( arg , ref = sig [ i ] [ ] ) for i , arg in enumerate ( args ) ] self . _add_dep ( function ) for arg in self . _args : ", "answer": "self . _add_dep ( arg )"}, {"prompt": " import collections import copy import datetime import itertools import logging import os import six from oslo_serialization import jsonutils from sqlalchemy import or_ from nailgun import consts from nailgun import errors as nailgun_errors from nailgun import notifier from nailgun import objects from nailgun . settings import settings from nailgun . consts import TASK_STATUSES from nailgun . db import db from nailgun . db . sqlalchemy . models import IPAddr from nailgun . db . sqlalchemy . models import Node from nailgun . db . sqlalchemy . models import Release from nailgun . extensions . network_manager import connectivity_check from nailgun . extensions . network_manager import utils as net_utils from nailgun . objects . plugin import ClusterPlugins from nailgun . task . helpers import TaskHelper from nailgun . utils import logs as logs_utils from nailgun . utils import reverse logger = logging . getLogger ( '' ) class NailgunReceiver ( object ) : @ classmethod def remove_nodes_resp ( cls , ** kwargs ) : logger . info ( \"\" % jsonutils . dumps ( kwargs ) ) task_uuid = kwargs . get ( '' ) nodes = kwargs . get ( '' ) or [ ] error_nodes = kwargs . get ( '' ) or [ ] inaccessible_nodes = kwargs . get ( '' ) or [ ] error_msg = kwargs . get ( '' ) status = kwargs . get ( '' ) progress = kwargs . get ( '' ) if status in [ consts . TASK_STATUSES . ready , consts . TASK_STATUSES . error ] : progress = task = objects . Task . get_by_uuid ( task_uuid , fail_if_not_found = True , lock_for_update = True ) if task . cluster_id is not None : objects . Cluster . get_by_uid ( task . cluster_id , fail_if_not_found = True , lock_for_update = True ) all_nodes = itertools . chain ( nodes , error_nodes , inaccessible_nodes ) all_nodes_ids = [ node [ '' ] if '' in node else node [ '' ] for node in all_nodes ] locked_nodes = objects . NodeCollection . order_by ( objects . NodeCollection . filter_by_list ( None , '' , all_nodes_ids , ) , '' ) objects . NodeCollection . lock_for_update ( locked_nodes ) . all ( ) def get_node_id ( n ) : return n . get ( '' , int ( n . get ( '' ) ) ) nodes_to_delete_ids = [ get_node_id ( n ) for n in nodes ] if len ( inaccessible_nodes ) > : inaccessible_node_ids = [ get_node_id ( n ) for n in inaccessible_nodes ] logger . warn ( u'' , inaccessible_nodes ) nodes_to_delete_ids . extend ( inaccessible_node_ids ) for node in objects . NodeCollection . filter_by_id_list ( None , nodes_to_delete_ids ) : logs_utils . delete_node_logs ( node ) objects . NodeCollection . delete_by_ids ( nodes_to_delete_ids ) for node in error_nodes : node_db = objects . Node . get_by_uid ( node [ '' ] ) if not node_db : logger . error ( u\"\" \"\" , str ( node ) ) else : node_db . pending_deletion = False node_db . status = '' db ( ) . add ( node_db ) node [ '' ] = node_db . name db ( ) . flush ( ) success_msg = u\"\" err_msg = u\"\" if nodes : success_msg = u\"\" . format ( len ( nodes ) ) notifier . notify ( \"\" , success_msg ) if error_nodes : err_msg = u\"\" . format ( len ( error_nodes ) , '' . join ( [ n . get ( '' ) or \"\" . format ( n [ '' ] ) for n in error_nodes ] ) ) notifier . notify ( \"\" , err_msg ) if not error_msg : error_msg = \"\" . join ( [ success_msg , err_msg ] ) data = { '' : status , '' : progress , '' : error_msg , } objects . Task . update ( task , data ) cls . _update_action_log_entry ( status , task . name , task_uuid , nodes ) @ classmethod def remove_cluster_resp ( cls , ** kwargs ) : logger . info ( \"\" % jsonutils . dumps ( kwargs ) ) task_uuid = kwargs . get ( '' ) cls . remove_nodes_resp ( ** kwargs ) task = objects . Task . get_by_uuid ( task_uuid , fail_if_not_found = True ) cluster = task . cluster if task . status in ( '' , ) : logger . debug ( \"\" ) cluster_name = cluster . name ips = db ( ) . query ( IPAddr ) . filter ( IPAddr . network . in_ ( [ n . id for n in cluster . network_groups ] ) ) for ip in ips : db ( ) . delete ( ip ) db ( ) . flush ( ) nm = objects . Cluster . get_network_manager ( cluster ) admin_nets = nm . get_admin_networks ( ) objects . Task . delete ( task ) for task_ in cluster . tasks : if task_ != task : objects . Transaction . delete ( task_ ) objects . Cluster . delete ( cluster ) if admin_nets != nm . get_admin_networks ( ) : from nailgun . task . manager import UpdateDnsmasqTaskManager UpdateDnsmasqTaskManager ( ) . execute ( ) notifier . notify ( \"\" , u\"\" % ( cluster_name ) ) elif task . status in ( '' , ) : cluster . status = '' db ( ) . add ( cluster ) db ( ) . flush ( ) if not task . message : task . message = \"\" . format ( cls . _generate_error_message ( task , error_types = ( '' , ) ) ) notifier . notify ( \"\" , task . message , cluster . id ) @ classmethod def remove_images_resp ( cls , ** kwargs ) : logger . info ( \"\" , jsonutils . dumps ( kwargs ) ) status = kwargs . get ( '' ) task_uuid = kwargs [ '' ] task = objects . Task . get_by_uuid ( task_uuid ) if status == consts . TASK_STATUSES . ready : logger . info ( \"\" ) elif status == consts . TASK_STATUSES . error : logger . error ( \"\" , task_uuid ) objects . Task . update ( task , { '' : status } ) @ classmethod def deploy_resp ( cls , ** kwargs ) : logger . info ( \"\" % jsonutils . dumps ( kwargs ) ) task_uuid = kwargs . get ( '' ) nodes = kwargs . get ( '' ) or [ ] message = kwargs . get ( '' ) status = kwargs . get ( '' ) progress = kwargs . get ( '' ) task = objects . Task . get_by_uuid ( task_uuid , fail_if_not_found = True ) objects . Cluster . get_by_uid ( task . cluster_id , fail_if_not_found = True , lock_for_update = True ) if not status : status = task . status nodes_by_id = { str ( n [ '' ] ) : n for n in nodes } master = nodes_by_id . pop ( consts . MASTER_NODE_UID , { } ) nodes_by_id . pop ( '' , { } ) if nodes_by_id : q_nodes = objects . NodeCollection . filter_by_id_list ( None , nodes_by_id , ) q_nodes = objects . NodeCollection . order_by ( q_nodes , '' ) db_nodes = objects . NodeCollection . lock_for_update ( q_nodes ) . all ( ) else : db_nodes = [ ] for node_db in db_nodes : node = nodes_by_id . pop ( node_db . uid ) update_fields = ( '' , '' , '' , '' , '' ) for param in update_fields : if param in node : logger . debug ( \"\" , node [ '' ] , param , node [ param ] ) setattr ( node_db , param , node [ param ] ) if param == '' and node . get ( '' ) == '' or node . get ( '' ) is False : node_db . progress = if node . get ( '' ) is False and not node_db . error_msg : node_db . error_msg = u\"\" notifier . notify ( consts . NOTIFICATION_TOPICS . error , u\"\" . format ( consts . TASK_NAMES . deploy , node_db . name , node_db . error_msg or \"\" ) , cluster_id = task . cluster_id , node_id = node [ '' ] , task_uuid = task_uuid ) if nodes_by_id : logger . warning ( \"\" , \"\" . join ( sorted ( nodes_by_id ) ) ) for node in nodes : if node . get ( '' ) and node . get ( '' ) : objects . DeploymentHistory . update_if_exist ( task . id , node [ '' ] , node [ '' ] , node [ '' ] , node . get ( '' ) ) db ( ) . flush ( ) if nodes and not progress : progress = TaskHelper . recalculate_deployment_task_progress ( task ) if master . get ( '' ) == consts . TASK_STATUSES . error : status = consts . TASK_STATUSES . error cls . _update_task_status ( task , status , progress , message , db_nodes ) cls . _update_action_log_entry ( status , task . name , task_uuid , nodes ) @ classmethod def provision_resp ( cls , ** kwargs ) : logger . info ( \"\" % jsonutils . dumps ( kwargs ) ) task_uuid = kwargs . get ( '' ) message = kwargs . get ( '' ) status = kwargs . get ( '' ) progress = kwargs . get ( '' ) nodes = kwargs . get ( '' , [ ] ) task = objects . Task . get_by_uuid ( task_uuid , fail_if_not_found = True , lock_for_update = True ) nodes_by_id = { str ( n [ '' ] ) : n for n in nodes } master = nodes_by_id . pop ( consts . MASTER_NODE_UID , { } ) if master . get ( '' ) == consts . TASK_STATUSES . error : status = consts . TASK_STATUSES . error progress = q_nodes = objects . NodeCollection . filter_by_id_list ( None , nodes_by_id ) q_nodes = objects . NodeCollection . order_by ( q_nodes , '' ) db_nodes = objects . NodeCollection . lock_for_update ( q_nodes ) . all ( ) for node_db in db_nodes : node = nodes_by_id . pop ( node_db . uid ) if node . get ( '' ) == consts . TASK_STATUSES . error : node_db . status = consts . TASK_STATUSES . error node_db . progress = node_db . error_type = consts . TASK_NAMES . provision node_db . error_msg = node . get ( '' , '' ) else : ", "answer": "node_db . status = node . get ( '' )"}, {"prompt": " \"\"\"\"\"\" from pyherc . data import level_size , blocks_los mult = [ [ , , , - , - , , , ] , [ , , - , , , - , , ] , ", "answer": "[ , , , , , - , - , ] ,"}, {"prompt": " \"\"\"\"\"\" import numpy as np from vispy . io import load_spatial_filters from vispy import gloo from vispy import app I = np . zeros ( ) . reshape ( ( , ) ) . astype ( np . float32 ) I [ : , : : ] = I [ : : , ] = I [ , ] = kernel , names = load_spatial_filters ( ) data = np . zeros ( , dtype = [ ( '' , np . float32 , ) , ( '' , np . float32 , ) ] ) data [ '' ] = np . array ( [ [ - , - ] , [ + , - ] , [ - , + ] , [ + , + ] ] ) data [ '' ] = np . array ( [ [ , ] , [ , ] , [ , ] , [ , ] ] ) VERT_SHADER = \"\"\"\"\"\" FRAG_SHADER = \"\"\"\"\"\" class Canvas ( app . Canvas ) : def __init__ ( self ) : app . Canvas . __init__ ( self , keys = '' , size = ( ( ) , ( ) ) ) self . program = gloo . Program ( VERT_SHADER , FRAG_SHADER % '' ) self . texture = gloo . Texture2D ( I , interpolation = '' ) self . kernel = gloo . Texture2D ( kernel , interpolation = '' ) self . program [ '' ] = self . texture self . names = names self . filter = self . title = '' % self . names [ self . filter ] self . program . bind ( gloo . VertexBuffer ( data ) ) self . context . set_clear_color ( '' ) self . context . set_viewport ( , , , ) ", "answer": "self . show ( )"}, {"prompt": " from django . utils . translation import pgettext_lazy from django . utils . translation import ugettext_lazy as _ ", "answer": "from horizon import tables"}, {"prompt": " import glob import importlib import mimetypes import os from time import sleep from bson import ObjectId from mako . lookup import TemplateLookup import markupsafe import requests from modularodm import fields from modularodm import Q from framework . auth import Auth from framework . auth . decorators import must_be_logged_in from framework . exceptions import ( PermissionsError , HTTPError , ) from framework . mongo import StoredObject from framework . routing import process_rules from website import settings from website . addons . base import serializer , logger from website . project . model import Node , User from website . util import waterbutler_url_for from website . oauth . signals import oauth_complete NODE_SETTINGS_TEMPLATE_DEFAULT = os . path . join ( settings . TEMPLATES_PATH , '' , '' , '' , ) USER_SETTINGS_TEMPLATE_DEFAULT = os . path . join ( settings . TEMPLATES_PATH , '' , '' , ) lookup = TemplateLookup ( directories = [ settings . TEMPLATES_PATH ] , default_filters = [ '' , '' , '' , ] , imports = [ '' , ] ) def _is_image ( filename ) : mtype , _ = mimetypes . guess_type ( filename ) return mtype and mtype . startswith ( '' ) class AddonConfig ( object ) : def __init__ ( self , short_name , full_name , owners , categories , added_default = None , added_mandatory = None , node_settings_model = None , user_settings_model = None , include_js = None , include_css = None , widget_help = None , views = None , configs = None , models = None , has_hgrid_files = False , get_hgrid_data = None , max_file_size = None , high_max_file_size = None , accept_extensions = True , node_settings_template = None , user_settings_template = None , ** kwargs ) : self . models = models self . settings_models = { } if node_settings_model : node_settings_model . config = self self . settings_models [ '' ] = node_settings_model if user_settings_model : user_settings_model . config = self self . settings_models [ '' ] = user_settings_model self . short_name = short_name self . full_name = full_name self . owners = owners self . categories = categories self . added_default = added_default or [ ] self . added_mandatory = added_mandatory or [ ] if set ( self . added_mandatory ) . difference ( self . added_default ) : raise ValueError ( '' ) self . include_js = self . _include_to_static ( include_js or { } ) self . include_css = self . _include_to_static ( include_css or { } ) self . widget_help = widget_help self . views = views or [ ] self . configs = configs or [ ] self . has_hgrid_files = has_hgrid_files self . get_hgrid_data = get_hgrid_data self . max_file_size = max_file_size self . high_max_file_size = high_max_file_size self . accept_extensions = accept_extensions self . user_settings_template = user_settings_template if not user_settings_template or not os . path . exists ( os . path . dirname ( user_settings_template ) ) : self . user_settings_template = USER_SETTINGS_TEMPLATE_DEFAULT self . node_settings_template = node_settings_template if not node_settings_template or not os . path . exists ( os . path . dirname ( node_settings_template ) ) : self . node_settings_template = NODE_SETTINGS_TEMPLATE_DEFAULT template_dirs = list ( set ( [ path for path in [ os . path . dirname ( self . user_settings_template ) , os . path . dirname ( self . node_settings_template ) , settings . TEMPLATES_PATH ] if os . path . exists ( path ) ] ) ) if template_dirs : self . template_lookup = TemplateLookup ( directories = template_dirs , default_filters = [ '' , '' , '' , ] , imports = [ '' , ] ) else : self . template_lookup = None def _static_url ( self , filename ) : \"\"\"\"\"\" if filename . startswith ( '' ) : return filename return '' . format ( addon = self . short_name , filename = filename , ) def _include_to_static ( self , include ) : \"\"\"\"\"\" return { key : [ self . _static_url ( item ) for item in value ] for key , value in include . iteritems ( ) } @ property def icon ( self ) : try : return self . _icon except : static_path = os . path . join ( '' , '' , self . short_name , '' ) static_files = glob . glob ( os . path . join ( static_path , '' ) ) image_files = [ os . path . split ( filename ) [ ] for filename in static_files if _is_image ( filename ) ] if len ( image_files ) == : self . _icon = image_files [ ] else : self . _icon = None return self . _icon @ property def icon_url ( self ) : return self . _static_url ( self . icon ) if self . icon else None def to_json ( self ) : return { '' : self . short_name , '' : self . full_name , '' : self . short_name in settings . ADDON_CAPABILITIES , '' : settings . ADDON_CAPABILITIES . get ( self . short_name ) , '' : self . icon_url , '' : '' in self . views , '' : '' in self . views , } @ property def path ( self ) : return os . path . join ( settings . BASE_PATH , self . short_name ) class AddonSettingsBase ( StoredObject ) : _id = fields . StringField ( default = lambda : str ( ObjectId ( ) ) ) deleted = fields . BooleanField ( default = False ) _meta = { '' : True , } def delete ( self , save = True ) : self . deleted = True self . on_delete ( ) if save : self . save ( ) def undelete ( self , save = True ) : self . deleted = False self . on_add ( ) if save : self . save ( ) def to_json ( self , user ) : return { '' : self . config . short_name , '' : self . config . full_name , } def on_add ( self ) : \"\"\"\"\"\" pass def on_delete ( self ) : \"\"\"\"\"\" pass class AddonUserSettingsBase ( AddonSettingsBase ) : owner = fields . ForeignField ( '' , index = True ) _meta = { '' : True , } def __repr__ ( self ) : if self . owner : return '' . format ( cls = self . __class__ . __name__ , uid = self . owner . _id ) else : return '' . format ( cls = self . __class__ . __name__ ) @ property def public_id ( self ) : return None @ property def has_auth ( self ) : \"\"\"\"\"\" return False @ property def nodes_authorized ( self ) : \"\"\"\"\"\" try : schema = self . config . settings_models [ '' ] except KeyError : return [ ] return [ node_addon . owner for node_addon in schema . find ( Q ( '' , '' , self ) ) if node_addon . owner and not node_addon . owner . is_deleted ] @ property def can_be_merged ( self ) : return hasattr ( self , '' ) def to_json ( self , user ) : ret = super ( AddonUserSettingsBase , self ) . to_json ( user ) ret [ '' ] = self . has_auth ret . update ( { '' : [ { '' : node . _id , '' : node . url , '' : node . title , '' : node . is_registration , '' : node . api_url } for node in self . nodes_authorized ] } ) return ret @ oauth_complete . connect def oauth_complete ( provider , account , user ) : if not user or not account : return user . add_addon ( account . provider ) user . save ( ) class AddonOAuthUserSettingsBase ( AddonUserSettingsBase ) : _meta = { '' : True , } oauth_grants = fields . DictionaryField ( ) oauth_provider = None serializer = serializer . OAuthAddonSerializer @ property def has_auth ( self ) : return bool ( self . external_accounts ) @ property def external_accounts ( self ) : \"\"\"\"\"\" return [ x for x in self . owner . external_accounts if x . provider == self . oauth_provider . short_name ] def delete ( self , save = True ) : for account in self . external_accounts : self . revoke_oauth_access ( account , save = False ) super ( AddonOAuthUserSettingsBase , self ) . delete ( save = save ) def grant_oauth_access ( self , node , external_account , metadata = None ) : \"\"\"\"\"\" if external_account not in self . owner . external_accounts : raise PermissionsError ( ) metadata = metadata or { } if node . _id not in self . oauth_grants : self . oauth_grants [ node . _id ] = { } if external_account . _id not in self . oauth_grants [ node . _id ] : self . oauth_grants [ node . _id ] [ external_account . _id ] = { } for key , value in metadata . iteritems ( ) : self . oauth_grants [ node . _id ] [ external_account . _id ] [ key ] = value self . save ( ) @ must_be_logged_in def revoke_oauth_access ( self , external_account , auth , save = True ) : \"\"\"\"\"\" for node in self . get_nodes_with_oauth_grants ( external_account ) : try : addon_settings = node . get_addon ( external_account . provider , deleted = True ) except AttributeError : pass else : addon_settings . deauthorize ( auth = auth ) if User . find ( Q ( '' , '' , external_account . _id ) ) . count ( ) == : self . revoke_remote_oauth_access ( external_account ) for key in self . oauth_grants : self . oauth_grants [ key ] . pop ( external_account . _id , None ) if save : self . save ( ) def revoke_remote_oauth_access ( self , external_account ) : \"\"\"\"\"\" pass def verify_oauth_access ( self , node , external_account , metadata = None ) : \"\"\"\"\"\" metadata = metadata or { } try : grants = self . oauth_grants [ node . _id ] [ external_account . _id ] except KeyError : return False for key , value in metadata . iteritems ( ) : if key not in grants or grants [ key ] != value : return False return True def get_nodes_with_oauth_grants ( self , external_account ) : for node_id , grants in self . oauth_grants . iteritems ( ) : node = Node . load ( node_id ) if external_account . _id in grants . keys ( ) and not node . is_deleted : yield node def get_attached_nodes ( self , external_account ) : for node in self . get_nodes_with_oauth_grants ( external_account ) : if node is None : continue node_settings = node . get_addon ( self . oauth_provider . short_name ) if node_settings is None : continue if node_settings . external_account == external_account : yield node def merge ( self , user_settings ) : \"\"\"\"\"\" if user_settings . __class__ is not self . __class__ : raise TypeError ( '' ) for node_id , data in user_settings . oauth_grants . iteritems ( ) : if node_id not in self . oauth_grants : self . oauth_grants [ node_id ] = data else : node_grants = user_settings . oauth_grants [ node_id ] . iteritems ( ) for ext_acct , meta in node_grants : if ext_acct not in self . oauth_grants [ node_id ] : self . oauth_grants [ node_id ] [ ext_acct ] = meta else : for k , v in meta : if k not in self . oauth_grants [ node_id ] [ ext_acct ] : self . oauth_grants [ node_id ] [ ext_acct ] [ k ] = v user_settings . oauth_grants = { } user_settings . save ( ) try : config = settings . ADDONS_AVAILABLE_DICT [ self . oauth_provider . short_name ] Model = config . settings_models [ '' ] except KeyError : pass else : connected = Model . find ( Q ( '' , '' , user_settings ) ) for node_settings in connected : node_settings . user_settings = self node_settings . save ( ) self . save ( ) def to_json ( self , user ) : ret = super ( AddonOAuthUserSettingsBase , self ) . to_json ( user ) ret [ '' ] = self . serializer ( user_settings = self ) . serialized_accounts return ret def on_delete ( self ) : \"\"\"\"\"\" super ( AddonOAuthUserSettingsBase , self ) . on_delete ( ) nodes = [ Node . load ( node_id ) for node_id in self . oauth_grants . keys ( ) ] for node in nodes : node_addon = node . get_addon ( self . oauth_provider . short_name ) if node_addon and node_addon . user_settings == self : node_addon . clear_auth ( ) class AddonNodeSettingsBase ( AddonSettingsBase ) : owner = fields . ForeignField ( '' , index = True ) _meta = { '' : True , } @ property def complete ( self ) : \"\"\"\"\"\" raise NotImplementedError ( ) @ property def configured ( self ) : \"\"\"\"\"\" return self . complete @ property def has_auth ( self ) : \"\"\"\"\"\" return False def to_json ( self , user ) : ret = super ( AddonNodeSettingsBase , self ) . to_json ( user ) ret . update ( { '' : { '' : self . owner . get_permissions ( user ) } , '' : { '' : self . owner . _id , '' : self . owner . api_url , '' : self . owner . url , '' : self . owner . is_registration , } , '' : os . path . basename ( self . config . node_settings_template ) , } ) return ret def render_config_error ( self , data ) : \"\"\"\"\"\" template = lookup . get_template ( '' ) return template . get_def ( '' ) . render ( title = self . config . full_name , name = self . config . short_name , ** data ) def before_page_load ( self , node , user ) : \"\"\"\"\"\" pass def before_remove_contributor ( self , node , removed ) : \"\"\"\"\"\" pass def after_remove_contributor ( self , node , removed , auth = None ) : \"\"\"\"\"\" pass def before_make_public ( self , node ) : \"\"\"\"\"\" pass def before_make_private ( self , node ) : \"\"\"\"\"\" pass def after_set_privacy ( self , node , permissions ) : \"\"\"\"\"\" pass def before_fork ( self , node , user ) : \"\"\"\"\"\" if hasattr ( self , \"\" ) : if self . user_settings is None : return ( u'' u'' u'' ) . format ( addon = self . config . full_name , category = node . project_or_component , ) elif self . user_settings and self . user_settings . owner == user : return ( u'' u'' u'' ) . format ( addon = self . config . full_name , category = node . project_or_component , ) else : return ( u'' u'' u'' ) . format ( addon = self . config . full_name , category = node . project_or_component , ) def after_fork ( self , node , fork , user , save = True ) : \"\"\"\"\"\" clone = self . clone ( ) clone . owner = fork if save : clone . save ( ) return clone , None def before_register ( self , node , user ) : \"\"\"\"\"\" pass def after_register ( self , node , registration , user , save = True ) : \"\"\"\"\"\" return None , None def after_delete ( self , node , user ) : \"\"\"\"\"\" pass class GenericRootNode ( object ) : path = '' name = '' class StorageAddonBase ( object ) : \"\"\"\"\"\" root_node = GenericRootNode ( ) @ property def archive_folder_name ( self ) : name = \"\" . format ( addon = self . config . full_name ) folder_name = getattr ( self , '' , '' ) . lstrip ( '' ) . strip ( ) if folder_name : name = name + \"\" . format ( folder = folder_name ) return name def _get_fileobj_child_metadata ( self , filenode , user , cookie = None , version = None ) : kwargs = dict ( provider = self . config . short_name , path = filenode . get ( '' , '' ) , node = self . owner , user = user , view_only = True , ) if cookie : kwargs [ '' ] = cookie if version : kwargs [ '' ] = version metadata_url = waterbutler_url_for ( '' , ** kwargs ) res = requests . get ( metadata_url ) if res . status_code != : raise HTTPError ( res . status_code , data = { '' : res . json ( ) , } ) sleep ( / ) return res . json ( ) . get ( '' , [ ] ) def _get_file_tree ( self , filenode = None , user = None , cookie = None , version = None ) : \"\"\"\"\"\" filenode = filenode or { '' : '' , '' : '' , '' : self . root_node . name , } if filenode . get ( '' ) == '' : return filenode elif '' in filenode : return filenode kwargs = { '' : version , '' : cookie , } filenode [ '' ] = [ self . _get_file_tree ( child , user , cookie = cookie ) for child in self . _get_fileobj_child_metadata ( filenode , user , ** kwargs ) ] return filenode class AddonOAuthNodeSettingsBase ( AddonNodeSettingsBase ) : _meta = { '' : True , } ", "answer": "external_account = fields . ForeignField ( '' )"}, {"prompt": " \"\"\"\"\"\" from exabgp . protocol . family import AFI from exabgp . protocol . family import SAFI from exabgp . bgp . message . open . capability . capability import Capability from exabgp . bgp . message . open . capability . addpath import AddPath from exabgp . bgp . message . open . capability . asn4 import ASN4 from exabgp . bgp . message . open . capability . graceful import Graceful from exabgp . bgp . message . open . capability . mp import MultiProtocol from exabgp . bgp . message . open . capability . ms import MultiSession from exabgp . bgp . message . open . capability . operational import Operational from exabgp . bgp . message . open . capability . refresh import RouteRefresh from exabgp . bgp . message . open . capability . refresh import EnhancedRouteRefresh from exabgp . bgp . message . open . capability . hostname import HostName from exabgp . bgp . message . notification import Notify class Parameter ( int ) : AUTHENTIFICATION_INFORMATION = CAPABILITIES = def __str__ ( self ) : if self == : return \"\" if self == : return \"\" return '' class Capabilities ( dict ) : def announced ( self , capability ) : return capability in self def __str__ ( self ) : r = [ ] for key in sorted ( self . keys ( ) ) : r . append ( str ( self [ key ] ) ) return '' . join ( r ) def _protocol ( self , neighbor ) : families = neighbor . families ( ) mp = MultiProtocol ( ) mp . extend ( families ) self [ Capability . CODE . MULTIPROTOCOL ] = mp def _asn4 ( self , neighbor ) : if not neighbor . asn4 : return self [ Capability . CODE . FOUR_BYTES_ASN ] = ASN4 ( neighbor . local_as ) def _addpath ( self , neighbor ) : if not neighbor . add_path : return families = neighbor . families ( ) ap_families = [ ] if ( AFI ( AFI . ipv4 ) , SAFI ( SAFI . unicast ) ) in families : ap_families . append ( ( AFI ( AFI . ipv4 ) , SAFI ( SAFI . unicast ) ) ) if ( AFI ( AFI . ipv6 ) , SAFI ( SAFI . unicast ) ) in families : ap_families . append ( ( AFI ( AFI . ipv6 ) , SAFI ( SAFI . unicast ) ) ) if ( AFI ( AFI . ipv4 ) , SAFI ( SAFI . nlri_mpls ) ) in families : ap_families . append ( ( AFI ( AFI . ipv4 ) , SAFI ( SAFI . nlri_mpls ) ) ) if ( AFI ( AFI . ipv6 ) , SAFI ( SAFI . unicast ) ) in families : ap_families . append ( ( AFI ( AFI . ipv6 ) , SAFI ( SAFI . unicast ) ) ) self [ Capability . CODE . ADD_PATH ] = AddPath ( ap_families , neighbor . add_path ) def _graceful ( self , neighbor , restarted ) : if not neighbor . graceful_restart : return self [ Capability . CODE . GRACEFUL_RESTART ] = Graceful ( ) . set ( Graceful . RESTART_STATE if restarted else , neighbor . graceful_restart , [ ( afi , safi , Graceful . FORWARDING_STATE ) for ( afi , safi ) in neighbor . families ( ) ] ) def _refresh ( self , neighbor ) : if not neighbor . route_refresh : return self [ Capability . CODE . ROUTE_REFRESH ] = RouteRefresh ( ) self [ Capability . CODE . ENHANCED_ROUTE_REFRESH ] = EnhancedRouteRefresh ( ) def _hostname ( self , neighbor ) : self [ Capability . CODE . HOSTNAME ] = HostName ( neighbor . host_name , neighbor . domain_name ) def _operational ( self , neighbor ) : if not neighbor . operational : return ", "answer": "self [ Capability . CODE . OPERATIONAL ] = Operational ( )"}, {"prompt": " from sqlalchemy import * from migrate import * from raggregate . guid_recipe import GUID ", "answer": "def upgrade ( migrate_engine ) :"}, {"prompt": " import sys from soccermetrics . rest import SoccermetricsRestClient if __name__ == \"\" : client = SoccermetricsRestClient ( ) if len ( sys . argv ) != : sys . stderr . write ( \"\" % sys . argv [ ] ) raise SystemExit ( ) matchday_start = int ( sys . argv [ ] ) matchday_end = int ( sys . argv [ ] ) for day in range ( matchday_start , matchday_end + ) : matches = client . club . information . get ( matchday = day , sort = '' ) . all ( ) for match in matches : print \"\" % ( match . matchday , match . matchDate , match . kickoffTime , match . homeTeamName , ", "answer": "match . awayTeamName , match . venueName , match . refereeName )"}, {"prompt": " \"\"\"\"\"\" from __future__ import unicode_literals import json import logging from datetime import date , timedelta import six from scrapi import requests from scrapi import settings from scrapi . base import JSONHarvester from scrapi . linter . document import RawDocument from scrapi . base . helpers import build_properties , datetime_formatter logger = logging . getLogger ( __name__ ) def process_NSF_contributors ( firstname , lastname , awardeename ) : return [ { '' : '' . format ( firstname , lastname ) , '' : firstname , '' : lastname , } , { '' : awardeename } ] def process_nsf_uris ( awd_id ) : nsf_url = '' . format ( awd_id ) return { '' : nsf_url , '' : [ nsf_url ] } def process_sponsorships ( agency , awd_id , title ) : return [ { '' : { '' : agency } , '' : { '' : '' . format ( awd_id ) , '' : title } } ] class NSFAwards ( JSONHarvester ) : short_name = '' long_name = '' url = '' URL = '' schema = { '' : '' , '' : ( '' , '' , '' , process_NSF_contributors ) , ", "answer": "'' : ( '' , datetime_formatter ) ,"}, {"prompt": " from google . appengine . ext import db class NamedStat ( db . Model ) : name = db . StringProperty ( ) value = db . FloatProperty ( ) @ staticmethod def get_stat ( name ) : stats = NamedStat . all ( ) . filter ( \"\" , name ) . get ( ) if stats is None : stats = NamedStat ( name = name , value = ) try : stats . put ( ) except db . TimeoutException : stats . put ( ) return stats @ staticmethod def get_value ( name ) : return NamedStat . get_stat ( name ) . value @ staticmethod def set_value ( name , value ) : stats = NamedStat . get_stat ( name ) stats . value = value stats . put ( ) @ staticmethod ", "answer": "def increment ( name ) :"}, {"prompt": " \"\"\"\"\"\" import ssl from social . backends . oauth import BaseOAuth2 class AmazonOAuth2 ( BaseOAuth2 ) : name = '' ID_KEY = '' AUTHORIZATION_URL = '' ACCESS_TOKEN_URL = '' DEFAULT_SCOPE = [ '' ] REDIRECT_STATE = False ACCESS_TOKEN_METHOD = '' SSL_PROTOCOL = ssl . PROTOCOL_TLSv1 ", "answer": "EXTRA_DATA = ["}, {"prompt": " from betamax import Betamax from tests . integration . helper import IntegrationHelper ", "answer": "class TestUnicode ( IntegrationHelper ) :"}, {"prompt": " import urwid from gertty import keymap from gertty import mywid from gertty . view . diff import BaseDiffComment , BaseDiffCommentEdit , BaseDiffLine from gertty . view . diff import BaseFileHeader , BaseFileReminder , BaseDiffView LN_COL_WIDTH = class SideDiffCommentEdit ( BaseDiffCommentEdit ) : def __init__ ( self , app , context , old_key = None , new_key = None , old = u'' , new = u'' ) : super ( SideDiffCommentEdit , self ) . __init__ ( [ ] ) self . app = app self . context = context self . old_key = old_key self . new_key = new_key self . old = mywid . MyEdit ( edit_text = old , multiline = True , ring = app . ring ) self . new = mywid . MyEdit ( edit_text = new , multiline = True , ring = app . ring ) self . contents . append ( ( urwid . Text ( u'' ) , ( '' , LN_COL_WIDTH , False ) ) ) if context . old_file_key and ( context . old_ln is not None or context . header ) : self . contents . append ( ( urwid . AttrMap ( self . old , '' ) , ( '' , , False ) ) ) else : self . contents . append ( ( urwid . Text ( u'' ) , ( '' , , False ) ) ) self . contents . append ( ( urwid . Text ( u'' ) , ( '' , LN_COL_WIDTH , False ) ) ) if context . new_file_key and ( context . new_ln is not None or context . header ) : self . contents . append ( ( urwid . AttrMap ( self . new , '' ) , ( '' , , False ) ) ) new_editable = True else : self . contents . append ( ( urwid . Text ( u'' ) , ( '' , , False ) ) ) new_editable = False if new_editable : self . focus_position = else : self . focus_position = def keypress ( self , size , key ) : if not self . app . input_buffer : key = super ( SideDiffCommentEdit , self ) . keypress ( size , key ) keys = self . app . input_buffer + [ key ] commands = self . app . config . keymap . getCommands ( keys ) if ( ( keymap . NEXT_SELECTABLE in commands ) or ( keymap . PREV_SELECTABLE in commands ) ) : if ( ( self . context . old_ln is not None and self . context . new_ln is not None ) or self . context . header ) : ", "answer": "if self . focus_position == :"}, {"prompt": " from distribute_setup import use_setuptools use_setuptools ( ) from setuptools import setup import repositories try : long_description = open ( '' ) . read ( ) except IOError : long_description = '' ", "answer": "setup ( name = '' ,"}, {"prompt": " import os import py from pypy . jit . tl . test import jitcrashers path = os . path . join ( os . path . dirname ( __file__ ) , \"\" , \"\" ) JIT_EXECUTABLE = py . path . local ( path ) del path CRASH_FILE = os . path . abspath ( jitcrashers . __file__ . rstrip ( \"\" ) ) if not JIT_EXECUTABLE . check ( ) : ", "answer": "py . test . skip ( \"\" )"}, {"prompt": " \"\"\"\"\"\" import os BASE_DIR = os . path . dirname ( os . path . dirname ( os . path . abspath ( __file__ ) ) ) SECRET_KEY = '' DEBUG = True ALLOWED_HOSTS = [ ] INSTALLED_APPS = [ '' , '' , '' , '' , '' , '' , '' , ] MIDDLEWARE_CLASSES = [ '' , '' , '' , '' , '' , '' , '' , '' , ] ROOT_URLCONF = '' TEMPLATES = [ { '' : '' , '' : [ ] , '' : True , '' : { '' : [ '' , '' , '' , '' , ] , } , } , ] WSGI_APPLICATION = '' DATABASES = { '' : { '' : '' , '' : os . path . join ( BASE_DIR , '' ) , } } AUTH_PASSWORD_VALIDATORS = [ { '' : '' , } , { ", "answer": "'' : '' ,"}, {"prompt": " import vcr import mock import pytest from scrapi import requests from scrapi . base import helpers @ pytest . fixture ( autouse = True ) def mock_maybe_load_response ( monkeypatch ) : mock_mlr = mock . Mock ( ) mock_mlr . return_value = None mock_save = lambda x : x monkeypatch . setattr ( requests , '' , mock_mlr ) monkeypatch . setattr ( requests . HarvesterResponse , '' , mock_save ) class TestHelpers ( object ) : def test_format_one_tag ( self ) : single_tag = '' single_output = helpers . format_tags ( single_tag ) assert single_output == [ '' ] assert isinstance ( single_output , list ) def test_format_many_tags ( self ) : many_tags = [ '' , '' , '' ] many_output = helpers . format_tags ( many_tags ) assert set ( many_output ) == set ( [ '' , '' , '' ] ) def test_format_sep_tags ( self ) : sep_tags = [ '' , '' ] sep_output = helpers . format_tags ( sep_tags , sep = '' ) assert set ( sep_output ) == set ( [ '' , '' , '' ] ) def test_extract_dois ( self ) : identifiers = [ '' , '' , '' ] valid_dois = helpers . oai_extract_dois ( identifiers ) assert valid_dois == [ '' , '' , '' ] def oai_process_uris ( self ) : identifiers = [ '' ] with pytest . raises ( ValueError ) : helpers . oai_extract_url ( identifiers ) def test_extract_uris ( self ) : identifiers = [ '' , '' , '' , '' , '' , '' ] uri_dict = helpers . oai_process_uris ( identifiers ) assert uri_dict == { '' : '' , '' : [ '' , '' , '' , '' ] , '' : [ '' , '' ] } def test_extract_uris_use_doi ( self ) : identifiers = [ '' , '' , '' , '' , '' , '' ] uri_dict = helpers . oai_process_uris ( identifiers , use_doi = True ) assert uri_dict == { '' : '' , '' : [ '' , '' , '' , '' ] , '' : [ '' , '' ] } def test_process_contributors ( self ) : args = [ '' , '' , '' ] response = helpers . oai_process_contributors ( args ) assert isinstance ( response , list ) @ vcr . use_cassette ( '' ) def test_oai_get_records_and_token ( self ) : url = '' force = False verify = True throttle = namespaces = { '' : '' , '' : '' , '' : '' , } records , token = helpers . oai_get_records_and_token ( url , throttle , force , namespaces , verify ) assert records assert token assert len ( records ) == def test_extract_doi_from_text ( self ) : text = [ \"\"\"\"\"\" ] extracted_doi = helpers . extract_doi_from_text ( text ) assert extracted_doi == '' def test_gather_identifiers ( self ) : identifiers = [ [ '' , '' ] , '' , '' , [ '' , '' ] ] gathered = helpers . gather_identifiers ( identifiers ) assert gathered == [ '' , '' , '' , '' , '' , '' ] def test_gather_object_uris ( self ) : identifiers = [ '' , '' , '' , '' , ", "answer": "'' ,"}, {"prompt": " import os , shutil , re , sys , errno import difflib , pprint , logging import xml . parsers . expat from xml . dom . minidom import parseString if sys . version_info [ ] >= : from io import StringIO else : from cStringIO import StringIO import svntest from svntest import main , verify , tree , wc from svntest import Failure logger = logging . getLogger ( ) def _log_tree_state ( msg , actual , subtree = \"\" ) : if subtree : subtree += os . sep o = StringIO ( ) o . write ( msg + '' ) tree . dump_tree_script ( actual , subtree , stream = o ) logger . warn ( o . getvalue ( ) ) o . close ( ) def no_sleep_for_timestamps ( ) : os . environ [ '' ] = '' def do_sleep_for_timestamps ( ) : os . environ [ '' ] = '' def no_relocate_validation ( ) : os . environ [ '' ] = '' def do_relocate_validation ( ) : os . environ [ '' ] = '' def setup_pristine_greek_repository ( ) : \"\"\"\"\"\" if not os . path . exists ( main . general_wc_dir ) : os . makedirs ( main . general_wc_dir ) if not os . path . exists ( main . general_repo_dir ) : os . makedirs ( main . general_repo_dir ) if not os . path . exists ( main . pristine_greek_repos_dir ) : main . create_repos ( main . pristine_greek_repos_dir ) if main . is_ra_type_dav ( ) : authz_file = os . path . join ( main . work_dir , \"\" ) main . file_write ( authz_file , \"\" ) main . greek_state . write_to_disk ( main . greek_dump_dir ) exit_code , output , errput = main . run_svn ( None , '' , '' , '' , main . greek_dump_dir , main . pristine_greek_repos_url ) if len ( errput ) : display_lines ( \"\" , '' , None , errput ) sys . exit ( ) lastline = output . pop ( ) . strip ( ) match = re . search ( \"\" , lastline ) if not match : logger . error ( \"\" ) logger . error ( \"\" ) logger . error ( lastline ) sys . exit ( ) output_tree = wc . State . from_commit ( output ) expected_output_tree = main . greek_state . copy ( main . greek_dump_dir ) expected_output_tree . tweak ( verb = '' , contents = None ) try : expected_output_tree . compare_and_display ( '' , output_tree ) except tree . SVNTreeUnequal : verify . display_trees ( \"\" , \"\" , expected_output_tree . old_tree ( ) , output_tree . old_tree ( ) ) sys . exit ( ) error_msg = \"\" create_failing_hook ( main . pristine_greek_repos_dir , '' , error_msg ) create_failing_hook ( main . pristine_greek_repos_dir , '' , error_msg ) create_failing_hook ( main . pristine_greek_repos_dir , '' , error_msg ) def guarantee_empty_repository ( path ) : \"\"\"\"\"\" if path == main . pristine_greek_repos_dir : logger . error ( \"\" ) sys . exit ( ) main . safe_rmtree ( path ) main . create_repos ( path ) def guarantee_greek_repository ( path , minor_version ) : \"\"\"\"\"\" if path == main . pristine_greek_repos_dir : logger . error ( \"\" ) sys . exit ( ) main . safe_rmtree ( path ) if main . copy_repos ( main . pristine_greek_repos_dir , path , , , minor_version ) : logger . error ( \"\" ) sys . exit ( ) main . chmod_tree ( path , , ) def run_and_verify_atomic_ra_revprop_change ( message , expected_stdout , expected_stderr , expected_exit , url , revision , propname , old_propval , propval , want_error ) : \"\"\"\"\"\" KEY_OLD_PROPVAL = \"\" KEY_NEW_PROPVAL = \"\" def skel_make_atom ( word ) : return \"\" % ( len ( word ) , word ) def make_proplist_skel_part ( nick , val ) : if val is None : return \"\" else : return \"\" % ( skel_make_atom ( nick ) , skel_make_atom ( val ) ) skel = \"\" % ( make_proplist_skel_part ( KEY_OLD_PROPVAL , old_propval ) , make_proplist_skel_part ( KEY_NEW_PROPVAL , propval ) ) exit_code , out , err = main . run_atomic_ra_revprop_change ( url , revision , propname , skel , want_error ) verify . verify_outputs ( \"\" , out , err , expected_stdout , expected_stderr ) verify . verify_exit_code ( message , exit_code , expected_exit ) return exit_code , out , err def run_and_verify_svnlook ( message , expected_stdout , expected_stderr , * varargs ) : \"\"\"\"\"\" expected_exit = if expected_stderr is not None and expected_stderr != [ ] : expected_exit = return run_and_verify_svnlook2 ( message , expected_stdout , expected_stderr , expected_exit , * varargs ) def run_and_verify_svnlook2 ( message , expected_stdout , expected_stderr , expected_exit , * varargs ) : \"\"\"\"\"\" exit_code , out , err = main . run_svnlook ( * varargs ) verify . verify_outputs ( \"\" , out , err , expected_stdout , expected_stderr ) verify . verify_exit_code ( message , exit_code , expected_exit ) return exit_code , out , err def run_and_verify_svnadmin ( message , expected_stdout , expected_stderr , * varargs ) : \"\"\"\"\"\" expected_exit = if expected_stderr is not None and expected_stderr != [ ] : expected_exit = return run_and_verify_svnadmin2 ( message , expected_stdout , expected_stderr , expected_exit , * varargs ) def run_and_verify_svnadmin2 ( message , expected_stdout , expected_stderr , expected_exit , * varargs ) : \"\"\"\"\"\" exit_code , out , err = main . run_svnadmin ( * varargs ) verify . verify_outputs ( \"\" , out , err , expected_stdout , expected_stderr ) verify . verify_exit_code ( message , exit_code , expected_exit ) return exit_code , out , err def run_and_verify_svnversion ( message , wc_dir , trail_url , expected_stdout , expected_stderr , * varargs ) : \"\"\"\"\"\" expected_exit = if expected_stderr is not None and expected_stderr != [ ] : expected_exit = return run_and_verify_svnversion2 ( message , wc_dir , trail_url , expected_stdout , expected_stderr , expected_exit , * varargs ) def run_and_verify_svnversion2 ( message , wc_dir , trail_url , expected_stdout , expected_stderr , expected_exit , * varargs ) : \"\"\"\"\"\" if trail_url is None : exit_code , out , err = main . run_svnversion ( wc_dir , * varargs ) else : exit_code , out , err = main . run_svnversion ( wc_dir , trail_url , * varargs ) verify . verify_outputs ( \"\" , out , err , expected_stdout , expected_stderr ) verify . verify_exit_code ( message , exit_code , expected_exit ) return exit_code , out , err def run_and_verify_svn ( message , expected_stdout , expected_stderr , * varargs ) : \"\"\"\"\"\" expected_exit = if expected_stderr is not None : if isinstance ( expected_stderr , verify . ExpectedOutput ) : if not expected_stderr . matches ( [ ] ) : expected_exit = elif expected_stderr != [ ] : expected_exit = return run_and_verify_svn2 ( message , expected_stdout , expected_stderr , expected_exit , * varargs ) def run_and_verify_svn2 ( message , expected_stdout , expected_stderr , expected_exit , * varargs ) : \"\"\"\"\"\" if expected_stderr is None : raise verify . SVNIncorrectDatatype ( \"\" ) want_err = None if isinstance ( expected_stderr , verify . ExpectedOutput ) : if not expected_stderr . matches ( [ ] ) : want_err = True elif expected_stderr != [ ] : want_err = True exit_code , out , err = main . run_svn ( want_err , * varargs ) verify . verify_outputs ( message , out , err , expected_stdout , expected_stderr ) verify . verify_exit_code ( message , exit_code , expected_exit ) return exit_code , out , err def run_and_verify_load ( repo_dir , dump_file_content , bypass_prop_validation = False ) : \"\" if not isinstance ( dump_file_content , list ) : raise TypeError ( \"\" ) expected_stderr = [ ] if bypass_prop_validation : exit_code , output , errput = main . run_command_stdin ( main . svnadmin_binary , expected_stderr , , , dump_file_content , '' , '' , '' , '' , repo_dir ) else : exit_code , output , errput = main . run_command_stdin ( main . svnadmin_binary , expected_stderr , , , dump_file_content , '' , '' , '' , repo_dir ) verify . verify_outputs ( \"\" , None , errput , None , expected_stderr ) def run_and_verify_dump ( repo_dir , deltas = False ) : \"\" if deltas : exit_code , output , errput = main . run_svnadmin ( '' , '' , repo_dir ) else : exit_code , output , errput = main . run_svnadmin ( '' , repo_dir ) verify . verify_outputs ( \"\" , output , errput , verify . AnyOutput , verify . AnyOutput ) return output def run_and_verify_svnrdump ( dumpfile_content , expected_stdout , expected_stderr , expected_exit , * varargs ) : \"\"\"\"\"\" exit_code , output , err = main . run_svnrdump ( dumpfile_content , * varargs ) if sys . platform == '' : err = map ( lambda x : x . replace ( '' , '' ) , err ) for index , line in enumerate ( err [ : ] ) : if re . search ( \"\" , line ) : del err [ index ] verify . verify_outputs ( \"\" , output , err , expected_stdout , expected_stderr ) verify . verify_exit_code ( \"\" , exit_code , expected_exit ) return output def run_and_verify_svnmucc ( message , expected_stdout , expected_stderr , * varargs ) : \"\"\"\"\"\" expected_exit = if expected_stderr is not None and expected_stderr != [ ] : expected_exit = return run_and_verify_svnmucc2 ( message , expected_stdout , expected_stderr , expected_exit , * varargs ) def run_and_verify_svnmucc2 ( message , expected_stdout , expected_stderr , expected_exit , * varargs ) : \"\"\"\"\"\" exit_code , out , err = main . run_svnmucc ( * varargs ) verify . verify_outputs ( \"\" , out , err , expected_stdout , expected_stderr ) verify . verify_exit_code ( message , exit_code , expected_exit ) return exit_code , out , err def load_repo ( sbox , dumpfile_path = None , dump_str = None , bypass_prop_validation = False ) : \"\" if not dump_str : dump_str = open ( dumpfile_path , \"\" ) . read ( ) main . safe_rmtree ( sbox . repo_dir , ) main . safe_rmtree ( sbox . wc_dir , ) main . create_repos ( sbox . repo_dir ) run_and_verify_load ( sbox . repo_dir , dump_str . splitlines ( True ) , bypass_prop_validation ) run_and_verify_svn ( None , None , [ ] , \"\" , sbox . repo_url , sbox . wc_dir ) return dump_str def expected_noop_update_output ( rev ) : \"\"\"\"\"\" return verify . createExpectedOutput ( \"\" % ( rev ) , \"\" ) def run_and_verify_checkout2 ( do_remove , URL , wc_dir_name , output_tree , disk_tree , singleton_handler_a = None , a_baton = None , singleton_handler_b = None , b_baton = None , * args ) : \"\"\"\"\"\" if isinstance ( output_tree , wc . State ) : output_tree = output_tree . old_tree ( ) if isinstance ( disk_tree , wc . State ) : disk_tree = disk_tree . old_tree ( ) if do_remove : main . safe_rmtree ( wc_dir_name ) exit_code , output , errput = main . run_svn ( None , '' , URL , wc_dir_name , * args ) actual = tree . build_tree_from_checkout ( output ) try : tree . compare_trees ( \"\" , actual , output_tree ) except tree . SVNTreeUnequal : _log_tree_state ( \"\" , actual , wc_dir_name ) raise actual = tree . build_tree_from_wc ( wc_dir_name ) try : tree . compare_trees ( \"\" , actual , disk_tree , singleton_handler_a , a_baton , singleton_handler_b , b_baton ) except tree . SVNTreeUnequal : _log_tree_state ( \"\" , actual , wc_dir_name ) raise def run_and_verify_checkout ( URL , wc_dir_name , output_tree , disk_tree , singleton_handler_a = None , a_baton = None , singleton_handler_b = None , b_baton = None , * args ) : \"\"\"\"\"\" return run_and_verify_checkout2 ( ( '' not in args ) , URL , wc_dir_name , output_tree , disk_tree , singleton_handler_a , a_baton , singleton_handler_b , b_baton , * args ) def run_and_verify_export ( URL , export_dir_name , output_tree , disk_tree , * args ) : \"\"\"\"\"\" assert isinstance ( output_tree , wc . State ) assert isinstance ( disk_tree , wc . State ) disk_tree = disk_tree . old_tree ( ) output_tree = output_tree . old_tree ( ) exit_code , output , errput = main . run_svn ( None , '' , URL , export_dir_name , * args ) actual = tree . build_tree_from_checkout ( output ) try : tree . compare_trees ( \"\" , actual , output_tree ) except tree . SVNTreeUnequal : _log_tree_state ( \"\" , actual , export_dir_name ) raise actual = tree . build_tree_from_wc ( export_dir_name , ignore_svn = False ) try : tree . compare_trees ( \"\" , actual , disk_tree ) except tree . SVNTreeUnequal : _log_tree_state ( \"\" , actual , export_dir_name ) raise class LogEntry : def __init__ ( self , revision , changed_paths = None , revprops = None ) : self . revision = revision if changed_paths == None : self . changed_paths = { } else : self . changed_paths = changed_paths if revprops == None : self . revprops = { } else : self . revprops = revprops def assert_changed_paths ( self , changed_paths ) : \"\"\"\"\"\" if self . changed_paths != changed_paths : raise Failure ( '' + '' . join ( difflib . ndiff ( pprint . pformat ( changed_paths ) . splitlines ( ) , pprint . pformat ( self . changed_paths ) . splitlines ( ) ) ) ) def assert_revprops ( self , revprops ) : \"\"\"\"\"\" if self . revprops != revprops : raise Failure ( '' + '' . join ( difflib . ndiff ( pprint . pformat ( revprops ) . splitlines ( ) , pprint . pformat ( self . revprops ) . splitlines ( ) ) ) ) class LogParser : def parse ( self , data ) : \"\"\"\"\"\" try : for i in data : self . parser . Parse ( i ) self . parser . Parse ( '' , True ) except xml . parsers . expat . ExpatError , e : raise verify . SVNUnexpectedStdout ( '' % ( e , '' . join ( data ) , ) ) return self . entries def __init__ ( self ) : self . parser = xml . parsers . expat . ParserCreate ( ) self . parser . StartElementHandler = self . handle_start_element self . parser . EndElementHandler = self . handle_end_element self . parser . CharacterDataHandler = self . handle_character_data self . ignore_elements ( '' , '' , '' ) self . ignore_tags ( '' , '' , '' , '' ) self . cdata = [ ] self . property = None self . kind = None self . action = None self . entries = [ ] def ignore ( self , * args , ** kwargs ) : del self . cdata [ : ] def ignore_tags ( self , * args ) : for tag in args : setattr ( self , tag , self . ignore ) def ignore_elements ( self , * args ) : for element in args : self . ignore_tags ( element + '' , element + '' ) def handle_start_element ( self , name , attrs ) : getattr ( self , name + '' ) ( attrs ) def handle_end_element ( self , name ) : getattr ( self , name + '' ) ( ) def handle_character_data ( self , data ) : self . cdata . append ( data ) def use_cdata ( self ) : result = '' . join ( self . cdata ) . strip ( ) del self . cdata [ : ] return result def svn_prop ( self , name ) : self . entries [ - ] . revprops [ '' + name ] = self . use_cdata ( ) def logentry_start ( self , attrs ) : self . entries . append ( LogEntry ( int ( attrs [ '' ] ) ) ) def author_end ( self ) : self . svn_prop ( '' ) def msg_end ( self ) : self . svn_prop ( '' ) def date_end ( self ) : self . cdata [ : ] = [ '' ] self . svn_prop ( '' ) def property_start ( self , attrs ) : self . property = attrs [ '' ] def property_end ( self ) : self . entries [ - ] . revprops [ self . property ] = self . use_cdata ( ) def path_start ( self , attrs ) : self . kind = attrs [ '' ] self . action = attrs [ '' ] def path_end ( self ) : self . entries [ - ] . changed_paths [ self . use_cdata ( ) ] = [ { '' : self . kind , '' : self . action } ] def run_and_verify_log_xml ( message = None , expected_paths = None , expected_revprops = None , expected_stdout = None , expected_stderr = None , args = [ ] ) : \"\"\"\"\"\" if message == None : message = '' . join ( args ) parse = True if expected_stderr == None : expected_stderr = [ ] else : parse = False if expected_stdout != None : parse = False log_args = list ( args ) if expected_paths != None : log_args . append ( '' ) ( exit_code , stdout , stderr ) = run_and_verify_svn ( message , expected_stdout , expected_stderr , '' , '' , * log_args ) if not parse : return entries = LogParser ( ) . parse ( stdout ) for index in range ( len ( entries ) ) : entry = entries [ index ] if expected_revprops != None : entry . assert_revprops ( expected_revprops [ index ] ) if expected_paths != None : entry . assert_changed_paths ( expected_paths [ index ] ) def verify_update ( actual_output , actual_mergeinfo_output , actual_elision_output , wc_dir_name , output_tree , mergeinfo_output_tree , elision_output_tree , disk_tree , status_tree , singleton_handler_a = None , a_baton = None , singleton_handler_b = None , b_baton = None , check_props = False ) : \"\"\"\"\"\" if isinstance ( actual_output , wc . State ) : actual_output = actual_output . old_tree ( ) if isinstance ( actual_mergeinfo_output , wc . State ) : actual_mergeinfo_output = actual_mergeinfo_output . old_tree ( ) if isinstance ( actual_elision_output , wc . State ) : actual_elision_output = actual_elision_output . old_tree ( ) if isinstance ( output_tree , wc . State ) : output_tree = output_tree . old_tree ( ) if isinstance ( mergeinfo_output_tree , wc . State ) : mergeinfo_output_tree = mergeinfo_output_tree . old_tree ( ) if isinstance ( elision_output_tree , wc . State ) : elision_output_tree = elision_output_tree . old_tree ( ) if isinstance ( disk_tree , wc . State ) : disk_tree = disk_tree . old_tree ( ) if isinstance ( status_tree , wc . State ) : status_tree = status_tree . old_tree ( ) if output_tree : try : tree . compare_trees ( \"\" , actual_output , output_tree ) except tree . SVNTreeUnequal : _log_tree_state ( \"\" , actual_output , wc_dir_name ) raise if mergeinfo_output_tree : try : tree . compare_trees ( \"\" , actual_mergeinfo_output , mergeinfo_output_tree ) except tree . SVNTreeUnequal : _log_tree_state ( \"\" , actual_mergeinfo_output , wc_dir_name ) raise if elision_output_tree : try : tree . compare_trees ( \"\" , actual_elision_output , elision_output_tree ) except tree . SVNTreeUnequal : _log_tree_state ( \"\" , actual_elision_output , wc_dir_name ) raise if disk_tree : actual_disk = tree . build_tree_from_wc ( wc_dir_name , check_props ) try : tree . compare_trees ( \"\" , actual_disk , disk_tree , singleton_handler_a , a_baton , singleton_handler_b , b_baton ) except tree . SVNTreeUnequal : _log_tree_state ( \"\" , disk_tree ) _log_tree_state ( \"\" , actual_disk ) raise if status_tree : run_and_verify_status ( wc_dir_name , status_tree ) def verify_disk ( wc_dir_name , disk_tree , check_props = False ) : \"\"\"\"\"\" verify_update ( None , None , None , wc_dir_name , None , None , None , disk_tree , None , check_props = check_props ) def run_and_verify_update ( wc_dir_name , output_tree , disk_tree , status_tree , error_re_string = None , singleton_handler_a = None , a_baton = None , singleton_handler_b = None , b_baton = None , check_props = False , * args ) : \"\"\"\"\"\" if len ( args ) : exit_code , output , errput = main . run_svn ( error_re_string , '' , * args ) else : exit_code , output , errput = main . run_svn ( error_re_string , '' , wc_dir_name , * args ) if error_re_string : rm = re . compile ( error_re_string ) for line in errput : match = rm . search ( line ) if match : return raise main . SVNUnmatchedError actual = wc . State . from_checkout ( output ) verify_update ( actual , None , None , wc_dir_name , output_tree , None , None , disk_tree , status_tree , singleton_handler_a , a_baton , singleton_handler_b , b_baton , check_props ) def run_and_parse_info ( * args ) : \"\"\"\"\"\" all_infos = [ ] iter_info = { } prev_key = None lock_comment_lines = lock_comments = [ ] exit_code , output , errput = main . run_svn ( None , '' , * args ) for line in output : line = line [ : - ] if lock_comment_lines > : lock_comments . append ( line ) lock_comment_lines = lock_comment_lines - if lock_comment_lines == : iter_info [ prev_key ] = lock_comments elif len ( line ) == : all_infos . append ( iter_info ) iter_info = { } prev_key = None lock_comment_lines = lock_comments = [ ] elif line [ ] . isspace ( ) : iter_info [ prev_key ] += line [ : ] else : key , value = line . split ( '' , ) if re . search ( '' , key ) : match = re . match ( '' , key ) key = match . group ( ) lock_comment_lines = int ( match . group ( ) ) elif len ( value ) > : iter_info [ key ] = value [ : ] else : iter_info [ key ] = '' prev_key = key return all_infos def run_and_verify_info ( expected_infos , * args ) : \"\"\"\"\"\" actual_infos = run_and_parse_info ( * args ) actual_infos . sort ( key = lambda info : info [ '' ] ) try : if len ( actual_infos ) != len ( expected_infos ) : raise verify . SVNUnexpectedStdout ( \"\" % ( len ( expected_infos ) , len ( actual_infos ) ) ) for actual , expected in zip ( actual_infos , expected_infos ) : for key , value in expected . items ( ) : assert '' not in key if value is None and key in actual : raise main . SVNLineUnequal ( \"\" % ( key , actual [ key ] ) ) if value is not None and key not in actual : raise main . SVNLineUnequal ( \"\" \"\" % ( key , value ) ) if value is not None and not re . match ( value , actual [ key ] ) : raise verify . SVNUnexpectedStdout ( \"\" \"\" \"\" % ( key , value , actual [ key ] ) ) except : sys . stderr . write ( \"\" \"\" \"\" % ( actual_infos , expected_infos ) ) raise def run_and_verify_merge ( dir , rev1 , rev2 , url1 , url2 , output_tree , mergeinfo_output_tree , elision_output_tree , disk_tree , status_tree , skip_tree , error_re_string = None , singleton_handler_a = None , a_baton = None , singleton_handler_b = None , b_baton = None , check_props = False , dry_run = True , * args ) : \"\"\"\"\"\" merge_command = [ \"\" ] if url2 : merge_command . extend ( ( url1 + \"\" + str ( rev1 ) , url2 + \"\" + str ( rev2 ) ) ) else : if not ( rev1 is None and rev2 is None ) : merge_command . append ( \"\" + str ( rev1 ) + \"\" + str ( rev2 ) ) merge_command . append ( url1 ) if len ( args ) == : merge_command . append ( dir ) merge_command = tuple ( merge_command ) if dry_run : pre_disk = tree . build_tree_from_wc ( dir ) dry_run_command = merge_command + ( '' , ) dry_run_command = dry_run_command + args exit_code , out_dry , err_dry = main . run_svn ( error_re_string , * dry_run_command ) post_disk = tree . build_tree_from_wc ( dir ) try : tree . compare_trees ( \"\" , post_disk , pre_disk ) except tree . SVNTreeError : logger . warn ( \"\" ) logger . warn ( \"\" ) logger . warn ( \"\" ) raise merge_command = merge_command + args exit_code , out , err = main . run_svn ( error_re_string , * merge_command ) if error_re_string : if not error_re_string . startswith ( \"\" ) : error_re_string = \"\" + error_re_string + \"\" expected_err = verify . RegexOutput ( error_re_string , match_all = False ) verify . verify_outputs ( None , None , err , None , expected_err ) return elif err : raise verify . SVNUnexpectedStderr ( err ) merge_diff_out = [ ] mergeinfo_notification_out = [ ] mergeinfo_elision_out = [ ] mergeinfo_notifications = False elision_notifications = False for line in out : if line . startswith ( '' ) : mergeinfo_notifications = True elision_notifications = False elif line . startswith ( '' ) : mergeinfo_notifications = False elision_notifications = True elif line . startswith ( '' ) or line . startswith ( '' ) or line . startswith ( '' ) or line . startswith ( '' ) : mergeinfo_notifications = False elision_notifications = False if mergeinfo_notifications : mergeinfo_notification_out . append ( line ) elif elision_notifications : mergeinfo_elision_out . append ( line ) else : merge_diff_out . append ( line ) if dry_run and merge_diff_out != out_dry : out_copy = set ( merge_diff_out [ : ] ) out_dry_copy = set ( out_dry [ : ] ) if out_copy != out_dry_copy : logger . warn ( \"\" ) logger . warn ( \"\" ) logger . warn ( \"\" ) for x in out_dry : logger . warn ( x ) logger . warn ( \"\" ) for x in out : logger . warn ( x ) logger . warn ( \"\" ) raise main . SVNUnmatchedError def missing_skip ( a , b ) : logger . warn ( \"\" ) logger . warn ( \"\" , a . path ) logger . warn ( \"\" ) raise Failure def extra_skip ( a , b ) : logger . warn ( \"\" ) logger . warn ( \"\" , a . path ) logger . warn ( \"\" ) raise Failure myskiptree = tree . build_tree_from_skipped ( out ) if isinstance ( skip_tree , wc . State ) : skip_tree = skip_tree . old_tree ( ) try : tree . compare_trees ( \"\" , myskiptree , skip_tree , extra_skip , None , missing_skip , None ) except tree . SVNTreeUnequal : _log_tree_state ( \"\" , myskiptree , dir ) raise actual_diff = svntest . wc . State . from_checkout ( merge_diff_out , False ) actual_mergeinfo = svntest . wc . State . from_checkout ( mergeinfo_notification_out , False ) actual_elision = svntest . wc . State . from_checkout ( mergeinfo_elision_out , False ) verify_update ( actual_diff , actual_mergeinfo , actual_elision , dir , output_tree , mergeinfo_output_tree , elision_output_tree , disk_tree , status_tree , singleton_handler_a , a_baton , singleton_handler_b , b_baton , check_props ) def run_and_verify_patch ( dir , patch_path , output_tree , disk_tree , status_tree , skip_tree , error_re_string = None , check_props = False , dry_run = True , * args ) : \"\"\"\"\"\" patch_command = [ \"\" ] patch_command . append ( patch_path ) patch_command . append ( dir ) patch_command = tuple ( patch_command ) if dry_run : pre_disk = tree . build_tree_from_wc ( dir ) dry_run_command = patch_command + ( '' , ) dry_run_command = dry_run_command + args exit_code , out_dry , err_dry = main . run_svn ( error_re_string , * dry_run_command ) post_disk = tree . build_tree_from_wc ( dir ) try : tree . compare_trees ( \"\" , post_disk , pre_disk ) except tree . SVNTreeError : logger . warn ( \"\" ) logger . warn ( \"\" ) logger . warn ( \"\" ) raise patch_command = patch_command + args exit_code , out , err = main . run_svn ( True , * patch_command ) if error_re_string : rm = re . compile ( error_re_string ) match = None for line in err : match = rm . search ( line ) if match : break if not match : raise main . SVNUnmatchedError elif err : logger . warn ( \"\" ) for x in err : logger . warn ( x ) raise verify . SVNUnexpectedStderr if dry_run and out != out_dry : out_dry_expected = svntest . verify . UnorderedOutput ( out ) verify . compare_and_display_lines ( '' , '' , out_dry_expected , out_dry ) def missing_skip ( a , b ) : logger . warn ( \"\" ) logger . warn ( \"\" , a . path ) logger . warn ( \"\" ) raise Failure def extra_skip ( a , b ) : logger . warn ( \"\" ) logger . warn ( \"\" , a . path ) logger . warn ( \"\" ) raise Failure myskiptree = tree . build_tree_from_skipped ( out ) if isinstance ( skip_tree , wc . State ) : skip_tree = skip_tree . old_tree ( ) tree . compare_trees ( \"\" , myskiptree , skip_tree , extra_skip , None , missing_skip , None ) mytree = tree . build_tree_from_checkout ( out , ) if ( isinstance ( output_tree , list ) or isinstance ( output_tree , verify . UnorderedOutput ) ) : verify . verify_outputs ( None , out , err , output_tree , error_re_string ) output_tree = None verify_update ( mytree , None , None , dir , output_tree , None , None , disk_tree , status_tree , check_props = check_props ) def run_and_verify_mergeinfo ( error_re_string = None , expected_output = [ ] , * args ) : \"\"\"\"\"\" mergeinfo_command = [ \"\" ] mergeinfo_command . extend ( args ) exit_code , out , err = main . run_svn ( error_re_string , * mergeinfo_command ) if error_re_string : if not error_re_string . startswith ( \"\" ) : error_re_string = \"\" + error_re_string + \"\" expected_err = verify . RegexOutput ( error_re_string , match_all = False ) verify . verify_outputs ( None , None , err , None , expected_err ) return out = [ _f for _f in [ x . rstrip ( ) [ : ] for x in out ] if _f ] expected_output . sort ( ) extra_out = [ ] if out != expected_output : exp_hash = dict . fromkeys ( expected_output ) for rev in out : if rev in exp_hash : del ( exp_hash [ rev ] ) else : extra_out . append ( rev ) extra_exp = list ( exp_hash . keys ( ) ) raise Exception ( \"\" \"\" \"\" % ( '' . join ( [ str ( x ) for x in extra_exp ] ) , '' . join ( [ str ( x ) for x in extra_out ] ) ) ) def run_and_verify_switch ( wc_dir_name , wc_target , switch_url , output_tree , disk_tree , status_tree , error_re_string = None , singleton_handler_a = None , a_baton = None , singleton_handler_b = None , b_baton = None , check_props = False , * args ) : \"\"\"\"\"\" exit_code , output , errput = main . run_svn ( error_re_string , '' , switch_url , wc_target , * args ) if error_re_string : if not error_re_string . startswith ( \"\" ) : error_re_string = \"\" + error_re_string + \"\" expected_err = verify . RegexOutput ( error_re_string , match_all = False ) verify . verify_outputs ( None , None , errput , None , expected_err ) return elif errput : raise verify . SVNUnexpectedStderr ( err ) actual = wc . State . from_checkout ( output ) verify_update ( actual , None , None , wc_dir_name , output_tree , None , None , disk_tree , status_tree , singleton_handler_a , a_baton , singleton_handler_b , b_baton , check_props ) def process_output_for_commit ( output ) : \"\"\"\"\"\" lastline = \"\" rest = [ ] def external_removal ( line ) : return line . startswith ( '' ) or line . startswith ( '' ) if len ( output ) : lastline = output . pop ( ) . strip ( ) while len ( output ) and external_removal ( lastline ) : rest . append ( lastline ) lastline = output . pop ( ) . strip ( ) cm = re . compile ( \"\" ) match = cm . search ( lastline ) if not match : logger . warn ( \"\" ) logger . warn ( \"\" ) logger . warn ( lastline ) raise main . SVNCommitFailure if len ( output ) : lastline = output . pop ( ) tm = re . compile ( \"\" ) match = tm . search ( lastline ) if not match : output . append ( lastline ) if len ( rest ) : output . extend ( rest ) return output def run_and_verify_commit ( wc_dir_name , output_tree , status_tree , error_re_string = None , * args ) : \"\"\"\"\"\" if isinstance ( output_tree , wc . State ) : output_tree = output_tree . old_tree ( ) if isinstance ( status_tree , wc . State ) : status_tree = status_tree . old_tree ( ) if '' not in args and '' not in args : args = list ( args ) + [ '' , '' ] exit_code , output , errput = main . run_svn ( error_re_string , '' , * args ) if error_re_string : if not error_re_string . startswith ( \"\" ) : error_re_string = \"\" + error_re_string + \"\" expected_err = verify . RegexOutput ( error_re_string , match_all = False ) verify . verify_outputs ( None , None , errput , None , expected_err ) return output = process_output_for_commit ( output ) actual = tree . build_tree_from_commit ( output ) try : tree . compare_trees ( \"\" , actual , output_tree ) except tree . SVNTreeError : verify . display_trees ( \"\" , \"\" , output_tree , actual ) _log_tree_state ( \"\" , actual , wc_dir_name ) raise if status_tree : run_and_verify_status ( wc_dir_name , status_tree ) def run_and_verify_status ( wc_dir_name , output_tree , singleton_handler_a = None , a_baton = None , singleton_handler_b = None , b_baton = None ) : \"\"\"\"\"\" if isinstance ( output_tree , wc . State ) : output_state = output_tree output_tree = output_tree . old_tree ( ) else : output_state = None exit_code , output , errput = main . run_svn ( None , '' , '' , '' , '' , wc_dir_name ) actual = tree . build_tree_from_status ( output ) try : tree . compare_trees ( \"\" , actual , output_tree , singleton_handler_a , a_baton , singleton_handler_b , b_baton ) except tree . SVNTreeError : verify . display_trees ( None , '' , output_tree , actual ) _log_tree_state ( \"\" , actual , wc_dir_name ) raise if output_state : entries_state = wc . State . from_entries ( wc_dir_name ) if entries_state : tweaked = output_state . copy ( ) tweaked . tweak_for_entries_compare ( ) try : tweaked . compare_and_display ( '' , entries_state ) except tree . SVNTreeUnequal : raise def run_and_verify_unquiet_status ( wc_dir_name , status_tree ) : \"\"\"\"\"\" if isinstance ( status_tree , wc . State ) : status_tree = status_tree . old_tree ( ) exit_code , output , errput = main . run_svn ( None , '' , '' , '' , wc_dir_name ) actual = tree . build_tree_from_status ( output ) try : tree . compare_trees ( \"\" , actual , status_tree ) except tree . SVNTreeError : _log_tree_state ( \"\" , actual , wc_dir_name ) raise def run_and_verify_status_xml ( expected_entries = [ ] , * args ) : \"\"\"\"\"\" exit_code , output , errput = run_and_verify_svn ( None , None , [ ] , '' , '' , * args ) if len ( errput ) > : raise Failure doc = parseString ( '' . join ( output ) ) entries = doc . getElementsByTagName ( '' ) def getText ( nodelist ) : rc = [ ] for node in nodelist : if node . nodeType == node . TEXT_NODE : rc . append ( node . data ) return '' . join ( rc ) actual_entries = { } for entry in entries : wcstatus = entry . getElementsByTagName ( '' ) [ ] commit = entry . getElementsByTagName ( '' ) author = entry . getElementsByTagName ( '' ) rstatus = entry . getElementsByTagName ( '' ) actual_entry = { '' : wcstatus . getAttribute ( '' ) , '' : wcstatus . getAttribute ( '' ) , } if wcstatus . hasAttribute ( '' ) : actual_entry [ '' ] = wcstatus . getAttribute ( '' ) if ( commit ) : actual_entry [ '' ] = commit [ ] . getAttribute ( '' ) if ( author ) : actual_entry [ '' ] = getText ( author [ ] . childNodes ) if ( rstatus ) : actual_entry [ '' ] = rstatus [ ] . getAttribute ( '' ) actual_entry [ '' ] = rstatus [ ] . getAttribute ( '' ) actual_entries [ entry . getAttribute ( '' ) ] = actual_entry if expected_entries != actual_entries : raise Failure ( '' + '' . join ( difflib . ndiff ( pprint . pformat ( expected_entries ) . splitlines ( ) , pprint . pformat ( actual_entries ) . splitlines ( ) ) ) ) def run_and_verify_diff_summarize_xml ( error_re_string = [ ] , expected_prefix = None , expected_paths = [ ] , expected_items = [ ] , expected_props = [ ] , expected_kinds = [ ] , * args ) : \"\"\"\"\"\" exit_code , output , errput = run_and_verify_svn ( None , None , error_re_string , '' , '' , '' , * args ) if len ( errput ) > : return doc = parseString ( '' . join ( output ) ) paths = doc . getElementsByTagName ( \"\" ) items = expected_items kinds = expected_kinds for path in paths : modified_path = path . childNodes [ ] . data if ( expected_prefix is not None and modified_path . find ( expected_prefix ) == ) : modified_path = modified_path . replace ( expected_prefix , '' ) [ : ] . strip ( ) if len ( modified_path ) == : modified_path = path . childNodes [ ] . data . split ( os . sep ) [ - ] if os . sep != \"\" : modified_path = modified_path . replace ( os . sep , \"\" ) if modified_path not in expected_paths : logger . warn ( \"\" , modified_path ) raise Failure index = expected_paths . index ( modified_path ) expected_item = items [ index ] expected_kind = kinds [ index ] expected_prop = expected_props [ index ] actual_item = path . getAttribute ( '' ) actual_kind = path . getAttribute ( '' ) actual_prop = path . getAttribute ( '' ) if expected_item != actual_item : logger . warn ( \"\" , expected_item , actual_item ) raise Failure if expected_kind != actual_kind : logger . warn ( \"\" , expected_kind , actual_kind ) raise Failure if expected_prop != actual_prop : logger . warn ( \"\" , expected_prop , actual_prop ) raise Failure def run_and_verify_diff_summarize ( output_tree , * args ) : \"\"\"\"\"\" if isinstance ( output_tree , wc . State ) : output_tree = output_tree . old_tree ( ) exit_code , output , errput = main . run_svn ( None , '' , '' , * args ) actual = tree . build_tree_from_diff_summarize ( output ) try : tree . compare_trees ( \"\" , actual , output_tree ) except tree . SVNTreeError : verify . display_trees ( None , '' , output_tree , actual ) _log_tree_state ( \"\" , actual ) raise def run_and_validate_lock ( path , username ) : \"\"\"\"\"\" comment = \"\" % path run_and_verify_svn ( None , \"\" , [ ] , '' , '' , username , '' , comment , path ) exit_code , output , err = run_and_verify_svn ( None , None , [ ] , '' , '' , path ) token_re = re . compile ( \"\" , re . DOTALL ) author_re = re . compile ( \"\" % username , re . DOTALL ) created_re = re . compile ( \"\" , re . DOTALL ) comment_re = re . compile ( \"\" % re . escape ( comment ) , re . DOTALL ) output = \"\" . join ( output ) if ( not ( token_re . match ( output ) and author_re . match ( output ) and created_re . match ( output ) and comment_re . match ( output ) ) ) : raise Failure def _run_and_verify_resolve ( cmd , expected_paths , * args ) : \"\"\"\"\"\" if len ( args ) == : args = expected_paths expected_output = verify . UnorderedOutput ( [ \"\" + path + \"\" for path in expected_paths ] ) run_and_verify_svn ( None , expected_output , [ ] , cmd , * args ) def run_and_verify_resolve ( expected_paths , * args ) : \"\"\"\"\"\" _run_and_verify_resolve ( '' , expected_paths , * args ) def run_and_verify_resolved ( expected_paths , * args ) : \"\"\"\"\"\" _run_and_verify_resolve ( '' , expected_paths , * args ) def run_and_verify_revert ( expected_paths , * args ) : \"\"\"\"\"\" if len ( args ) == : args = expected_paths expected_output = verify . UnorderedOutput ( [ \"\" + path + \"\" for path in expected_paths ] ) run_and_verify_svn ( None , expected_output , [ ] , \"\" , * args ) def make_repo_and_wc ( sbox , create_wc = True , read_only = False , minor_version = None ) : \"\"\"\"\"\" if not read_only : guarantee_greek_repository ( sbox . repo_dir , minor_version ) if create_wc : expected_output = main . greek_state . copy ( ) expected_output . wc_dir = sbox . wc_dir expected_output . tweak ( status = '' , contents = None ) expected_wc = main . greek_state run_and_verify_checkout ( sbox . repo_url , sbox . wc_dir , expected_output , expected_wc ) else : try : os . mkdir ( main . general_wc_dir ) except OSError , err : if err . errno != errno . EEXIST : raise def duplicate_dir ( wc_name , wc_copy_name ) : \"\"\"\"\"\" main . safe_rmtree ( wc_copy_name ) shutil . copytree ( wc_name , wc_copy_name ) def get_virginal_state ( wc_dir , rev ) : \"\" rev = str ( rev ) state = main . greek_state . copy ( ) state . wc_dir = wc_dir state . desc [ '' ] = wc . StateItem ( ) state . tweak ( contents = None , status = '' , wc_rev = rev ) return state def lock_admin_dir ( wc_dir , recursive = False ) : \"\" db , root_path , relpath = wc . open_wc_db ( wc_dir ) svntest . main . run_wc_lock_tester ( recursive , wc_dir ) def set_incomplete ( wc_dir , revision ) : \"\" svntest . main . run_wc_incomplete_tester ( wc_dir , revision ) def get_wc_uuid ( wc_dir ) : \"\" return run_and_parse_info ( wc_dir ) [ ] [ '' ] def get_wc_base_rev ( wc_dir ) : \"\" return run_and_parse_info ( wc_dir ) [ ] [ '' ] def hook_failure_message ( hook_name ) : \"\"\"\"\"\" if svntest . main . options . server_minor_version < : return \"\" % hook_name else : if hook_name in [ \"\" , \"\" ] : action = \"\" elif hook_name == \"\" : action = \"\" elif hook_name == \"\" : action = \"\" elif hook_name == \"\" : ", "answer": "action = \"\""}, {"prompt": " from __future__ import unicode_literals import json from django . utils import six from kgb import SpyAgency from reviewboard . hostingsvcs . github import GitHub from reviewboard . hostingsvcs . models import HostingServiceAccount from reviewboard . hostingsvcs . repository import RemoteRepository from reviewboard . hostingsvcs . utils . paginator import APIPaginator from reviewboard . webapi . resources import resources from reviewboard . webapi . tests . base import BaseWebAPITestCase from reviewboard . webapi . tests . mimetypes import ( remote_repository_item_mimetype , remote_repository_list_mimetype ) from reviewboard . webapi . tests . mixins import BasicTestsMetaclass from reviewboard . webapi . tests . urls import ( get_remote_repository_item_url , get_remote_repository_list_url ) def _compare_item ( self , item_rsp , remote_repository ) : self . assertEqual ( item_rsp [ '' ] , remote_repository . id ) self . assertEqual ( item_rsp [ '' ] , remote_repository . name ) self . assertEqual ( item_rsp [ '' ] , remote_repository . owner ) self . assertEqual ( item_rsp [ '' ] , remote_repository . scm_type ) self . assertEqual ( item_rsp [ '' ] , remote_repository . path ) self . assertEqual ( item_rsp [ '' ] , remote_repository . mirror_path ) class RemoteRepositoryTestPaginator ( APIPaginator ) : def __init__ ( self , results ) : self . results = results super ( RemoteRepositoryTestPaginator , self ) . __init__ ( client = None , url = '' ) def fetch_url ( self , url ) : return { '' : self . results , } @ six . add_metaclass ( BasicTestsMetaclass ) class ResourceListTests ( SpyAgency , BaseWebAPITestCase ) : \"\"\"\"\"\" fixtures = [ '' ] sample_api_url = '' resource = resources . remote_repository basic_get_use_admin = True ", "answer": "compare_item = _compare_item"}, {"prompt": " from js_helper import TestCase class TestFunctionTraversal ( TestCase ) : \"\"\"\"\"\" def test_function_declaration_order ( self ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " \"\"\"\"\"\" from os import getenv , chdir from re import sub from subprocess import check_output , check_call from tempfile import mkdtemp from shutil import rmtree if getenv ( '' ) != '' : print \"\" ", "answer": "exit ( )"}, {"prompt": " from zope . interface import implements from sub_collab . negotiator import base from sub_collab . peer import basic from sub_collab import common , event , registry , status_bar from twisted . words . protocols import irc from twisted . internet import reactor , ssl , protocol , error , defer import logging , sys , socket , functools import sublime class IRCNegotiator ( base . BaseNegotiator , common . Observable , protocol . ClientFactory , base . PatchedIRCClient ) : \"\"\"\"\"\" logger = logging . getLogger ( '' ) versionName = '' versionNum = '' versionEnv = \"\" negotiateCallback = None onNegotiateCallback = None rejectedOrFailedCallback = None def __init__ ( self , id , config ) : common . Observable . __init__ ( self ) base . BaseNegotiator . __init__ ( self , id , config ) base . PatchedIRCClient . __init__ ( self ) assert config . has_key ( '' ) , '' assert config . has_key ( '' ) , '' assert config . has_key ( '' ) , '' assert config . has_key ( '' ) , '' self . clientConnection = None self . host = self . config [ '' ] . encode ( ) self . port = int ( self . config [ '' ] ) self . nickname = self . config [ '' ] . encode ( ) if self . config . has_key ( '' ) : self . password = self . config [ '' ] . encode ( ) if self . config . has_key ( '' ) : self . useSSL = self . config [ '' ] else : self . useSSL = False self . channel = self . config [ '' ] . encode ( ) self . peerUsers = [ ] self . unverifiedUsers = None self . connectionFailed = False self . pendingSession = None self . hostAddressToTryQueue = None def connect ( self ) : \"\"\"\"\"\" if self . isConnected ( ) : return if self . clientConnection : self . clientConnection . disconnect ( ) status_bar . status_message ( '' % self . str ( ) ) if self . useSSL : self . logger . info ( '' % self . str ( ) ) self . clientConnection = reactor . connectSSL ( self . host , self . port , self , ssl . ClientContextFactory ( ) ) else : self . logger . info ( '' % self . str ( ) ) self . clientConnection = reactor . connectTCP ( self . host , self . port , self ) def isConnected ( self ) : \"\"\"\"\"\" connected = None if self . clientConnection : if self . _registered : connected = True else : connected = False return connected def disconnect ( self ) : \"\"\"\"\"\" if self . clientConnection : if self . clientConnection . state == '' : self . clientConnection = None self . _registered = False self . peerUsers = None else : self . clientConnection . disconnect ( ) self . logger . info ( '' % self . host ) status_bar . status_message ( '' % self . str ( ) ) self . clientConnection = None self . _registered = False self . peerUsers = None self . unverifiedUsers = None def listUsers ( self ) : \"\"\"\"\"\" fullList = [ ] if self . peerUsers : for peer in self . peerUsers : fullList . append ( peer ) if self . unverifiedUsers : for unverified in self . unverifiedUsers : fullList . append ( '' + unverified ) return fullList def getUserName ( self ) : \"\"\"\"\"\" return self . nickname def negotiateSession ( self , username ) : \"\"\"\"\"\" if ( not username in self . peerUsers ) and ( not username in self . unverifiedUsers ) : self . addUserToLists ( username ) if self . hostAddressToTryQueue == None or len ( self . hostAddressToTryQueue ) == : self . hostAddressToTryQueue = socket . gethostbyname_ex ( socket . gethostname ( ) ) [ ] ipaddress = self . hostAddressToTryQueue . pop ( ) session = basic . BasicPeer ( username , self ) port = session . hostConnect ( ) self . logger . debug ( '' % ( username , ipaddress , port ) ) status_bar . status_message ( '' % ( username , ipaddress ) ) self . pendingSession = session registry . registerSession ( session ) self . ctcpMakeQuery ( username , [ ( '' , '' % ( base . DCC_PROTOCOL_COLLABORATE , ipaddress , port ) ) ] ) def acceptSessionRequest ( self , username , host , port ) : self . logger . debug ( '' % ( username , host , port ) ) status_bar . status_message ( '' % ( username , host , port ) ) self . logger . info ( '' % ( username , host , port ) ) session = basic . BasicPeer ( username , self ) session . clientConnect ( host , port ) registry . registerSession ( session ) def rejectSessionRequest ( self , username ) : self . logger . debug ( '' % username ) self . msg ( username , base . SESSION_REJECTED ) def retrySessionRequest ( self , username ) : self . logger . debug ( '' % username ) self . msg ( username , base . SESSION_RETRY ) def buildProtocol ( self , addr ) : return self def clientConnectionLost ( self , connector , reason ) : if error . ConnectionDone == reason . type : self . disconnect ( ) else : self . logger . error ( '' % ( reason . type , reason . value ) ) status_bar . status_message ( '' % self . str ( ) ) def clientConnectionFailed ( self , connector , reason ) : self . logger . error ( '' % ( reason . type , reason . value ) ) status_bar . status_message ( '' % self . str ( ) ) self . connectionFailed = True self . disconnect ( ) def connectionMade ( self ) : self . logger . debug ( '' ) base . PatchedIRCClient . connectionMade ( self ) self . logger . info ( '' + self . host ) def signedOn ( self ) : status_bar . status_message ( '' + self . str ( ) ) self . logger . info ( '' + self . channel ) self . join ( self . channel ) def joined ( self , channel ) : self . logger . info ( '' + self . channel ) self . names ( self . channel ) def channelNames ( self , channel , names ) : assert self . channel == channel . lstrip ( irc . CHANNEL_PREFIXES ) names . remove ( self . nickname ) self . logger . debug ( '' % names ) self . unverifiedUsers = [ ] self . peerUsers = [ ] for name in names : self . addUserToLists ( name ) def userJoined ( self , user , channel ) : assert self . channel == channel . lstrip ( irc . CHANNEL_PREFIXES ) self . addUserToLists ( user ) def userLeft ( self , user , channel ) : assert self . channel == channel . lstrip ( irc . CHANNEL_PREFIXES ) self . dropUserFromLists ( user ) def userQuit ( self , user , quitMessage ) : self . dropUserFromLists ( user ) def userKicked ( self , kickee , channel , kicker , message ) : assert self . channel == channel . lstrip ( irc . CHANNEL_PREFIXES ) self . dropUserFromLists ( user ) def userRenamed ( self , oldname , newname ) : assert self . channel == channel . lstrip ( irc . CHANNEL_PREFIXES ) self . dropUserFromLists ( oldname ) self . addUserToLists ( newname ) def privmsg ( self , user , channel , message ) : \"\"\"\"\"\" username = user . lstrip ( self . getNickPrefixes ( ) ) if '' in username : username = username . split ( '' , ) [ ] self . logger . debug ( '' % ( message , username ) ) if message == base . SESSION_RETRY : registry . removeSession ( self . pendingSession ) self . pendingSession . disconnect ( ) ; self . pendingSession = None self . negotiateSession ( username ) elif message == base . SESSION_FAILED : self . logger . warn ( '' ) registry . removeSession ( self . pendingSession ) self . pendingSession . disconnect ( ) ; self . pendingSession = None elif message == base . SESSION_REJECTED : ", "answer": "self . logger . info ( '' % username )"}, {"prompt": " \"\"\"\"\"\" import logging import multiprocessing import os import random import threading import unittest from google . cloud . dataflow . io import gcsio from google . cloud . dataflow . internal . clients import storage class FakeGcsClient ( object ) : def __init__ ( self ) : self . objects = FakeGcsObjects ( ) class FakeFile ( object ) : def __init__ ( self , bucket , obj , contents , generation ) : self . bucket = bucket self . object = obj self . contents = contents self . generation = generation def get_metadata ( self ) : return storage . Object ( bucket = self . bucket , name = self . object , generation = self . generation , size = len ( self . contents ) ) class FakeGcsObjects ( object ) : def __init__ ( self ) : self . files = { } self . list_page_tokens = { } def add_file ( self , f ) : self . files [ ( f . bucket , f . object ) ] = f def get_file ( self , bucket , obj ) : return self . files . get ( ( bucket , obj ) , None ) def Get ( self , get_request , download = None ) : f = self . get_file ( get_request . bucket , get_request . object ) if f is None : raise ValueError ( '' ) if download is None : return f . get_metadata ( ) else : stream = download . stream def get_range_callback ( start , end ) : assert start >= and end >= start and end < len ( f . contents ) stream . write ( f . contents [ start : end + ] ) download . GetRange = get_range_callback def Insert ( self , insert_request , upload = None ) : assert upload is not None generation = f = self . get_file ( insert_request . bucket , insert_request . name ) if f is not None : generation = f . generation + f = FakeFile ( insert_request . bucket , insert_request . name , '' , generation ) stream = upload . stream data_list = [ ] while True : data = stream . read ( * ) if not data : break data_list . append ( data ) f . contents = '' . join ( data_list ) self . add_file ( f ) def List ( self , list_request ) : bucket = list_request . bucket prefix = list_request . prefix or '' matching_files = [ ] for file_bucket , file_name in sorted ( iter ( self . files ) ) : if bucket == file_bucket and file_name . startswith ( prefix ) : file_object = self . files [ ( file_bucket , file_name ) ] . get_metadata ( ) matching_files . append ( file_object ) items_per_page = if not list_request . pageToken : range_start = else : if list_request . pageToken not in self . list_page_tokens : raise ValueError ( '' ) range_start = self . list_page_tokens [ list_request . pageToken ] del self . list_page_tokens [ list_request . pageToken ] result = storage . Objects ( items = matching_files [ range_start : range_start + items_per_page ] ) if range_start + items_per_page < len ( matching_files ) : next_range_start = range_start + items_per_page next_page_token = '' % ( bucket , prefix , next_range_start ) self . list_page_tokens [ next_page_token ] = next_range_start result . nextPageToken = next_page_token return result class TestGCSPathParser ( unittest . TestCase ) : def test_gcs_path ( self ) : self . assertEqual ( gcsio . parse_gcs_path ( '' ) , ( '' , '' ) ) self . assertEqual ( gcsio . parse_gcs_path ( '' ) , ( '' , '' ) ) def test_bad_gcs_path ( self ) : self . assertRaises ( ValueError , gcsio . parse_gcs_path , '' ) self . assertRaises ( ValueError , gcsio . parse_gcs_path , '' ) self . assertRaises ( ValueError , gcsio . parse_gcs_path , '' ) self . assertRaises ( ValueError , gcsio . parse_gcs_path , '' ) self . assertRaises ( ValueError , gcsio . parse_gcs_path , '' ) self . assertRaises ( ValueError , gcsio . parse_gcs_path , '' ) class TestGCSIO ( unittest . TestCase ) : def _insert_random_file ( self , client , path , size , generation = ) : bucket , name = gcsio . parse_gcs_path ( path ) f = FakeFile ( bucket , name , os . urandom ( size ) , generation ) client . objects . add_file ( f ) return f def setUp ( self ) : self . client = FakeGcsClient ( ) self . gcs = gcsio . GcsIO ( self . client ) def test_full_file_read ( self ) : file_name = '' file_size = * * + random_file = self . _insert_random_file ( self . client , file_name , file_size ) f = self . gcs . open ( file_name ) f . seek ( , os . SEEK_END ) self . assertEqual ( f . tell ( ) , file_size ) self . assertEqual ( f . read ( ) , '' ) f . seek ( ) self . assertEqual ( f . read ( ) , random_file . contents ) def test_file_random_seek ( self ) : file_name = '' file_size = * * - random_file = self . _insert_random_file ( self . client , file_name , file_size ) f = self . gcs . open ( file_name ) random . seed ( ) for _ in range ( , ) : a = random . randint ( , file_size - ) b = random . randint ( , file_size - ) start , end = min ( a , b ) , max ( a , b ) f . seek ( start ) self . assertEqual ( f . tell ( ) , start ) self . assertEqual ( f . read ( end - start + ) , random_file . contents [ start : end + ] ) self . assertEqual ( f . tell ( ) , end + ) def test_file_read_line ( self ) : file_name = '' lines = [ ] read_buffer_size = lines . append ( '' * + '' ) for _ in range ( , ) : line_length = random . randint ( , ) line = os . urandom ( line_length ) . replace ( '' , '' ) + '' lines . append ( line ) contents = '' . join ( lines ) file_size = len ( contents ) bucket , name = gcsio . parse_gcs_path ( file_name ) self . client . objects . add_file ( FakeFile ( bucket , name , contents , ) ) f = self . gcs . open ( file_name , read_buffer_size = read_buffer_size ) f . seek ( ) self . assertEqual ( f . readline ( ) , lines [ ] ) self . assertEqual ( f . tell ( ) , len ( lines [ ] ) ) self . assertEqual ( f . readline ( ) , lines [ ] ) f . seek ( file_size - len ( lines [ - ] ) - ) self . assertEqual ( f . readline ( ) , '' ) f . seek ( file_size ) self . assertEqual ( f . readline ( ) , '' ) random . seed ( ) for _ in range ( , ) : start = random . randint ( , file_size - ) line_index = chars_left = start while True : next_line_length = len ( lines [ line_index ] ) if chars_left - next_line_length < : break chars_left -= next_line_length line_index += f . seek ( start ) self . assertEqual ( f . readline ( ) , lines [ line_index ] [ chars_left : ] ) def test_file_write ( self ) : file_name = '' file_size = * * + contents = os . urandom ( file_size ) f = self . gcs . open ( file_name , '' ) f . write ( contents [ : ] ) f . write ( contents [ : * ] ) f . write ( contents [ * : ] ) f . close ( ) bucket , name = gcsio . parse_gcs_path ( file_name ) self . assertEqual ( self . client . objects . get_file ( bucket , name ) . contents , contents ) def test_context_manager ( self ) : file_name = '' file_size = contents = os . urandom ( file_size ) with self . gcs . open ( file_name , '' ) as f : f . write ( contents ) bucket , name = gcsio . parse_gcs_path ( file_name ) self . assertEqual ( self . client . objects . get_file ( bucket , name ) . contents , contents ) with self . gcs . open ( file_name ) as f : self . assertEqual ( f . read ( ) , contents ) with self . assertRaises ( ZeroDivisionError ) : with self . gcs . open ( file_name ) as f : f . read ( / ) def test_glob ( self ) : bucket_name = '' object_names = [ '' , '' , ", "answer": "'' ,"}, {"prompt": " import json import numpy as np from vispy import app , gloo from vispy . util import load_data_file from vispy . visuals . collections import PathCollection , PolygonCollection from vispy . visuals . transforms import PanZoomTransform path = load_data_file ( '' ) with open ( path , '' ) as f : geo = json . load ( f ) def unique_rows ( data ) : v = data . view ( data . dtype . descr * data . shape [ ] ) _ , idx = np . unique ( v , return_index = True ) ", "answer": "return data [ np . sort ( idx ) ]"}, {"prompt": " from django import template from django . core . urlresolvers import reverse from django . utils . translation import ugettext as _ register = template . Library ( ) def user_collections_dashboard ( collections , user ) : html = '' for collection in collections : is_default = collection . is_default_to_user ( user ) classname = u'' if is_default else u'' name = collection . name edit_url = reverse ( '' , args = [ collection . pk ] ) edit_label = _ ( '' ) activation_label = _ ( '' ) activation_url = reverse ( '' , args = [ user . pk , collection . pk ] ) if not is_default : activation_snippet = u\"\"\"\"\"\" . format ( activation_url = activation_url , activation_label = activation_label , lowercase_name = name . lower ( ) ) . strip ( ) else : activation_snippet = u\"\"\"\"\"\" . format ( activation_url = activation_url , activation_label = activation_label , lowercase_name = name . lower ( ) ) . strip ( ) if collection . is_managed_by_user ( user ) : html_edit = u\"\"\"\"\"\" . format ( edit_url = edit_url , edit_label = edit_label , lowercase_name = name . lower ( ) ) . strip ( ) else : ", "answer": "html_edit = u\"\"\"\"\"\" . format ( edit_url = edit_url ,"}, {"prompt": " from assertpy import assert_that , fail import sys if sys . version_info [ ] == : unicode = str else : unicode = unicode class TestString ( object ) : def test_is_length ( self ) : assert_that ( '' ) . is_length ( ) def test_is_length_failure ( self ) : try : assert_that ( '' ) . is_length ( ) fail ( '' ) except AssertionError as ex : assert_that ( str ( ex ) ) . is_equal_to ( '' ) def test_contains ( self ) : assert_that ( '' ) . contains ( '' ) assert_that ( '' ) . contains ( '' ) assert_that ( '' ) . contains ( '' , '' ) assert_that ( '' ) . contains ( '' ) assert_that ( '' ) . contains ( '' , '' , '' ) def test_contains_single_item_failure ( self ) : try : assert_that ( '' ) . contains ( '' ) fail ( '' ) except AssertionError as ex : assert_that ( str ( ex ) ) . is_equal_to ( '' ) def test_contains_multi_item_failure ( self ) : try : assert_that ( '' ) . contains ( '' , '' , '' ) fail ( '' ) except AssertionError as ex : assert_that ( str ( ex ) ) . is_equal_to ( \"\" ) def test_contains_ignoring_case ( self ) : assert_that ( '' ) . contains_ignoring_case ( '' ) assert_that ( '' ) . contains_ignoring_case ( '' ) assert_that ( '' ) . contains_ignoring_case ( '' ) assert_that ( '' ) . contains_ignoring_case ( '' , '' , '' , '' , '' , '' , '' ) def test_contains_ignoring_case_type_failure ( self ) : try : assert_that ( ) . contains_ignoring_case ( '' ) fail ( '' ) ", "answer": "except TypeError as ex :"}, {"prompt": " from django . contrib import admin from . models import DiscoveryModule class DiscoveryModuleAdmin ( admin . ModelAdmin ) : list_display = ( '' , '' , '' , '' ) ", "answer": "admin . site . register ( DiscoveryModule , DiscoveryModuleAdmin ) "}, {"prompt": " import os import sys import json import time import struct import socket import logging import ssl if sys . version_info [ ] == : import httplib import urlparse else : from urllib import parse as urlparse from http import client as httplib __all__ = ( '' , '' , '' , '' ) def random_luid ( ) : rnd = os . urandom ( ) + '' luid = struct . unpack ( '' , rnd ) [ ] return luid def update_luids ( obj ) : \"\"\"\"\"\" if isinstance ( obj , dict ) : for key in obj : value = obj [ key ] if key == '' : obj [ '' ] = random_luid ( ) elif isinstance ( value , dict ) or isinstance ( value , list ) : update_luids ( value ) elif isinstance ( obj , list ) : for elem in obj : update_luids ( elem ) return obj class RavelloError ( Exception ) : \"\"\"\"\"\" def __str__ ( self ) : if len ( self . args ) == : return '' % ( self . args [ ] , self . args [ ] ) else : return self . args [ ] def should_retry ( exc ) : \"\"\"\"\"\" if isinstance ( exc , socket . timeout ) : return True elif isinstance ( exc , ssl . SSLError ) : return '' in exc [ ] return False def idempotent ( method ) : return method in ( '' , '' , '' ) class RavelloClient ( object ) : \"\"\"\"\"\" default_retries = default_timeout = default_url = '' def __init__ ( self , username = None , password = None , service_url = None , token = None , retries = None , timeout = None ) : \"\"\"\"\"\" self . logger = logging . getLogger ( '' ) self . username = username self . password = password self . _set_url ( service_url ) self . token = token self . retries = retries or self . default_retries self . timeout = timeout or self . default_timeout self . connection = None self . _cookie = None self . _project = None self . _total_retries = def __getstate__ ( self ) : \"\"\"\"\"\" state = self . __dict__ . copy ( ) state [ '' ] = None if state [ '' ] : state [ '' ] = True return state def __setstate__ ( self , state ) : \"\"\"\"\"\" self . __dict__ . update ( state ) self . logger = logging . getLogger ( '' ) if self . connection : self . _connect ( ) def __repr__ ( self ) : res = '' . format ( self . __class__ . __name__ , self . url ) if self . _cookie : res += '' elif self . connection : res += '' else : res += '' res += '>' return res def _set_url ( self , url ) : \"\"\"\"\"\" if url is None : url = self . default_url ", "answer": "parsed = urlparse . urlsplit ( url )"}, {"prompt": " import os from setuptools import find_packages , setup name = '' version = '' readme = os . path . join ( os . path . dirname ( __file__ ) , '' ) long_description = open ( readme ) . read ( ) classifiers = [ '' , '' , ", "answer": "'' ,"}, {"prompt": " \"\"\"\"\"\" from sympy . polys . domains import QQ , ZZ from sympy . polys . polyerrors import ExactQuotientFailed , CoercionFailed , NotReversible from sympy . abc import x , y from sympy . utilities . pytest import raises def test_build_order ( ) : R = QQ . old_poly_ring ( x , y , order = ( ( \"\" , x ) , ( \"\" , y ) ) ) assert R . order ( ( , ) ) == ( ( , ) , ( - , ) ) def test_globalring ( ) : Qxy = QQ . old_frac_field ( x , y ) R = QQ . old_poly_ring ( x , y ) X = R . convert ( x ) Y = R . convert ( y ) assert x in R assert / x not in R assert / ( + x ) not in R assert Y in R assert X . ring == R assert X * ( Y ** + ) == R . convert ( x * ( y ** + ) ) assert X * y == X * Y == R . convert ( x * y ) == x * Y assert X + y == X + Y == R . convert ( x + y ) == x + Y assert X - y == X - Y == R . convert ( x - y ) == x - Y assert X + == R . convert ( x + ) raises ( ExactQuotientFailed , lambda : X / Y ) raises ( ExactQuotientFailed , lambda : x / Y ) raises ( ExactQuotientFailed , lambda : X / y ) assert X ** / X == X assert R . from_GlobalPolynomialRing ( ZZ . old_poly_ring ( x , y ) . convert ( x ) , ZZ . old_poly_ring ( x , y ) ) == X assert R . from_FractionField ( Qxy . convert ( x ) , Qxy ) == X assert R . from_FractionField ( Qxy . convert ( x ) / y , Qxy ) is None assert R . _sdm_to_vector ( R . _vector_to_sdm ( [ X , Y ] , R . order ) , ) == [ X , Y ] def test_localring ( ) : Qxy = QQ . old_frac_field ( x , y ) R = QQ . old_poly_ring ( x , y , order = \"\" ) X = R . convert ( x ) Y = R . convert ( y ) assert x in R assert / x not in R assert / ( + x ) in R assert Y in R assert X . ring == R assert X * ( Y ** + ) / ( + X ) == R . convert ( x * ( y ** + ) / ( + x ) ) assert X * y == X * Y raises ( ExactQuotientFailed , lambda : X / Y ) raises ( ExactQuotientFailed , lambda : x / Y ) raises ( ExactQuotientFailed , lambda : X / y ) assert X + y == X + Y == R . convert ( x + y ) == x + Y assert X - y == X - Y == R . convert ( x - y ) == x - Y assert X + == R . convert ( x + ) assert X ** / X == X assert R . from_GlobalPolynomialRing ( ZZ . old_poly_ring ( x , y ) . convert ( x ) , ZZ . old_poly_ring ( x , y ) ) == X assert R . from_FractionField ( Qxy . convert ( x ) , Qxy ) == X raises ( CoercionFailed , lambda : R . from_FractionField ( Qxy . convert ( x ) / y , Qxy ) ) raises ( ExactQuotientFailed , lambda : X / Y ) raises ( NotReversible , lambda : X . invert ( ) ) assert R . _sdm_to_vector ( R . _vector_to_sdm ( [ X / ( X + ) , Y / ( + X * Y ) ] , R . order ) , ) == [ X * ( + X * Y ) , Y * ( + X ) ] def test_conversion ( ) : L = QQ . old_poly_ring ( x , y , order = \"\" ) G = QQ . old_poly_ring ( x , y ) assert L . convert ( x ) == L . convert ( G . convert ( x ) , G ) assert G . convert ( x ) == G . convert ( L . convert ( x ) , L ) raises ( CoercionFailed , lambda : G . convert ( L . convert ( / ( + x ) ) , L ) ) def test_units ( ) : ", "answer": "R = QQ . old_poly_ring ( x )"}, {"prompt": " \"\"\"\"\"\" from . . phonemetadata import NumberFormat , PhoneNumberDesc , PhoneMetadata PHONE_METADATA_CX = PhoneMetadata ( id = '' , country_code = , international_prefix = '' , general_desc = PhoneNumberDesc ( national_number_pattern = '' , possible_number_pattern = '' ) , fixed_line = PhoneNumberDesc ( national_number_pattern = '' , possible_number_pattern = '' , example_number = '' ) , mobile = PhoneNumberDesc ( national_number_pattern = '' , possible_number_pattern = '' , example_number = '' ) , toll_free = PhoneNumberDesc ( national_number_pattern = '' , possible_number_pattern = '' , example_number = '' ) , premium_rate = PhoneNumberDesc ( national_number_pattern = '' , possible_number_pattern = '' , example_number = '' ) , shared_cost = PhoneNumberDesc ( national_number_pattern = '' , possible_number_pattern = '' ) , personal_number = PhoneNumberDesc ( national_number_pattern = '' , possible_number_pattern = '' , example_number = '' ) , voip = PhoneNumberDesc ( national_number_pattern = '' , possible_number_pattern = '' , example_number = '' ) , pager = PhoneNumberDesc ( national_number_pattern = '' , possible_number_pattern = '' ) , uan = PhoneNumberDesc ( national_number_pattern = '' , possible_number_pattern = '' ) , emergency = PhoneNumberDesc ( national_number_pattern = '' , possible_number_pattern = '' , example_number = '' ) , voicemail = PhoneNumberDesc ( national_number_pattern = '' , possible_number_pattern = '' ) , no_international_dialling = PhoneNumberDesc ( national_number_pattern = '' , possible_number_pattern = '' ) , preferred_international_prefix = '' , ", "answer": "national_prefix = '' ,"}, {"prompt": " \"\"\"\"\"\" from subprocess import Popen , PIPE , check_output , CalledProcessError from contextlib import contextmanager from io import BytesIO from threading import current_thread from pipes import quote from zope . interface import Interface , implementer from characteristic import with_cmp , with_repr class INode ( Interface ) : \"\"\"\"\"\" def run ( remote_command ) : \"\"\"\"\"\" def get_output ( remote_command ) : \"\"\"\"\"\" @ with_cmp ( [ \"\" ] ) @ with_repr ( [ \"\" ] ) @ implementer ( INode ) class ProcessNode ( object ) : \"\"\"\"\"\" def __init__ ( self , initial_command_arguments , quote = lambda d : d ) : \"\"\"\"\"\" self . initial_command_arguments = tuple ( initial_command_arguments ) self . _quote = quote @ contextmanager def run ( self , remote_command ) : process = Popen ( self . initial_command_arguments + tuple ( map ( self . _quote , remote_command ) ) , stdin = PIPE ) try : yield process . stdin finally : process . stdin . close ( ) exit_code = process . wait ( ) if exit_code : raise IOError ( \"\" , remote_command , exit_code ) def get_output ( self , remote_command ) : try : return check_output ( self . initial_command_arguments + tuple ( map ( self . _quote , remote_command ) ) ) except CalledProcessError as e : raise IOError ( \"\" , remote_command , e . returncode , e . output ) @ classmethod def using_ssh ( cls , host , port , username , private_key ) : \"\"\"\"\"\" return cls ( initial_command_arguments = ( b\"\" , b\"\" , b\"\" , private_key . path , ", "answer": "b\"\" , username ,"}, {"prompt": " from __future__ import unicode_literals import os import re from django . utils import six from django . utils . six . moves import range from reviewboard . diffviewer . processors import ( filter_interdiff_opcodes , post_process_filtered_equals ) class MoveRange ( object ) : \"\"\"\"\"\" def __init__ ( self , start , end , groups = [ ] ) : self . start = start self . end = end self . groups = groups @ property def last_group ( self ) : return self . groups [ - ] def add_group ( self , group , group_index ) : if self . groups [ - ] != group : self . groups . append ( ( group , group_index ) ) def __repr__ ( self ) : return '' % ( self . start , self . end , self . groups ) class DiffOpcodeGenerator ( object ) : ALPHANUM_RE = re . compile ( r'' ) WHITESPACE_RE = re . compile ( r'' ) MOVE_PREFERRED_MIN_LINES = MOVE_MIN_LINE_LENGTH = TAB_SIZE = def __init__ ( self , differ , diff = None , interdiff = None ) : self . differ = differ self . diff = diff self . interdiff = interdiff def __iter__ ( self ) : \"\"\"\"\"\" self . groups = [ ] self . removes = { } self . inserts = [ ] opcodes = self . differ . get_opcodes ( ) opcodes = self . _apply_processors ( opcodes ) opcodes = self . _generate_opcode_meta ( opcodes ) opcodes = self . _apply_meta_processors ( opcodes ) self . _group_opcodes ( opcodes ) self . _compute_moves ( ) for opcodes in self . groups : yield opcodes def _apply_processors ( self , opcodes ) : if self . diff and self . interdiff : opcodes = filter_interdiff_opcodes ( opcodes , self . diff , self . interdiff ) for opcode in opcodes : yield opcode def _generate_opcode_meta ( self , opcodes ) : for tag , i1 , i2 , j1 , j2 in opcodes : meta = { '' : False , '' : [ ] , } if tag == '' : assert ( i2 - i1 ) == ( j2 - j1 ) for i , j in zip ( range ( i1 , i2 ) , range ( j1 , j2 ) ) : if ( self . WHITESPACE_RE . sub ( '' , self . differ . a [ i ] ) == self . WHITESPACE_RE . sub ( '' , self . differ . b [ j ] ) ) : meta [ '' ] . append ( ( i + , j + ) ) if len ( meta [ '' ] ) == ( i2 - i1 ) : meta [ '' ] = True elif tag == '' : for group in self . _compute_chunk_indentation ( i1 , i2 , j1 , j2 ) : ii1 , ii2 , ij1 , ij2 , indentation_changes = group if indentation_changes : new_meta = dict ( { '' : indentation_changes , } , ** meta ) else : new_meta = meta yield tag , ii1 , ii2 , ij1 , ij2 , new_meta continue yield tag , i1 , i2 , j1 , j2 , meta def _apply_meta_processors ( self , opcodes ) : if self . interdiff : opcodes = post_process_filtered_equals ( opcodes ) for opcode in opcodes : yield opcode def _group_opcodes ( self , opcodes ) : for group_index , group in enumerate ( opcodes ) : self . groups . append ( group ) tag = group [ ] if tag in ( '' , '' ) : i1 = group [ ] i2 = group [ ] for i in range ( i1 , i2 ) : line = self . differ . a [ i ] . strip ( ) if line : self . removes . setdefault ( line , [ ] ) . append ( ( i , group , group_index ) ) if tag in ( '' , '' ) : self . inserts . append ( group ) def _compute_chunk_indentation ( self , i1 , i2 , j1 , j2 ) : indentation_changes = { } prev_has_indent = False prev_start_i = i1 prev_start_j = j1 for i , j in zip ( range ( i1 , i2 ) , range ( j1 , j2 ) ) : old_line = self . differ . a [ i ] new_line = self . differ . b [ j ] new_indentation_changes = { } indent_info = self . _compute_line_indentation ( old_line , new_line ) has_indent = indent_info is not None if has_indent : key = '' % ( i + , j + ) new_indentation_changes [ key ] = indent_info if has_indent != prev_has_indent : if prev_start_i != i or prev_start_j != j : yield prev_start_i , i , prev_start_j , j , indentation_changes prev_start_i = i prev_start_j = j prev_has_indent = has_indent indentation_changes = new_indentation_changes elif has_indent : indentation_changes . update ( new_indentation_changes ) if prev_start_i != i2 or prev_start_j != j2 : yield prev_start_i , i2 , prev_start_j , j2 , indentation_changes def _compute_line_indentation ( self , old_line , new_line ) : if old_line == new_line : return None old_line_stripped = old_line . lstrip ( ) new_line_stripped = new_line . lstrip ( ) old_line_indent_len = len ( old_line ) - len ( old_line_stripped ) new_line_indent_len = len ( new_line ) - len ( new_line_stripped ) old_line_indent = old_line [ : old_line_indent_len ] new_line_indent = new_line [ : new_line_indent_len ] norm_old_line_indent = old_line_indent . expandtabs ( self . TAB_SIZE ) norm_new_line_indent = new_line_indent . expandtabs ( self . TAB_SIZE ) norm_old_line_indent_len = len ( norm_old_line_indent ) norm_new_line_indent_len = len ( norm_new_line_indent ) norm_old_line_len = ( norm_old_line_indent_len + len ( old_line_stripped ) ) norm_new_line_len = ( norm_new_line_indent_len + len ( new_line_stripped ) ) line_len_diff = norm_new_line_len - norm_old_line_len if line_len_diff == : return None is_indent = ( line_len_diff > ) if is_indent : raw_indent_len = new_line_indent_len else : raw_indent_len = old_line_indent_len raw_indent_len -= len ( os . path . commonprefix ( [ old_line_indent [ : : - ] , new_line_indent [ : : - ] , ] ) ) return ( is_indent , raw_indent_len , abs ( norm_old_line_indent_len - norm_new_line_indent_len ) ) def _compute_moves ( self ) : for insert in self . inserts : self . _compute_move_for_insert ( * insert ) def _compute_move_for_insert ( self , itag , ii1 , ii2 , ij1 , ij2 , imeta ) : i_move_cur = ij1 i_move_range = MoveRange ( i_move_cur , i_move_cur ) r_move_ranges = { } move_key = None is_replace = ( itag == '' ) ", "answer": "while i_move_cur < ij2 :"}, {"prompt": " \"\"\"\"\"\" import os import re import sys import stat import time import gflags _VERSION = '' def _GetDefaultDestDir ( ) : ", "answer": "home = os . environ . get ( '' , '' )"}, {"prompt": " '''''' def __virtual__ ( ) : '''''' return '' in __salt__ def _append_comment ( ret , comment ) : '''''' if len ( ret [ '' ] ) : ret [ '' ] = ret [ '' ] . rstrip ( ) + '' + comment else : ret [ '' ] = comment return ret def present ( name , persist = False , mods = None ) : '''''' if not isinstance ( mods , ( list , tuple ) ) : mods = [ name ] ret = { '' : name , '' : True , '' : { } , '' : '' } loaded_mods = __salt__ [ '' ] ( ) if persist : persist_mods = __salt__ [ '' ] ( True ) loaded_mods = list ( set ( loaded_mods ) & set ( persist_mods ) ) already_loaded = list ( set ( loaded_mods ) & set ( mods ) ) if len ( already_loaded ) == : comment = '' . format ( already_loaded [ ] ) _append_comment ( ret , comment ) elif len ( already_loaded ) > : comment = '' . format ( '' . join ( already_loaded ) ) _append_comment ( ret , comment ) if len ( already_loaded ) == len ( mods ) : return ret not_loaded = list ( set ( mods ) - set ( already_loaded ) ) if __opts__ [ '' ] : ret [ '' ] = None if len ( ret [ '' ] ) : ret [ '' ] += '' if len ( not_loaded ) == : comment = '' . format ( not_loaded [ ] ) else : comment = '' . format ( '' . join ( not_loaded ) ) _append_comment ( ret , comment ) return ret unavailable = list ( set ( not_loaded ) - set ( __salt__ [ '' ] ( ) ) ) if unavailable : if len ( unavailable ) == : comment = '' . format ( unavailable [ ] ) else : comment = '' . format ( '' . join ( unavailable ) ) _append_comment ( ret , comment ) ret [ '' ] = False available = list ( set ( not_loaded ) - set ( unavailable ) ) loaded = { '' : [ ] , '' : [ ] , '' : [ ] } for mod in available : load_result = __salt__ [ '' ] ( mod , persist ) if isinstance ( load_result , ( list , tuple ) ) : if len ( load_result ) > : for module in load_result : ret [ '' ] [ module ] = '' loaded [ '' ] . append ( mod ) else : ret [ '' ] = False loaded [ '' ] . append ( mod ) else : ret [ '' ] = False loaded [ '' ] . append ( [ mod , load_result ] ) if len ( loaded [ '' ] ) == : _append_comment ( ret , '' . format ( loaded [ '' ] [ ] ) ) elif len ( loaded [ '' ] ) > : _append_comment ( ret , '' . format ( '' . join ( loaded [ '' ] ) ) ) if len ( loaded [ '' ] ) == : _append_comment ( ret , '' . format ( loaded [ '' ] [ ] ) ) if len ( loaded [ '' ] ) > : _append_comment ( ret , '' . format ( '' . join ( loaded [ '' ] ) ) ) if len ( loaded [ '' ] ) : for mod , msg in loaded [ '' ] : _append_comment ( ret , '' . format ( mod , msg ) ) return ret def absent ( name , persist = False , comment = True , mods = None ) : '''''' if not isinstance ( mods , ( list , tuple ) ) : mods = [ name ] ret = { '' : name , '' : True , '' : { } , '' : '' } loaded_mods = __salt__ [ '' ] ( ) if persist : persist_mods = __salt__ [ '' ] ( True ) loaded_mods = list ( set ( loaded_mods ) | set ( persist_mods ) ) to_unload = list ( set ( mods ) & set ( loaded_mods ) ) if to_unload : if __opts__ [ '' ] : ret [ '' ] = None if len ( to_unload ) == : _append_comment ( ret , '' . format ( to_unload [ ] ) ) elif len ( to_unload ) > : _append_comment ( ret , '' . format ( '' . join ( to_unload ) ) ) return ret unloaded = { '' : [ ] , '' : [ ] , '' : [ ] } for mod in to_unload : unload_result = __salt__ [ '' ] ( mod , persist , comment ) if isinstance ( unload_result , ( list , tuple ) ) : if len ( unload_result ) > : for module in unload_result : ret [ '' ] [ module ] = '' unloaded [ '' ] . append ( mod ) else : ret [ '' ] = False unloaded [ '' ] . append ( mod ) else : ret [ '' ] = False unloaded [ '' ] . append ( [ mod , unload_result ] ) if len ( unloaded [ '' ] ) == : _append_comment ( ret , '' . format ( unloaded [ '' ] [ ] ) ) elif len ( unloaded [ '' ] ) > : _append_comment ( ret , '' . format ( '' . join ( unloaded [ '' ] ) ) ) if len ( unloaded [ '' ] ) == : _append_comment ( ret , '' . format ( unloaded [ '' ] [ ] ) ) if len ( unloaded [ '' ] ) > : _append_comment ( ret , '' . format ( '' . join ( unloaded [ '' ] ) ) ) if len ( unloaded [ '' ] ) : for mod , msg in unloaded [ '' ] : _append_comment ( ret , '' . format ( mod , msg ) ) return ret else : if len ( mods ) == : ret [ '' ] = '' . format ( mods [ ] ) ", "answer": "else :"}, {"prompt": " import static_pdfs from pdfrw import PdfReader try : import unittest2 as unittest ", "answer": "except ImportError :"}, {"prompt": " import time from fabric . api import env , run , sudo from fabric . context_managers import settings as fabric_settings from fabric . contrib . files import append , comment , sed , uncomment from fabric . operations import reboot import settings DISTRO = \"\" SALT_INSTALLERS = [ \"\" , \"\" ] def bootstrap ( ) : \"\"\"\"\"\" base_packages = [ \"\" , \"\" , \"\" , ] run ( \"\" ) run ( \"\" ) append ( \"\" , '' ) run ( \"\" ) run ( \"\" ) run ( \"\" . format ( pkgs = \"\" . join ( base_packages ) ) ) append ( \"\" , \"\" . format ( env . master_server . private_ip ) ) uncomment ( \"\" , \"\" ) comment ( \"\" , \"\" ) with fabric_settings ( warn_only = True ) : reboot ( ) def install_salt ( installer = \"\" ) : \"\"\"\"\"\" if installer == \"\" : run ( \"\" ) elif installer == \"\" : run ( \"\" ) else : raise NotImplementedError ( ) def setup_salt ( ) : \"\"\"\"\"\" server = [ s for s in env . bootmachine_servers if s . public_ip == env . host ] [ ] if env . host == env . master_server . public_ip : append ( \"\" , \"\" . format ( settings . REMOTE_STATES_DIR ) ) append ( \"\" , \"\" . format ( settings . REMOTE_PILLARS_DIR ) ) run ( \"\" ) sed ( \"\" , \"\" , \"\" . format ( env . master_server . private_ip ) ) sed ( \"\" , \"\" , \"\" . format ( server . name ) ) append ( \"\" , \"\" ) for role in server . roles : append ( \"\" , \"\" . format ( role ) ) run ( \"\" ) run ( \"\" ) def start_salt ( ) : \"\"\"\"\"\" ", "answer": "with fabric_settings ( warn_only = True ) :"}, {"prompt": " import sublime , sublime_plugin import re common = { \"\" : [ \"\" , \"\" ] , \"\" : [ \"\" , \"\" , \"\" , \"\" ] , \"\" : [ \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ] , \"\" : [ \"\" , \"\" , \"\" , \"\" ] , \"\" : [ \"\" ] , \"\" : [ \"\" , \"\" ] , \"\" : [ \"\" ] , \"\" : [ \"\" ] } tss_data = \"\"\"\"\"\" def parse_tss_data ( data ) : props = { } for l in data . splitlines ( ) : if l == \"\" : continue names , values = l . split ( '' ) allowed_values = [ ] for v in values . split ( '' ) : v = v . strip ( ) if v [ ] == '' and v [ - ] == '>' : key = v [ : - ] if key in common : allowed_values += common [ key ] else : allowed_values . append ( v ) for e in names . split ( ) : if e [ ] == '' : props [ e [ : - ] ] = sorted ( allowed_values ) else : break return props class TSSCompletions ( sublime_plugin . EventListener ) : props = None rex = None def on_query_completions ( self , view , prefix , locations ) : if not view . match_selector ( locations [ ] , \"\" ) : return [ ] if not self . props : self . props = parse_tss_data ( tss_data ) self . rex = re . compile ( \"\" ) l = [ ] if ( view . match_selector ( locations [ ] , \"\" ) or view . match_selector ( locations [ ] - , \"\" ) ) : loc = locations [ ] - len ( prefix ) line = view . substr ( sublime . Region ( view . line ( loc ) . begin ( ) , loc ) ) m = re . search ( self . rex , line ) if m : prop_name = m . group ( ) if prop_name in self . props : values = self . props [ prop_name ] add_semi_colon = view . substr ( sublime . Region ( locations [ ] , locations [ ] + ) ) != '' for v in values : desc = v snippet = v if add_semi_colon : snippet += \"\" if snippet . find ( \"\" ) != - : desc = desc . replace ( \"\" , \"\" ) l . append ( ( desc , snippet ) ) return ( l , sublime . INHIBIT_WORD_COMPLETIONS ) return None else : add_colon = not view . match_selector ( locations [ ] , \"\" ) for p in self . props : if add_colon : l . append ( ( p , p + \"\" ) ) else : l . append ( ( p , p ) ) ", "answer": "return ( l , sublime . INHIBIT_WORD_COMPLETIONS ) "}, {"prompt": " __all__ = [ '' , '' , '' , '' ] class Queue ( object ) : def __new__ ( cls , mode = '' , * args , ** kwargs ) : if mode == '' : from zenqueue . queue import async return async . Queue ( * args , ** kwargs ) elif mode == '' : from zenqueue . queue import sync ", "answer": "return sync . Queue ( * args , ** kwargs )"}, {"prompt": " from __future__ import print_function , absolute_import , division import itertools import math import sys import numpy as np from numba import unittest_support as unittest from numba . compiler import compile_isolated , Flags , utils from numba import jit , typeof , types from numba . numpy_support import version as np_version from . support import TestCase , CompilationCache no_pyobj_flags = Flags ( ) no_pyobj_flags . set ( \"\" ) def sinc ( x ) : return np . sinc ( x ) def angle1 ( x ) : return np . angle ( x ) def angle2 ( x , deg ) : return np . angle ( x , deg ) def diff1 ( a ) : return np . diff ( a ) def diff2 ( a , n ) : return np . diff ( a , n ) def bincount1 ( a ) : return np . bincount ( a ) def bincount2 ( a , w ) : return np . bincount ( a , weights = w ) def searchsorted ( a , v ) : return np . searchsorted ( a , v ) def digitize ( * args ) : return np . digitize ( * args ) def histogram ( * args ) : return np . histogram ( * args ) class TestNPFunctions ( TestCase ) : \"\"\"\"\"\" def setUp ( self ) : self . ccache = CompilationCache ( ) self . rnd = np . random . RandomState ( ) def run_unary ( self , pyfunc , x_types , x_values , flags = no_pyobj_flags , func_extra_types = None , func_extra_args = None , ignore_sign_on_zero = False , abs_tol = None , ** kwargs ) : \"\"\"\"\"\" for tx , vx in zip ( x_types , x_values ) : if func_extra_args is None : func_extra_types = func_extra_args = [ ( ) ] for xtypes , xargs in zip ( func_extra_types , func_extra_args ) : cr = self . ccache . compile ( pyfunc , ( tx , ) + xtypes , flags = flags ) cfunc = cr . entry_point got = cfunc ( vx , * xargs ) expected = pyfunc ( vx , * xargs ) try : scalty = tx . dtype except AttributeError : scalty = tx prec = ( '' if scalty in ( types . float32 , types . complex64 ) else '' ) msg = '' % ( vx , prec ) self . assertPreciseEqual ( got , expected , prec = prec , msg = msg , ignore_sign_on_zero = ignore_sign_on_zero , abs_tol = abs_tol , ** kwargs ) def test_sinc ( self ) : \"\"\"\"\"\" isoz = True tol = \"\" pyfunc = sinc def check ( x_types , x_values , ** kwargs ) : self . run_unary ( pyfunc , x_types , x_values , ignore_sign_on_zero = isoz , abs_tol = tol , ** kwargs ) x_values = [ , - , , - , , - , , - , , - ] x_types = [ types . float32 , types . float64 ] * ( len ( x_values ) // ) check ( x_types , x_values ) x_values = [ np . array ( x_values , dtype = np . float64 ) ] x_types = [ typeof ( v ) for v in x_values ] ", "answer": "check ( x_types , x_values )"}, {"prompt": " \"\"\"\"\"\" from cinderclient import base class Capabilities ( base . Resource ) : NAME_ATTR = '' def __repr__ ( self ) : ", "answer": "return \"\" % self . name"}, {"prompt": " import numpy as np from numpy . testing import assert_array_equal , run_module_suite from skimage . measure import label import skimage . measure . _ccomp as ccomp from skimage . _shared . _warnings import expected_warnings BG = class TestConnectedComponents : def setup ( self ) : self . x = np . array ( [ [ , , , , , ] , [ , , , , , ] , [ , , , , , ] , [ , , , , , ] ] ) self . labels = np . array ( [ [ , , , , , ] , [ , , , , , ] , [ , , , , , ] , [ , , , , , ] ] ) def test_basic ( self ) : assert_array_equal ( label ( self . x ) , self . labels ) assert self . x [ , ] == def test_random ( self ) : x = ( np . random . rand ( , ) * ) . astype ( np . int ) labels = label ( x ) n = labels . max ( ) for i in range ( n ) : values = x [ labels == i ] assert np . all ( values == values [ ] ) def test_diag ( self ) : x = np . array ( [ [ , , ] , [ , , ] , [ , , ] ] ) assert_array_equal ( label ( x ) , x ) def test_4_vs_8 ( self ) : x = np . array ( [ [ , ] , [ , ] ] , dtype = int ) assert_array_equal ( label ( x , ) , [ [ , ] , [ , ] ] ) assert_array_equal ( label ( x , ) , [ [ , ] , [ , ] ] ) def test_background ( self ) : x = np . array ( [ [ , , ] , [ , , ] , [ , , ] ] ) assert_array_equal ( label ( x ) , [ [ , , ] , [ , , ] , [ , , ] ] ) assert_array_equal ( label ( x , background = ) , [ [ , , ] , [ , , ] , [ , , ] ] ) def test_background_two_regions ( self ) : x = np . array ( [ [ , , ] , [ , , ] , [ , , ] ] ) res = label ( x , background = ) assert_array_equal ( res , [ [ , , ] , [ , , ] , [ , , ] ] ) def test_background_one_region_center ( self ) : x = np . array ( [ [ , , ] , [ , , ] , [ , , ] ] ) assert_array_equal ( label ( x , neighbors = , background = ) , [ [ , , ] , [ , , ] , [ , , ] ] ) def test_return_num ( self ) : x = np . array ( [ [ , , ] , [ , , ] , [ , , ] ] ) assert_array_equal ( label ( x , return_num = True ) [ ] , ) assert_array_equal ( label ( x , background = - , return_num = True ) [ ] , ) class TestConnectedComponents3d : def setup ( self ) : self . x = np . zeros ( ( , , ) , int ) self . x [ ] = np . array ( [ [ , , , , ] , [ , , , , ] , ", "answer": "[ , , , , ] ,"}, {"prompt": " from __future__ import print_function from __future__ import unicode_literals try : from urllib . parse import quote as urlquote except ImportError : from urllib import quote as urlquote class DatabaseAPI ( object ) : def list_databases ( self ) : \"\"\"\"\"\" with self . get ( \"\" ) as res : code , body = res . status , res . read ( ) if code != : self . raise_error ( \"\" , res , body ) js = self . checked_json ( body , [ \"\" ] ) result = { } for m in js [ \"\" ] : name = m . get ( \"\" ) count = m . get ( \"\" ) created_at = self . _parsedate ( self . get_or_else ( m , \"\" , \"\" ) , \"\" ) ", "answer": "updated_at = self . _parsedate ( self . get_or_else ( m , \"\" , \"\" ) , \"\" )"}, {"prompt": " '''''' ", "answer": "import re , urllib"}, {"prompt": " \"\"\"\"\"\" import inspect import itertools import logging import logging . config import logging . handlers import os import sys import traceback from oslo_config import cfg import six from six import moves _PY26 = sys . version_info [ : ] == ( , ) from os_doc_tools . openstack . common . gettextutils import _ from os_doc_tools . openstack . common import importutils from os_doc_tools . openstack . common import jsonutils from os_doc_tools . openstack . common import local from os_doc_tools . openstack . common . strutils import mask_password _DEFAULT_LOG_DATE_FORMAT = \"\" common_cli_opts = [ cfg . BoolOpt ( '' , short = '' , default = False , help = '' '' ) , cfg . BoolOpt ( '' , short = '' , default = False , help = '' '' ) , ] logging_cli_opts = [ cfg . StrOpt ( '' , metavar = '' , deprecated_name = '' , help = '' '' '' '' ) , cfg . StrOpt ( '' , metavar = '' , help = '' '' '' '' '' '' ) , cfg . StrOpt ( '' , default = _DEFAULT_LOG_DATE_FORMAT , metavar = '' , help = '' '' ) , cfg . StrOpt ( '' , metavar = '' , deprecated_name = '' , help = '' '' ) , cfg . StrOpt ( '' , deprecated_name = '' , help = '' '' ) , cfg . BoolOpt ( '' , default = False , help = '' '' '' ) , cfg . BoolOpt ( '' , default = False , help = '' '' '' '' '' ) , cfg . StrOpt ( '' , default = '' , help = '' ) ] generic_log_opts = [ cfg . BoolOpt ( '' , default = True , help = '' ) ] DEFAULT_LOG_LEVELS = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ] log_opts = [ cfg . StrOpt ( '' , default = '' '' '' , help = '' ) , cfg . StrOpt ( '' , default = '' '' , help = '' ) , cfg . StrOpt ( '' , default = '' , help = '' ) , cfg . StrOpt ( '' , default = '' '' , help = '' ) , cfg . ListOpt ( '' , default = DEFAULT_LOG_LEVELS , help = '' ) , cfg . BoolOpt ( '' , default = False , help = '' ) , cfg . BoolOpt ( '' , default = False , help = '' ) , cfg . StrOpt ( '' , ", "answer": "default = '' ,"}, {"prompt": " from django . db import models from django . contrib . auth . models import User from postgres . fields import JSONField from django . contrib . postgres . fields import ArrayField from django . dispatch import receiver from django . db . models . signals import pre_delete , post_save class Session ( models . Model ) : user = models . ForeignKey ( User ) start = models . DateTimeField ( auto_now_add = True ) @ classmethod def current_for_user ( kls , user ) : sessions = list ( kls . objects . filter ( user = user ) . order_by ( '' ) [ : ] ) if sessions : sess = sessions [ ] else : sess = kls ( user = user ) sess . save ( ) return sess def __str__ ( self ) : return \"\" % ( self . user . username , self . start . date ( ) . isoformat ( ) ) class Meta : index_together = ( ( '' , '' ) ) class Firm ( models . Model ) : ", "answer": "name = models . TextField ( )"}, {"prompt": " \"\"\"\"\"\" __author__ = '' import base64 import clientsecrets import copy import datetime import httplib2 import logging import os import sys import time import urllib import urlparse from oauth2client import GOOGLE_AUTH_URI from oauth2client import GOOGLE_REVOKE_URI from oauth2client import GOOGLE_TOKEN_URI from oauth2client import util from oauth2client . anyjson import simplejson HAS_OPENSSL = False HAS_CRYPTO = False try : from oauth2client import crypt HAS_CRYPTO = True if crypt . OpenSSLVerifier is not None : HAS_OPENSSL = True except ImportError : pass try : from urlparse import parse_qsl except ImportError : from cgi import parse_qsl logger = logging . getLogger ( __name__ ) EXPIRY_FORMAT = '' ID_TOKEN_VERIFICATON_CERTS = '' OOB_CALLBACK_URN = '' REFRESH_STATUS_CODES = [ ] class Error ( Exception ) : \"\"\"\"\"\" class FlowExchangeError ( Error ) : \"\"\"\"\"\" class AccessTokenRefreshError ( Error ) : \"\"\"\"\"\" class TokenRevokeError ( Error ) : \"\"\"\"\"\" class UnknownClientSecretsFlowError ( Error ) : \"\"\"\"\"\" class AccessTokenCredentialsError ( Error ) : \"\"\"\"\"\" class VerifyJwtTokenError ( Error ) : \"\"\"\"\"\" class NonAsciiHeaderError ( Error ) : \"\"\"\"\"\" def _abstract ( ) : raise NotImplementedError ( '' ) class MemoryCache ( object ) : \"\"\"\"\"\" def __init__ ( self ) : self . cache = { } def get ( self , key ) : return self . cache . get ( key ) def set ( self , key , value ) : self . cache [ key ] = value def delete ( self , key ) : self . cache . pop ( key , None ) class Credentials ( object ) : \"\"\"\"\"\" NON_SERIALIZED_MEMBERS = [ '' ] def authorize ( self , http ) : \"\"\"\"\"\" _abstract ( ) def refresh ( self , http ) : \"\"\"\"\"\" _abstract ( ) def revoke ( self , http ) : \"\"\"\"\"\" _abstract ( ) def apply ( self , headers ) : \"\"\"\"\"\" _abstract ( ) def _to_json ( self , strip ) : \"\"\"\"\"\" t = type ( self ) d = copy . copy ( self . __dict__ ) for member in strip : if member in d : del d [ member ] if '' in d and isinstance ( d [ '' ] , datetime . datetime ) : d [ '' ] = d [ '' ] . strftime ( EXPIRY_FORMAT ) d [ '' ] = t . __name__ d [ '' ] = t . __module__ return simplejson . dumps ( d ) def to_json ( self ) : \"\"\"\"\"\" return self . _to_json ( Credentials . NON_SERIALIZED_MEMBERS ) @ classmethod def new_from_json ( cls , s ) : \"\"\"\"\"\" data = simplejson . loads ( s ) module = data [ '' ] try : m = __import__ ( module ) except ImportError : module = module . replace ( '' , '' ) m = __import__ ( module ) m = __import__ ( module , fromlist = module . split ( '' ) [ : - ] ) kls = getattr ( m , data [ '' ] ) from_json = getattr ( kls , '' ) return from_json ( s ) @ classmethod def from_json ( cls , s ) : \"\"\"\"\"\" return Credentials ( ) class Flow ( object ) : \"\"\"\"\"\" pass class Storage ( object ) : \"\"\"\"\"\" def acquire_lock ( self ) : \"\"\"\"\"\" pass def release_lock ( self ) : \"\"\"\"\"\" pass def locked_get ( self ) : \"\"\"\"\"\" _abstract ( ) def locked_put ( self , credentials ) : \"\"\"\"\"\" _abstract ( ) def locked_delete ( self ) : \"\"\"\"\"\" _abstract ( ) def get ( self ) : \"\"\"\"\"\" self . acquire_lock ( ) try : return self . locked_get ( ) finally : self . release_lock ( ) def put ( self , credentials ) : \"\"\"\"\"\" self . acquire_lock ( ) try : self . locked_put ( credentials ) finally : self . release_lock ( ) def delete ( self ) : \"\"\"\"\"\" self . acquire_lock ( ) try : return self . locked_delete ( ) finally : self . release_lock ( ) def clean_headers ( headers ) : \"\"\"\"\"\" clean = { } try : for k , v in headers . iteritems ( ) : clean [ str ( k ) ] = str ( v ) except UnicodeEncodeError : raise NonAsciiHeaderError ( k + '' + v ) return clean def _update_query_params ( uri , params ) : \"\"\"\"\"\" parts = list ( urlparse . urlparse ( uri ) ) query_params = dict ( parse_qsl ( parts [ ] ) ) query_params . update ( params ) parts [ ] = urllib . urlencode ( query_params ) return urlparse . urlunparse ( parts ) class OAuth2Credentials ( Credentials ) : \"\"\"\"\"\" @ util . positional ( ) def __init__ ( self , access_token , client_id , client_secret , refresh_token , token_expiry , token_uri , user_agent , revoke_uri = None , id_token = None , token_response = None ) : \"\"\"\"\"\" self . access_token = access_token self . client_id = client_id self . client_secret = client_secret self . refresh_token = refresh_token self . store = None self . token_expiry = token_expiry self . token_uri = token_uri self . user_agent = user_agent self . revoke_uri = revoke_uri self . id_token = id_token self . token_response = token_response self . invalid = False def authorize ( self , http ) : \"\"\"\"\"\" request_orig = http . request @ util . positional ( ) def new_request ( uri , method = '' , body = None , headers = None , redirections = httplib2 . DEFAULT_MAX_REDIRECTS , connection_type = None ) : if not self . access_token : logger . info ( '' ) self . _refresh ( request_orig ) if headers is None : headers = { } self . apply ( headers ) if self . user_agent is not None : if '' in headers : headers [ '' ] = self . user_agent + '' + headers [ '' ] else : headers [ '' ] = self . user_agent resp , content = request_orig ( uri , method , body , clean_headers ( headers ) , redirections , connection_type ) if resp . status in REFRESH_STATUS_CODES : logger . info ( '' % str ( resp . status ) ) self . _refresh ( request_orig ) self . apply ( headers ) return request_orig ( uri , method , body , clean_headers ( headers ) , redirections , connection_type ) else : return ( resp , content ) http . request = new_request setattr ( http . request , '' , self ) return http def refresh ( self , http ) : \"\"\"\"\"\" self . _refresh ( http . request ) def revoke ( self , http ) : \"\"\"\"\"\" self . _revoke ( http . request ) def apply ( self , headers ) : \"\"\"\"\"\" headers [ '' ] = '' + self . access_token def to_json ( self ) : return self . _to_json ( Credentials . NON_SERIALIZED_MEMBERS ) @ classmethod def from_json ( cls , s ) : \"\"\"\"\"\" data = simplejson . loads ( s ) if '' in data and not isinstance ( data [ '' ] , datetime . datetime ) : try : data [ '' ] = datetime . datetime . strptime ( data [ '' ] , EXPIRY_FORMAT ) except : data [ '' ] = None retval = cls ( data [ '' ] , data [ '' ] , data [ '' ] , data [ '' ] , data [ '' ] , data [ '' ] , data [ '' ] , revoke_uri = data . get ( '' , None ) , id_token = data . get ( '' , None ) , token_response = data . get ( '' , None ) ) retval . invalid = data [ '' ] return retval @ property def access_token_expired ( self ) : \"\"\"\"\"\" if self . invalid : return True if not self . token_expiry : return False now = datetime . datetime . utcnow ( ) if now >= self . token_expiry : logger . info ( '' , now , self . token_expiry ) return True return False def set_store ( self , store ) : \"\"\"\"\"\" self . store = store def _updateFromCredential ( self , other ) : \"\"\"\"\"\" self . __dict__ . update ( other . __getstate__ ( ) ) def __getstate__ ( self ) : \"\"\"\"\"\" d = copy . copy ( self . __dict__ ) del d [ '' ] return d def __setstate__ ( self , state ) : \"\"\"\"\"\" self . __dict__ . update ( state ) self . store = None def _generate_refresh_request_body ( self ) : \"\"\"\"\"\" body = urllib . urlencode ( { '' : '' , '' : self . client_id , '' : self . client_secret , '' : self . refresh_token , } ) return body def _generate_refresh_request_headers ( self ) : \"\"\"\"\"\" headers = { '' : '' , } if self . user_agent is not None : headers [ '' ] = self . user_agent return headers def _refresh ( self , http_request ) : \"\"\"\"\"\" if not self . store : self . _do_refresh_request ( http_request ) else : self . store . acquire_lock ( ) try : new_cred = self . store . locked_get ( ) if ( new_cred and not new_cred . invalid and new_cred . access_token != self . access_token ) : logger . info ( '' ) self . _updateFromCredential ( new_cred ) else : self . _do_refresh_request ( http_request ) finally : self . store . release_lock ( ) def _do_refresh_request ( self , http_request ) : \"\"\"\"\"\" body = self . _generate_refresh_request_body ( ) headers = self . _generate_refresh_request_headers ( ) logger . info ( '' ) resp , content = http_request ( self . token_uri , method = '' , body = body , headers = headers ) if resp . status == : d = simplejson . loads ( content ) self . token_response = d self . access_token = d [ '' ] self . refresh_token = d . get ( '' , self . refresh_token ) if '' in d : self . token_expiry = datetime . timedelta ( seconds = int ( d [ '' ] ) ) + datetime . datetime . utcnow ( ) else : self . token_expiry = None if self . store : self . store . locked_put ( self ) else : logger . info ( '' % content ) error_msg = '' % resp [ '' ] try : d = simplejson . loads ( content ) if '' in d : error_msg = d [ '' ] self . invalid = True if self . store : self . store . locked_put ( self ) except StandardError : pass raise AccessTokenRefreshError ( error_msg ) def _revoke ( self , http_request ) : \"\"\"\"\"\" self . _do_revoke ( http_request , self . refresh_token ) def _do_revoke ( self , http_request , token ) : \"\"\"\"\"\" logger . info ( '' ) query_params = { '' : token } token_revoke_uri = _update_query_params ( self . revoke_uri , query_params ) resp , content = http_request ( token_revoke_uri ) if resp . status == : self . invalid = True else : error_msg = '' % resp . status try : d = simplejson . loads ( content ) if '' in d : error_msg = d [ '' ] except StandardError : pass raise TokenRevokeError ( error_msg ) if self . store : self . store . delete ( ) class AccessTokenCredentials ( OAuth2Credentials ) : \"\"\"\"\"\" def __init__ ( self , access_token , user_agent , revoke_uri = None ) : \"\"\"\"\"\" super ( AccessTokenCredentials , self ) . __init__ ( access_token , None , None , None , None , None , user_agent , revoke_uri = revoke_uri ) @ classmethod def from_json ( cls , s ) : data = simplejson . loads ( s ) retval = AccessTokenCredentials ( data [ '' ] , data [ '' ] ) return retval def _refresh ( self , http_request ) : raise AccessTokenCredentialsError ( '' ) def _revoke ( self , http_request ) : \"\"\"\"\"\" self . _do_revoke ( http_request , self . access_token ) class AssertionCredentials ( OAuth2Credentials ) : \"\"\"\"\"\" @ util . positional ( ) def __init__ ( self , assertion_type , user_agent = None , token_uri = GOOGLE_TOKEN_URI , revoke_uri = GOOGLE_REVOKE_URI , ** unused_kwargs ) : \"\"\"\"\"\" super ( AssertionCredentials , self ) . __init__ ( None , None , None , None , None , token_uri , user_agent , revoke_uri = revoke_uri ) self . assertion_type = assertion_type def _generate_refresh_request_body ( self ) : assertion = self . _generate_assertion ( ) body = urllib . urlencode ( { '' : assertion , '' : '' , } ) return body def _generate_assertion ( self ) : \"\"\"\"\"\" _abstract ( ) def _revoke ( self , http_request ) : \"\"\"\"\"\" self . _do_revoke ( http_request , self . access_token ) if HAS_CRYPTO : class SignedJwtAssertionCredentials ( AssertionCredentials ) : \"\"\"\"\"\" MAX_TOKEN_LIFETIME_SECS = @ util . positional ( ) def __init__ ( self , service_account_name , private_key , scope , private_key_password = '' , user_agent = None , token_uri = GOOGLE_TOKEN_URI , revoke_uri = GOOGLE_REVOKE_URI , ** kwargs ) : \"\"\"\"\"\" super ( SignedJwtAssertionCredentials , self ) . __init__ ( None , user_agent = user_agent , token_uri = token_uri , revoke_uri = revoke_uri , ) self . scope = util . scopes_to_string ( scope ) self . private_key = base64 . b64encode ( private_key ) self . private_key_password = private_key_password self . service_account_name = service_account_name self . kwargs = kwargs @ classmethod def from_json ( cls , s ) : data = simplejson . loads ( s ) retval = SignedJwtAssertionCredentials ( data [ '' ] , base64 . b64decode ( data [ '' ] ) , data [ '' ] , private_key_password = data [ '' ] , user_agent = data [ '' ] , token_uri = data [ '' ] , ** data [ '' ] ) retval . invalid = data [ '' ] retval . access_token = data [ '' ] return retval def _generate_assertion ( self ) : \"\"\"\"\"\" now = long ( time . time ( ) ) payload = { '' : self . token_uri , '' : self . scope , '' : now , '' : now + SignedJwtAssertionCredentials . MAX_TOKEN_LIFETIME_SECS , '' : self . service_account_name } payload . update ( self . kwargs ) logger . debug ( str ( payload ) ) private_key = base64 . b64decode ( self . private_key ) return crypt . make_signed_jwt ( crypt . Signer . from_string ( private_key , self . private_key_password ) , payload ) _cached_http = httplib2 . Http ( MemoryCache ( ) ) @ util . positional ( ) def verify_id_token ( id_token , audience , http = None , cert_uri = ID_TOKEN_VERIFICATON_CERTS ) : \"\"\"\"\"\" if http is None : http = _cached_http resp , content = http . request ( cert_uri ) if resp . status == : certs = simplejson . loads ( content ) return crypt . verify_signed_jwt_with_certs ( id_token , certs , audience ) else : raise VerifyJwtTokenError ( '' % resp . status ) def _urlsafe_b64decode ( b64string ) : b64string = b64string . encode ( '' ) padded = b64string + '' * ( - len ( b64string ) % ) return base64 . urlsafe_b64decode ( padded ) def _extract_id_token ( id_token ) : \"\"\"\"\"\" segments = id_token . split ( '' ) if ( len ( segments ) != ) : raise VerifyJwtTokenError ( '' % id_token ) return simplejson . loads ( _urlsafe_b64decode ( segments [ ] ) ) def _parse_exchange_token_response ( content ) : \"\"\"\"\"\" resp = { } try : resp = simplejson . loads ( content ) except StandardError : resp = dict ( parse_qsl ( content ) ) if resp and '' in resp : resp [ '' ] = resp . pop ( '' ) return resp @ util . positional ( ) def credentials_from_code ( client_id , client_secret , scope , code , redirect_uri = '' , http = None , user_agent = None , token_uri = GOOGLE_TOKEN_URI , auth_uri = GOOGLE_AUTH_URI , revoke_uri = GOOGLE_REVOKE_URI ) : \"\"\"\"\"\" flow = OAuth2WebServerFlow ( client_id , client_secret , scope , redirect_uri = redirect_uri , user_agent = user_agent , auth_uri = auth_uri , token_uri = token_uri , revoke_uri = revoke_uri ) credentials = flow . step2_exchange ( code , http = http ) return credentials @ util . positional ( ) def credentials_from_clientsecrets_and_code ( filename , scope , code , message = None , redirect_uri = '' , http = None , cache = None ) : \"\"\"\"\"\" flow = flow_from_clientsecrets ( filename , scope , message = message , cache = cache , redirect_uri = redirect_uri ) credentials = flow . step2_exchange ( code , http = http ) return credentials class OAuth2WebServerFlow ( Flow ) : \"\"\"\"\"\" @ util . positional ( ) def __init__ ( self , client_id , client_secret , scope , redirect_uri = None , user_agent = None , auth_uri = GOOGLE_AUTH_URI , token_uri = GOOGLE_TOKEN_URI , revoke_uri = GOOGLE_REVOKE_URI , ** kwargs ) : \"\"\"\"\"\" self . client_id = client_id self . client_secret = client_secret self . scope = util . scopes_to_string ( scope ) self . redirect_uri = redirect_uri self . user_agent = user_agent self . auth_uri = auth_uri self . token_uri = token_uri self . revoke_uri = revoke_uri self . params = { '' : '' , '' : '' , } self . params . update ( kwargs ) @ util . positional ( ) def step1_get_authorize_url ( self , redirect_uri = None ) : \"\"\"\"\"\" if redirect_uri is not None : logger . warning ( ( '' '' '' ) ) self . redirect_uri = redirect_uri if self . redirect_uri is None : raise ValueError ( '' ) query_params = { '' : self . client_id , '' : self . redirect_uri , '' : self . scope , } query_params . update ( self . params ) return _update_query_params ( self . auth_uri , query_params ) @ util . positional ( ) def step2_exchange ( self , code , http = None ) : \"\"\"\"\"\" if not ( isinstance ( code , str ) or isinstance ( code , unicode ) ) : if '' not in code : if '' in code : error_msg = code [ '' ] else : error_msg = '' raise FlowExchangeError ( error_msg ) ", "answer": "else :"}, {"prompt": " from pledger . transaction import Transaction from pledger . ledger_processor import LedgerProcessor import itertools ", "answer": "import os . path"}, {"prompt": " from . constants import Classref , Fieldref , Methodref , InterfaceMethodref , String , Integer , Long , Float , Double , Constant class Opcode : opcodes = None def __init__ ( self ) : self . references = [ ] self . starts_line = None def __repr__ ( self ) : return '' % ( self . __class__ . __name__ , self . __arg_repr__ ( ) ) def __arg_repr__ ( self ) : return '' def __len__ ( self ) : return @ classmethod def read ( cls , reader , dump = None ) : code = reader . read_u1 ( ) if Opcode . opcodes is None : Opcode . opcodes = { } for name in globals ( ) : klass = globals ( ) [ name ] try : if name != '' and issubclass ( klass , Opcode ) : Opcode . opcodes [ klass . code ] = klass except TypeError : pass instance = Opcode . opcodes [ code ] . read_extra ( reader , dump ) if dump : reader . debug ( \"\" * dump , '' % ( reader . offset , instance ) ) return instance @ classmethod def read_extra ( cls , reader , dump = None ) : return cls ( ) def write ( self , writer ) : writer . write_u1 ( self . code ) self . write_extra ( writer ) def write_extra ( self , writer ) : pass def resolve ( self , constant_pool ) : pass @ property def stack_effect ( self ) : return self . produce_count - self . consume_count def process ( self , context ) : return True class AALOAD ( Opcode ) : code = def __init__ ( self ) : super ( AALOAD , self ) . __init__ ( ) @ property def consume_count ( self ) : return @ property def produce_count ( self ) : return class AASTORE ( Opcode ) : code = def __init__ ( self ) : super ( AASTORE , self ) . __init__ ( ) @ property def consume_count ( self ) : return @ property def produce_count ( self ) : return class ACONST_NULL ( Opcode ) : code = def __init__ ( self ) : super ( ACONST_NULL , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class ALOAD ( Opcode ) : code = def __init__ ( self , var ) : super ( ALOAD , self ) . __init__ ( ) self . var = var def __len__ ( self ) : return def __arg_repr__ ( self ) : return '' % self . var @ classmethod def read_extra ( cls , reader , dump = None ) : var = reader . read_u1 ( ) return cls ( var ) def write_extra ( self , writer ) : writer . write_u1 ( self . var ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class ALOAD_0 ( Opcode ) : code = def __init__ ( self ) : super ( ALOAD_0 , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class ALOAD_1 ( Opcode ) : code = def __init__ ( self ) : super ( ALOAD_1 , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class ALOAD_2 ( Opcode ) : code = def __init__ ( self ) : super ( ALOAD_2 , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class ALOAD_3 ( Opcode ) : code = def __init__ ( self ) : super ( ALOAD_3 , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class ANEWARRAY ( Opcode ) : code = def __init__ ( self , class_name ) : super ( ANEWARRAY , self ) . __init__ ( ) self . klass = Classref ( class_name ) def __len__ ( self ) : return def __arg_repr__ ( self ) : return '' % self . klass . name @ classmethod def read_extra ( cls , reader , dump = None ) : klass = reader . read_u2 ( ) return cls ( reader . constant_pool [ klass ] . name . bytes . decode ( '' ) ) def write_extra ( self , writer ) : writer . write_u2 ( writer . constant_pool . index ( self . klass ) ) def resolve ( self , constant_pool ) : self . klass . resolve ( constant_pool ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class ARETURN ( Opcode ) : code = def __init__ ( self ) : super ( ARETURN , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class ARRAYLENGTH ( Opcode ) : code = def __init__ ( self ) : super ( ARRAYLENGTH , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class ASTORE ( Opcode ) : code = def __init__ ( self , var ) : super ( ASTORE , self ) . __init__ ( ) self . var = var def __len__ ( self ) : return def __arg_repr__ ( self ) : return '' % self . var @ classmethod def read_extra ( cls , reader , dump = None ) : var = reader . read_u1 ( ) return cls ( var ) def write_extra ( self , writer ) : writer . write_u1 ( self . var ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class ASTORE_0 ( Opcode ) : code = def __init__ ( self ) : super ( ASTORE_0 , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class ASTORE_1 ( Opcode ) : code = def __init__ ( self ) : super ( ASTORE_1 , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class ASTORE_2 ( Opcode ) : code = def __init__ ( self ) : super ( ASTORE_2 , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class ASTORE_3 ( Opcode ) : code = def __init__ ( self ) : super ( ASTORE_3 , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class ATHROW ( Opcode ) : code = def __init__ ( self ) : super ( ATHROW , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class BALOAD ( Opcode ) : code = def __init__ ( self ) : super ( BALOAD , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class BASTORE ( Opcode ) : code = def __init__ ( self ) : super ( BASTORE , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class BIPUSH ( Opcode ) : code = def __init__ ( self , const ) : super ( BIPUSH , self ) . __init__ ( ) self . const = const def __len__ ( self ) : return def __arg_repr__ ( self ) : return '' + repr ( self . const ) @ classmethod def read_extra ( cls , reader , dump = None ) : const = reader . read_u1 ( ) return cls ( const ) def write_extra ( self , writer ) : writer . write_s1 ( self . const ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class BREAKPOINT ( Opcode ) : code = def __init__ ( self ) : super ( BREAKPOINT , self ) . __init__ ( ) class CALOAD ( Opcode ) : code = def __init__ ( self ) : super ( CALOAD , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class CASTORE ( Opcode ) : code = def __init__ ( self ) : super ( CASTORE , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class CHECKCAST ( Opcode ) : code = def __init__ ( self , class_name ) : super ( CHECKCAST , self ) . __init__ ( ) self . klass = Classref ( class_name ) def __len__ ( self ) : return def __arg_repr__ ( self ) : return '' % ( self . klass ) @ classmethod def read_extra ( cls , reader , dump = None ) : class_name = reader . constant_pool [ reader . read_u2 ( ) ] . name . bytes . decode ( '' ) return cls ( class_name ) def write_extra ( self , writer ) : writer . write_u2 ( writer . constant_pool . index ( self . klass ) ) def resolve ( self , constant_pool ) : self . klass . resolve ( constant_pool ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class D2F ( Opcode ) : code = def __init__ ( self ) : super ( D2F , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class D2I ( Opcode ) : code = def __init__ ( self ) : super ( D2I , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class D2L ( Opcode ) : code = def __init__ ( self ) : super ( D2L , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class DADD ( Opcode ) : code = def __init__ ( self ) : super ( DADD , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class DALOAD ( Opcode ) : code = def __init__ ( self ) : super ( DALOAD , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class DASTORE ( Opcode ) : code = def __init__ ( self ) : super ( DASTORE , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class DCMPG ( Opcode ) : code = def __init__ ( self ) : super ( DCMPG , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class DCMPL ( Opcode ) : code = def __init__ ( self ) : super ( DCMPL , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class DCONST_0 ( Opcode ) : code = def __init__ ( self ) : super ( DCONST_0 , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class DCONST_1 ( Opcode ) : code = def __init__ ( self ) : super ( DCONST_1 , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class DDIV ( Opcode ) : code = def __init__ ( self ) : super ( DDIV , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class DLOAD ( Opcode ) : code = def __init__ ( self , var ) : super ( DLOAD , self ) . __init__ ( ) self . var = var def __len__ ( self ) : return def __arg_repr__ ( self ) : return '' % self . var @ classmethod def read_extra ( cls , reader , dump = None ) : var = reader . read_u1 ( ) return cls ( var ) def write_extra ( self , writer ) : writer . write_u1 ( self . var ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class DLOAD_0 ( Opcode ) : code = def __init__ ( self , var ) : super ( DLOAD_0 , self ) . __init__ ( ) self . var = var def __len__ ( self ) : return def __arg_repr__ ( self ) : return '' % self . var @ classmethod def read_extra ( cls , reader , dump = None ) : var = reader . read_u1 ( ) return cls ( var ) def write_extra ( self , writer ) : writer . write_u1 ( self . var ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class DLOAD_1 ( Opcode ) : code = def __init__ ( self ) : super ( DLOAD_1 , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class DLOAD_2 ( Opcode ) : code = def __init__ ( self ) : super ( DLOAD_2 , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class DLOAD_3 ( Opcode ) : code = def __init__ ( self ) : super ( DLOAD_3 , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class DMUL ( Opcode ) : code = def __init__ ( self ) : super ( DMUL , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class DNEG ( Opcode ) : code = def __init__ ( self ) : super ( DNEG , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class DREM ( Opcode ) : code = def __init__ ( self ) : super ( DREM , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class DRETURN ( Opcode ) : code = def __init__ ( self ) : super ( DRETURN , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class DSTORE ( Opcode ) : code = def __init__ ( self , var ) : super ( DSTORE , self ) . __init__ ( ) self . var = var def __len__ ( self ) : return def __arg_repr__ ( self ) : return '' % self . var @ classmethod def read_extra ( cls , reader , dump = None ) : var = reader . read_u1 ( ) return cls ( var ) def write_extra ( self , writer ) : writer . write_u1 ( self . var ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class DSTORE_0 ( Opcode ) : code = def __init__ ( self ) : super ( DSTORE_0 , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class DSTORE_1 ( Opcode ) : code = def __init__ ( self ) : super ( DSTORE_1 , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class DSTORE_2 ( Opcode ) : code = def __init__ ( self ) : super ( DSTORE_2 , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class DSTORE_3 ( Opcode ) : code = def __init__ ( self ) : super ( DSTORE_3 , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class DSUB ( Opcode ) : code = def __init__ ( self ) : super ( DSUB , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class DUP ( Opcode ) : code = def __init__ ( self ) : super ( DUP , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class DUP_X1 ( Opcode ) : code = def __init__ ( self ) : super ( DUP_X1 , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class DUP_X2 ( Opcode ) : code = def __init__ ( self ) : super ( DUP_X2 , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class DUP2 ( Opcode ) : code = def __init__ ( self ) : super ( DUP2 , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class DUP2_X1 ( Opcode ) : code = def __init__ ( self ) : super ( DUP2_X1 , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class DUP2_X2 ( Opcode ) : code = def __init__ ( self ) : super ( DUP2_X2 , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class F2D ( Opcode ) : code = def __init__ ( self ) : super ( F2D , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class F2I ( Opcode ) : code = def __init__ ( self ) : super ( F2I , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class F2L ( Opcode ) : code = def __init__ ( self ) : super ( F2L , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class FADD ( Opcode ) : code = def __init__ ( self ) : super ( FADD , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class FALOAD ( Opcode ) : code = def __init__ ( self ) : super ( FALOAD , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class FASTORE ( Opcode ) : code = def __init__ ( self ) : super ( FASTORE , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class FCMPG ( Opcode ) : code = def __init__ ( self ) : super ( FCMPG , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class FCMPL ( Opcode ) : code = def __init__ ( self ) : super ( FCMPL , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class FCONST_0 ( Opcode ) : code = def __init__ ( self ) : super ( FCONST_0 , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class FCONST_1 ( Opcode ) : code = def __init__ ( self ) : super ( FCONST_1 , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class FCONST_2 ( Opcode ) : code = def __init__ ( self ) : super ( FCONST_2 , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class FDIV ( Opcode ) : code = def __init__ ( self ) : super ( FDIV , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class FLOAD ( Opcode ) : code = def __init__ ( self , var ) : super ( FLOAD , self ) . __init__ ( ) self . var = var def __len__ ( self ) : return def __arg_repr__ ( self ) : return '' % self . var @ classmethod def read_extra ( cls , reader , dump = None ) : var = reader . read_u1 ( ) return cls ( var ) def write_extra ( self , writer ) : writer . write_u1 ( self . var ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class FLOAD_0 ( Opcode ) : code = def __init__ ( self ) : super ( FLOAD_0 , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class FLOAD_1 ( Opcode ) : code = def __init__ ( self ) : super ( FLOAD_1 , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class FLOAD_2 ( Opcode ) : code = def __init__ ( self ) : super ( FLOAD_2 , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class FLOAD_3 ( Opcode ) : code = def __init__ ( self ) : super ( FLOAD_3 , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class FMUL ( Opcode ) : code = def __init__ ( self ) : super ( FMUL , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class FNEG ( Opcode ) : code = def __init__ ( self ) : super ( FNEG , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class FREM ( Opcode ) : code = def __init__ ( self ) : super ( FREM , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class FRETURN ( Opcode ) : code = def __init__ ( self ) : super ( FRETURN , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class FSTORE ( Opcode ) : code = def __init__ ( self , var ) : super ( FSTORE , self ) . __init__ ( ) self . var = var def __len__ ( self ) : return def __arg_repr__ ( self ) : return '' % self . var @ classmethod def read_extra ( cls , reader , dump = None ) : var = reader . read_u1 ( ) return cls ( var ) def write_extra ( self , writer ) : writer . write_u1 ( self . var ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class FSTORE_0 ( Opcode ) : code = def __init__ ( self ) : super ( FSTORE_0 , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class FSTORE_1 ( Opcode ) : code = def __init__ ( self ) : super ( FSTORE_1 , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class FSTORE_2 ( Opcode ) : code = def __init__ ( self ) : super ( FSTORE_2 , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class FSTORE_3 ( Opcode ) : code = def __init__ ( self ) : super ( FSTORE_3 , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class FSUB ( Opcode ) : code = def __init__ ( self ) : super ( FSUB , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class GETFIELD ( Opcode ) : code = def __init__ ( self , class_name , field_name , descriptor ) : super ( GETFIELD , self ) . __init__ ( ) self . field = Fieldref ( class_name , field_name , descriptor ) def __len__ ( self ) : return def __arg_repr__ ( self ) : return '' % ( self . field . class_name , self . field . name , self . field . name_and_type . descriptor ) @ classmethod def read_extra ( cls , reader , dump = None ) : field = reader . constant_pool [ reader . read_u2 ( ) ] return cls ( field . class_name , field . name , field . name_and_type . descriptor . bytes . decode ( '' ) ) def write_extra ( self , writer ) : writer . write_u2 ( writer . constant_pool . index ( self . field ) ) def resolve ( self , constant_pool ) : self . field . resolve ( constant_pool ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class GETSTATIC ( Opcode ) : code = def __init__ ( self , class_name , field_name , descriptor ) : super ( GETSTATIC , self ) . __init__ ( ) self . field = Fieldref ( class_name , field_name , descriptor ) def __len__ ( self ) : return def __arg_repr__ ( self ) : return '' % ( self . field . class_name , self . field . name , self . field . name_and_type . descriptor ) @ classmethod def read_extra ( cls , reader , dump = None ) : field = reader . constant_pool [ reader . read_u2 ( ) ] return cls ( field . class_name , field . name , field . name_and_type . descriptor . bytes . decode ( '' ) ) def write_extra ( self , writer ) : writer . write_u2 ( writer . constant_pool . index ( self . field ) ) def resolve ( self , constant_pool ) : self . field . resolve ( constant_pool ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class GOTO ( Opcode ) : code = def __init__ ( self , offset ) : super ( GOTO , self ) . __init__ ( ) self . offset = offset def __len__ ( self ) : return def __arg_repr__ ( self ) : return '' % self . offset @ classmethod def read_extra ( cls , reader , dump = None ) : offset = reader . read_s2 ( ) return cls ( offset ) def write_extra ( self , writer ) : writer . write_s2 ( self . offset ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class GOTO_W ( Opcode ) : code = def __init__ ( self , offset ) : super ( GOTO_W , self ) . __init__ ( ) self . offset = offset def __len__ ( self ) : return def __arg_repr__ ( self ) : return '' % self . offset @ classmethod def read_extra ( cls , reader , dump = None ) : offset = reader . read_s4 ( ) return cls ( offset ) def write_extra ( self , writer ) : writer . write_s4 ( self . offset ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class I2B ( Opcode ) : code = def __init__ ( self ) : super ( I2B , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class I2C ( Opcode ) : code = def __init__ ( self ) : super ( I2C , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class I2D ( Opcode ) : code = def __init__ ( self ) : super ( I2D , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class I2F ( Opcode ) : code = def __init__ ( self ) : super ( I2F , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class I2L ( Opcode ) : code = def __init__ ( self ) : super ( I2L , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class I2S ( Opcode ) : code = def __init__ ( self ) : super ( I2S , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class IADD ( Opcode ) : code = def __init__ ( self ) : super ( IADD , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class IALOAD ( Opcode ) : code = def __init__ ( self ) : super ( IALOAD , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class IAND ( Opcode ) : code = def __init__ ( self ) : super ( IAND , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class IASTORE ( Opcode ) : code = def __init__ ( self ) : super ( IASTORE , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class ICONST_M1 ( Opcode ) : code = def __init__ ( self ) : super ( ICONST_M1 , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class ICONST_0 ( Opcode ) : code = def __init__ ( self ) : super ( ICONST_0 , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class ICONST_1 ( Opcode ) : code = def __init__ ( self ) : super ( ICONST_1 , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class ICONST_2 ( Opcode ) : code = def __init__ ( self ) : super ( ICONST_2 , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class ICONST_3 ( Opcode ) : code = def __init__ ( self ) : super ( ICONST_3 , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class ICONST_4 ( Opcode ) : code = def __init__ ( self ) : super ( ICONST_4 , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class ICONST_5 ( Opcode ) : code = def __init__ ( self ) : super ( ICONST_5 , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class IDIV ( Opcode ) : code = def __init__ ( self ) : super ( IDIV , self ) . __init__ ( ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class IF_ACMPEQ ( Opcode ) : code = def __init__ ( self , offset ) : super ( IF_ACMPEQ , self ) . __init__ ( ) self . offset = offset def __len__ ( self ) : return def __arg_repr__ ( self ) : return '' % self . offset @ classmethod def read_extra ( cls , reader , dump = None ) : offset = reader . read_s2 ( ) return cls ( offset ) def write_extra ( self , writer ) : writer . write_s2 ( self . offset ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class IF_ACMPNE ( Opcode ) : code = def __init__ ( self , offset ) : super ( IF_ACMPNE , self ) . __init__ ( ) self . offset = offset def __len__ ( self ) : return def __arg_repr__ ( self ) : return '' % self . offset @ classmethod def read_extra ( cls , reader , dump = None ) : offset = reader . read_s2 ( ) return cls ( offset ) def write_extra ( self , writer ) : writer . write_s2 ( self . offset ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class IF_ICMPEQ ( Opcode ) : code = def __init__ ( self , offset ) : super ( IF_ICMPEQ , self ) . __init__ ( ) self . offset = offset def __len__ ( self ) : return def __arg_repr__ ( self ) : return '' % self . offset @ classmethod def read_extra ( cls , reader , dump = None ) : offset = reader . read_s2 ( ) return cls ( offset ) def write_extra ( self , writer ) : writer . write_s2 ( self . offset ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class IF_ICMPGE ( Opcode ) : code = def __init__ ( self , offset ) : super ( IF_ICMPGE , self ) . __init__ ( ) self . offset = offset def __len__ ( self ) : return def __arg_repr__ ( self ) : return '' % self . offset @ classmethod def read_extra ( cls , reader , dump = None ) : offset = reader . read_s2 ( ) return cls ( offset ) def write_extra ( self , writer ) : writer . write_s2 ( self . offset ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class IF_ICMPGT ( Opcode ) : code = def __init__ ( self , offset ) : super ( IF_ICMPGT , self ) . __init__ ( ) self . offset = offset def __len__ ( self ) : return def __arg_repr__ ( self ) : return '' % self . offset @ classmethod def read_extra ( cls , reader , dump = None ) : offset = reader . read_s2 ( ) return cls ( offset ) def write_extra ( self , writer ) : writer . write_s2 ( self . offset ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class IF_ICMPLE ( Opcode ) : code = def __init__ ( self , offset ) : super ( IF_ICMPLE , self ) . __init__ ( ) self . offset = offset def __len__ ( self ) : return def __arg_repr__ ( self ) : return '' % self . offset @ classmethod def read_extra ( cls , reader , dump = None ) : offset = reader . read_s2 ( ) return cls ( offset ) def write_extra ( self , writer ) : writer . write_s2 ( self . offset ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class IF_ICMPLT ( Opcode ) : code = def __init__ ( self , offset ) : super ( IF_ICMPLT , self ) . __init__ ( ) self . offset = offset def __len__ ( self ) : return def __arg_repr__ ( self ) : return '' % self . offset @ classmethod def read_extra ( cls , reader , dump = None ) : offset = reader . read_s2 ( ) return cls ( offset ) def write_extra ( self , writer ) : writer . write_s2 ( self . offset ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class IF_ICMPNE ( Opcode ) : code = def __init__ ( self , offset ) : super ( IF_ICMPNE , self ) . __init__ ( ) self . offset = offset def __len__ ( self ) : return def __arg_repr__ ( self ) : return '' % self . offset @ classmethod def read_extra ( cls , reader , dump = None ) : offset = reader . read_s2 ( ) return cls ( offset ) def write_extra ( self , writer ) : writer . write_s2 ( self . offset ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class IFEQ ( Opcode ) : code = def __init__ ( self , offset ) : super ( IFEQ , self ) . __init__ ( ) self . offset = offset def __len__ ( self ) : return def __arg_repr__ ( self ) : return '' % self . offset @ classmethod def read_extra ( cls , reader , dump = None ) : offset = reader . read_s2 ( ) return cls ( offset ) def write_extra ( self , writer ) : writer . write_s2 ( self . offset ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class IFGE ( Opcode ) : code = def __init__ ( self , offset ) : super ( IFGE , self ) . __init__ ( ) self . offset = offset def __len__ ( self ) : return def __arg_repr__ ( self ) : return '' % self . offset @ classmethod def read_extra ( cls , reader , dump = None ) : offset = reader . read_s2 ( ) return cls ( offset ) def write_extra ( self , writer ) : writer . write_s2 ( self . offset ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class IFGT ( Opcode ) : code = def __init__ ( self , offset ) : super ( IFGT , self ) . __init__ ( ) self . offset = offset def __len__ ( self ) : return def __arg_repr__ ( self ) : return '' % self . offset @ classmethod def read_extra ( cls , reader , dump = None ) : offset = reader . read_s2 ( ) return cls ( offset ) def write_extra ( self , writer ) : writer . write_s2 ( self . offset ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class IFLE ( Opcode ) : code = def __init__ ( self , offset ) : super ( IFLE , self ) . __init__ ( ) self . offset = offset def __len__ ( self ) : return def __arg_repr__ ( self ) : return '' % self . offset @ classmethod def read_extra ( cls , reader , dump = None ) : offset = reader . read_s2 ( ) return cls ( offset ) def write_extra ( self , writer ) : writer . write_s2 ( self . offset ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class IFLT ( Opcode ) : code = def __init__ ( self , offset ) : super ( IFLT , self ) . __init__ ( ) self . offset = offset def __len__ ( self ) : return def __arg_repr__ ( self ) : return '' % self . offset @ classmethod def read_extra ( cls , reader , dump = None ) : offset = reader . read_s2 ( ) return cls ( offset ) def write_extra ( self , writer ) : writer . write_s2 ( self . offset ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class IFNE ( Opcode ) : code = def __init__ ( self , offset ) : super ( IFNE , self ) . __init__ ( ) self . offset = offset def __len__ ( self ) : return def __arg_repr__ ( self ) : return '' % self . offset @ classmethod def read_extra ( cls , reader , dump = None ) : offset = reader . read_s2 ( ) return cls ( offset ) def write_extra ( self , writer ) : writer . write_s2 ( self . offset ) @ property def produce_count ( self ) : return @ property def consume_count ( self ) : return class IFNONNULL ( Opcode ) : code = def __init__ ( self , offset ) : super ( IFNONNULL , self ) . __init__ ( ) self . offset = offset def __len__ ( self ) : return def __arg_repr__ ( self ) : return '' % self . offset @ classmethod def read_extra ( cls , reader , dump = None ) : offset = reader . read_s2 ( ) return cls ( offset ) def write_extra ( self , writer ) : writer . write_s2 ( self . offset ) @ property ", "answer": "def produce_count ( self ) :"}, {"prompt": " from __future__ import print_function , unicode_literals import unittest from weblab . data . experiments import ExperimentId , ExperimentInstanceId class ExperimentIdsTestCase ( unittest . TestCase ) : def setUp ( self ) : self . experiment_id = ExperimentId ( '' , '' ) self . experiment_instance_id = ExperimentInstanceId ( '' , '' , '' ) def _check_repr ( self , obj ) : ", "answer": "self . assertEquals ( repr ( obj ) , repr ( eval ( repr ( obj ) ) ) )"}, {"prompt": " import requests import json from lxml import html api_key = '' url_template = '' session_cookie = '' input_fetch = { '' : False , '' : { ", "answer": "'' : None ,"}, {"prompt": " from twisted . trial import unittest from twisted . conch . insults import helper , text A = text . attributes class Serialization ( unittest . TestCase ) : def setUp ( self ) : self . attrs = helper . CharacterAttribute ( ) def testTrivial ( self ) : self . assertEqual ( text . flatten ( A . normal [ '' ] , self . attrs ) , '' ) def testBold ( self ) : self . assertEqual ( text . flatten ( A . bold [ '' ] , self . attrs ) , '' ) def testUnderline ( self ) : self . assertEqual ( text . flatten ( A . underline [ '' ] , self . attrs ) , '' ) def testBlink ( self ) : self . assertEqual ( text . flatten ( A . blink [ '' ] , self . attrs ) , '' ) def testReverseVideo ( self ) : self . assertEqual ( text . flatten ( A . reverseVideo [ '' ] , self . attrs ) , '' ) def testMinus ( self ) : self . assertEqual ( text . flatten ( A . bold [ A . blink [ '' , - A . bold [ '' ] , '' ] ] , self . attrs ) , '' ) def testForeground ( self ) : self . assertEqual ( text . flatten ( A . normal [ A . fg . red [ '' ] , A . fg . green [ '' ] ] , self . attrs ) , '' ) def testBackground ( self ) : self . assertEqual ( text . flatten ( A . normal [ A . bg . red [ '' ] , A . bg . green [ '' ] ] , self . attrs ) , '' ) class EfficiencyTestCase ( unittest . TestCase ) : todo = ( \"\" \"\" \"\" \"\" \"\" ) def setUp ( self ) : self . attrs = helper . CharacterAttribute ( ) ", "answer": "def testComplexStructure ( self ) :"}, {"prompt": " \"\"\"\"\"\" ", "answer": "import copy"}, {"prompt": " import pytest from sprinter . next . environment . injections import Injections ", "answer": "@ pytest . fixture"}, {"prompt": " from nose . tools import eq_ from . . recall import recall def test_boolean ( ) : test_statistic = recall ( ) score_labels = [ ( { '' : True } , { '' : True } , True ) , ( { '' : False } , { '' : True } , False ) , ( { '' : True } , { '' : True } , True ) , ( { '' : False } , { '' : True } , False ) , ( { '' : True } , { '' : True } , True ) , ( { '' : False } , { '' : True } , False ) , ( { '' : True } , { '' : True } , True ) , ( { '' : False } , { '' : True } , False ) , ( { '' : True } , { '' : True } , True ) , ( { '' : False } , { '' : True } , False ) ] all_right , half_right , labels = zip ( * score_labels ) stats = test_statistic . score ( all_right , labels ) eq_ ( stats , ) ", "answer": "stats = test_statistic . score ( half_right , labels )"}, {"prompt": " from __future__ import unicode_literals import re import json from . common import InfoExtractor from . . utils import ( int_or_none , parse_age_limit , ) class BreakIE ( InfoExtractor ) : _VALID_URL = r'' _TESTS = [ { '' : '' , '' : { '' : '' , '' : '' , '' : '' , } } , { '' : '' , '' : True , } ] def _real_extract ( self , url ) : video_id = self . _match_id ( url ) webpage = self . _download_webpage ( '' % video_id , video_id ) info = json . loads ( self . _search_regex ( r'' , webpage , '' , flags = re . DOTALL ) ) youtube_id = info . get ( '' ) if youtube_id : return self . url_result ( youtube_id , '' ) formats = [ { '' : media [ '' ] + '' + info [ '' ] , '' : media [ '' ] , ", "answer": "'' : media [ '' ] ,"}, {"prompt": " \"\"\"\"\"\" import sys from setuptools import setup , find_packages sys . path . append ( '' ) sys . path . append ( '' ) setup ( name = '' , version = '' , url = '' , license = '' , maintainer = '' , ", "answer": "maintainer_email = '' ,"}, {"prompt": " \"\"\"\"\"\" import os from google . appengine . api import datastore_errors from google . appengine . ext import webapp from google . appengine . ext . datastore_admin import copy_handler from google . appengine . ext . datastore_admin import delete_handler from google . appengine . ext . datastore_admin import utils from google . appengine . ext . db import stats from google . appengine . ext . db import metadata from google . appengine . ext . webapp import util GET_ACTIONS = { '' : copy_handler . ConfirmCopyHandler . Render , '' : delete_handler . ConfirmDeleteHandler . Render , } def _GetDatastoreStats ( kinds_list , use_stats_kinds = False ) : \"\"\"\"\"\" global_stat = stats . GlobalStat . all ( ) . fetch ( ) if not global_stat : return _KindsListToTuple ( kinds_list ) global_ts = global_stat [ ] . timestamp kind_stats = stats . KindStat . all ( ) . filter ( '' , global_ts ) . fetch ( ) if not kind_stats : return _KindsListToTuple ( kinds_list ) results = { } for kind_ent in kind_stats : if ( not kind_ent . kind_name . startswith ( '' ) and ( use_stats_kinds or kind_ent . kind_name in kinds_list ) ) : results [ kind_ent . kind_name ] = _PresentatableKindStats ( kind_ent ) utils . CacheStats ( results . values ( ) ) for kind_str in kinds_list or [ ] : if kind_str not in results : results [ kind_str ] = { '' : kind_str } return ( global_ts , sorted ( results . values ( ) , key = lambda x : x [ '' ] ) ) def _KindsListToTuple ( kinds_list ) : \"\"\"\"\"\" return '' , [ { '' : kind } for kind in sorted ( kinds_list ) ] def _PresentatableKindStats ( kind_ent ) : \"\"\"\"\"\" count = kind_ent . count total_bytes = kind_ent . bytes average_bytes = total_bytes / count return { '' : kind_ent . kind_name , '' : utils . FormatThousands ( kind_ent . count ) , '' : utils . GetPrettyBytes ( total_bytes ) , '' : total_bytes , '' : utils . GetPrettyBytes ( average_bytes ) , } class RouteByActionHandler ( webapp . RequestHandler ) : \"\"\"\"\"\" def ListActions ( self , error = None ) : \"\"\"\"\"\" use_stats_kinds = False kinds = [ ] try : kinds = self . GetKinds ( ) if not kinds : use_stats_kinds = True except datastore_errors . Error : use_stats_kinds = True last_stats_update , kind_stats = _GetDatastoreStats ( kinds , use_stats_kinds = use_stats_kinds ) template_params = { '' : kind_stats , '' : self . request . path + '' + self . request . query_string , '' : last_stats_update , '' : self . request . get ( '' ) , '' : self . request . get ( '' ) , '' : sorted ( GET_ACTIONS . keys ( ) ) , '' : error , '' : utils . DatastoreAdminOperation . all ( ) . fetch ( ) , } utils . RenderToResponse ( self , '' , template_params ) def RouteAction ( self , action_dict ) : action = self . request . get ( '' ) if not action : self . ListActions ( ) elif action not in action_dict : error = '' % action self . ListActions ( error = error ) else : action_dict [ action ] ( self ) def get ( self ) : self . RouteAction ( GET_ACTIONS ) def post ( self ) : self . RouteAction ( GET_ACTIONS ) def GetKinds ( self ) : \"\"\"\"\"\" kinds = metadata . Kind . all ( ) . fetch ( ) kind_names = [ ] for kind in kinds : kind_name = kind . kind_name if ( kind_name . startswith ( '' ) or kind_name == utils . DatastoreAdminOperation . kind ( ) ) : continue kind_names . append ( kind_name ) return kind_names class StaticResourceHandler ( webapp . RequestHandler ) : \"\"\"\"\"\" _BASE_FILE_PATH = os . path . dirname ( __file__ ) _RESOURCE_MAP = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , } def get ( self ) : relative_path = self . request . path . split ( utils . config . BASE_PATH + '' ) [ ] if relative_path not in self . _RESOURCE_MAP : self . response . set_status ( ) self . response . out . write ( '' ) return path = os . path . join ( self . _BASE_FILE_PATH , relative_path ) self . response . headers [ '' ] = '' self . response . headers [ '' ] = self . _RESOURCE_MAP [ relative_path ] if relative_path == '' : self . response . out . write ( open ( path ) . read ( ) . replace ( '' , '' ) ) else : self . response . out . write ( open ( path ) . read ( ) ) def CreateApplication ( ) : \"\"\"\"\"\" return webapp . WSGIApplication ( [ ( r'' % ( utils . config . BASE_PATH , delete_handler . ConfirmDeleteHandler . SUFFIX ) , delete_handler . ConfirmDeleteHandler ) , ( r'' % ( utils . config . BASE_PATH , delete_handler . DoDeleteHandler . SUFFIX ) , delete_handler . DoDeleteHandler ) , ( r'' % ( utils . config . BASE_PATH , utils . MapreduceDoneHandler . SUFFIX ) , utils . MapreduceDoneHandler ) , ] + copy_handler . handlers_list ( utils . config . BASE_PATH ) + [ ( r'' % utils . config . BASE_PATH , StaticResourceHandler ) , ", "answer": "( r'' , RouteByActionHandler ) ,"}, {"prompt": " \"\"\"\"\"\" from __future__ import division import warnings from math import log import numpy as np from scipy . optimize import fmin_bfgs from . base import BaseEstimator , ClassifierMixin , RegressorMixin , clone from . preprocessing import LabelBinarizer from . utils import check_X_y , check_array , indexable , column_or_1d from . utils . validation import check_is_fitted from . utils . fixes import signature from . isotonic import IsotonicRegression from . svm import LinearSVC from . model_selection import check_cv from . metrics . classification import _check_binary_probabilistic_predictions class CalibratedClassifierCV ( BaseEstimator , ClassifierMixin ) : \"\"\"\"\"\" def __init__ ( self , base_estimator = None , method = '' , cv = ) : self . base_estimator = base_estimator self . method = method self . cv = cv def fit ( self , X , y , sample_weight = None ) : \"\"\"\"\"\" X , y = check_X_y ( X , y , accept_sparse = [ '' , '' , '' ] , force_all_finite = False ) X , y = indexable ( X , y ) lb = LabelBinarizer ( ) . fit ( y ) self . classes_ = lb . classes_ n_folds = self . cv if isinstance ( self . cv , int ) else self . cv . n_folds if hasattr ( self . cv , \"\" ) else None if n_folds and np . any ( [ np . sum ( y == class_ ) < n_folds for class_ in self . classes_ ] ) : raise ValueError ( \"\" \"\" % ( n_folds , n_folds ) ) self . calibrated_classifiers_ = [ ] if self . base_estimator is None : base_estimator = LinearSVC ( random_state = ) else : base_estimator = self . base_estimator if self . cv == \"\" : calibrated_classifier = _CalibratedClassifier ( base_estimator , method = self . method ) if sample_weight is not None : calibrated_classifier . fit ( X , y , sample_weight ) else : calibrated_classifier . fit ( X , y ) self . calibrated_classifiers_ . append ( calibrated_classifier ) else : cv = check_cv ( self . cv , y , classifier = True ) fit_parameters = signature ( base_estimator . fit ) . parameters estimator_name = type ( base_estimator ) . __name__ if ( sample_weight is not None and \"\" not in fit_parameters ) : warnings . warn ( \"\" \"\" \"\" % estimator_name ) base_estimator_sample_weight = None else : base_estimator_sample_weight = sample_weight for train , test in cv . split ( X , y ) : this_estimator = clone ( base_estimator ) if base_estimator_sample_weight is not None : this_estimator . fit ( X [ train ] , y [ train ] , sample_weight = base_estimator_sample_weight [ train ] ) else : this_estimator . fit ( X [ train ] , y [ train ] ) calibrated_classifier = _CalibratedClassifier ( this_estimator , method = self . method ) if sample_weight is not None : calibrated_classifier . fit ( X [ test ] , y [ test ] , sample_weight [ test ] ) else : calibrated_classifier . fit ( X [ test ] , y [ test ] ) self . calibrated_classifiers_ . append ( calibrated_classifier ) return self def predict_proba ( self , X ) : \"\"\"\"\"\" check_is_fitted ( self , [ \"\" , \"\" ] ) X = check_array ( X , accept_sparse = [ '' , '' , '' ] , force_all_finite = False ) mean_proba = np . zeros ( ( X . shape [ ] , len ( self . classes_ ) ) ) for calibrated_classifier in self . calibrated_classifiers_ : proba = calibrated_classifier . predict_proba ( X ) mean_proba += proba mean_proba /= len ( self . calibrated_classifiers_ ) return mean_proba def predict ( self , X ) : \"\"\"\"\"\" check_is_fitted ( self , [ \"\" , \"\" ] ) return self . classes_ [ np . argmax ( self . predict_proba ( X ) , axis = ) ] class _CalibratedClassifier ( object ) : \"\"\"\"\"\" def __init__ ( self , base_estimator , method = '' ) : self . base_estimator = base_estimator self . method = method def _preproc ( self , X ) : n_classes = len ( self . classes_ ) if hasattr ( self . base_estimator , \"\" ) : df = self . base_estimator . decision_function ( X ) if df . ndim == : df = df [ : , np . newaxis ] elif hasattr ( self . base_estimator , \"\" ) : df = self . base_estimator . predict_proba ( X ) if n_classes == : df = df [ : , : ] else : raise RuntimeError ( '' '' ) idx_pos_class = np . arange ( df . shape [ ] ) return df , idx_pos_class def fit ( self , X , y , sample_weight = None ) : \"\"\"\"\"\" lb = LabelBinarizer ( ) Y = lb . fit_transform ( y ) self . classes_ = lb . classes_ df , idx_pos_class = self . _preproc ( X ) self . calibrators_ = [ ] for k , this_df in zip ( idx_pos_class , df . T ) : if self . method == '' : calibrator = IsotonicRegression ( out_of_bounds = '' ) elif self . method == '' : calibrator = _SigmoidCalibration ( ) else : raise ValueError ( '' '' % self . method ) calibrator . fit ( this_df , Y [ : , k ] , sample_weight ) self . calibrators_ . append ( calibrator ) return self def predict_proba ( self , X ) : \"\"\"\"\"\" n_classes = len ( self . classes_ ) proba = np . zeros ( ( X . shape [ ] , n_classes ) ) df , idx_pos_class = self . _preproc ( X ) for k , this_df , calibrator in zip ( idx_pos_class , df . T , self . calibrators_ ) : if n_classes == : k += proba [ : , k ] = calibrator . predict ( this_df ) if n_classes == : proba [ : , ] = - proba [ : , ] else : proba /= np . sum ( proba , axis = ) [ : , np . newaxis ] proba [ np . isnan ( proba ) ] = / n_classes proba [ ( < proba ) & ( proba <= + ) ] = return proba ", "answer": "def _sigmoid_calibration ( df , y , sample_weight = None ) :"}, {"prompt": " from test_plus . test import TestCase class TestUser ( TestCase ) : def setUp ( self ) : self . user = self . make_user ( ) def test__str__ ( self ) : self . assertEqual ( self . user . __str__ ( ) , ", "answer": "''"}, {"prompt": " from oslo_config import cfg from nova . compute import vm_states from nova . tests . functional . api_sample_tests import test_servers CONF = cfg . CONF CONF . import_opt ( '' , '' ) CONF . import_opt ( '' , '' ) class ServersSampleHideAddressesJsonTest ( test_servers . ServersSampleJsonTest ) : extension_name = '' ", "answer": "sample_dir = extension_name"}, {"prompt": " \"\"\"\"\"\" from compass . hdsdiscovery import base CLASS_NAME = '' class Pica8 ( base . BaseSnmpVendor ) : \"\"\"\"\"\" def __init__ ( self ) : base . BaseSnmpVendor . __init__ ( self , [ '' ] ) self . _name = '' @ property ", "answer": "def name ( self ) :"}, {"prompt": " from __future__ import unicode_literals from django . db import models , migrations class Migration ( migrations . Migration ) : dependencies = [ ( '' , '' ) , ", "answer": "]"}, {"prompt": " from openstack_dashboard . test . integration_tests import helpers from openstack_dashboard . test . integration_tests . regions import messages class TestHostAggregates ( helpers . AdminTestCase ) : HOST_AGGREGATE_NAME = helpers . gen_random_resource_name ( \"\" ) HOST_AGGREGATE_AVAILABILITY_ZONE = \"\" def test_host_aggregate_create ( self ) : \"\"\"\"\"\" hostaggregates_page = self . home_pg . go_to_system_hostaggregatespage ( ) hostaggregates_page . create_host_aggregate ( name = self . HOST_AGGREGATE_NAME , availability_zone = self . HOST_AGGREGATE_AVAILABILITY_ZONE ) self . assertTrue ( hostaggregates_page . find_message_and_dismiss ( messages . SUCCESS ) ) self . assertFalse ( hostaggregates_page . find_message_and_dismiss ( messages . ERROR ) ) self . assertTrue ( hostaggregates_page . is_host_aggregate_present ( self . HOST_AGGREGATE_NAME ) ) hostaggregates_page . delete_host_aggregate ( self . HOST_AGGREGATE_NAME ) ", "answer": "self . assertTrue ("}, {"prompt": " from db . conn import ( test as _test , food as _food , user as _user , test_files as _test_files , food_files as _food_files , user_files as _user_files , ) MONGO_DB_MAPPING = { '' : { '' : _test , '' : _food , '' : _user , } , '' : { '' : _test_files , '' : _food_files , '' : _user_files , ", "answer": "}"}, {"prompt": " from django . http import HttpResponse from django . utils . encoding import iri_to_uri class HttpResponseReload ( HttpResponse ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " from django . core . management . base import BaseCommand from olympia . tags . models import Tag from olympia . tags . tasks import clean_tag class Command ( BaseCommand ) : help = '' def handle ( self , * args , ** kw ) : pks = list ( Tag . objects . values_list ( '' , flat = True ) . order_by ( '' ) ) print \"\" % len ( pks ) ", "answer": "for pk in pks :"}, {"prompt": " \"\"\"\"\"\" from flask_velox . mixins . sqla . delete import ( DeleteObjectMixin , MultiDeleteObjectMixin ) class DeleteObjectView ( DeleteObjectMixin ) : \"\"\"\"\"\" ", "answer": "pass"}, {"prompt": " import datetime import decimal import re import time import math from itertools import tee import django . utils . copycompat as copy from django . db import connection from django . db . models . fields . subclassing import LegacyConnection from django . db . models . query_utils import QueryWrapper from django . conf import settings from django import forms from django . core import exceptions , validators from django . utils . datastructures import DictWrapper from django . utils . functional import curry from django . utils . text import capfirst from django . utils . translation import ugettext_lazy as _ from django . utils . encoding import smart_unicode , force_unicode , smart_str from django . utils import datetime_safe class NOT_PROVIDED : pass BLANK_CHOICE_DASH = [ ( \"\" , \"\" ) ] BLANK_CHOICE_NONE = [ ( \"\" , \"\" ) ] class FieldDoesNotExist ( Exception ) : pass class Field ( object ) : \"\"\"\"\"\" __metaclass__ = LegacyConnection empty_strings_allowed = True creation_counter = auto_creation_counter = - default_validators = [ ] default_error_messages = { '' : _ ( u'' ) , '' : _ ( u'' ) , '' : _ ( u'' ) , } def _description ( self ) : return _ ( u'' ) % { '' : self . __class__ . __name__ } description = property ( _description ) def __init__ ( self , verbose_name = None , name = None , primary_key = False , max_length = None , unique = False , blank = False , null = False , db_index = False , rel = None , default = NOT_PROVIDED , editable = True , serialize = True , unique_for_date = None , unique_for_month = None , unique_for_year = None , choices = None , help_text = '' , db_column = None , db_tablespace = None , auto_created = False , validators = [ ] , error_messages = None ) : self . name = name self . verbose_name = verbose_name self . primary_key = primary_key self . max_length , self . _unique = max_length , unique self . blank , self . null = blank , null if self . empty_strings_allowed and connection . features . interprets_empty_strings_as_nulls : self . null = True self . rel = rel self . default = default self . editable = editable self . serialize = serialize self . unique_for_date , self . unique_for_month = unique_for_date , unique_for_month self . unique_for_year = unique_for_year self . _choices = choices or [ ] self . help_text = help_text self . db_column = db_column self . db_tablespace = db_tablespace or settings . DEFAULT_INDEX_TABLESPACE self . auto_created = auto_created self . db_index = db_index if auto_created : self . creation_counter = Field . auto_creation_counter Field . auto_creation_counter -= else : self . creation_counter = Field . creation_counter Field . creation_counter += self . validators = self . default_validators + validators messages = { } for c in reversed ( self . __class__ . __mro__ ) : messages . update ( getattr ( c , '' , { } ) ) messages . update ( error_messages or { } ) self . error_messages = messages def __cmp__ ( self , other ) : return cmp ( self . creation_counter , other . creation_counter ) def __deepcopy__ ( self , memodict ) : obj = copy . copy ( self ) if self . rel : obj . rel = copy . copy ( self . rel ) memodict [ id ( self ) ] = obj return obj def to_python ( self , value ) : \"\"\"\"\"\" return value def run_validators ( self , value ) : if value in validators . EMPTY_VALUES : return errors = [ ] for v in self . validators : try : v ( value ) except exceptions . ValidationError , e : if hasattr ( e , '' ) and e . code in self . error_messages : message = self . error_messages [ e . code ] if e . params : message = message % e . params errors . append ( message ) else : errors . extend ( e . messages ) if errors : raise exceptions . ValidationError ( errors ) def validate ( self , value , model_instance ) : \"\"\"\"\"\" if not self . editable : return if self . _choices and value : for option_key , option_value in self . choices : if isinstance ( option_value , ( list , tuple ) ) : for optgroup_key , optgroup_value in option_value : if value == optgroup_key : return elif value == option_key : return raise exceptions . ValidationError ( self . error_messages [ '' ] % value ) if value is None and not self . null : raise exceptions . ValidationError ( self . error_messages [ '' ] ) if not self . blank and value in validators . EMPTY_VALUES : raise exceptions . ValidationError ( self . error_messages [ '' ] ) def clean ( self , value , model_instance ) : \"\"\"\"\"\" value = self . to_python ( value ) self . validate ( value , model_instance ) self . run_validators ( value ) return value def db_type ( self , connection ) : \"\"\"\"\"\" data = DictWrapper ( self . __dict__ , connection . ops . quote_name , \"\" ) try : return connection . creation . data_types [ self . get_internal_type ( ) ] % data except KeyError : return None def unique ( self ) : return self . _unique or self . primary_key unique = property ( unique ) def set_attributes_from_name ( self , name ) : self . name = name self . attname , self . column = self . get_attname_column ( ) if self . verbose_name is None and name : self . verbose_name = name . replace ( '' , '' ) def contribute_to_class ( self , cls , name ) : self . set_attributes_from_name ( name ) self . model = cls cls . _meta . add_field ( self ) if self . choices : setattr ( cls , '' % self . name , curry ( cls . _get_FIELD_display , field = self ) ) def get_attname ( self ) : return self . name def get_attname_column ( self ) : attname = self . get_attname ( ) column = self . db_column or attname return attname , column def get_cache_name ( self ) : return '' % self . name def get_internal_type ( self ) : return self . __class__ . __name__ def pre_save ( self , model_instance , add ) : \"\" return getattr ( model_instance , self . attname ) def get_prep_value ( self , value ) : \"\" return value def get_db_prep_value ( self , value , connection , prepared = False ) : \"\"\"\"\"\" if not prepared : value = self . get_prep_value ( value ) return value def get_db_prep_save ( self , value , connection ) : \"\" return self . get_db_prep_value ( value , connection = connection , prepared = False ) def get_prep_lookup ( self , lookup_type , value ) : \"\" if hasattr ( value , '' ) : return value . prepare ( ) if hasattr ( value , '' ) : return value . _prepare ( ) if lookup_type in ( '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ) : return value elif lookup_type in ( '' , '' , '' , '' , '' ) : return self . get_prep_value ( value ) elif lookup_type in ( '' , '' ) : return [ self . get_prep_value ( v ) for v in value ] elif lookup_type == '' : try : return int ( value ) except ValueError : raise ValueError ( \"\" ) raise TypeError ( \"\" % lookup_type ) def get_db_prep_lookup ( self , lookup_type , value , connection , prepared = False ) : \"\" if not prepared : value = self . get_prep_lookup ( lookup_type , value ) if hasattr ( value , '' ) : value = value . get_compiler ( connection = connection ) if hasattr ( value , '' ) or hasattr ( value , '' ) : if hasattr ( value , '' ) : return value if hasattr ( value , '' ) : sql , params = value . as_sql ( ) else : sql , params = value . _as_sql ( connection = connection ) return QueryWrapper ( ( '' % sql ) , params ) if lookup_type in ( '' , '' , '' , '' , '' , '' ) : return [ value ] elif lookup_type in ( '' , '' , '' , '' , '' ) : return [ self . get_db_prep_value ( value , connection = connection , prepared = prepared ) ] elif lookup_type in ( '' , '' ) : return [ self . get_db_prep_value ( v , connection = connection , prepared = prepared ) for v in value ] elif lookup_type in ( '' , '' ) : return [ \"\" % connection . ops . prep_for_like_query ( value ) ] elif lookup_type == '' : return [ connection . ops . prep_for_iexact_query ( value ) ] elif lookup_type in ( '' , '' ) : return [ \"\" % connection . ops . prep_for_like_query ( value ) ] elif lookup_type in ( '' , '' ) : return [ \"\" % connection . ops . prep_for_like_query ( value ) ] elif lookup_type == '' : return [ ] elif lookup_type == '' : if self . get_internal_type ( ) == '' : return connection . ops . year_lookup_bounds_for_date_field ( value ) else : return connection . ops . year_lookup_bounds ( value ) def has_default ( self ) : \"\" return self . default is not NOT_PROVIDED def get_default ( self ) : \"\" if self . has_default ( ) : if callable ( self . default ) : return self . default ( ) return force_unicode ( self . default , strings_only = True ) if not self . empty_strings_allowed or ( self . null and not connection . features . interprets_empty_strings_as_nulls ) : return None return \"\" def get_validator_unique_lookup_type ( self ) : return '' % self . name def get_choices ( self , include_blank = True , blank_choice = BLANK_CHOICE_DASH ) : \"\"\"\"\"\" first_choice = include_blank and blank_choice or [ ] if self . choices : return first_choice + list ( self . choices ) rel_model = self . rel . to if hasattr ( self . rel , '' ) : lst = [ ( getattr ( x , self . rel . get_related_field ( ) . attname ) , smart_unicode ( x ) ) for x in rel_model . _default_manager . complex_filter ( self . rel . limit_choices_to ) ] else : lst = [ ( x . _get_pk_val ( ) , smart_unicode ( x ) ) for x in rel_model . _default_manager . complex_filter ( self . rel . limit_choices_to ) ] return first_choice + lst def get_choices_default ( self ) : return self . get_choices ( ) def get_flatchoices ( self , include_blank = True , blank_choice = BLANK_CHOICE_DASH ) : \"\" first_choice = include_blank and blank_choice or [ ] return first_choice + list ( self . flatchoices ) def _get_val_from_obj ( self , obj ) : if obj is not None : return getattr ( obj , self . attname ) else : return self . get_default ( ) def value_to_string ( self , obj ) : \"\"\"\"\"\" return smart_unicode ( self . _get_val_from_obj ( obj ) ) def bind ( self , fieldmapping , original , bound_field_class ) : return bound_field_class ( self , fieldmapping , original ) def _get_choices ( self ) : if hasattr ( self . _choices , '' ) : choices , self . _choices = tee ( self . _choices ) return choices else : return self . _choices choices = property ( _get_choices ) def _get_flatchoices ( self ) : \"\"\"\"\"\" flat = [ ] for choice , value in self . choices : if isinstance ( value , ( list , tuple ) ) : flat . extend ( value ) else : flat . append ( ( choice , value ) ) return flat flatchoices = property ( _get_flatchoices ) def save_form_data ( self , instance , data ) : setattr ( instance , self . name , data ) def formfield ( self , form_class = forms . CharField , ** kwargs ) : \"\" defaults = { '' : not self . blank , '' : capfirst ( self . verbose_name ) , '' : self . help_text } if self . has_default ( ) : if callable ( self . default ) : defaults [ '' ] = self . default defaults [ '' ] = True else : defaults [ '' ] = self . get_default ( ) if self . choices : include_blank = self . blank or not ( self . has_default ( ) or '' in kwargs ) defaults [ '' ] = self . get_choices ( include_blank = include_blank ) defaults [ '' ] = self . to_python if self . null : defaults [ '' ] = None form_class = forms . TypedChoiceField for k in kwargs . keys ( ) : if k not in ( '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ) : del kwargs [ k ] defaults . update ( kwargs ) return form_class ( ** defaults ) def value_from_object ( self , obj ) : \"\" return getattr ( obj , self . attname ) class AutoField ( Field ) : description = _ ( \"\" ) empty_strings_allowed = False default_error_messages = { '' : _ ( u'' ) , } def __init__ ( self , * args , ** kwargs ) : assert kwargs . get ( '' , False ) is True , \"\" % self . __class__ . __name__ kwargs [ '' ] = True Field . __init__ ( self , * args , ** kwargs ) def get_internal_type ( self ) : return \"\" def to_python ( self , value ) : if value is None : return value try : return int ( value ) except ( TypeError , ValueError ) : raise exceptions . ValidationError ( self . error_messages [ '' ] ) def validate ( self , value , model_instance ) : pass def get_prep_value ( self , value ) : if value is None : return None return int ( value ) def contribute_to_class ( self , cls , name ) : assert not cls . _meta . has_auto_field , \"\" super ( AutoField , self ) . contribute_to_class ( cls , name ) cls . _meta . has_auto_field = True cls . _meta . auto_field = self def formfield ( self , ** kwargs ) : return None class BooleanField ( Field ) : empty_strings_allowed = False default_error_messages = { '' : _ ( u'' ) , } description = _ ( \"\" ) def __init__ ( self , * args , ** kwargs ) : kwargs [ '' ] = True if '' not in kwargs and not kwargs . get ( '' ) : kwargs [ '' ] = False Field . __init__ ( self , * args , ** kwargs ) def get_internal_type ( self ) : return \"\" def to_python ( self , value ) : if value in ( True , False ) : return bool ( value ) if value in ( '' , '' , '' ) : return True if value in ( '' , '' , '' ) : return False raise exceptions . ValidationError ( self . error_messages [ '' ] ) def get_prep_lookup ( self , lookup_type , value ) : if value in ( '' , '' ) : value = bool ( int ( value ) ) return super ( BooleanField , self ) . get_prep_lookup ( lookup_type , value ) def get_prep_value ( self , value ) : if value is None : return None return bool ( value ) def formfield ( self , ** kwargs ) : if self . choices : include_blank = self . null or not ( self . has_default ( ) or '' in kwargs ) defaults = { '' : self . get_choices ( include_blank = include_blank ) } else : defaults = { '' : forms . BooleanField } defaults . update ( kwargs ) return super ( BooleanField , self ) . formfield ( ** defaults ) class CharField ( Field ) : description = _ ( \"\" ) def __init__ ( self , * args , ** kwargs ) : super ( CharField , self ) . __init__ ( * args , ** kwargs ) self . validators . append ( validators . MaxLengthValidator ( self . max_length ) ) def get_internal_type ( self ) : return \"\" def to_python ( self , value ) : if isinstance ( value , basestring ) or value is None : return value return smart_unicode ( value ) def get_prep_value ( self , value ) : return self . to_python ( value ) def formfield ( self , ** kwargs ) : defaults = { '' : self . max_length } defaults . update ( kwargs ) return super ( CharField , self ) . formfield ( ** defaults ) class CommaSeparatedIntegerField ( CharField ) : default_validators = [ validators . validate_comma_separated_integer_list ] description = _ ( \"\" ) def formfield ( self , ** kwargs ) : defaults = { '' : { '' : _ ( u'' ) , } } defaults . update ( kwargs ) return super ( CommaSeparatedIntegerField , self ) . formfield ( ** defaults ) ansi_date_re = re . compile ( r'' ) class DateField ( Field ) : description = _ ( \"\" ) empty_strings_allowed = False default_error_messages = { '' : _ ( '' ) , '' : _ ( '' ) , } def __init__ ( self , verbose_name = None , name = None , auto_now = False , auto_now_add = False , ** kwargs ) : self . auto_now , self . auto_now_add = auto_now , auto_now_add if auto_now or auto_now_add : kwargs [ '' ] = False kwargs [ '' ] = True ", "answer": "Field . __init__ ( self , verbose_name , name , ** kwargs )"}, {"prompt": " import threading import time import datetime import re import os import ciscolib PASSWORD = '' USERNAME = '' USER_PASSWORD = '' models = [ ] models_lock = threading . Lock ( ) class Grabber ( threading . Thread ) : def __init__ ( self , host ) : threading . Thread . __init__ ( self ) self . host = host def run ( self ) : try : device = ciscolib . Device ( self . host , PASSWORD ) device . connect ( ) except ciscolib . AuthenticationError : try : device = ciscolib . Device ( self . host , USER_PASSWORD , USERNAME ) device . connect ( ) except : print ( \"\" % self . host ) return except : print ( \"\" % self . host ) return try : model = device . get_model ( ) except ciscolib . ModelNotSupported : print ( \"\" % self . host ) return if model in models : return else : with models_lock : models . append ( model ) output_dir = '' % model try : os . mkdir ( output_dir ) except OSError as e : ", "answer": "if e . errno != :"}, {"prompt": " \"\"\"\"\"\" from _abcoll import * class Counter ( dict ) : '''''' def __init__ ( self , iterable = None , ** kwds ) : '''''' super ( Counter , self ) . __init__ ( ) self . update ( iterable , ** kwds ) def __missing__ ( self , key ) : '' return def most_common ( self , n = None ) : '''''' if n is None : return sorted ( self . iteritems ( ) , key = _itemgetter ( ) , reverse = True ) return _heapq . nlargest ( n , self . iteritems ( ) , key = _itemgetter ( ) ) def elements ( self ) : '''''' return _chain . from_iterable ( _starmap ( _repeat , self . iteritems ( ) ) ) @ classmethod def fromkeys ( cls , iterable , v = None ) : raise NotImplementedError ( '' ) def update ( self , iterable = None , ** kwds ) : '''''' if iterable is not None : if isinstance ( iterable , Mapping ) : if self : self_get = self . get for elem , count in iterable . iteritems ( ) : self [ elem ] = self_get ( elem , ) + count else : super ( Counter , self ) . update ( iterable ) else : self_get = self . get for elem in iterable : ", "answer": "self [ elem ] = self_get ( elem , ) + "}, {"prompt": " import stripe from stripe . test . helper import ( StripeResourceTest , DUMMY_DISPUTE , NOW ) class DisputeTest ( StripeResourceTest ) : def test_list_all_disputes ( self ) : stripe . Dispute . list ( created = { '' : NOW } ) self . requestor_mock . request . assert_called_with ( '' , '' , { '' : { '' : NOW } , } ) def test_create_dispute ( self ) : stripe . Dispute . create ( idempotency_key = '' , ** DUMMY_DISPUTE ) self . requestor_mock . request . assert_called_with ( '' , '' , DUMMY_DISPUTE , { '' : '' } , ) def test_retrieve_dispute ( self ) : stripe . Dispute . retrieve ( '' ) self . requestor_mock . request . assert_called_with ( '' , '' , { } , None ) def test_update_dispute ( self ) : dispute = stripe . Dispute . construct_from ( { '' : '' , '' : { '' : '' , } , } , '' ) dispute . evidence [ '' ] = '' dispute . evidence [ '' ] = '' dispute . save ( ) self . requestor_mock . request . assert_called_with ( '' , '' , { '' : { '' : '' , '' : '' , } } , None ) def test_close_dispute ( self ) : ", "answer": "dispute = stripe . Dispute ( id = '' )"}, {"prompt": " import pyglet import physicalobject , resources class Bullet ( physicalobject . PhysicalObject ) : \"\"\"\"\"\" def __init__ ( self , * args , ** kwargs ) : super ( Bullet , self ) . __init__ ( resources . bullet_image , * args , ** kwargs ) ", "answer": "pyglet . clock . schedule_once ( self . die , )"}, {"prompt": " \"\"\"\"\"\" import posixpath __all__ = [ '' , '' , '' , '' , '' , '' , ] class FileWrapper : \"\"\"\"\"\" def __init__ ( self , filelike , blksize = ) : self . filelike = filelike self . blksize = blksize if hasattr ( filelike , '' ) : self . close = filelike . close def __getitem__ ( self , key ) : data = self . filelike . read ( self . blksize ) if data : return data raise IndexError def __iter__ ( self ) : return self def next ( self ) : data = self . filelike . read ( self . blksize ) if data : return data raise StopIteration def guess_scheme ( environ ) : \"\"\"\"\"\" if environ . get ( \"\" ) in ( '' , '' , '' ) : return '' else : return '' def application_uri ( environ ) : \"\"\"\"\"\" url = environ [ '' ] + '' from urllib import quote if environ . get ( '' ) : url += environ [ '' ] else : url += environ [ '' ] if environ [ '' ] == '' : if environ [ '' ] != '' : url += '' + environ [ '' ] else : if environ [ '' ] != '' : url += '' + environ [ '' ] url += quote ( environ . get ( '' ) or '' ) return url def request_uri ( environ , include_query = ) : \"\"\"\"\"\" url = application_uri ( environ ) from urllib import quote path_info = quote ( environ . get ( '' , '' ) ) if not environ . get ( '' ) : url += path_info [ : ] else : url += path_info if include_query and environ . get ( '' ) : url += '' + environ [ '' ] return url def shift_path_info ( environ ) : \"\"\"\"\"\" path_info = environ . get ( '' , '' ) if not path_info : return None path_parts = path_info . split ( '' ) path_parts [ : - ] = [ p for p in path_parts [ : - ] if p and p < > '' ] name = path_parts [ ] del path_parts [ ] script_name = environ . get ( '' , '' ) script_name = posixpath . normpath ( script_name + '' + name ) if script_name . endswith ( '' ) : script_name = script_name [ : - ] if not name and not script_name . endswith ( '' ) : script_name += '' environ [ '' ] = script_name environ [ '' ] = '' . join ( path_parts ) if name == '' : name = None return name def setup_testing_defaults ( environ ) : \"\"\"\"\"\" environ . setdefault ( '' , '' ) environ . setdefault ( '' , '' ) environ . setdefault ( '' , environ [ '' ] ) environ . setdefault ( '' , '' ) if '' not in environ and '' not in environ : environ . setdefault ( '' , '' ) environ . setdefault ( '' , '' ) environ . setdefault ( '' , ( , ) ) environ . setdefault ( '' , ) environ . setdefault ( '' , ) environ . setdefault ( '' , ) from StringIO import StringIO environ . setdefault ( '' , StringIO ( \"\" ) ) environ . setdefault ( '' , StringIO ( ) ) environ . setdefault ( '' , guess_scheme ( environ ) ) if environ [ '' ] == '' : environ . setdefault ( '' , '' ) ", "answer": "elif environ [ '' ] == '' :"}, {"prompt": " \"\"\"\"\"\" import csv from pokemon . models import * def build_pokes ( ) : file = open ( '' , '' ) rdr = csv . reader ( file , delimiter = '' ) for row in rdr : if row [ ] != '' : new_p = Pokemon ( pkdx_id = int ( row [ ] ) , name = str ( row [ ] ) , exp = int ( row [ ] ) , catch_rate = , happiness = , hp = , attack = , defense = , speed = , sp_atk = , sp_def = , total = , egg_cycles = , ) new_p . save ( ) print '' % new_p . name def build_abilities ( ) : file = open ( '' , '' ) rdr = csv . reader ( file , delimiter = '' ) for row in rdr : if row [ ] != '' : new_a = Ability ( name = row [ ] , description = '' , ) new_a . save ( ) print '' % new_a . name def build_moves ( ) : file = open ( '' , '' ) rdr = csv . reader ( file , delimiter = '' ) for row in rdr : if row [ ] != '' : new_a = Move ( name = row [ ] , description = '' , ) new_a . accuracy = row [ ] if row [ ] != '' else new_a . pp = row [ ] if row [ ] != '' else new_a . power = row [ ] if row [ ] != '' else new_a . save ( ) print '' % new_a . name def build_ability_pokes ( ) : file = open ( '' , '' ) rdr = csv . reader ( file , delimiter = '' ) for row in rdr : if row [ ] != '' : poke = Pokemon . objects . filter ( pkdx_id = row [ ] ) [ ] ab = Ability . objects . get ( pk = int ( row [ ] ) ) poke . abilities . add ( ab ) poke . save ( ) print '' + ab . name + '' + poke . name def build_move_pokes ( ) : file = open ( '' , '' ) rdr = csv . reader ( file , delimiter = '' ) LEARN = [ '' , '' , '' , '' , '' , '' ] for row in rdr : if row [ ] != '' : poke = Pokemon . objects . filter ( pkdx_id = row [ ] ) [ ] mv = Move . objects . get ( pk = int ( row [ ] ) ) pm , created = MovePokemon . objects . get_or_create ( pokemon = poke , move = mv , ) if created : learn = LEARN [ int ( row [ ] ) ] if int ( row [ ] ) <= else LEARN [ ] pm . learn_type = learn pm . level = row [ ] if row [ ] != '' else pm . save ( ) print '' + pm . __unicode__ ( ) def build_egg_pokes ( ) : file = open ( '' , '' ) rdr = csv . reader ( file , delimiter = '' ) for row in rdr : if row [ ] != '' : poke = Pokemon . objects . filter ( pkdx_id = row [ ] ) [ ] egg = EggGroup . objects . get ( pk = int ( row [ ] ) ) poke . egg_group . add ( egg ) poke . save ( ) def build_type_pokes ( ) : file = open ( '' , '' ) rdr = csv . reader ( file , delimiter = '' ) for row in rdr : if row [ ] != '' : poke = Pokemon . objects . filter ( pkdx_id = row [ ] ) [ ] ty = Type . objects . get ( pk = int ( row [ ] ) ) poke . types . add ( ty ) poke . save ( ) print '' + ty . name + '' + poke . name def build_sprites ( ) : for i in range ( , ) : str_num = str ( i ) sfile = '' % str_num p = Pokemon . objects . filter ( pkdx_id = i ) if p . exists ( ) : p = p [ ] s = Sprite ( name = p . name + '' , image = sfile ) s . save ( ) print '' % p . name else : print '' % i def poke_sprite_links ( ) : for i in Sprite . objects . all ( ) : p = Pokemon . objects . filter ( name = i . name [ : - ] ) if p . exists ( ) : p = p [ ] p . sprites . add ( i ) p . save ( ) print '' % p . name else : print '' % i . name [ : - ] def build_poke_stats ( ) : \"\"\"\"\"\" file = open ( '' , '' ) rdr = csv . reader ( file , delimiter = '' ) for row in rdr : if row [ ] != '' : p = Pokemon . objects . filter ( pkdx_id = row [ ] ) if p . exists ( ) : p = p [ ] p . height = row [ ] if row [ ] != '' else p . weight = row [ ] if row [ ] != '' else p . happiness = row [ ] if row [ ] != '' else p . save ( ) print '' % p . name file = open ( '' ) rdr = csv . reader ( file , delimiter = '' ) for row in rdr : if row [ ] != '' : p = Pokemon . objects . filter ( pkdx_id = row [ ] ) if p . exists ( ) : p = p [ ] if row [ ] == '' : p . hp = row [ ] if row [ ] == '' : p . attack = row [ ] if row [ ] == '' : p . defense = row [ ] if row [ ] == '' : p . sp_atk = row [ ] if row [ ] == '' : p . sp_def = row [ ] if row [ ] == '' : p . speed = row [ ] p . save ( ) print '' % p . name def build_evolutions ( ) : \"\"\"\"\"\" file = open ( '' , '' ) rdr = csv . reader ( file , delimiter = '' ) method = [ '' , '' , '' , '' , '' ] for row in rdr : if row [ ] != '' : frm = Pokemon . objects . filter ( pkdx_id = int ( row [ ] ) - ) if not frm . exists ( ) : frm = Pokemon . objects . filter ( pkdx_id = ) [ ] else : frm = frm [ ] to = Pokemon . objects . filter ( pkdx_id = int ( row [ ] ) ) if not to . exists ( ) : to = Pokemon . objects . filter ( pkdx_id = ) [ ] else : to = to [ ] if method [ int ( row [ ] ) ] == '' : e = Evolution ( frm = frm , to = to , method = method [ int ( row [ ] ) ] , level = row [ ] if row [ ] != '' else ) e . save ( ) print '' % e . __unicode__ ( ) def build_move_descriptions ( ) : \"\"\"\"\"\" for m in Move . objects . all ( ) : f_moves = open ( '' , '' ) f_descrips = open ( '' , '' ) for row in csv . reader ( f_moves , delimiter = '' ) : if str ( row [ ] ) == m . name : for drow in csv . reader ( f_descrips , delimiter = '' ) : if str ( row [ ] ) == str ( drow [ ] ) : s = str ( drow [ ] ) . replace ( '' , str ( row [ ] ) ) s = s . replace ( '' , '' ) s = s . replace ( '' , '' ) m . description = s m . save ( ) print '' % m . name def build_complex_evolutions ( ) : \"\"\"\"\"\" fspecies = open ( '' , '' ) fevols = open ( '' , '' ) method = [ '' , '' , '' , '' , '' ] c = for row in csv . reader ( fspecies , delimiter = '' ) : if row [ ] != '' and row [ ] != '' : frm = Pokemon . objects . get ( pkdx_id = int ( row [ ] ) ) fevols = open ( '' , '' ) for erow in csv . reader ( fevols , delimiter = '' ) : if erow [ ] != '' : to = Pokemon . objects . get ( pkdx_id = int ( erow [ ] ) ) if int ( erow [ ] ) == int ( row [ ] ) : mthd = method [ int ( erow [ ] ) ] lvl = erow [ ] if erow [ ] != '' else e = Evolution ( frm = frm , to = to , method = mthd , level = lvl ) e . save ( ) print '' % ( frm . name , to . name ) c += print '' % str ( c ) def build_pokedex_descriptions ( ) : \"\"\"\"\"\" gens = { : '' , : '' , : '' , : '' , : '' , : '' , : '' , : '' , : '' , : '' , : '' , : '' , : '' , : '' , : '' , : '' , : '' , : '' , : '' , : '' , : '' , : '' , : '' , : '' } descrips = open ( '' , '' ) c = for row in csv . reader ( descrips , delimiter = '' ) : ", "answer": "if row [ ] != '' and int ( row [ ] ) == :"}, {"prompt": " \"\"\"\"\"\" from . damage import DamageEffect from . damagemodifier import DamageModifier ", "answer": "from . effectscollection import EffectsCollection"}, {"prompt": " __author__ = '' __version__ = '' from pybrain . utilities import Named , abstractMethod class Trainer ( Named ) : \"\"\"\"\"\" ds = None module = None def __init__ ( self , module ) : self . module = module ", "answer": "def setData ( self , dataset ) :"}, {"prompt": " \"\"\"\"\"\" import os import sys from django import forms from django . db import router from django . core . exceptions import ValidationError from django . core . urlresolvers import reverse from treeio . core . models import Object from captcha . fields import CaptchaField from django . utils . translation import ugettext as _ from treeio . core . conf import settings from django . db . models import Q import django . contrib . auth . models as django_auth from jinja2 . filters import do_striptags , do_truncate from treeio . core . models import Location , User , Widget , Tag , ConfigSetting from treeio . core . mail import EmailPassword from treeio . identities . models import Contact , ContactType , ContactValue class PermissionForm ( forms . ModelForm ) : \"\" def __init__ ( self , * args , ** kwargs ) : \"\" super ( PermissionForm , self ) . __init__ ( * args , ** kwargs ) self . fields [ '' ] . help_text = \"\" self . fields [ '' ] . required = False self . fields [ '' ] . widget . attrs . update ( { '' : '' , '' : reverse ( '' ) } ) self . fields [ '' ] . help_text = \"\" self . fields [ '' ] . required = False self . fields [ '' ] . widget . attrs . update ( { '' : '' , '' : reverse ( '' ) } ) class Meta : \"\" model = Object fields = ( '' , '' ) class SubscribeForm ( forms . Form ) : \"\" subscriber = forms . ModelChoiceField ( queryset = User . objects . all ( ) ) def __init__ ( self , instance , * args , ** kwargs ) : \"\" subscriptions = instance . subscribers . all ( ) super ( SubscribeForm , self ) . __init__ ( * args , ** kwargs ) self . subscriptions = subscriptions self . instance = instance self . fields [ '' ] . label = \"\" self . fields [ '' ] . queryset = User . objects . exclude ( pk__in = subscriptions ) self . fields [ '' ] . widget . attrs . update ( { '' : '' , '' : reverse ( '' ) } ) def save ( self ) : \"\" user = self . cleaned_data [ '' ] object = self . instance if user not in self . subscriptions : object . subscribers . add ( user ) self . subscriptions = object . subscribers . all ( ) return self . subscriptions class ObjectLinksForm ( forms . Form ) : \"\"\"\"\"\" links = forms . ModelChoiceField ( queryset = [ ] , empty_label = None , label = '' ) def __init__ ( self , user , response_format , instance , * args , ** kwargs ) : super ( ObjectLinksForm , self ) . __init__ ( * args , ** kwargs ) queryset = Object . filter_permitted ( user , Object . objects ) self . fields [ '' ] . queryset = queryset if '' not in response_format : if instance : queryset = queryset . exclude ( pk__in = instance . links . all ( ) ) choices = [ ] for obj in queryset : human_type = obj . get_human_type ( ) name = do_truncate ( do_striptags ( unicode ( obj . object_name ) ) , , True ) if human_type : name += u\"\" + human_type + u\"\" choices . append ( ( obj . id , name ) ) self . fields [ '' ] . choices = choices self . fields [ '' ] . label = \"\" self . fields [ '' ] . initial = \"\" self . fields [ '' ] . widget . attrs . update ( { '' : '' , '' : reverse ( '' ) } ) class TagsForm ( forms . Form ) : tags = forms . ModelMultipleChoiceField ( queryset = Tag . objects . all ( ) ) def __init__ ( self , tags , * args , ** kwargs ) : super ( TagsForm , self ) . __init__ ( * args , ** kwargs ) self . fields [ '' ] . label = \"\" self . fields [ '' ] . initial = [ tag . id for tag in tags ] self . fields [ '' ] . required = False self . fields [ '' ] . widget . attrs . update ( { '' : '' , '' : reverse ( '' ) } ) def save ( self ) : return self . cleaned_data [ '' ] class LoginForm ( forms . Form ) : \"\"\"\"\"\" captcha = CaptchaField ( label = _ ( \"\" ) ) def __init__ ( self , * args , ** kwargs ) : super ( LoginForm , self ) . __init__ ( * args , ** kwargs ) if settings . CAPTCHA_DISABLE : del self . fields [ '' ] class PasswordResetForm ( forms . Form ) : \"\" username = forms . CharField ( label = ( \"\" ) , max_length = ) def __init__ ( self , * args , ** kwargs ) : super ( PasswordResetForm , self ) . __init__ ( * args , ** kwargs ) self . fields [ '' ] . label = _ ( \"\" ) def clean_username ( self ) : \"\"\"\"\"\" username = self . cleaned_data [ \"\" ] if '' in username : emails = ContactValue . objects . filter ( value = username , field__field_type = '' , contact__trash = False , contact__related_user__isnull = False ) users = [ email . contact . related_user . user for email in emails ] else : users = User . objects . filter ( user__username = username ) if len ( users ) == : raise forms . ValidationError ( _ ( \"\" ) ) else : username = users [ ] return username def save ( self ) : \"\" user = self . cleaned_data [ \"\" ] if user : toaddr = user . get_contact ( ) . get_email ( ) if toaddr : password = user . generate_new_password ( ) email = EmailPassword ( toaddr , user . user . username , password ) email . send_email ( ) class InvitationForm ( forms . Form ) : \"\"\"\"\"\" invitation = None def __init__ ( self , invitation = None , * args , ** kwargs ) : super ( InvitationForm , self ) . __init__ ( * args , ** kwargs ) self . fields [ '' ] = forms . CharField ( max_length = , label = _ ( \"\" ) ) self . fields [ '' ] = forms . CharField ( max_length = , label = _ ( \"\" ) ) self . fields [ '' ] = forms . CharField ( max_length = , label = _ ( \"\" ) , widget = forms . PasswordInput ( render_value = False ) ) self . fields [ '' ] = forms . CharField ( max_length = , label = _ ( \"\" ) , widget = forms . PasswordInput ( render_value = False ) ) self . invitation = invitation def clean_username ( self ) : \"\" data = self . cleaned_data [ '' ] query = Q ( name = data ) existing = User . objects . filter ( query ) if existing : raise forms . ValidationError ( _ ( \"\" ) % data ) user_limit = getattr ( settings , '' , ) if user_limit > : ", "answer": "user_number = User . objects . filter ( disabled = False ) . count ( )"}, {"prompt": " from unittest import TestCase import plotly . graph_objs as go import plotly . graph_reference as gr OLD_CLASS_NAMES = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ] class TestBackwardsCompat ( TestCase ) : def test_old_class_names ( self ) : for class_name in OLD_CLASS_NAMES : self . assertIn ( class_name , go . __dict__ . keys ( ) ) class TestGraphObjs ( TestCase ) : def test_traces_should_be_defined ( self ) : class_names = [ gr . string_to_class_name ( object_name ) for object_name in gr . TRACE_NAMES ] for class_name in class_names : self . assertIn ( class_name , go . __dict__ . keys ( ) ) def test_no_new_classes ( self ) : expected_class_names = { gr . string_to_class_name ( object_name ) for object_name in gr . TRACE_NAMES } expected_class_names . update ( OLD_CLASS_NAMES ) current_class_names = { key for key in go . __dict__ . keys ( ) if key [ ] . isupper ( ) } ", "answer": "self . assertEqual ( current_class_names , expected_class_names ) "}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import from io import open import os import subprocess from penelope . dictionary_ebook import DictionaryEbook from penelope . utilities import print_debug from penelope . utilities import print_error from penelope . utilities import print_info from penelope . utilities import create_temp_directory from penelope . utilities import copy_file from penelope . utilities import delete_directory __author__ = \"\" __copyright__ = \"\" __license__ = \"\" __version__ = \"\" __email__ = \"\" __status__ = \"\" KINDLEGEN = u\"\" def read ( dictionary , args , input_file_paths ) : print_error ( \"\" ) return None def write ( dictionary , args , output_file_path ) : result = None output_file_path_absolute = os . path . abspath ( output_file_path ) dictionary . sort ( by_headword = True , ignore_case = args . sort_ignore_case ) special_group , group_keys , group_dict = dictionary . group ( prefix_function_path = args . group_by_prefix_function , prefix_length = int ( args . group_by_prefix_length ) , merge_min_size = int ( args . group_by_prefix_merge_min_size ) , merge_across_first = args . group_by_prefix_merge_across_first ) all_group_keys = group_keys if special_group is not None : all_group_keys += [ u\"\" ] mobi = DictionaryEbook ( ebook_format = DictionaryEbook . MOBI , args = args ) for key in all_group_keys : if key == u\"\" : group_entries = special_group else : group_entries = group_dict [ key ] mobi . add_group ( key , group_entries ) print_debug ( \"\" % ( output_file_path_absolute ) , args . debug ) mobi . write ( output_file_path_absolute , compress = False ) result = [ output_file_path ] print_debug ( \"\" % ( output_file_path_absolute ) , args . debug ) tmp_path = mobi . get_tmp_path ( ) if args . mobi_no_kindlegen : print_info ( \"\" % tmp_path ) result = [ tmp_path ] else : try : print_debug ( \"\" , args . debug ) kindlegen_path = KINDLEGEN opf_file_path_absolute = os . path . join ( tmp_path , \"\" , \"\" ) mobi_file_path_relative = u\"\" mobi_file_path_absolute = os . path . join ( tmp_path , \"\" , mobi_file_path_relative ) if args . kindlegen_path is None : print_info ( \"\" % KINDLEGEN ) else : ", "answer": "kindlegen_path = args . kindlegen_path"}, {"prompt": " from django . conf . urls import patterns , include , url from django . contrib . staticfiles . urls import staticfiles_urlpatterns from django . contrib import admin ", "answer": "admin . autodiscover ( )"}, {"prompt": " from __future__ import absolute_import , division , print_function from django . test import TestCase class UrlRoutingTest ( TestCase ) : ", "answer": "def test_dummy ( self ) :"}, {"prompt": " from __future__ import print_function import argparse from neutronclient . _i18n import _ from neutronclient . common import utils from neutronclient . neutron import v2_0 as neutronv20 def _format_firewall_rules ( firewall_policy ) : try : output = '' + '' . join ( [ rule for rule in firewall_policy [ '' ] ] ) + '' return output except ( TypeError , KeyError ) : return '' def add_common_args ( parser ) : parser . add_argument ( '' , help = _ ( '' ) ) parser . add_argument ( '' , type = lambda x : x . split ( ) , help = _ ( '' '' ) ) def parse_common_args ( client , parsed_args ) : if parsed_args . firewall_rules : _firewall_rules = [ ] for f in parsed_args . firewall_rules : _firewall_rules . append ( neutronv20 . find_resourceid_by_name_or_id ( client , '' , f ) ) body = { '' : _firewall_rules } else : body = { } neutronv20 . update_dict ( parsed_args , body , [ '' , '' , '' , '' , '' ] ) return { '' : body } class ListFirewallPolicy ( neutronv20 . ListCommand ) : \"\"\"\"\"\" resource = '' list_columns = [ '' , '' , '' ] _formatters = { '' : _format_firewall_rules , } pagination_support = True sorting_support = True class ShowFirewallPolicy ( neutronv20 . ShowCommand ) : \"\"\"\"\"\" resource = '' class CreateFirewallPolicy ( neutronv20 . CreateCommand ) : \"\"\"\"\"\" resource = '' def add_known_arguments ( self , parser ) : parser . add_argument ( '' , metavar = '' , help = _ ( '' ) ) parser . add_argument ( '' , action = '' , help = _ ( '' ) , default = argparse . SUPPRESS ) parser . add_argument ( '' , action = '' , help = _ ( '' ) , default = argparse . SUPPRESS ) add_common_args ( parser ) def args2body ( self , parsed_args ) : return parse_common_args ( self . get_client ( ) , parsed_args ) class UpdateFirewallPolicy ( neutronv20 . UpdateCommand ) : \"\"\"\"\"\" resource = '' def add_known_arguments ( self , parser ) : add_common_args ( parser ) parser . add_argument ( '' , help = _ ( '' ) ) utils . add_boolean_argument ( parser , '' , help = _ ( '' '' ) ) utils . add_boolean_argument ( parser , '' , help = _ ( '' '' ) ) def args2body ( self , parsed_args ) : return parse_common_args ( self . get_client ( ) , parsed_args ) class DeleteFirewallPolicy ( neutronv20 . DeleteCommand ) : \"\"\"\"\"\" resource = '' class FirewallPolicyInsertRule ( neutronv20 . UpdateCommand ) : \"\"\"\"\"\" resource = '' def call_api ( self , neutron_client , firewall_policy_id , body ) : return neutron_client . firewall_policy_insert_rule ( firewall_policy_id , body ) def args2body ( self , parsed_args ) : _rule = '' if parsed_args . firewall_rule_id : _rule = neutronv20 . find_resourceid_by_name_or_id ( self . get_client ( ) , '' , parsed_args . firewall_rule_id ) _insert_before = '' if '' in parsed_args : if parsed_args . insert_before : _insert_before = neutronv20 . find_resourceid_by_name_or_id ( self . get_client ( ) , '' , parsed_args . insert_before ) _insert_after = '' if '' in parsed_args : if parsed_args . insert_after : _insert_after = neutronv20 . find_resourceid_by_name_or_id ( self . get_client ( ) , '' , parsed_args . insert_after ) body = { '' : _rule , '' : _insert_before , '' : _insert_after } return body def get_parser ( self , prog_name ) : parser = super ( FirewallPolicyInsertRule , self ) . get_parser ( prog_name ) parser . add_argument ( '' , metavar = '' , help = _ ( '' ) ) parser . add_argument ( '' , metavar = '' , help = _ ( '' ) ) parser . add_argument ( '' , metavar = '' , help = _ ( '' ) ) self . add_known_arguments ( parser ) return parser def take_action ( self , parsed_args ) : neutron_client = self . get_client ( ) body = self . args2body ( parsed_args ) _id = neutronv20 . find_resourceid_by_name_or_id ( neutron_client , self . resource , parsed_args . id ) self . call_api ( neutron_client , _id , body ) print ( ( _ ( '' ) % { '' : parsed_args . id } ) , file = self . app . stdout ) class FirewallPolicyRemoveRule ( neutronv20 . UpdateCommand ) : \"\"\"\"\"\" resource = '' ", "answer": "def call_api ( self , neutron_client , firewall_policy_id , body ) :"}, {"prompt": " \"\"\"\"\"\" from Handler import Handler import urllib2 class HttpPostHandler ( Handler ) : def __init__ ( self , config = None ) : Handler . __init__ ( self , config ) self . metrics = [ ] self . batch_size = int ( self . config [ '' ] ) self . url = self . config . get ( '' ) def get_default_config_help ( self ) : \"\"\"\"\"\" config = super ( HttpPostHandler , self ) . get_default_config_help ( ) config . update ( { '' : '' , '' : '' , } ) return config def get_default_config ( self ) : \"\"\"\"\"\" config = super ( HttpPostHandler , self ) . get_default_config ( ) config . update ( { '' : '' , '' : , } ) return config def process ( self , metric ) : self . metrics . append ( str ( metric ) ) if len ( self . metrics ) >= self . batch_size : self . post ( ) def flush ( self ) : \"\"\"\"\"\" self . post ( ) def post ( self ) : req = urllib2 . Request ( self . url , \"\" . join ( self . metrics ) ) ", "answer": "urllib2 . urlopen ( req )"}, {"prompt": " \"\"\"\"\"\" import unittest , datetime from django . utils . functional import curry from django . core import serializers from django . db import transaction from django . core import management from models import * def data_create ( pk , klass , data ) : instance = klass ( id = pk ) instance . data = data instance . save ( ) return instance def generic_create ( pk , klass , data ) : instance = klass ( id = pk ) instance . data = data [ ] instance . save ( ) for tag in data [ : ] : instance . tags . create ( data = tag ) return instance def fk_create ( pk , klass , data ) : instance = klass ( id = pk ) setattr ( instance , '' , data ) instance . save ( ) return instance def m2m_create ( pk , klass , data ) : instance = klass ( id = pk ) instance . save ( ) instance . data = data return instance def o2o_create ( pk , klass , data ) : instance = klass ( ) instance . data_id = data instance . save ( ) return instance def pk_create ( pk , klass , data ) : instance = klass ( ) instance . data = data instance . save ( ) return instance def data_compare ( testcase , pk , klass , data ) : instance = klass . objects . get ( id = pk ) testcase . assertEqual ( data , instance . data , \"\" % ( pk , data , type ( data ) , instance . data , type ( instance . data ) ) ) def generic_compare ( testcase , pk , klass , data ) : instance = klass . objects . get ( id = pk ) testcase . assertEqual ( data [ ] , instance . data ) testcase . assertEqual ( data [ : ] , [ t . data for t in instance . tags . all ( ) ] ) def fk_compare ( testcase , pk , klass , data ) : instance = klass . objects . get ( id = pk ) testcase . assertEqual ( data , instance . data_id ) def m2m_compare ( testcase , pk , klass , data ) : instance = klass . objects . get ( id = pk ) testcase . assertEqual ( data , [ obj . id for obj in instance . data . all ( ) ] ) def o2o_compare ( testcase , pk , klass , data ) : instance = klass . objects . get ( data = data ) testcase . assertEqual ( data , instance . data_id ) def pk_compare ( testcase , pk , klass , data ) : instance = klass . objects . get ( data = data ) testcase . assertEqual ( data , instance . data ) data_obj = ( data_create , data_compare ) generic_obj = ( generic_create , generic_compare ) fk_obj = ( fk_create , fk_compare ) m2m_obj = ( m2m_create , m2m_compare ) o2o_obj = ( o2o_create , o2o_compare ) pk_obj = ( pk_create , pk_compare ) test_data = [ ( data_obj , , BooleanData , True ) , ( data_obj , , BooleanData , False ) , ( data_obj , , CharData , \"\" ) , ( data_obj , , CharData , \"\" ) , ( data_obj , , CharData , \"\" ) , ( data_obj , , CharData , \"\" ) , ( data_obj , , CharData , \"\" ) , ( data_obj , , CharData , None ) , ( data_obj , , DateData , datetime . date ( , , ) ) , ( data_obj , , DateData , None ) , ( data_obj , , DateTimeData , datetime . datetime ( , , , , , ) ) , ( data_obj , , DateTimeData , None ) , ( data_obj , , EmailData , \"\" ) , ( data_obj , , EmailData , None ) , ( data_obj , , FileData , '' ) , ( data_obj , , FileData , None ) , ( data_obj , , FilePathData , \"\" ) , ( data_obj , , FilePathData , None ) , ( data_obj , , FloatData , ) , ( data_obj , , FloatData , - ) , ( data_obj , , FloatData , ) , ( data_obj , , FloatData , None ) , ( data_obj , , IntegerData , ) , ( data_obj , , IntegerData , - ) , ( data_obj , , IntegerData , ) , ( data_obj , , IntegerData , None ) , ( data_obj , , IPAddressData , \"\" ) , ( data_obj , , IPAddressData , None ) , ( data_obj , , NullBooleanData , True ) , ( data_obj , , NullBooleanData , False ) , ( data_obj , , NullBooleanData , None ) , ( data_obj , , PhoneData , \"\" ) , ( data_obj , , PhoneData , None ) , ( data_obj , , PositiveIntegerData , ) , ( data_obj , , PositiveIntegerData , None ) , ( data_obj , , PositiveSmallIntegerData , ) , ( data_obj , , PositiveSmallIntegerData , None ) , ( data_obj , , SlugData , \"\" ) , ( data_obj , , SlugData , None ) , ( data_obj , , SmallData , ) , ( data_obj , , SmallData , - ) , ( data_obj , , SmallData , ) , ( data_obj , , SmallData , None ) , ( data_obj , , TextData , \"\"\"\"\"\" ) , ( data_obj , , TextData , \"\" ) , ( data_obj , , TextData , None ) , ( data_obj , , TimeData , datetime . time ( , , ) ) , ( data_obj , , TimeData , None ) , ( data_obj , , USStateData , \"\" ) , ( data_obj , , USStateData , None ) , ( data_obj , , XMLData , \"\" ) , ( data_obj , , XMLData , None ) , ( generic_obj , , GenericData , [ '' , '' , '' ] ) , ( generic_obj , , GenericData , [ '' , '' , '' ] ) , ( data_obj , , Anchor , \"\" ) , ( data_obj , , Anchor , \"\" ) , ( fk_obj , , FKData , ) , ( fk_obj , , FKData , ) , ( fk_obj , , FKData , None ) , ( m2m_obj , , M2MData , [ ] ) , ( m2m_obj , , M2MData , [ , ] ) , ( m2m_obj , , M2MData , [ , ] ) , ( m2m_obj , , M2MData , [ , , , ] ) , ( o2o_obj , None , O2OData , ) , ( o2o_obj , None , O2OData , ) , ( fk_obj , , FKSelfData , ) , ( fk_obj , , FKSelfData , ) , ( fk_obj , , FKSelfData , None ) , ( m2m_obj , , M2MSelfData , [ ] ) , ( m2m_obj , , M2MSelfData , [ ] ) , ( m2m_obj , , M2MSelfData , [ , ] ) , ( m2m_obj , , M2MSelfData , [ , ] ) , ( m2m_obj , , M2MSelfData , [ , , , ] ) , ( m2m_obj , , M2MSelfData , [ ] ) , ( m2m_obj , , M2MSelfData , [ ] ) , ( data_obj , , Anchor , \"\" ) , ( data_obj , , Anchor , \"\" ) , ( pk_obj , , BooleanPKData , True ) , ( pk_obj , , BooleanPKData , False ) , ( pk_obj , , CharPKData , \"\" ) , ( pk_obj , , EmailPKData , \"\" ) , ( pk_obj , , FilePKData , '' ) , ( pk_obj , , FilePathPKData , \"\" ) , ( pk_obj , , FloatPKData , ) , ( pk_obj , , FloatPKData , - ) , ( pk_obj , , FloatPKData , ) , ( pk_obj , , IntegerPKData , ) , ( pk_obj , , IntegerPKData , - ) , ( pk_obj , , IntegerPKData , ) , ( pk_obj , , IPAddressPKData , \"\" ) , ( pk_obj , , NullBooleanPKData , True ) , ( pk_obj , , NullBooleanPKData , False ) , ( pk_obj , , PhonePKData , \"\" ) , ( pk_obj , , PositiveIntegerPKData , ) , ( pk_obj , , PositiveSmallIntegerPKData , ) , ( pk_obj , , SlugPKData , \"\" ) , ( pk_obj , , SmallPKData , ) , ( pk_obj , , SmallPKData , - ) , ( pk_obj , , SmallPKData , ) , ( pk_obj , , USStatePKData , \"\" ) , ] class SerializerTests ( unittest . TestCase ) : pass def serializerTest ( format , self ) : management . flush ( verbosity = , interactive = False ) objects = [ ] transaction . enter_transaction_management ( ) transaction . managed ( True ) for ( func , pk , klass , datum ) in test_data : objects . append ( func [ ] ( pk , klass , datum ) ) transaction . commit ( ) transaction . leave_transaction_management ( ) ", "answer": "objects . extend ( Tag . objects . all ( ) )"}, {"prompt": " from __future__ import print_function , unicode_literals import os import shutil import subprocess import sys import tempfile from optparse import OptionParser options = None def die ( msg ) : sys . stderr . write ( msg ) sys . exit ( ) def clone_git_tree ( git_dir ) : new_git_dir = tempfile . mkdtemp ( prefix = '' ) os . chdir ( new_git_dir ) execute ( [ '' , '' , git_dir , '' ] ) return new_git_dir def execute ( cmdline , return_errcode = False , show_output = True ) : if isinstance ( cmdline , list ) : print ( \"\" % subprocess . list2cmdline ( cmdline ) ) else : print ( \"\" % cmdline ) p = subprocess . Popen ( cmdline , shell = False , stdout = subprocess . PIPE ) s = '' for data in p . stdout . readlines ( ) : s += data if show_output : sys . stdout . write ( data ) rc = p . wait ( ) if return_errcode : return s , rc if rc != : die ( \"\" ) return s def run_python ( cmdline , * args , ** kwargs ) : return execute ( [ sys . executable ] + cmdline , * args , ** kwargs ) def clean_pyc ( ) : for root , dirs , files in os . walk ( os . getcwd ( ) ) : for filename in files : if filename . endswith ( '' ) : os . unlink ( os . path . join ( root , filename ) ) ", "answer": "def parse_options ( args ) :"}, {"prompt": " \"\"\"\"\"\" from string import ascii_letters from string import digits from exabgp . configuration . core . error import Error class Section ( Error ) : name = '' known = dict ( ) default = dict ( ) action = { } assign = { } def __init__ ( self , tokerniser , scope , error , logger ) : Error . __init__ ( self ) self . tokeniser = tokerniser self . scope = scope self . error = error self . logger = logger self . _names = [ ] ", "answer": "def clear ( self ) :"}, {"prompt": " import compileall import os import pep8 import yaml FLINTROCK_ROOT_DIR = ( os . path . dirname ( os . path . dirname ( os . path . realpath ( __file__ ) ) ) ) TEST_TARGETS = [ '' , '' , '' ] TEST_PATHS = [ os . path . join ( FLINTROCK_ROOT_DIR , path ) for path in TEST_TARGETS ] def test_code_compiles ( ) : for path in TEST_PATHS : if os . path . isdir ( path ) : result = compileall . compile_dir ( path ) else : result = compileall . compile_file ( path ) assert result == def test_pep8_compliance ( ) : style = pep8 . StyleGuide ( config_file = os . path . join ( FLINTROCK_ROOT_DIR , '' ) ) result = style . check_files ( TEST_PATHS ) assert result . total_errors == def test_config_template_is_valid ( ) : config_template = os . path . join ( FLINTROCK_ROOT_DIR , '' , '' ) ", "answer": "with open ( config_template ) as f :"}, {"prompt": " \"\"\"\"\"\" from time import time from mbed_host_tests import BaseHostTest class WaitusTest ( BaseHostTest ) : \"\"\"\"\"\" __result = None DEVIATION = ticks = [ ] def _callback_exit ( self , key , value , timeout ) : self . notify_complete ( ) def _callback_tick ( self , key , value , timestamp ) : \"\"\"\"\"\" self . log ( \"\" + str ( timestamp ) ) self . ticks . append ( ( key , value , timestamp ) ) def setup ( self ) : self . register_callback ( '' , self . _callback_exit ) ", "answer": "self . register_callback ( '' , self . _callback_tick )"}, {"prompt": " import mock from rally import exceptions from rally . plugins . common import types from tests . unit import test class PathOrUrlTestCase ( test . TestCase ) : @ mock . patch ( \"\" ) @ mock . patch ( \"\" ) def test_transform_file ( self , mock_requests_head , mock_isfile ) : mock_isfile . return_value = True path = types . PathOrUrl . transform ( None , \"\" ) ", "answer": "self . assertEqual ( \"\" , path )"}, {"prompt": " \"\"\"\"\"\" ", "answer": "from . _wrapper import proxyEndpoint"}, {"prompt": " import os import gzip import tempfile import unittest from conary . lib import util from conary . repository import filecontainer from conary . repository . filecontainer import FileContainer from conary . repository . filecontents import FromFile , FromString def fileCount ( ) : l = os . listdir ( \"\" % os . getpid ( ) ) return len ( l ) - def checkFiles ( c , names , data , tags ) : names = names [ : ] i = rc = c . getNextFile ( ) while rc : name , tag , f = rc assert ( name == names [ ] ) del names [ ] s = gzip . GzipFile ( None , \"\" , fileobj = f ) . read ( ) if s != data [ i ] : raise AssertionError , \"\" % names [ i ] if tag != tags [ i ] : raise AssertionError , \"\" % names [ i ] i += rc = c . getNextFile ( ) if names : raise AssertionError , \"\" % \"\" . join ( names ) class FilecontainerTest ( unittest . TestCase ) : def setUp ( self ) : fd , self . fn = tempfile . mkstemp ( ) def test ( self ) : count = fileCount ( ) f = util . ExtendedFile ( \"\" , \"\" , buffering = False ) self . assertRaises ( filecontainer . BadContainer , FileContainer , f ) f . close ( ) if ( count != fileCount ( ) ) : raise AssertionError , \"\" % count f = util . ExtendedFile ( self . fn , \"\" , buffering = False ) c = FileContainer ( f ) c . close ( ) data = [ ] tags = [ ] names = [ ] c = FileContainer ( f ) self . assertRaises ( AssertionError , c . addFile , \"\" , FromString ( \"\" ) , \"\" ) c . close ( ) os . unlink ( self . fn ) f = util . ExtendedFile ( self . fn , \"\" , buffering = False ) c = FileContainer ( f ) data . append ( \"\" ) tags . append ( \"\" ) names . append ( \"\" ) c . addFile ( names [ ] , FromString ( data [ ] ) , tags [ ] ) data . append ( \"\" ) tags . append ( \"\" ) ", "answer": "names . append ( \"\" )"}, {"prompt": " \"\"\"\"\"\" import itertools import numpy as np import pickle , gzip import re import scipy . stats as ss import sys sys . path . append ( '' ) import bbob_pproc as bb import bbob_pproc . algportfolio import bbob_pproc . bestalg import bbob_pproc . readalign as ra class PortfolioDataSets : \"\"\"\"\"\" def __init__ ( self , algorithms = { } , strategies = { } , pickleFile = None ) : \"\"\"\"\"\" if pickleFile is None : self . algds = algorithms self . stratds = strategies self . _bestalg = None self . _unifpf = None else : if pickleFile . find ( '' ) < : pickleFile += '' with gzip . open ( pickleFile ) as f : entry = pickle . load ( f ) self . algds = entry . algds self . stratds = entry . stratds self . _bestalg = entry . _bestalg self . _unifpf = entry . _unifpf def add_algorithm ( self , name , ds ) : \"\"\"\"\"\" self . algds [ name ] = ds self . _bestalg = None self . _unfipf = None def add_strategy ( self , name , ds ) : \"\"\"\"\"\" self . stratds [ name ] = ds def bestalg ( self , dimfun ) : \"\"\"\"\"\" if self . _bestalg is None : self . _bestalg = bb . bestalg . generate ( self . algds ) return self . _bestalg [ dimfun ] if dimfun is not None else self . _bestalg def oracle ( self , dimfun ) : \"\"\"\"\"\" ( dim , funcId ) = dimfun bestfinalfunval = max ( np . median ( self . bestalg ( dimfun ) . bestfinalfunvals ) , ) algs = list ( self . algds_dimfunc ( dimfun ) ) maxevals = np . max ( [ ds . maxevals for ( name , ds ) in algs ] ) evals = np . array ( [ ds . detEvals ( [ bestfinalfunval ] ) for ( name , ds ) in algs ] ) nanmask = np . isnan ( evals ) medevals = [ maxevals ] * len ( algs ) for i in range ( len ( algs ) ) : algnanmask = ~ np . isnan ( evals ) [ i ] if np . any ( algnanmask ) : medevals [ i ] = np . median ( evals [ i , algnanmask ] ) else : medevals [ i ] = maxevals nametarget = [ ( algs [ i ] [ ] , medevals [ i ] ) for i in range ( len ( algs ) ) ] ( name , target ) = min ( nametarget , key = lambda k : k [ ] ) return self . algds [ name ] . dictByDimFunc ( ) [ dim ] [ funcId ] [ ] def unifpf ( self ) : \"\"\"\"\"\" if self . _unifpf is None : self . _unifpf = bb . algportfolio . build ( self . algds ) return self . _unifpf def pickle ( self , pickleFile ) : \"\"\"\"\"\" if pickleFile . find ( '' ) < : pickleFile += '' with gzip . open ( pickleFile , '' ) as f : pickle . dump ( self , f ) def algds_dimfunc ( self , dimfun ) : \"\"\"\"\"\" ( dim , funcId ) = dimfun for ( algname , dset ) in self . algds . iteritems ( ) : yield ( algname , dset . dictByDimFunc ( ) [ dim ] [ funcId ] [ ] ) def stratds_dimfunc ( self , dimfun ) : \"\"\"\"\"\" ( dim , funcId ) = dimfun for ( stratname , dset ) in self . stratds . iteritems ( ) : yield ( stratname , dset . dictByDimFunc ( ) [ dim ] [ funcId ] [ ] ) def maxevals ( self , dimfun ) : \"\"\"\"\"\" evals = [ np . median ( ds . maxevals ) for ( name , ds ) in self . algds_dimfunc ( dimfun ) ] return max ( evals ) / dimfun [ ] def ranking ( self , dimfun , groupby , ftarget = ** - ) : \"\"\"\"\"\" nameds = list ( itertools . chain ( self . algds_dimfunc ( dimfun ) , self . stratds_dimfunc ( dimfun ) ) ) count = len ( nameds ) fvset = [ ] for ( name , ds ) in nameds : budgets = ds . funvals [ : , ] f1vals = np . maximum ( groupby ( ds . funvals [ : , : ] , axis = ) , ftarget ) fv = np . transpose ( np . vstack ( [ budgets , f1vals ] ) ) fvset . append ( fv ) fva = ra . alignArrayData ( ra . VArrayMultiReader ( fvset ) ) budgets = fva [ : , ] values = fva [ : , : ] . copy ( ) firstconv = np . ones ( count ) * ( np . size ( budgets ) + ) for i in range ( count ) : try : firstconv [ i ] = np . nonzero ( values [ : , i ] == ftarget ) [ ] [ ] except IndexError : continue firstconvranks = ss . mstats . rankdata ( firstconv ) for i in range ( count ) : r = firstconvranks [ i ] values [ firstconv [ i ] : , i ] = ftarget - ( - r / count ) * ftarget ranks = ss . mstats . rankdata ( values , axis = ) return np . transpose ( np . vstack ( [ budgets , ranks . T ] ) ) ", "answer": "def resolve_fid ( fid ) :"}, {"prompt": " { '' : { '' : '' , '' : '' , } , '' : { '' : '' , '' : '' , '' : [ '' , '' , '' , '' , '' , ] , '' : '' , '' : '' , '' : , } , '' : { '' : '' , '' : '' , '' : [ '' , '' , '' , '' , '' , ] , '' : '' , '' : '' , '' : , } , '' : { '' : '' , '' : , } , '' : { '' : { '' : [ , , ] , } , '' : , '' : - , } , '' : { '' : '' , '' : { '' : '' } , '' : { '' : '' , '' : '' , } , } , '' : { '' : '' , '' : [ ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ] , ", "answer": "} ,"}, {"prompt": " from dateutil . relativedelta import relativedelta from django . contrib . auth . models import User from django . core . management . base import BaseCommand from django . db . models import Count from django . utils . timezone import now class Command ( BaseCommand ) : \"\"\"\"\"\" help = \"\" output_transaction = True def handle ( self , * args , ** kwargs ) : \"\"\"\"\"\" month = now ( ) - relativedelta ( months = ) users = list ( User . objects . annotate ( num_articles = Count ( '' ) ) . filter ( num_articles = , last_login__lte = month ) ) for user in users : user . delete ( ) self . stdout . write ( '' % user ) ", "answer": "self . stdout . write ( \"\" % len ( users ) ) "}, {"prompt": " \"\"\"\"\"\" __title__ = '' __version__ = '' __build__ = __author__ = '' __license__ = '' __copyright__ = '' try : ", "answer": "from . packages . urllib3 . contrib import pyopenssl"}, {"prompt": " from distutils . core import setup setup ( name = '' , ", "answer": "url = '' ,"}, {"prompt": " \"\"\"\"\"\" from collections import defaultdict from operator import itemgetter from base import TextManager from utils import load_file , save_to_file from sulci . log import sulci_logger from corpus import Corpus class Lexicon ( TextManager ) : \"\"\"\"\"\" _loaded = { } def __init__ ( self , path = \"\" ) : self . CORPUS_EXT = \"\" self . VALID_EXT = \"\" self . PENDING_EXT = \"\" self . PATH = path self . _raw_content = \"\" self . _prefixes = None self . _suffixes = None self . factors = set ( ) def __iter__ ( self ) : return self . loaded . __iter__ ( ) def __getitem__ ( self , item ) : return self . loaded . __getitem__ ( item ) def __len__ ( self ) : return len ( self . loaded ) def items ( self ) : return self . loaded . items ( ) def __contains__ ( self , key ) : if isinstance ( key , object ) and key . __class__ . __name__ == \"\" : key = key . original return key in self . loaded @ property def loaded ( self ) : \"\"\"\"\"\" if not self . PATH in self . _loaded : sulci_logger . debug ( \"\" , \"\" , True ) lx = load_file ( \"\" % self . PATH ) self . _loaded [ self . PATH ] = { } for line in lx . split ( \"\" ) : if line : lexicon_entity = LexiconEntity ( line ) self . add_factors ( lexicon_entity . word ) self . _loaded [ self . PATH ] [ lexicon_entity . word ] = lexicon_entity return self . _loaded [ self . PATH ] def add_factors ( self , token ) : \"\"\"\"\"\" prefix = token while prefix : suffix = prefix while suffix : if not suffix == token : self . factors . add ( suffix ) suffix = suffix [ : ] prefix = prefix [ : - ] def make ( self , force = False ) : \"\"\"\"\"\" final = { } lemme_to_original = { } C = Corpus ( self . CORPUS_EXT ) for tk in C . tokens : if tk . verified_tag [ : ] == \"\" : continue if not tk . original in final : final [ tk . original ] = defaultdict ( int ) final [ tk . original ] [ tk . verified_tag ] += if not tk . original in lemme_to_original : lemme_to_original [ tk . original ] = { } if not tk . verified_tag in lemme_to_original [ tk . original ] : lemme_to_original [ tk . original ] [ tk . verified_tag ] = defaultdict ( int ) lemme_to_original [ tk . original ] [ tk . verified_tag ] [ tk . verified_lemme ] += def get_one_line ( key ) : \"\"\"\"\"\" return u\"\" % ( key , get_tags ( key ) ) def get_tags ( key ) : \"\"\"\"\"\" tags = sorted ( [ ( k , v ) for k , v in final [ key ] . iteritems ( ) ] , key = itemgetter ( ) , reverse = True ) final_data = [ ] for tag , score in tags : computed_lemmes = get_lemmes ( key , tag ) lemme , score = computed_lemmes [ ] final_data . append ( u\"\" % ( tag , lemme ) ) return u\"\" . join ( final_data ) def get_lemmes ( key , tag ) : \"\"\"\"\"\" return sorted ( ( ( k , v ) for k , v in lemme_to_original [ key ] [ tag ] . iteritems ( ) ) , key = itemgetter ( ) , reverse = True ) d = [ ] for k , v in sorted ( final . iteritems ( ) ) : d . append ( get_one_line ( k ) ) final_d = u\"\" . join ( d ) ext = force and self . VALID_EXT or self . PENDING_EXT save_to_file ( \"\" % ( self . PATH , ext ) , unicode ( final_d ) ) def create_afixes ( self ) : \"\"\"\"\"\" prefixes = defaultdict ( int ) suffixes = defaultdict ( int ) max_prefix_length = max_suffix_length = for tokenstring , _ in self . items ( ) : tlen = len ( tokenstring ) for i in xrange ( , min ( max_prefix_length + , tlen ) ) : prefix = tokenstring [ : i ] prefixes [ prefix ] += len ( prefix ) for i in xrange ( , min ( max_suffix_length + , tlen ) ) : suffix = tokenstring [ tlen - i : tlen ] suffixes [ suffix ] += len ( suffix ) self . _prefixes = set ( key for key , value in sorted ( ( ( k , v ) for k , v in prefixes . items ( ) if v > len ( k ) * ) , key = itemgetter ( ) , reverse = True ) ) self . _suffixes = set ( key for key , value in sorted ( ( ( k , v ) for k , v in suffixes . items ( ) if v > len ( k ) * ) , key = itemgetter ( ) , reverse = True ) ) @ property def prefixes ( self ) : if self . _prefixes is None : self . create_afixes ( ) return self . _prefixes @ property def suffixes ( self ) : if self . _suffixes is None : self . create_afixes ( ) return self . _suffixes def get_entry ( self , entry ) : if entry in self : sulci_logger . info ( unicode ( self [ entry ] ) , \"\" ) else : sulci_logger . info ( u'' % entry , \"\" ) def check ( self ) : \"\"\"\"\"\" for key , entity in self . items ( ) : if len ( entity . tags ) > : sulci_logger . info ( u\"\" % ( len ( entity . tags ) , key ) , \"\" ) sulci_logger . info ( entity . tags , \"\" ) class LexiconEntity ( object ) : \"\"\"\"\"\" def __init__ ( self , raw_data , ** kwargs ) : self . default_tag = None self . default_lemme = None self . word , tags = raw_data . split ( \"\" ) ", "answer": "self . tags = dict ( )"}, {"prompt": " from __future__ import ( absolute_import , division , generators , nested_scopes , print_function , unicode_literals , with_statement ) from hashlib import sha1 class PayloadFieldAlreadyDefinedError ( Exception ) : pass class PayloadFrozenError ( Exception ) : pass class Payload ( object ) : \"\"\"\"\"\" def __init__ ( self ) : self . _fields = { } self . _frozen = False self . _fingerprint_memo_map = { } @ property def fields ( self ) : return self . _fields . items ( ) def freeze ( self ) : \"\"\"\"\"\" self . _frozen = True def get_field ( self , key , default = None ) : \"\"\"\"\"\" return self . _fields . get ( key , default ) def get_field_value ( self , key , default = None ) : \"\"\"\"\"\" if key in self . _fields : payload_field = self . _fields [ key ] if payload_field : return payload_field . value ", "answer": "return default"}, {"prompt": " from __future__ import absolute_import , division , print_function , with_statement import os import time import socket import select import errno import logging from collections import defaultdict from shadowsocks import shell __all__ = [ '' , '' , '' , '' , '' , '' , '' , '' ] POLL_NULL = POLL_IN = POLL_OUT = POLL_ERR = POLL_HUP = POLL_NVAL = EVENT_NAMES = { POLL_NULL : '' , POLL_IN : '' , POLL_OUT : '' , POLL_ERR : '' , POLL_HUP : '' , POLL_NVAL : '' , } TIMEOUT_PRECISION = class KqueueLoop ( object ) : MAX_EVENTS = def __init__ ( self ) : self . _kqueue = select . kqueue ( ) self . _fds = { } def _control ( self , fd , mode , flags ) : events = [ ] if mode & POLL_IN : events . append ( select . kevent ( fd , select . KQ_FILTER_READ , flags ) ) if mode & POLL_OUT : events . append ( select . kevent ( fd , select . KQ_FILTER_WRITE , flags ) ) for e in events : self . _kqueue . control ( [ e ] , ) def poll ( self , timeout ) : if timeout < : timeout = None events = self . _kqueue . control ( None , KqueueLoop . MAX_EVENTS , timeout ) results = defaultdict ( lambda : POLL_NULL ) for e in events : fd = e . ident if e . filter == select . KQ_FILTER_READ : results [ fd ] |= POLL_IN elif e . filter == select . KQ_FILTER_WRITE : results [ fd ] |= POLL_OUT return results . items ( ) def register ( self , fd , mode ) : self . _fds [ fd ] = mode self . _control ( fd , mode , select . KQ_EV_ADD ) def unregister ( self , fd ) : self . _control ( fd , self . _fds [ fd ] , select . KQ_EV_DELETE ) del self . _fds [ fd ] def modify ( self , fd , mode ) : self . unregister ( fd ) self . register ( fd , mode ) def close ( self ) : self . _kqueue . close ( ) class SelectLoop ( object ) : def __init__ ( self ) : self . _r_list = set ( ) self . _w_list = set ( ) self . _x_list = set ( ) def poll ( self , timeout ) : r , w , x = select . select ( self . _r_list , self . _w_list , self . _x_list , timeout ) results = defaultdict ( lambda : POLL_NULL ) for p in [ ( r , POLL_IN ) , ( w , POLL_OUT ) , ( x , POLL_ERR ) ] : for fd in p [ ] : results [ fd ] |= p [ ] return results . items ( ) def register ( self , fd , mode ) : if mode & POLL_IN : self . _r_list . add ( fd ) if mode & POLL_OUT : self . _w_list . add ( fd ) if mode & POLL_ERR : self . _x_list . add ( fd ) def unregister ( self , fd ) : if fd in self . _r_list : self . _r_list . remove ( fd ) if fd in self . _w_list : self . _w_list . remove ( fd ) if fd in self . _x_list : ", "answer": "self . _x_list . remove ( fd )"}, {"prompt": " from __future__ import unicode_literals import datetime import os import subprocess def get_version ( version = None ) : \"\" if version is None : from django import VERSION as version else : assert len ( version ) == assert version [ ] in ( '' , '' , '' , '' ) parts = if version [ ] == else main = '' . join ( str ( x ) for x in version [ : parts ] ) sub = '' if version [ ] == '' and version [ ] == : git_changeset = get_git_changeset ( ) if git_changeset : sub = '' % git_changeset elif version [ ] != '' : mapping = { '' : '' , '' : '' , '' : '' } sub = mapping [ version [ ] ] + str ( version [ ] ) return str ( main + sub ) def get_git_changeset ( ) : \"\"\"\"\"\" repo_dir = os . path . dirname ( os . path . dirname ( os . path . abspath ( __file__ ) ) ) git_log = subprocess . Popen ( '' , stdout = subprocess . PIPE , stderr = subprocess . PIPE , shell = True , cwd = repo_dir , universal_newlines = True ) timestamp = git_log . communicate ( ) [ ] try : ", "answer": "timestamp = datetime . datetime . utcfromtimestamp ( int ( timestamp ) )"}, {"prompt": " import argparse import glob import os import subprocess BASE = '' . split ( '' ) API_BASE = '' . split ( '' ) STUB = \"\"\"\"\"\" def get_last_migration ( base ) : path = os . path . join ( * tuple ( base + [ '' ] ) ) migrations = sorted ( [ os . path . split ( fn ) [ - ] for fn in glob . glob ( path ) ] ) ", "answer": "return int ( migrations [ - ] . split ( '' ) [ ] )"}, {"prompt": " import vim from os import path import json import subprocess import time import re import socket server_addr = vim . eval ( '' ) server_command = vim . eval ( '' ) cli = vim . eval ( '' ) composer = vim . eval ( '' ) timeout = float ( vim . eval ( '' ) ) padawanPath = path . join ( path . dirname ( __file__ ) , '' ) BUFFER_SIZE = class Server : def __init__ ( self ) : fullAddr = server_addr . split ( \"\" ) self . addr = ( fullAddr [ ] , int ( fullAddr [ ] ) ) def start ( self ) : command = '' . format ( server_command , padawanPath ) subprocess . Popen ( command , shell = True , stdout = subprocess . PIPE , stderr = subprocess . STDOUT ) self . socket = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) def stop ( self ) : try : self . sendRequest ( '' , { } ) return True except Exception : return False def restart ( self ) : if self . stop ( ) : self . start ( ) def sendRequest ( self , command , params ) : s = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) s . connect ( self . addr ) s . setsockopt ( socket . IPPROTO_TCP , socket . TCP_NODELAY , ) requestData = json . dumps ( { '' : command , '' : params } ) s . send ( requestData ) response = \"\" while : chunk = s . recv ( BUFFER_SIZE ) if not chunk : break response += chunk result = json . loads ( response ) if \"\" in result : raise Exception ( result [ \"\" ] ) return result class Editor : def prepare ( self , message ) : return message . replace ( \"\" , \"\" ) def log ( self , message ) : vim . command ( \"\" % self . prepare ( message ) ) def notify ( self , message ) : vim . command ( \"\" % self . prepare ( message ) ) def progress ( self , progress ) : bars = int ( progress / ) barsStr = '' for i in range ( ) : if i < bars : barsStr += '' else : barsStr += '' barsStr = '' + barsStr + '' vim . command ( \"\" + barsStr + '' + str ( progress ) + \"\" ) return def error ( self , error ) : self . notify ( error ) def callAfter ( self , timeout , callback ) : time . sleep ( timeout ) while callback ( ) : time . sleep ( timeout ) server = Server ( ) editor = Editor ( ) pathError = '''''' class PadawanClient : def GetCompletion ( self , filepath , line_num , column_num , contents ) : curPath = self . GetProjectRoot ( filepath ) params = { '' : filepath . replace ( curPath , \"\" ) , '' : line_num , '' : column_num , '' : curPath , '' : contents } result = self . DoRequest ( '' , params , contents ) if not result : return { \"\" : [ ] } return result def GetClassesList ( self , cwd ) : params = { '' : cwd } return self . DoRequest ( \"\" , params ) def SaveIndex ( self , filepath ) : return self . DoRequest ( '' , { '' : filepath } ) def DoRequest ( self , command , params , data = '' , tries = ) : try : return server . sendRequest ( command , params ) except socket . error as e : if tries > : editor . error ( \"\" ) else : self . StartServer ( ) return self . DoRequest ( command , params , tries + ) except Exception as e : editor . error ( \"\" . format ( e . message ) ) return False def AddPlugin ( self , plugin ) : composerCommand = composer + '' command = '' . format ( composerCommand , cli , plugin ) ", "answer": "stream = subprocess . Popen ("}, {"prompt": " import base64 import cPickle as pickle ", "answer": "from django . db import models"}, {"prompt": " import pandas as pd import numpy as np from sklearn . feature_extraction import DictVectorizer import alias def explode ( cues ) : if isinstance ( cues , basestring ) : cues = cues . split ( '' ) return { } . fromkeys ( cues , True ) def orthoCoding ( strs , grams = , sep = None ) : if not np . iterable ( grams ) : grams = [ grams ] result = [ ] for str in strs : cues = [ ] str = list ( str ) for n in grams : if n > : seq = [ '' ] + str + [ '' ] else : seq = str count = max ( , len ( seq ) - n + ) cues . extend ( '' . join ( seq [ i : i + n ] ) for i in xrange ( count ) ) if sep : result . append ( sep . join ( cues ) ) else : result . append ( tuple ( cues ) ) return result def danks ( data ) : feats = DictVectorizer ( dtype = int , sparse = False ) marginals = data . groupby ( '' , as_index = False ) . Frequency . sum ( ) marginals = marginals . rename ( columns = { '' : '' } ) data = pd . merge ( data , marginals , on = '' ) result = pd . DataFrame ( ) for outcome in data . Outcomes . unique ( ) : yes = data [ data . Outcomes == outcome ] M = feats . fit_transform ( [ explode ( c ) for c in yes . Cues ] ) P = np . diag ( yes . Total / sum ( yes . Total ) ) MTP = M . T . dot ( P ) O = yes . Frequency / yes . Total left = MTP . dot ( M ) right = MTP . dot ( O ) V = np . linalg . solve ( left , right ) result [ outcome ] = V result . index = feats . get_feature_names ( ) return result def ndl ( data ) : vec = DictVectorizer ( dtype = float , sparse = False ) D = vec . fit_transform ( [ explode ( c ) for c in data . Cues ] ) * data . Frequency [ : , np . newaxis ] n = len ( vec . get_feature_names ( ) ) C = np . zeros ( ( n , n ) ) for row in D : for nz in np . nonzero ( row ) : C [ nz ] += row Z = C . sum ( axis = ) C1 = C / Z [ : , np . newaxis ] out = DictVectorizer ( dtype = float , sparse = False ) X = out . fit_transform ( [ explode ( c ) for c in data . Outcomes ] ) * data . Frequency [ : , np . newaxis ] O = np . zeros ( ( len ( vec . get_feature_names ( ) ) , len ( out . get_feature_names ( ) ) ) ) for i in xrange ( len ( X ) ) : for nz in np . nonzero ( D [ i ] ) : O [ nz ] += X [ i ] O1 = O / Z [ : , np . newaxis ] W = np . linalg . pinv ( C1 ) . dot ( O1 ) return pd . DataFrame ( W , columns = out . get_feature_names ( ) , index = vec . get_feature_names ( ) ) def activation ( cues , W ) : A = np . zeros ( len ( W . columns ) ) if isinstance ( cues , basestring ) : cues = cues . split ( '' ) for cue in cues : ", "answer": "A += W . loc [ cue ]"}, {"prompt": " from allauth . socialaccount . providers . oauth2 . urls import default_urlpatterns ", "answer": "from . provider import AmazonProvider"}, {"prompt": " import socket from gevent import monkey from cachebrowser . network import ConnectionHandler , HttpServer , HttpConnectionHandler import unittest from mock import Mock , patch monkey . patch_all ( ) class ServerTest ( unittest . TestCase ) : def test_server ( self ) : pass def test_connection_handler ( self ) : sock = Mock ( spec = socket . socket ) sock . recv = Mock ( side_effect = [ '' , '' ] ) handler = ConnectionHandler ( ) handler . on_connect = Mock ( ) handler . on_data = Mock ( ) handler . on_close = Mock ( ) handler . on_error = Mock ( ) handler . loop ( sock , '' ) handler . on_connect . assert_called_once_with ( ) handler . on_data . assert_called_once_with ( '' ) handler . on_close . assert_called_once_with ( ) handler . on_error . assert_not_called ( ) sock . recv = Mock ( side_effect = socket . error ) handler = ConnectionHandler ( ) handler . on_error = Mock ( ) handler . loop ( sock , '' ) assert handler . on_error . called class HttpServerTest ( unittest . TestCase ) : \"\"\"\"\"\" PORT = @ classmethod def setUpClass ( cls ) : cls . handler = HttpConnectionHandler ( ) ", "answer": "cls . server = HttpServer ( cls . PORT , handler = cls . handler )"}, {"prompt": " from decimal import Decimal from . util import namedtuple , optional from . import CoinbaseAmount class CoinbasePaymentButton ( namedtuple ( '' , optional = '' '' '' '' ) ) : \"\"\"\"\"\" @ classmethod def from_coinbase_dict ( cls , x ) : kwargs = { '' : x . get ( '' ) , } for key in [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ] : kwargs [ key ] = x . get ( key ) if x . get ( '' ) : prices = [ ] for i in range ( , ) : ", "answer": "s = x . get ( '' + str ( i ) )"}, {"prompt": " import maya . OpenMaya as OpenMaya import maya . cmds as cmds import sys import maya . OpenMayaMPx as OpenMayaMPx import unittest class testCallbackStrings ( unittest . TestCase ) : \"\"\"\"\"\" def testFileNewCheckCallback ( self ) : pass def testFileNewCheckCallbackAllow ( self ) : pass def testFileNewCheckCallbackStop ( self ) : pass def testFileOpenFileqCheckCallback ( self ) : pass def testBeforeOpenFileCheckCallback ( retCode , fileObject , clientData ) : ", "answer": "pass"}, {"prompt": " \"\"\"\"\"\" from multiprocessing import freeze_support ", "answer": "from mbed_host_tests import init_host_test_cli_params"}, {"prompt": " \"\"\"\"\"\" from pyjamas . ui . SplitPanel import SplitPanel from pyjamas import Factory class HorizontalSplitPanel ( SplitPanel ) : def __init__ ( self , ** kwargs ) : SplitPanel . __init__ ( self , vertical = False , ** kwargs ) def setLeftWidget ( self , leftWidget ) : self . setWidget ( , leftWidget ) def getLeftWidget ( self ) : ", "answer": "return self . getWidget ( )"}, {"prompt": " import sys try : from setuptools import setup ", "answer": "have_setuptools = True"}, {"prompt": " import argparse import numpy as np import urllib , urllib2 import cStringIO import sys def main ( ) : parser = argparse . ArgumentParser ( description = '' ) parser . add_argument ( '' , action = \"\" ) parser . add_argument ( '' , action = \"\" ) parser . add_argument ( '' , action = \"\" ) parser . add_argument ( '' , action = \"\" ) parser . add_argument ( '' , action = \"\" , type = int , default = ) result = parser . parse_args ( ) url = '' % ( result . baseurl , result . token , result . channel , result . resolution ) print url fh = open ( result . filename ) try : f = urllib2 . urlopen ( url , fh . read ( ) ) except urllib2 . URLError , e : print \"\" % ( url , e ) sys . exit ( - ) ", "answer": "if __name__ == \"\" :"}, {"prompt": " import shade class SanityChecks ( object ) : @ staticmethod def keystone ( cloud ) : [ tenant for tenant in cloud . keystone_client . tenants . list ( ) ] @ staticmethod def glance ( cloud ) : [ image for image in cloud . glance_client . images . list ( ) ] @ staticmethod def cinder ( cloud ) : [ volume for volume in cloud . cinder_client . volumes . list ( ) ] @ staticmethod def swift ( cloud ) : [ container for container in cloud . swift_client . list ( ) ] def main ( ) : module = AnsibleModule ( argument_spec = openstack_full_argument_spec ( password = dict ( required = True , type = '' ) , project = dict ( required = True , type = '' ) , role = dict ( required = True , type = '' ) , ", "answer": "user = dict ( required = True , type = '' ) ,"}, {"prompt": " from __future__ import unicode_literals import io from nose . tools import istest , assert_equal from mammoth . docx import xmlparser as xml , office_xml @ istest def alternate_content_is_replaced_by_contents_of_fallback ( ) : xml_string = ( '' + '' + '' + '' + '' + '' + ", "answer": "'' +"}, {"prompt": " from messagebird . base import Base class Recipient ( Base ) : def __init__ ( self ) : self . recipient = None self . status = None ", "answer": "self . _statusDatetime = None"}, {"prompt": " __author__ = '' from django . utils . translation import ugettext as _ def find_project_root ( contents ) : MANIFEST = '' SRC_DIR = '' for base_dir in contents : print base_dir try : dir_end = base_dir . index ( MANIFEST ) print dir_end except ValueError : continue else : if dir_end + len ( MANIFEST ) != len ( base_dir ) : print '' continue base_dir = base_dir [ : dir_end ] print base_dir for source_dir in contents : if source_dir [ : dir_end ] != base_dir : continue if not source_dir . endswith ( '' ) and not source_dir . endswith ( '' ) : continue if source_dir [ dir_end : dir_end + len ( SRC_DIR ) ] != SRC_DIR : continue break else : ", "answer": "continue"}, {"prompt": " __author__ = '' from pybrain . utilities import iterCombinations , Named from pybrain . structure . moduleslice import ModuleSlice from functools import reduce class ModuleMesh ( Named ) : \"\"\"\"\"\" def __init__ ( self , constructor , dimensions , name = None , baserename = False ) : \"\"\"\"\"\" ", "answer": "self . dims = dimensions"}, {"prompt": " import autopath class AppTestRange : def test_range_toofew ( self ) : raises ( TypeError , range ) def test_range_toomany ( self ) : raises ( TypeError , range , , , , ) def test_range_one ( self ) : assert range ( ) == [ ] def test_range_posstartisstop ( self ) : assert range ( , ) == [ ] def test_range_negstartisstop ( self ) : assert range ( - , - ) == [ ] def test_range_zero ( self ) : assert range ( ) == [ ] def test_range_twoargs ( self ) : assert range ( , ) == [ ] def test_range_decreasingtwoargs ( self ) : assert range ( , ) == [ ] def test_range_negatives ( self ) : assert range ( - ) == [ ] def test_range_decreasing_negativestep ( self ) : assert range ( , - , - ) == [ , , , , , , - ] def test_range_posfencepost1 ( self ) : assert range ( , , ) == [ , , ] def test_range_posfencepost2 ( self ) : assert range ( , , ) == [ , , , ] def test_range_posfencepost3 ( self ) : assert range ( , , ) == [ , , , ] def test_range_negfencepost1 ( self ) : assert range ( - , - , - ) == [ - , - , - ] def test_range_negfencepost2 ( self ) : assert range ( - , - , - ) == [ - , - , - , - ] def test_range_negfencepost3 ( self ) : assert range ( - , - , - ) == [ - , - , - , - ] def test_range_decreasing_negativelargestep ( self ) : assert range ( , - , - ) == [ , , - ] def test_range_increasing_positivelargestep ( self ) : assert range ( - , , ) == [ - , - , ] def test_range_zerostep ( self ) : raises ( ValueError , range , , , ) def test_range_float ( self ) : \"\" assert range ( , , ) == [ , ] def test_range_wrong_type ( self ) : raises ( TypeError , range , \"\" ) def test_range_object_with___int__ ( self ) : class A ( object ) : def __int__ ( self ) : return assert range ( A ( ) ) == [ , , , , ] assert range ( , A ( ) ) == [ , , , , ] assert range ( , , A ( ) ) == [ , ] ", "answer": "def test_range_long ( self ) :"}, {"prompt": " from setuptools import setup , find_packages PACKAGE_NAME = \"\" VERSION = \"\" requirements = open ( '' , '' ) ", "answer": "setup ("}, {"prompt": " \"\"\"\"\"\" from xml . dom import minidom as dom import os . path , re from cStringIO import StringIO from twisted . lore import default from twisted . web import domhelpers from twisted . python import text from twisted . lore . latex import BaseLatexSpitter , LatexSpitter , processFile from twisted . lore . latex import getLatexText , HeadingLatexSpitter from twisted . lore . tree import getHeaders from twisted . lore . tree import removeH1 , fixAPI , fontifyPython from twisted . lore . tree import addPyListings , addHTMLListings , setTitle hacked_entities = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' } entities = { '' : '' , '' : '>' , '' : '' , '' : '' , '' : '' } class MagicpointOutput ( BaseLatexSpitter ) : bulletDepth = def writeNodeData ( self , node ) : buf = StringIO ( ) getLatexText ( node , buf . write , entities = hacked_entities ) data = buf . getvalue ( ) . rstrip ( ) . replace ( '' , '' ) self . writer ( re . sub ( '' , '' , data ) ) def visitNode_title ( self , node ) : self . title = domhelpers . getNodeText ( node ) def visitNode_body ( self , node ) : self . fontStack = [ ( '' , None ) ] self . writer ( self . start_h2 ) self . writer ( self . title ) self . writer ( self . end_h2 ) self . writer ( '' ) for authorNode in domhelpers . findElementsWithAttribute ( node , '' , '' ) : getLatexText ( authorNode , self . writer , entities = entities ) self . writer ( '' ) self . writer ( self . start_h2 ) self . writer ( self . title ) self . writer ( self . end_h2 ) for element in getHeaders ( node ) : level = int ( element . tagName [ ] ) - self . writer ( level * '' ) self . writer ( domhelpers . getNodeText ( element ) ) self . writer ( '' ) self . visitNodeDefault ( node ) def visitNode_div_author ( self , node ) : pass ", "answer": "def visitNode_div_pause ( self , node ) :"}, {"prompt": " try : from urllib . parse import urljoin except ImportError : from urlparse import urljoin try : FileNotFoundError except NameError : FileNotFoundError = IOError from io import BytesIO import requests import warnings from django . core . exceptions import ImproperlyConfigured from django . conf import settings from django . utils . encoding import filepath_to_uri from localdevstorage . base import BaseStorage class HttpStorage ( BaseStorage ) : ", "answer": "def __init__ ( self , location = None , base_url = None , fallback_url = None , fallback_domain = None ) :"}, {"prompt": " \"\"\"\"\"\" import urlparse from boto . sqs . message import Message class Queue : def __init__ ( self , connection = None , url = None , message_class = Message ) : self . connection = connection self . url = url self . message_class = message_class self . visibility_timeout = None def __repr__ ( self ) : return '' % self . url def _id ( self ) : if self . url : val = urlparse . urlparse ( self . url ) [ ] else : val = self . url return val id = property ( _id ) def _name ( self ) : if self . url : val = urlparse . urlparse ( self . url ) [ ] . split ( '' ) [ ] else : val = self . url return val name = property ( _name ) def startElement ( self , name , attrs , connection ) : return None def endElement ( self , name , value , connection ) : if name == '' : self . url = value elif name == '' : self . visibility_timeout = int ( value ) else : setattr ( self , name , value ) def set_message_class ( self , message_class ) : \"\"\"\"\"\" self . message_class = message_class def get_attributes ( self , attributes = '' ) : \"\"\"\"\"\" return self . connection . get_queue_attributes ( self , attributes ) def set_attribute ( self , attribute , value ) : \"\"\"\"\"\" return self . connection . set_queue_attribute ( self , attribute , value ) def get_timeout ( self ) : \"\"\"\"\"\" a = self . get_attributes ( '' ) return int ( a [ '' ] ) def set_timeout ( self , visibility_timeout ) : \"\"\"\"\"\" retval = self . set_attribute ( '' , visibility_timeout ) if retval : self . visibility_timeout = visibility_timeout return retval def add_permission ( self , label , aws_account_id , action_name ) : \"\"\"\"\"\" return self . connection . add_permission ( self , label , aws_account_id , action_name ) def remove_permission ( self , label ) : \"\"\"\"\"\" return self . connection . remove_permission ( self , label ) def read ( self , visibility_timeout = None ) : \"\"\"\"\"\" rs = self . get_messages ( , visibility_timeout ) if len ( rs ) == : return rs [ ] else : return None def write ( self , message , delay_seconds = None ) : \"\"\"\"\"\" new_msg = self . connection . send_message ( self , message . get_body_encoded ( ) , delay_seconds ) message . id = new_msg . id message . md5 = new_msg . md5 return message def new_message ( self , body = '' ) : \"\"\"\"\"\" m = self . message_class ( self , body ) m . queue = self return m def get_messages ( self , num_messages = , visibility_timeout = None , attributes = None ) : \"\"\"\"\"\" return self . connection . receive_message ( self , number_messages = num_messages , visibility_timeout = visibility_timeout , attributes = attributes ) def delete_message ( self , message ) : \"\"\"\"\"\" return self . connection . delete_message ( self , message ) def delete ( self ) : \"\"\"\"\"\" return self . connection . delete_queue ( self ) def clear ( self , page_size = , vtimeout = ) : \"\"\"\"\"\" n = l = self . get_messages ( page_size , vtimeout ) while l : for m in l : self . delete_message ( m ) ", "answer": "n += "}, {"prompt": " from . api import ChanjoAPI from . core import Store ", "answer": "from . models import ( Exon , ExonStatistic , Exon_Transcript , Gene , Sample ,"}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import import json from openxc . formats . base import VehicleMessageStreamer class JsonStreamer ( VehicleMessageStreamer ) : SERIALIZED_COMMAND_TERMINATOR = b\"\" def parse_next_message ( self ) : parsed_message = None remainder = self . message_buffer message = \"\" ", "answer": "if self . SERIALIZED_COMMAND_TERMINATOR in self . message_buffer :"}, {"prompt": " from django . conf . urls import url from . import views urlpatterns = ( ", "answer": "url ( r'' , views . message_log , name = \"\" ) ,"}, {"prompt": " import ee from adaboost import * from dnns import * from ee_classifiers import * from misc_algorithms import * from modis_utilities import * from simple_modis_algorithms import * import cmt . radar . active_contour '''''' EVI = XIAO = DIFFERENCE = CART = SVM = RANDOM_FORESTS = ", "answer": "DNNS = "}, {"prompt": " from msct_pca import PCA from msct_gmseg_utils import * import sct_utils as sct import pickle from math import sqrt from math import exp class Param : def __init__ ( self ) : self . debug = self . path_dictionary = None self . todo_model = None self . model_dir = '' self . reg = [ '' ] self . reg_metric = '' self . target_denoising = True self . first_reg = False self . use_levels = True self . weight_gamma = self . equation_id = self . weight_label_fusion = False self . mode_weight_similarity = False self . z_regularisation = False self . res_type = '' self . verbose = def __repr__ ( self ) : s = '' s += '' + str ( self . path_dictionary ) + '' s += '' + str ( self . todo_model ) + '' s += '' + str ( self . model_dir ) + '' s += '' + str ( self . reg ) + '' s += '' + str ( self . reg_metric ) + '' s += '' + str ( self . target_denoising ) + '' s += '' + str ( self . first_reg ) + '' s += '' + str ( self . use_levels ) + '' s += '' + str ( self . weight_gamma ) + '' s += '' + str ( self . equation_id ) + '' s += '' + str ( self . weight_label_fusion ) + '' s += '' + str ( self . mode_weight_similarity ) + '' s += '' + str ( self . z_regularisation ) + '' s += '' + str ( self . res_type ) + '' s += '' + str ( self . verbose ) + '' return s class ModelDictionary : \"\"\"\"\"\" def __init__ ( self , dic_param = None ) : \"\"\"\"\"\" if dic_param is None : self . param = Param ( ) else : self . param = dic_param self . level_label = { : '' , : '' , : '' , : '' , : '' , : '' , : '' , : '' , : '' , : '' , : '' , : '' , : '' , : '' } self . coregistration_transfos = None self . slices = None self . J = None self . N = None self . mean_seg = None self . mean_image = None self . coregistration_transfos = self . param . reg if self . param . todo_model == '' : self . compute_model ( ) elif self . param . todo_model == '' : self . load_model ( ) def compute_model ( self ) : sct . printv ( '' , self . param . verbose , '' ) sct . run ( '' + self . param . model_dir ) param_fic = open ( self . param . model_dir + '' , '' ) param_fic . write ( str ( self . param ) ) param_fic . close ( ) sct . printv ( '' , self . param . verbose , '' ) self . slices = self . load_data_dictionary ( ) self . J = len ( [ dic_slice . im for dic_slice in self . slices ] ) self . N = len ( self . slices [ ] . im . flatten ( ) ) self . invert_seg ( ) sct . printv ( '' , self . param . verbose , '' ) self . mean_seg = self . seg_coregistration ( transfo_to_apply = self . coregistration_transfos ) sct . printv ( '' , self . param . verbose , '' ) self . coregister_data ( transfo_to_apply = self . coregistration_transfos ) self . mean_image = self . compute_mean_dic_image ( np . asarray ( [ dic_slice . im_M for dic_slice in self . slices ] ) ) self . save_model ( ) def load_data_dictionary ( self ) : \"\"\"\"\"\" slices = [ ] j = for subject_dir in os . listdir ( self . param . path_dictionary ) : subject_path = self . param . path_dictionary + '' + subject_dir if os . path . isdir ( subject_path ) : for file_name in os . listdir ( subject_path ) : if '' in file_name : slice_level = name_list = file_name . split ( '' ) for word in name_list : if word . upper ( ) in self . level_label . values ( ) : slice_level = get_key_from_val ( self . level_label , word . upper ( ) ) slices . append ( Slice ( slice_id = j , im = Image ( subject_path + '' + file_name ) . data , level = slice_level , reg_to_m = [ ] ) ) seg_file = sct . extract_fname ( file_name ) [ ] [ : - ] + '' slices [ j ] . set ( gm_seg = Image ( subject_path + '' + seg_file ) . data ) j += return np . asarray ( slices ) def invert_seg ( self ) : \"\"\"\"\"\" for dic_slice in self . slices : im_dic = Image ( param = dic_slice . im ) sc = im_dic . copy ( ) nz_coord_sc = sc . getNonZeroCoordinates ( ) im_seg = Image ( param = dic_slice . gm_seg ) '''''' inverted_slice_decision = inverse_gmseg_to_wmseg ( im_seg , im_dic , save = False ) dic_slice . set ( wm_seg = inverted_slice_decision . data ) def seg_coregistration ( self , transfo_to_apply = None ) : \"\"\"\"\"\" current_mean_seg = compute_majority_vote_mean_seg ( np . asarray ( [ dic_slice . wm_seg for dic_slice in self . slices ] ) ) first = True ", "answer": "for transfo in transfo_to_apply :"}, {"prompt": " \"\"\"\"\"\" from weakref import WeakValueDictionary from Serving import DEFAULT_PORT from Rpyc . Stream import SocketStream , PipeStream from Rpyc . Channel import Channel from Rpyc . Connection import Connection from Rpyc . AsyncNetProxy import AsyncNetProxy __all__ = [ \"\" , \"\" , \"\" , \"\" , \"\" ] def SocketConnection ( host , port = DEFAULT_PORT ) : \"\"\"\"\"\" return Connection ( Channel ( SocketStream . from_new_socket ( host , port ) ) ) def PipeConnection ( incoming , outgoing ) : \"\"\"\"\"\" return Connection ( Channel ( PipeStream ( incoming , outgoing ) ) ) class LoginError ( Exception ) : pass def SecSocketConnection ( host , username , password , port = DEFAULT_PORT ) : \"\"\"\"\"\" try : stream = SocketStream . from_new_secure_socket ( host , port , username , password ) except : raise LoginError ( \"\" ) return Connection ( Channel ( stream ) ) _async_proxy_cache = WeakValueDictionary ( ) ", "answer": "def Async ( proxy ) :"}, {"prompt": " \"\"\"\"\"\" from cafe . drivers . unittest . decorators import data_driven_test , DataDrivenFixture from cloudcafe . blockstorage . volumes_api . common . models import statuses from cloudcafe . blockstorage . datasets import BlockstorageDatasets from cloudroast . blockstorage . volumes_api . fixtures import VolumesTestFixture complete_volume_types = BlockstorageDatasets . volume_types ( ) complete_volume_types . apply_test_tags ( '' ) default_volume_type = BlockstorageDatasets . default_volume_type ( ) default_volume_type . apply_test_tags ( '' ) complete_volume_types . merge_dataset_tags ( default_volume_type ) @ DataDrivenFixture class SnapshotActions ( VolumesTestFixture ) : ", "answer": "@ data_driven_test ( complete_volume_types )"}, {"prompt": " import sys from pypy . rpython . lltypesystem import lltype , rffi from pypy . rpython . tool import rffi_platform as platform from pypy . translator . tool . cbuild import ExternalCompilationInfo ", "answer": "from pypy . rlib . rsdl import RSDL"}, {"prompt": " from pymouse import PyMouse import random , time try : from pymouse import PyMouseEvent class event ( PyMouseEvent ) : def move ( self , x , y ) : print \"\" , x , y def click ( self , x , y , button , press ) : if press : print \"\" , x , y , \"\" , button else : print \"\" , x , y , \"\" , button e = event ( ) e . start ( ) except ImportError : print \"\" m = PyMouse ( ) try : size = m . screen_size ( ) print \"\" % ( str ( size ) ) pos = ( random . randint ( , size [ ] ) , random . randint ( , size [ ] ) ) except : pos = ( random . randint ( , ) , random . randint ( , ) ) print \"\" % ( str ( pos ) ) m . move ( pos [ ] , pos [ ] ) time . sleep ( ) ", "answer": "m . click ( pos [ ] , pos [ ] , )"}, {"prompt": " \"\"\"\"\"\" import pytest import re import six from pytest_bdd import ( scenario , ", "answer": "given ,"}, {"prompt": " from twisted . internet import reactor from twisted . internet . defer import succeed from nevow . appserver import NevowSite from nevow . rend import Page , Fragment from nevow . page import Element , renderer from nevow . loaders import stan from nevow . tags import directive , div , span class Static : ", "answer": "docFactory = stan ( \"\" * )"}, {"prompt": " from neutron . plugins . common import constants as p_const from neutron . plugins . ml2 import config from neutron . plugins . ml2 . drivers import type_gre from neutron . tests . unit . plugins . ml2 . drivers import base_type_tunnel from neutron . tests . unit . plugins . ml2 import test_rpc ", "answer": "from neutron . tests . unit import testlib_api"}, {"prompt": " import os import shlex import shutil import tempfile from oslo_concurrency import processutils from oslo_log import log from ironic_python_agent import errors from ironic_python_agent . extensions import base from ironic_python_agent . extensions import iscsi from ironic_python_agent import hardware from ironic_python_agent import utils LOG = log . getLogger ( __name__ ) BIND_MOUNTS = ( '' , '' ) def _get_partition ( device , uuid ) : \"\"\"\"\"\" LOG . debug ( \"\" , { '' : device , '' : uuid } ) try : try : utils . execute ( '' , '' , device , attempts = , delay_on_retry = True ) utils . execute ( '' , '' ) except processutils . ProcessExecutionError : LOG . warning ( \"\" \"\" % device ) report = utils . execute ( '' , '' , device ) [ ] for line in report . split ( '' ) : part = { } vals = shlex . split ( line ) for key , val in ( v . split ( '' , ) for v in vals ) : part [ key ] = val . strip ( ) if part . get ( '' ) != '' : continue if part . get ( '' ) == uuid : LOG . debug ( \"\" \"\" , { '' : uuid , '' : device } ) return '' + part . get ( '' ) else : error_msg = ( \"\" \"\" % { '' : uuid , '' : device } ) LOG . error ( error_msg ) raise errors . DeviceNotFound ( error_msg ) except processutils . ProcessExecutionError as e : error_msg = ( '' '' % { '' : uuid , '' : device , '' : e } ) LOG . error ( error_msg ) raise errors . CommandExecutionError ( error_msg ) def _install_grub2 ( device , root_uuid , efi_system_part_uuid = None ) : \"\"\"\"\"\" LOG . debug ( \"\" , device ) root_partition = _get_partition ( device , uuid = root_uuid ) efi_partition = None efi_partition_mount_point = None try : path = tempfile . mkdtemp ( ) if efi_system_part_uuid : efi_partition = _get_partition ( device , uuid = efi_system_part_uuid ) efi_partition_mount_point = os . path . join ( path , \"\" ) utils . execute ( '' , root_partition , path ) for fs in BIND_MOUNTS : utils . execute ( '' , '' , '' , fs , path + fs ) utils . execute ( '' , '' , '' , '' , path + '' ) if efi_partition : if not os . path . exists ( efi_partition_mount_point ) : os . makedirs ( efi_partition_mount_point ) utils . execute ( '' , efi_partition , efi_partition_mount_point ) binary_name = \"\" if os . path . exists ( os . path . join ( path , '' ) ) : binary_name = \"\" path_variable = os . environ . get ( '' , '' ) path_variable = '' % path_variable utils . execute ( '' '' % { '' : path , '' : binary_name , '' : device } , shell = True , env_variables = { '' : path_variable } ) ", "answer": "utils . execute ( ''"}, {"prompt": " from agate import Table from agate . data_types import * from agate . type_tester import TypeTester from agate . testcase import AgateTestCase class TestDenormalize ( AgateTestCase ) : def setUp ( self ) : self . rows = ( ( '' , '' , '' , '' ) , ( '' , '' , '' , '' ) , ( '' , '' , '' , '' ) , ( '' , '' , '' , '' ) ) self . text_type = Text ( ) self . column_names = [ '' , '' , '' , '' ] self . column_types = [ self . text_type , self . text_type , self . text_type , self . text_type ] def test_denormalize ( self ) : table = Table ( self . rows , self . column_names , self . column_types ) normalized_table = table . denormalize ( '' , '' , '' ) normal_rows = ( ( '' , '' , ) , ( '' , '' , ) , ) self . assertRows ( normalized_table , normal_rows ) self . assertColumnNames ( normalized_table , [ '' , '' , '' ] ) self . assertColumnTypes ( normalized_table , [ Text , Text , Number ] ) self . assertRowNames ( normalized_table , [ '' , '' ] ) def test_denormalize_no_key ( self ) : table = Table ( self . rows , self . column_names , self . column_types ) normalized_table = table . denormalize ( None , '' , '' ) normal_rows = ( ( '' , ) , ) self . assertRows ( normalized_table , normal_rows ) self . assertColumnNames ( normalized_table , [ '' , '' ] ) self . assertColumnTypes ( normalized_table , [ Text , Number ] ) def test_denormalize_multiple_keys ( self ) : table = Table ( self . rows , self . column_names , self . column_types ) normalized_table = table . denormalize ( [ '' , '' ] , '' , '' ) normal_rows = ( ( '' , '' , '' , ) , ( '' , '' , '' , None ) , ( '' , '' , None , ) , ) self . assertRows ( normalized_table , normal_rows ) self . assertColumnNames ( normalized_table , [ '' , '' , '' , '' ] ) ", "answer": "self . assertColumnTypes ( normalized_table , [ Text , Text , Text , Number ] )"}, {"prompt": " from website . files . models . base import File , Folder , FileNode __all__ = ( '' , '' , '' ) class GithubFileNode ( FileNode ) : provider = '' ", "answer": "class GithubFolder ( GithubFileNode , Folder ) :"}, {"prompt": " \"\"\"\"\"\" TYPE_ACCOUNTING = '' TYPE_AIRPORT = '' TYPE_AMUSEMENT_PARK = '' TYPE_AQUARIUM = '' TYPE_ART_GALLERY = '' TYPE_ATM = '' TYPE_BAKERY = '' TYPE_BANK = '' TYPE_BAR = '' TYPE_BEAUTY_SALON = '' TYPE_BICYCLE_STORE = '' TYPE_BOOK_STORE = '' TYPE_BOWLING_ALLEY = '' TYPE_BUS_STATION = '' TYPE_CAFE = '' TYPE_CAMPGROUND = '' TYPE_CAR_DEALER = '' ", "answer": "TYPE_CAR_RENTAL = ''"}, {"prompt": " \"\"\"\"\"\" import autopath import os ROOT = autopath . pypydir EXCLUDE = { } def test_no_tabs ( ) : def walk ( reldir ) : if reldir in EXCLUDE : return if reldir : path = os . path . join ( ROOT , * reldir . split ( '' ) ) else : ", "answer": "path = ROOT"}, {"prompt": " \"\"\"\"\"\" from datetime import timedelta , datetime from django . contrib . auth import get_user_model from django . core . exceptions import ValidationError from django . test import TestCase from django . test . utils import override_settings from django . utils . timezone import now from mock import patch from model_mommy import mommy from open_connect . accounts import forms from open_connect . accounts . models import Invite from open_connect . connectmessages . models import Thread from open_connect . connectmessages . tests import ConnectMessageTestCase from open_connect . connect_core . tests . test_utils_mixins import TEST_HTML User = get_user_model ( ) class UserFormTest ( ConnectMessageTestCase ) : \"\"\"\"\"\" @ patch . object ( forms . SanitizeHTMLMixin , '' ) def test_form_cleans_html ( self , mock ) : \"\"\"\"\"\" form = forms . UserForm ( { '' : TEST_HTML } , instance = self . user1 ) form . is_valid ( ) mock . assert_called_once_with ( TEST_HTML ) class UserAdminFormTest ( TestCase ) : \"\"\"\"\"\" def test_init ( self ) : \"\"\"\"\"\" class BanUserFormTest ( TestCase ) : \"\"\"\"\"\" def setUp ( self ) : \"\"\"\"\"\" super ( BanUserFormTest , self ) . setUp ( ) self . group1 = mommy . make ( '' ) self . normal_user = mommy . make ( '' ) self . normal_user . add_to_group ( self . group1 . pk ) self . banned_user = mommy . make ( '' ) self . banned_user . add_to_group ( self . group1 . pk ) thread = mommy . make ( '' , group = self . group1 ) self . message1 = mommy . make ( '' , sender = self . banned_user , thread = thread ) self . message1 . created_at = now ( ) - timedelta ( hours = ) self . message1 . save ( ) self . message2 = mommy . make ( '' , sender = self . normal_user , thread = thread ) self . thread = Thread . objects . get ( pk = thread . pk ) def test_save_first_message_sender_is_banned_user ( self ) : \"\"\"\"\"\" self . assertEqual ( self . thread . first_message , self . message1 ) self . assertEqual ( self . thread . latest_message , self . message2 ) self . assertFalse ( self . banned_user . is_banned ) form = forms . BanUserForm ( { '' : self . banned_user . pk , '' : True } ) self . assertTrue ( form . is_valid ( ) ) form . save ( ) thread = Thread . objects . get ( pk = self . thread . pk ) self . assertEqual ( thread . latest_message , self . message2 ) user = User . objects . get ( pk = self . banned_user . pk ) self . assertTrue ( user . is_banned ) def test_save_latest_message_sender_is_banned_user ( self ) : \"\"\"\"\"\" self . message1 . sender = self . normal_user self . message1 . save ( ) ", "answer": "self . message2 . sender = self . normal_user"}, {"prompt": " \"\"\"\"\"\" import factory from geokey . core . tests . helpers . image_helpers import get_image from geokey . users . tests . model_factories import UserFactory from geokey . projects . tests . model_factories import ProjectFactory from . . models import ( Category , TextField , NumericField , DateTimeField , DateField , TimeField , LookupField , LookupValue , Field , MultipleLookupField , MultipleLookupValue ) class CategoryFactory ( factory . django . DjangoModelFactory ) : class Meta : model = Category creator = factory . SubFactory ( UserFactory ) name = factory . Sequence ( lambda n : '' % n ) description = factory . LazyAttribute ( lambda o : '' % o . name ) project = factory . SubFactory ( ProjectFactory ) status = '' class FieldFactory ( factory . django . DjangoModelFactory ) : class Meta : model = Field name = factory . Sequence ( lambda n : '' % n ) key = factory . Sequence ( lambda n : '' % n ) description = factory . LazyAttribute ( lambda o : '' % o . name ) category = factory . SubFactory ( CategoryFactory ) status = '' required = False order = class TextFieldFactory ( factory . django . DjangoModelFactory ) : class Meta : model = TextField name = factory . Sequence ( lambda n : '' % n ) key = factory . Sequence ( lambda n : '' % n ) description = factory . LazyAttribute ( lambda o : '' % o . name ) category = factory . SubFactory ( CategoryFactory ) status = '' required = False class NumericFieldFactory ( factory . django . DjangoModelFactory ) : class Meta : model = NumericField name = factory . Sequence ( lambda n : '' % n ) key = factory . Sequence ( lambda n : '' % n ) description = factory . LazyAttribute ( lambda o : '' % o . name ) category = factory . SubFactory ( CategoryFactory ) status = '' required = False ", "answer": "class DateTimeFieldFactory ( factory . django . DjangoModelFactory ) :"}, {"prompt": " from rest_framework import exceptions from dynamic_rest . viewsets import DynamicModelViewSet from tests . models import Cat , Dog , Group , Horse , Location , Profile , User , Zebra from tests . serializers import ( CatSerializer , DogSerializer , GroupSerializer , HorseSerializer , LocationSerializer , ProfileSerializer , UserLocationSerializer , UserSerializer , ZebraSerializer ) class UserViewSet ( DynamicModelViewSet ) : features = ( DynamicModelViewSet . INCLUDE , DynamicModelViewSet . EXCLUDE , DynamicModelViewSet . FILTER , DynamicModelViewSet . SORT ) model = User serializer_class = UserSerializer queryset = User . objects . all ( ) def get_queryset ( self ) : location = self . request . query_params . get ( '' ) qs = self . queryset if location : qs = qs . filter ( location = location ) return qs def list ( self , request , * args , ** kwargs ) : query_params = self . request . query_params if query_params . get ( '' ) : query_params . add ( '' , query_params . get ( '' ) ) return super ( UserViewSet , self ) . list ( request , * args , ** kwargs ) ", "answer": "class GroupNoMergeDictViewSet ( DynamicModelViewSet ) :"}, {"prompt": " \"\"\"\"\"\" import codecs import serial try : unicode except ( NameError , AttributeError ) : unicode = str HEXDIGITS = '' def hex_encode ( data , errors = '' ) : \"\"\"\"\"\" return ( serial . to_bytes ( [ int ( h , ) for h in data . split ( ) ] ) , len ( data ) ) def hex_decode ( data , errors = '' ) : \"\"\"\"\"\" return ( unicode ( '' . join ( '' . format ( ord ( b ) ) for b in serial . iterbytes ( data ) ) ) , len ( data ) ) class Codec ( codecs . Codec ) : def encode ( self , data , errors = '' ) : \"\"\"\"\"\" return serial . to_bytes ( [ int ( h , ) for h in data . split ( ) ] ) def decode ( self , data , errors = '' ) : \"\"\"\"\"\" return unicode ( '' . join ( '' . format ( ord ( b ) ) for b in serial . iterbytes ( data ) ) ) class IncrementalEncoder ( codecs . IncrementalEncoder ) : \"\"\"\"\"\" def __init__ ( self , errors = '' ) : self . errors = errors self . state = def reset ( self ) : self . state = def getstate ( self ) : return self . state def setstate ( self , state ) : self . state = state def encode ( self , data , final = False ) : \"\"\"\"\"\" state = self . state encoded = [ ] for c in data . upper ( ) : if c in HEXDIGITS : z = HEXDIGITS . index ( c ) if state : encoded . append ( z + ( state & ) ) state = else : state = + ( z << ) elif c == '' : if state and self . errors == '' : raise UnicodeError ( '' ) state = else : if self . errors == '' : raise UnicodeError ( '' % c ) self . state = state return serial . to_bytes ( encoded ) class IncrementalDecoder ( codecs . IncrementalDecoder ) : \"\"\"\"\"\" def decode ( self , data , final = False ) : return unicode ( '' . join ( '' . format ( ord ( b ) ) for b in serial . iterbytes ( data ) ) ) class StreamWriter ( Codec , codecs . StreamWriter ) : \"\"\"\"\"\" class StreamReader ( Codec , codecs . StreamReader ) : \"\"\"\"\"\" ", "answer": "def getregentry ( ) :"}, {"prompt": " from flask import Flask , render_template , redirect , url_for , current_app from flask_plugins import PluginManager , get_enabled_plugins , get_plugin , Plugin , emit_event class AppPlugin ( Plugin ) : def register_blueprint ( self , blueprint , ** kwargs ) : \"\"\"\"\"\" current_app . register_blueprint ( blueprint , ** kwargs ) SECRET_KEY = \"\" app = Flask ( __name__ ) app . config . from_object ( __name__ ) plugin_manager = PluginManager ( app ) @ app . route ( \"\" ) ", "answer": "def index ( ) :"}, {"prompt": " \"\"\"\"\"\" __author__ = '' from scalyr_agent . scalyr_monitor import ScalyrMonitor from scalyr_agent . scalyr_monitor import BadMonitorConfiguration from scalyr_agent . scalyr_monitor import MonitorConfig ", "answer": "from scalyr_agent . scalyr_monitor import UnsupportedSystem"}, {"prompt": " import bson import os import simplejson as json import struct import memcacheConstants import pump BSON_SCHEME = \"\" class BSONSource ( pump . Source ) : \"\"\"\"\"\" def __init__ ( self , opts , spec , source_bucket , source_node , source_map , sink_map , ctl , cur ) : super ( BSONSource , self ) . __init__ ( opts , spec , source_bucket , source_node , source_map , sink_map , ctl , cur ) ", "answer": "self . done = False"}, {"prompt": " from django import template from django . conf import settings from django . core . cache import cache from links . models import Link register = template . Library ( ) @ register . inclusion_tag ( '' ) def object_links ( obj ) : l = Link . objects . for_model ( obj ) return { '' : l , '' : settings . MEDIA_URL } @ register . inclusion_tag ( '' ) def object_icon_links ( obj ) : \"\" key = \"\" % ( obj . _meta . app_label , obj . _meta . module_name , obj . pk ) l = cache . get ( key , None ) if l is None : l = Link . objects . for_model ( obj ) cache . set ( key , l , settings . LONG_CACHE_TIME ) ", "answer": "return { '' : l } "}, {"prompt": " \"\"\"\"\"\" import sys import bisect import time import shutil from cvs2svn_lib import config from cvs2svn_lib . common import InternalError from cvs2svn_lib . log import logger from cvs2svn_lib . context import Ctx from cvs2svn_lib . symbol import Trunk from cvs2svn_lib . symbol import Branch from cvs2svn_lib . symbol import Tag from cvs2svn_lib . cvs_item import CVSSymbol from cvs2svn_lib . dvcs_common import DVCSOutputOption from cvs2svn_lib . dvcs_common import MirrorUpdater from cvs2svn_lib . key_generator import KeyGenerator from cvs2svn_lib . artifact_manager import artifact_manager class GitRevisionWriter ( MirrorUpdater ) : def start ( self , mirror , f ) : MirrorUpdater . start ( self , mirror ) self . f = f def _modify_file ( self , cvs_item , post_commit ) : raise NotImplementedError ( ) def add_file ( self , cvs_rev , post_commit ) : MirrorUpdater . add_file ( self , cvs_rev , post_commit ) self . _modify_file ( cvs_rev , post_commit ) def modify_file ( self , cvs_rev , post_commit ) : MirrorUpdater . modify_file ( self , cvs_rev , post_commit ) self . _modify_file ( cvs_rev , post_commit ) def delete_file ( self , cvs_rev , post_commit ) : MirrorUpdater . delete_file ( self , cvs_rev , post_commit ) self . f . write ( '' % ( cvs_rev . cvs_file . cvs_path , ) ) def branch_file ( self , cvs_symbol ) : MirrorUpdater . branch_file ( self , cvs_symbol ) self . _modify_file ( cvs_symbol , post_commit = False ) def finish ( self ) : MirrorUpdater . finish ( self ) del self . f class GitRevisionMarkWriter ( GitRevisionWriter ) : def register_artifacts ( self , which_pass ) : GitRevisionWriter . register_artifacts ( self , which_pass ) if Ctx ( ) . revision_collector . blob_filename is None : artifact_manager . register_temp_file_needed ( config . GIT_BLOB_DATAFILE , which_pass , ) def start ( self , mirror , f ) : GitRevisionWriter . start ( self , mirror , f ) if Ctx ( ) . revision_collector . blob_filename is None : logger . normal ( '' ) blobf = open ( artifact_manager . get_temp_file ( config . GIT_BLOB_DATAFILE ) , '' , ) shutil . copyfileobj ( blobf , f ) blobf . close ( ) def _modify_file ( self , cvs_item , post_commit ) : if cvs_item . cvs_file . executable : mode = '' else : mode = '' self . f . write ( '' % ( mode , cvs_item . revision_reader_token , cvs_item . cvs_file . cvs_path , ) ) class GitRevisionInlineWriter ( GitRevisionWriter ) : def __init__ ( self , revision_reader ) : self . revision_reader = revision_reader def register_artifacts ( self , which_pass ) : GitRevisionWriter . register_artifacts ( self , which_pass ) self . revision_reader . register_artifacts ( which_pass ) def start ( self , mirror , f ) : GitRevisionWriter . start ( self , mirror , f ) self . revision_reader . start ( ) def _modify_file ( self , cvs_item , post_commit ) : if cvs_item . cvs_file . executable : mode = '' else : mode = '' self . f . write ( '' % ( mode , cvs_item . cvs_file . cvs_path , ) ) if isinstance ( cvs_item , CVSSymbol ) : cvs_rev = cvs_item . get_cvs_revision_source ( Ctx ( ) . _cvs_items_db ) else : cvs_rev = cvs_item fulltext = self . revision_reader . get_content ( cvs_rev ) self . f . write ( '' % ( len ( fulltext ) , ) ) self . f . write ( fulltext ) self . f . write ( '' ) def finish ( self ) : GitRevisionWriter . finish ( self ) self . revision_reader . finish ( ) class GitOutputOption ( DVCSOutputOption ) : \"\"\"\"\"\" name = \"\" _first_commit_mark = def __init__ ( self , revision_writer , dump_filename = None , author_transforms = None , tie_tag_fixup_branches = False , ) : \"\"\"\"\"\" DVCSOutputOption . __init__ ( self ) self . dump_filename = dump_filename self . revision_writer = revision_writer self . author_transforms = self . normalize_author_transforms ( author_transforms ) self . tie_tag_fixup_branches = tie_tag_fixup_branches self . _mark_generator = KeyGenerator ( GitOutputOption . _first_commit_mark ) def register_artifacts ( self , which_pass ) : DVCSOutputOption . register_artifacts ( self , which_pass ) self . revision_writer . register_artifacts ( which_pass ) def check_symbols ( self , symbol_map ) : pass def setup ( self , svn_rev_count ) : DVCSOutputOption . setup ( self , svn_rev_count ) if self . dump_filename is None : self . f = sys . stdout else : self . f = open ( self . dump_filename , '' ) self . _youngest = self . _marks = { } self . revision_writer . start ( self . _mirror , self . f ) def _create_commit_mark ( self , lod , revnum ) : mark = self . _mark_generator . gen_id ( ) self . _set_lod_mark ( lod , revnum , mark ) return mark def _set_lod_mark ( self , lod , revnum , mark ) : \"\"\"\"\"\" assert revnum >= self . _youngest entry = ( revnum , mark ) try : modifications = self . _marks [ lod ] except KeyError : self . _marks [ lod ] = [ entry ] else : if modifications [ - ] [ ] == revnum : modifications [ - ] = entry else : modifications . append ( entry ) self . _youngest = revnum def _get_author ( self , svn_commit ) : \"\"\"\"\"\" cvs_author = svn_commit . get_author ( ) return self . _map_author ( cvs_author ) def _map_author ( self , cvs_author ) : return self . author_transforms . get ( cvs_author , \"\" % ( cvs_author , ) ) @ staticmethod def _get_log_msg ( svn_commit ) : return svn_commit . get_log_msg ( ) def process_initial_project_commit ( self , svn_commit ) : self . _mirror . start_commit ( svn_commit . revnum ) self . _mirror . end_commit ( ) def process_primary_commit ( self , svn_commit ) : author = self . _get_author ( svn_commit ) log_msg = self . _get_log_msg ( svn_commit ) lods = set ( ) for cvs_rev in svn_commit . get_cvs_items ( ) : lods . add ( cvs_rev . lod ) if len ( lods ) != : raise InternalError ( '' % ( len ( lods ) , ) ) lod = lods . pop ( ) self . _mirror . start_commit ( svn_commit . revnum ) if isinstance ( lod , Trunk ) : self . f . write ( '' ) else : self . f . write ( '' % ( lod . name , ) ) mark = self . _create_commit_mark ( lod , svn_commit . revnum ) logger . normal ( '' % ( svn_commit . revnum , lod , mark , ) ) self . f . write ( '' % ( mark , ) ) self . f . write ( '' % ( author , svn_commit . date , ) ) self . f . write ( '' % ( len ( log_msg ) , ) ) self . f . write ( '' % ( log_msg , ) ) for cvs_rev in svn_commit . get_cvs_items ( ) : self . revision_writer . process_revision ( cvs_rev , post_commit = False ) self . f . write ( '' ) self . _mirror . end_commit ( ) def process_post_commit ( self , svn_commit ) : author = self . _get_author ( svn_commit ) log_msg = self . _get_log_msg ( svn_commit ) source_lods = set ( ) for cvs_rev in svn_commit . cvs_revs : source_lods . add ( cvs_rev . lod ) if len ( source_lods ) != : raise InternalError ( '' % ( len ( source_lods ) , ) ) source_lod = source_lods . pop ( ) self . _mirror . start_commit ( svn_commit . revnum ) self . f . write ( '' ) mark = self . _create_commit_mark ( None , svn_commit . revnum ) logger . normal ( '' % ( svn_commit . revnum , mark , ) ) self . f . write ( '' % ( mark , ) ) self . f . write ( '' % ( author , svn_commit . date , ) ) self . f . write ( '' % ( len ( log_msg ) , ) ) self . f . write ( '' % ( log_msg , ) ) self . f . write ( '' % ( self . _get_source_mark ( source_lod , svn_commit . revnum ) , ) ) for cvs_rev in svn_commit . cvs_revs : self . revision_writer . process_revision ( cvs_rev , post_commit = True ) self . f . write ( '' ) self . _mirror . end_commit ( ) def _get_source_mark ( self , source_lod , revnum ) : \"\"\"\"\"\" modifications = self . _marks [ source_lod ] i = bisect . bisect_left ( modifications , ( revnum + , ) ) - ( revnum , mark ) = modifications [ i ] return mark def describe_lod_to_user ( self , lod ) : \"\"\"\"\"\" if isinstance ( lod , Trunk ) : return '' else : return lod . name def _describe_commit ( self , svn_commit , lod ) : author = self . _map_author ( svn_commit . get_author ( ) ) if author . endswith ( \"\" ) : author = author [ : - ] date = time . strftime ( \"\" , time . gmtime ( svn_commit . date ) ) log_msg = svn_commit . get_log_msg ( ) if log_msg . find ( '' ) != - : log_msg = log_msg [ : log_msg . index ( '' ) ] return \"\" % ( self . describe_lod_to_user ( lod ) , date , author , log_msg , ) def _process_symbol_commit ( self , svn_commit , git_branch , source_groups ) : author = self . _get_author ( svn_commit ) log_msg = self . _get_log_msg ( svn_commit ) is_initial_lod_creation = svn_commit . symbol not in self . _marks mark = self . _create_commit_mark ( svn_commit . symbol , svn_commit . revnum ) if is_initial_lod_creation : p_source_revnum , p_source_lod , p_cvs_symbols = source_groups [ ] try : p_source_node = self . _mirror . get_old_lod_directory ( p_source_lod , p_source_revnum ) except KeyError : raise InternalError ( '' % ( p_source_lod , ) ) cvs_files_to_delete = set ( self . _get_all_files ( p_source_node ) ) ", "answer": "for ( source_revnum , source_lod , cvs_symbols , ) in source_groups :"}, {"prompt": " import re from . aligners import FirstColumnAligner , ColumnAligner , NullAligner ", "answer": "from . dataextractor import DataExtractor"}, {"prompt": " import os import sys import termios from urwid . util import int_scale from urwid import signals from urwid . compat import B , bytes3 UNPRINTABLE_TRANS_TABLE = B ( \"\" ) * + bytes3 ( range ( , ) ) UPDATE_PALETTE_ENTRY = \"\" INPUT_DESCRIPTORS_CHANGED = \"\" _BASIC_START = _CUBE_START = _CUBE_SIZE_256 = _GRAY_SIZE_256 = _GRAY_START_256 = _CUBE_SIZE_256 ** + _CUBE_START _CUBE_WHITE_256 = _GRAY_START_256 - _CUBE_SIZE_88 = _GRAY_SIZE_88 = _GRAY_START_88 = _CUBE_SIZE_88 ** + _CUBE_START _CUBE_WHITE_88 = _GRAY_START_88 - _CUBE_BLACK = _CUBE_START _CUBE_STEPS_256 = [ , , , , , ] _GRAY_STEPS_256 = [ , , , , , , , , , , , , , , , , , , , , , , , ] _CUBE_STEPS_88 = [ , , , ] _GRAY_STEPS_88 = [ , , , , , , , ] _BASIC_COLOR_VALUES = [ ( , , ) , ( , , ) , ( , , ) , ( , , ) , ( , , ) , ( , , ) , ( , , ) , ( , , ) , ( , , ) , ( , , ) , ( , , ) , ( , , ) , ( , , ) , ( , , ) , ( , , ) , ( , , ) ] _COLOR_VALUES_256 = ( _BASIC_COLOR_VALUES + [ ( r , g , b ) for r in _CUBE_STEPS_256 for g in _CUBE_STEPS_256 for b in _CUBE_STEPS_256 ] + [ ( gr , gr , gr ) for gr in _GRAY_STEPS_256 ] ) _COLOR_VALUES_88 = ( _BASIC_COLOR_VALUES + [ ( r , g , b ) for r in _CUBE_STEPS_88 for g in _CUBE_STEPS_88 for b in _CUBE_STEPS_88 ] + [ ( gr , gr , gr ) for gr in _GRAY_STEPS_88 ] ) assert len ( _COLOR_VALUES_256 ) == assert len ( _COLOR_VALUES_88 ) == _FG_COLOR_MASK = _BG_COLOR_MASK = _FG_BASIC_COLOR = _FG_HIGH_COLOR = _BG_BASIC_COLOR = _BG_HIGH_COLOR = _BG_SHIFT = _HIGH_88_COLOR = _STANDOUT = _UNDERLINE = _BOLD = _BLINK = _FG_MASK = ( _FG_COLOR_MASK | _FG_BASIC_COLOR | _FG_HIGH_COLOR | _STANDOUT | _UNDERLINE | _BLINK | _BOLD ) _BG_MASK = _BG_COLOR_MASK | _BG_BASIC_COLOR | _BG_HIGH_COLOR DEFAULT = '' BLACK = '' DARK_RED = '' DARK_GREEN = '' BROWN = '' DARK_BLUE = '' DARK_MAGENTA = '' DARK_CYAN = '' LIGHT_GRAY = '' DARK_GRAY = '' LIGHT_RED = '' LIGHT_GREEN = '' YELLOW = '' LIGHT_BLUE = '' LIGHT_MAGENTA = '' LIGHT_CYAN = '' WHITE = '' _BASIC_COLORS = [ BLACK , DARK_RED , DARK_GREEN , BROWN , DARK_BLUE , DARK_MAGENTA , DARK_CYAN , LIGHT_GRAY , DARK_GRAY , LIGHT_RED , LIGHT_GREEN , YELLOW , LIGHT_BLUE , LIGHT_MAGENTA , LIGHT_CYAN , WHITE , ] _ATTRIBUTES = { '' : _BOLD , '' : _UNDERLINE , '' : _BLINK , '' : _STANDOUT , } def _value_lookup_table ( values , size ) : \"\"\"\"\"\" middle_values = [ ] + [ ( values [ i ] + values [ i + ] + ) // for i in range ( len ( values ) - ) ] + [ size ] lookup_table = [ ] for i in range ( len ( middle_values ) - ) : count = middle_values [ i + ] - middle_values [ i ] lookup_table . extend ( [ i ] * count ) return lookup_table _CUBE_256_LOOKUP = _value_lookup_table ( _CUBE_STEPS_256 , ) _GRAY_256_LOOKUP = _value_lookup_table ( [ ] + _GRAY_STEPS_256 + [ ] , ) _CUBE_88_LOOKUP = _value_lookup_table ( _CUBE_STEPS_88 , ) _GRAY_88_LOOKUP = _value_lookup_table ( [ ] + _GRAY_STEPS_88 + [ ] , ) _CUBE_STEPS_256_16 = [ int_scale ( n , , ) for n in _CUBE_STEPS_256 ] _GRAY_STEPS_256_101 = [ int_scale ( n , , ) for n in _GRAY_STEPS_256 ] _CUBE_STEPS_88_16 = [ int_scale ( n , , ) for n in _CUBE_STEPS_88 ] _GRAY_STEPS_88_101 = [ int_scale ( n , , ) for n in _GRAY_STEPS_88 ] _CUBE_256_LOOKUP_16 = [ _CUBE_256_LOOKUP [ int_scale ( n , , ) ] for n in range ( ) ] _GRAY_256_LOOKUP_101 = [ _GRAY_256_LOOKUP [ int_scale ( n , , ) ] for n in range ( ) ] _CUBE_88_LOOKUP_16 = [ _CUBE_88_LOOKUP [ int_scale ( n , , ) ] for n in range ( ) ] _GRAY_88_LOOKUP_101 = [ _GRAY_88_LOOKUP [ int_scale ( n , , ) ] for n in range ( ) ] def _gray_num_256 ( gnum ) : \"\"\"\"\"\" gnum -= if gnum < : return _CUBE_BLACK if gnum >= _GRAY_SIZE_256 : return _CUBE_WHITE_256 return _GRAY_START_256 + gnum def _gray_num_88 ( gnum ) : \"\"\"\"\"\" gnum -= if gnum < : return _CUBE_BLACK if gnum >= _GRAY_SIZE_88 : return _CUBE_WHITE_88 return _GRAY_START_88 + gnum def _color_desc_256 ( num ) : \"\"\"\"\"\" assert num >= and num < , num if num < _CUBE_START : return '' % num if num < _GRAY_START_256 : num -= _CUBE_START b , num = num % _CUBE_SIZE_256 , num // _CUBE_SIZE_256 g , num = num % _CUBE_SIZE_256 , num // _CUBE_SIZE_256 r = num % _CUBE_SIZE_256 return '' % ( _CUBE_STEPS_256_16 [ r ] , _CUBE_STEPS_256_16 [ g ] , _CUBE_STEPS_256_16 [ b ] ) return '' % _GRAY_STEPS_256_101 [ num - _GRAY_START_256 ] def _color_desc_88 ( num ) : \"\"\"\"\"\" assert num > and num < if num < _CUBE_START : ", "answer": "return '' % num"}, {"prompt": " '''''' from __future__ import absolute_import from salttesting import TestCase , skipIf from salttesting . mock import ( MagicMock , patch , NO_MOCK , NO_MOCK_REASON ) from salt . modules import event import salt . utils . event import sys sys . path . append ( '' ) event . __grains__ = { } event . __salt__ = { } event . __context__ = { } event . __opts__ = { } @ skipIf ( NO_MOCK , NO_MOCK_REASON ) class EventTestCase ( TestCase ) : '''''' @ patch ( '' ) @ patch ( '' ) def test_fire_master ( self , salt_crypt_sauth , salt_transport_channel_factory ) : '''''' preload = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' } ", "answer": "with patch . dict ( event . __opts__ , { '' : '' ,"}, {"prompt": " import re from django import forms from django . shortcuts import redirect from django . core . urlresolvers import reverse from django . forms import formsets , ValidationError from django . views . generic import TemplateView from django . utils . datastructures import SortedDict from django . utils . decorators import classonlymethod from formwizard . storage import get_storage from formwizard . storage . exceptions import NoFileStorageConfigured from formwizard . forms import ManagementForm def normalize_name ( name ) : new = re . sub ( '' , '' , name ) return new . lower ( ) . strip ( '' ) class StepsHelper ( object ) : def __init__ ( self , wizard ) : self . _wizard = wizard def __dir__ ( self ) : return self . all def __len__ ( self ) : return self . count def __repr__ ( self ) : return '' % ( self . _wizard , self . all ) @ property def all ( self ) : \"\" return self . _wizard . get_form_list ( ) . keys ( ) @ property def count ( self ) : \"\" return len ( self . all ) @ property def current ( self ) : \"\"\"\"\"\" return self . _wizard . storage . current_step or self . first @ property def first ( self ) : \"\" return self . all [ ] @ property def last ( self ) : \"\" return self . all [ - ] @ property def next ( self ) : \"\" return self . _wizard . get_next_step ( ) @ property def prev ( self ) : \"\" return self . _wizard . get_prev_step ( ) @ property def index ( self ) : \"\" return self . _wizard . get_step_index ( ) @ property def step0 ( self ) : return int ( self . index ) @ property def step1 ( self ) : return int ( self . index ) + class WizardView ( TemplateView ) : \"\"\"\"\"\" storage_name = None form_list = None initial_dict = None instance_dict = None condition_dict = None template_name = '' def __repr__ ( self ) : return '' % ( self . __class__ . __name__ , self . form_list ) @ classonlymethod def as_view ( cls , * args , ** kwargs ) : \"\"\"\"\"\" initkwargs = cls . get_initkwargs ( * args , ** kwargs ) return super ( WizardView , cls ) . as_view ( ** initkwargs ) @ classmethod def get_initkwargs ( cls , form_list , initial_dict = None , instance_dict = None , condition_dict = None , * args , ** kwargs ) : \"\"\"\"\"\" kwargs . update ( { '' : initial_dict or { } , '' : instance_dict or { } , '' : condition_dict or { } , } ) init_form_list = SortedDict ( ) assert len ( form_list ) > , '' for i , form in enumerate ( form_list ) : if isinstance ( form , ( list , tuple ) ) : init_form_list [ unicode ( form [ ] ) ] = form [ ] else : init_form_list [ unicode ( i ) ] = form for form in init_form_list . itervalues ( ) : if issubclass ( form , formsets . BaseFormSet ) : form = form . form for field in form . base_fields . itervalues ( ) : if ( isinstance ( field , forms . FileField ) and not hasattr ( cls , '' ) ) : raise NoFileStorageConfigured kwargs [ '' ] = init_form_list return kwargs def get_wizard_name ( self ) : return normalize_name ( self . __class__ . __name__ ) def get_prefix ( self ) : return self . wizard_name def get_form_list ( self ) : \"\"\"\"\"\" form_list = SortedDict ( ) for form_key , form_class in self . form_list . iteritems ( ) : condition = self . condition_dict . get ( form_key , True ) if callable ( condition ) : condition = condition ( self ) if condition : form_list [ form_key ] = form_class return form_list def dispatch ( self , request , * args , ** kwargs ) : \"\"\"\"\"\" self . wizard_name = self . get_wizard_name ( ) self . prefix = self . get_prefix ( ) self . storage = get_storage ( self . storage_name , self . prefix , request , getattr ( self , '' , None ) ) self . steps = StepsHelper ( self ) response = super ( WizardView , self ) . dispatch ( request , * args , ** kwargs ) self . storage . update_response ( response ) return response def get ( self , request , * args , ** kwargs ) : \"\"\"\"\"\" self . storage . reset ( ) self . storage . current_step = self . steps . first return self . render ( self . get_form ( ) ) def post ( self , * args , ** kwargs ) : \"\"\"\"\"\" wizard_prev_step = self . request . POST . get ( '' , None ) if wizard_prev_step and wizard_prev_step in self . get_form_list ( ) : self . storage . current_step = wizard_prev_step form = self . get_form ( data = self . storage . get_step_data ( self . steps . current ) , files = self . storage . get_step_files ( self . steps . current ) ) return self . render ( form ) management_form = ManagementForm ( self . request . POST , prefix = self . prefix ) if not management_form . is_valid ( ) : raise ValidationError ( '' ) form_current_step = management_form . cleaned_data [ '' ] if ( form_current_step != self . steps . current and self . storage . current_step is not None ) : self . storage . current_step = form_current_step form = self . get_form ( data = self . request . POST , files = self . request . FILES ) if form . is_valid ( ) : self . storage . set_step_data ( self . steps . current , self . process_step ( form ) ) self . storage . set_step_files ( self . steps . current , self . process_step_files ( form ) ) if self . steps . current == self . steps . last : return self . render_done ( form , ** kwargs ) else : return self . render_next_step ( form ) return self . render ( form ) def render_next_step ( self , form , ** kwargs ) : \"\"\"\"\"\" next_step = self . steps . next new_form = self . get_form ( next_step , data = self . storage . get_step_data ( next_step ) , files = self . storage . get_step_files ( next_step ) ) self . storage . current_step = next_step return self . render ( new_form , ** kwargs ) def render_done ( self , form , ** kwargs ) : \"\"\"\"\"\" final_form_list = [ ] for form_key in self . get_form_list ( ) : form_obj = self . get_form ( step = form_key , data = self . storage . get_step_data ( form_key ) , files = self . storage . get_step_files ( form_key ) ) if not form_obj . is_valid ( ) : return self . render_revalidation_failure ( form_key , form_obj , ** kwargs ) final_form_list . append ( form_obj ) done_response = self . done ( final_form_list , ** kwargs ) self . storage . reset ( ) return done_response def get_form_prefix ( self , step = None , form = None ) : \"\"\"\"\"\" if step is None : step = self . steps . current return str ( step ) def get_form_initial ( self , step ) : \"\"\"\"\"\" return self . initial_dict . get ( step , { } ) def get_form_instance ( self , step ) : \"\"\"\"\"\" return self . instance_dict . get ( step , None ) def get_form_kwargs ( self , step = None ) : \"\"\"\"\"\" return { } def get_form ( self , step = None , data = None , files = None ) : \"\"\"\"\"\" if step is None : step = self . steps . current kwargs = self . get_form_kwargs ( step ) kwargs . update ( { '' : data , '' : files , '' : self . get_form_prefix ( step , self . form_list [ step ] ) , '' : self . get_form_initial ( step ) , } ) if issubclass ( self . form_list [ step ] , forms . ModelForm ) : kwargs . update ( { '' : self . get_form_instance ( step ) } ) elif issubclass ( self . form_list [ step ] , forms . models . BaseModelFormSet ) : kwargs . update ( { '' : self . get_form_instance ( step ) } ) return self . form_list [ step ] ( ** kwargs ) def process_step ( self , form ) : \"\"\"\"\"\" return self . get_form_step_data ( form ) def process_step_files ( self , form ) : \"\"\"\"\"\" return self . get_form_step_files ( form ) def render_revalidation_failure ( self , step , form , ** kwargs ) : \"\"\"\"\"\" self . storage . current_step = step return self . render ( form , ** kwargs ) def get_form_step_data ( self , form ) : \"\"\"\"\"\" return form . data def get_form_step_files ( self , form ) : \"\"\"\"\"\" return form . files def get_all_cleaned_data ( self ) : \"\"\"\"\"\" cleaned_data = { } for form_key in self . get_form_list ( ) : form_obj = self . get_form ( step = form_key , data = self . storage . get_step_data ( form_key ) , files = self . storage . get_step_files ( form_key ) ) if form_obj . is_valid ( ) : if isinstance ( form_obj . cleaned_data , ( tuple , list ) ) : cleaned_data . update ( { '' % form_key : form_obj . cleaned_data } ) else : cleaned_data . update ( form_obj . cleaned_data ) return cleaned_data def get_cleaned_data_for_step ( self , step ) : \"\"\"\"\"\" if step in self . form_list : form_obj = self . get_form ( step = step , data = self . storage . get_step_data ( step ) , files = self . storage . get_step_files ( step ) ) if form_obj . is_valid ( ) : return form_obj . cleaned_data return None def get_next_step ( self , step = None ) : \"\"\"\"\"\" if step is None : step = self . steps . current form_list = self . get_form_list ( ) key = form_list . keyOrder . index ( step ) + if len ( form_list . keyOrder ) > key : return form_list . keyOrder [ key ] return None def get_prev_step ( self , step = None ) : \"\"\"\"\"\" if step is None : step = self . steps . current form_list = self . get_form_list ( ) key = form_list . keyOrder . index ( step ) - if key >= : return form_list . keyOrder [ key ] return None def get_step_index ( self , step = None ) : \"\"\"\"\"\" if step is None : step = self . steps . current return self . get_form_list ( ) . keyOrder . index ( step ) def get_context_data ( self , form , * args , ** kwargs ) : \"\"\"\"\"\" context = super ( WizardView , self ) . get_context_data ( * args , ** kwargs ) context . update ( self . storage . extra_data ) context [ '' ] = { '' : form , '' : self . steps , '' : ManagementForm ( prefix = self . prefix , initial = { '' : self . steps . current , } ) , } return context def render ( self , form = None , ** kwargs ) : \"\"\"\"\"\" form = form or self . get_form ( ) context = self . get_context_data ( form , ** kwargs ) return self . render_to_response ( context ) def done ( self , form_list , ** kwargs ) : \"\"\"\"\"\" raise NotImplementedError ( \"\" \"\" % self . __class__ . __name__ ) class SessionWizardView ( WizardView ) : \"\"\"\"\"\" storage_name = '' class CookieWizardView ( WizardView ) : \"\"\"\"\"\" storage_name = '' class NamedUrlWizardView ( WizardView ) : \"\"\"\"\"\" url_name = None done_step_name = None @ classmethod def get_initkwargs ( cls , * args , ** kwargs ) : \"\"\"\"\"\" assert '' in kwargs , '' extra_kwargs = { '' : kwargs . pop ( '' , '' ) , '' : kwargs . pop ( '' ) , } initkwargs = super ( NamedUrlWizardView , cls ) . get_initkwargs ( * args , ** kwargs ) initkwargs . update ( extra_kwargs ) assert initkwargs [ '' ] not in initkwargs [ '' ] , '' % initkwargs [ '' ] return initkwargs def get ( self , * args , ** kwargs ) : \"\"\"\"\"\" step_url = kwargs . get ( '' , None ) if step_url is None : if '' in self . request . GET : self . storage . reset ( ) self . storage . current_step = self . steps . first if self . request . GET : query_string = \"\" % self . request . GET . urlencode ( ) else : query_string = \"\" next_step_url = reverse ( self . url_name , kwargs = { '' : self . steps . current , } ) + query_string return redirect ( next_step_url ) elif step_url == self . done_step_name : last_step = self . steps . last return self . render_done ( self . get_form ( step = last_step , data = self . storage . get_step_data ( last_step ) , files = self . storage . get_step_files ( last_step ) ) , ** kwargs ) elif step_url == self . steps . current : return self . render ( self . get_form ( data = self . storage . current_step_data , files = self . storage . current_step_data , ) , ** kwargs ) elif step_url in self . get_form_list ( ) : self . storage . current_step = step_url return self . render ( self . get_form ( data = self . storage . current_step_data , files = self . storage . current_step_data , ) , ** kwargs ) else : self . storage . current_step = self . steps . first ", "answer": "return redirect ( self . url_name , step = self . steps . first )"}, {"prompt": " from __future__ import absolute_import from ... spec . base import NullContext from ... scan import Dispatcher from ... errs import SchemaError from ... utils import scope_compose , get_or_none from ... consts import private from ... spec . v1_2 . objects import ( ResourceList , Resource , Operation , Authorization , Parameter , Model , ) from ... spec . v2_0 import objects import os import six def update_type_and_ref ( dst , src , scope , sep , app ) : ref = getattr ( src , '' ) if ref : dst . update_field ( '' , '' + scope_compose ( scope , ref , sep = sep ) ) if app . prim_factory . is_primitive ( getattr ( src , '' , None ) ) : dst . update_field ( '' , src . type . lower ( ) ) elif src . type : dst . update_field ( '' , '' + scope_compose ( scope , src . type , sep = sep ) ) def convert_min_max ( dst , src ) : def _from_str ( name ) : v = getattr ( src , name , None ) if v : if src . type == '' : dst . update_field ( name , int ( float ( v ) ) ) elif src . type == '' : dst . update_field ( name , float ( v ) ) else : raise SchemaError ( '' . format ( src . type ) ) else : dst . update_field ( name , None ) _from_str ( '' ) _from_str ( '' ) def convert_schema_from_datatype ( obj , scope , sep , app ) : if obj == None : return None s = objects . Schema ( NullContext ( ) ) update_type_and_ref ( s , obj , scope , sep , app ) s . update_field ( '' , obj . format ) if obj . is_set ( '' ) : s . update_field ( '' , obj . defaultValue ) convert_min_max ( s , obj ) s . update_field ( '' , obj . uniqueItems ) s . update_field ( '' , obj . enum ) if obj . items : i = objects . Schema ( NullContext ( ) ) update_type_and_ref ( i , obj . items , scope , sep , app ) i . update_field ( '' , obj . items . format ) s . update_field ( '' , i ) return s def convert_items ( o , app ) : item = objects . Items ( NullContext ( ) ) if getattr ( o , '' ) : raise SchemaError ( '' ) if not app . prim_factory . is_primitive ( getattr ( o , '' , None ) ) : raise SchemaError ( '' ) item . update_field ( '' , o . type . lower ( ) ) item . update_field ( '' , o . format ) return item class Upgrade ( object ) : \"\"\"\"\"\" class Disp ( Dispatcher ) : pass def __init__ ( self , sep = private . SCOPE_SEPARATOR ) : self . __swagger = None self . __sep = sep @ Disp . register ( [ ResourceList ] ) def _resource_list ( self , path , obj , app ) : o = objects . Swagger ( NullContext ( ) ) info = objects . Info ( NullContext ( ) ) info . update_field ( '' , obj . apiVersion ) info . update_field ( '' , get_or_none ( obj , '' , '' ) ) info . update_field ( '' , get_or_none ( obj , '' , '' ) ) info . update_field ( '' , get_or_none ( obj , '' , '' ) ) if obj . info . contact : contact = objects . Contact ( NullContext ( ) ) contact . update_field ( '' , get_or_none ( obj , '' , '' ) ) info . update_field ( '' , contact ) if obj . info . license or obj . info . licenseUrl : license = objects . License ( NullContext ( ) ) license . update_field ( '' , get_or_none ( obj , '' , '' ) ) license . update_field ( '' , get_or_none ( obj , '' , '' ) ) info . update_field ( '' , license ) o . update_field ( '' , info ) o . update_field ( '' , '' ) o . update_field ( '' , [ '' , '' ] ) o . update_field ( '' , '' ) o . update_field ( '' , '' ) o . update_field ( '' , [ ] ) o . update_field ( '' , { } ) o . update_field ( '' , { } ) o . update_field ( '' , { } ) o . update_field ( '' , { } ) o . update_field ( '' , [ ] ) o . update_field ( '' , { } ) o . update_field ( '' , [ ] ) o . update_field ( '' , [ ] ) self . __swagger = o @ Disp . register ( [ Resource ] ) def _resource ( self , path , obj , app ) : name = obj . get_name ( path ) for t in self . __swagger . tags : if t . name == name : break else : tt = objects . Tag ( NullContext ( ) ) tt . update_field ( '' , name ) self . __swagger . tags . append ( tt ) @ Disp . register ( [ Operation ] ) def _operation ( self , path , obj , app ) : o = objects . Operation ( NullContext ( ) ) scope = obj . _parent_ . get_name ( path ) o . update_field ( '' , [ scope ] ) o . update_field ( '' , obj . nickname ) o . update_field ( '' , obj . summary ) o . update_field ( '' , obj . notes ) o . update_field ( '' , obj . deprecated == '' ) c = obj . consumes if obj . consumes and len ( obj . consumes ) > else obj . _parent_ . consumes o . update_field ( '' , c if c else [ ] ) p = obj . produces if obj . produces and len ( obj . produces ) > else obj . _parent_ . produces o . update_field ( '' , p if p else [ ] ) o . update_field ( '' , [ ] ) o . update_field ( '' , [ ] ) _auth = obj . authorizations if obj . authorizations and len ( obj . authorizations ) > else obj . _parent_ . authorizations if _auth : for name , scopes in six . iteritems ( _auth ) : o . security . append ( { name : [ v . scope for v in scopes ] } ) o . update_field ( '' , { } ) resp = objects . Response ( NullContext ( ) ) if obj . type != '' : resp . update_field ( '' , convert_schema_from_datatype ( obj , scope , self . __sep , app ) ) o . responses [ '' ] = resp path = obj . _parent_ . basePath + obj . path if path not in self . __swagger . paths : self . __swagger . paths [ path ] = objects . PathItem ( NullContext ( ) ) method = obj . method . lower ( ) self . __swagger . paths [ path ] . update_field ( method , o ) @ Disp . register ( [ Authorization ] ) def _authorization ( self , path , obj , app ) : o = objects . SecurityScheme ( NullContext ( ) ) if obj . type == '' : o . update_field ( '' , '' ) else : o . update_field ( '' , obj . type ) o . update_field ( '' , { } ) for s in obj . scopes or [ ] : o . scopes [ s . scope ] = s . description if o . type == '' : o . update_field ( '' , get_or_none ( obj , '' , '' , '' , '' ) ) o . update_field ( '' , get_or_none ( obj , '' , '' , '' , '' ) ) if o . authorizationUrl : o . update_field ( '' , '' ) elif o . tokenUrl : o . update_field ( '' , '' ) elif o . type == '' : o . update_field ( '' , obj . keyname ) o . update_field ( '' , obj . passAs ) self . __swagger . securityDefinitions [ obj . get_name ( path ) ] = o @ Disp . register ( [ Parameter ] ) def _parameter ( self , path , obj , app ) : o = objects . Parameter ( NullContext ( ) ) scope = obj . _parent_ . _parent_ . get_name ( path ) o . update_field ( '' , obj . name ) o . update_field ( '' , obj . required ) o . update_field ( '' , obj . description ) if obj . paramType == '' : o . update_field ( '' , '' ) else : o . update_field ( '' , obj . paramType ) if '' == getattr ( o , '' ) : o . update_field ( '' , convert_schema_from_datatype ( obj , scope , self . __sep , app ) ) else : if getattr ( obj , '' ) : raise SchemaError ( '' ) if obj . allowMultiple == True and obj . items == None : o . update_field ( '' , '' ) o . update_field ( '' , '' ) o . update_field ( '' , obj . uniqueItems ) o . update_field ( '' , convert_items ( obj , app ) ) if obj . is_set ( \"\" ) : o . update_field ( '' , [ obj . defaultValue ] ) o . items . update_field ( '' , obj . enum ) else : o . update_field ( '' , obj . type . lower ( ) ) o . update_field ( '' , obj . format ) if obj . is_set ( \"\" ) : o . update_field ( '' , obj . defaultValue ) convert_min_max ( o , obj ) o . update_field ( '' , obj . enum ) if obj . items : o . update_field ( '' , '' ) o . update_field ( '' , obj . uniqueItems ) o . update_field ( '' , convert_items ( obj . items , app ) ) path = obj . _parent_ . _parent_ . basePath + obj . _parent_ . path method = obj . _parent_ . method . lower ( ) op = getattr ( self . __swagger . paths [ path ] , method ) op . parameters . append ( o ) @ Disp . register ( [ Model ] ) def _model ( self , path , obj , app ) : scope = obj . _parent_ . get_name ( path ) s = scope_compose ( scope , obj . get_name ( path ) , sep = self . __sep ) o = self . __swagger . definitions . get ( s , None ) if not o : ", "answer": "o = objects . Schema ( NullContext ( ) )"}, {"prompt": " import django . http ", "answer": "import numpy as np"}, {"prompt": " from prob11 import generateAESKey from prob9 import addPKCS7Padding from prob10 import aes_ecb_enc from prob1 import base64toRaw from prob8 import chunks global_aes_key = generateAESKey ( ) ; def constant_ecb_encrypt ( rawInput ) : return aes_ecb_enc ( addPKCS7Padding ( rawInput , ) , global_aes_key ) ; def append_and_encrypt ( rawInput ) : unknownB64 = b'' + b'' + b'' + b'' unknownRaw = base64toRaw ( unknownB64 ) ; return constant_ecb_encrypt ( rawInput + unknownRaw ) ; def determineBlockSize ( ) : plaintext = b'' ; size1 = len ( append_and_encrypt ( plaintext ) ) ; plaintext += b'' ; size2 = len ( append_and_encrypt ( plaintext ) ) ; while ( size1 == size2 ) : plaintext += b'' ; size2 = len ( append_and_encrypt ( plaintext ) ) ; return ( size2 - size1 ) ; def determinePlaintextLength ( ) : plaintext = b'' ; emptyCipherLength = len ( append_and_encrypt ( plaintext ) ) ; maxPlaintextLength = emptyCipherLength - ; while ( True ) : plaintext += b'' ; thisCipherLength = len ( append_and_encrypt ( plaintext ) ) ; if ( thisCipherLength == emptyCipherLength ) : maxPlaintextLength -= ; else : return maxPlaintextLength ; def detectMode ( ) : plaintext = b'' * ; cipher = append_and_encrypt ( plaintext ) ; blocks = chunks ( cipher , ) ; if ( blocks [ ] == blocks [ ] ) : return \"\" ; else : return \"\" ; padStr = b'' ; def determineNextByte ( rawPrefix , observedCipher ) : '''''' blockSize = determineBlockSize ( ) plain = ( padStr ) * ( blockSize - - len ( rawPrefix ) ) ; plain += rawPrefix ; for i in range ( ) : thisPlain = plain + bytes ( chr ( i ) , '' ) ; thisCipher = append_and_encrypt ( thisPlain ) ; if ( chunks ( thisCipher , blockSize ) [ ] == observedCipher ) : return bytes ( chr ( i ) , '' ) ; return b'' ; def determinePlaintext ( ) : blockSize = determineBlockSize ( ) plaintextLength = determinePlaintextLength ( ) ; knownPlaintext = b'' ; for i in range ( plaintextLength ) : padLen = ( blockSize - ) - ( len ( knownPlaintext ) % blockSize ) ; pad = padStr * padLen ; ", "answer": "cipherOutput = append_and_encrypt ( pad ) ;"}, {"prompt": " if __name__ == '' : import nose try : import rednose ", "answer": "except ImportError :"}, {"prompt": " import logging import os ", "answer": "from flask import Flask"}, {"prompt": " from django . http import JsonResponse from django . template . loader import render_to_string from tethys_compute . models import TethysJob from tethys_gizmos . gizmo_options . jobs_table import JobsTable def execute ( request , job_id ) : try : job = TethysJob . objects . filter ( id = job_id ) [ ] . child job . execute ( ) success = True ", "answer": "message = ''"}, {"prompt": " PANEL = '' ", "answer": "PANEL_DASHBOARD = ''"}, {"prompt": " from __future__ import print_function ", "answer": "from nltk . corpus import ( gutenberg , genesis , inaugural ,"}, {"prompt": " \"\"\"\"\"\" import unittest from google . appengine . tools . devappserver2 import start_response_utils class TestCapturingStartResponse ( unittest . TestCase ) : \"\"\"\"\"\" def test_success ( self ) : start_response = start_response_utils . CapturingStartResponse ( ) stream = start_response ( '' , [ ( '' , '' ) ] ) stream . write ( '' ) self . assertEqual ( '' , start_response . status ) self . assertEqual ( None , start_response . exc_info ) self . assertEqual ( [ ( '' , '' ) ] , start_response . response_headers ) self . assertEqual ( '' , start_response . response_stream . getvalue ( ) ) def test_exception ( self ) : ", "answer": "exc_info = ( object ( ) , object ( ) , object ( ) )"}, {"prompt": " \"\"\"\"\"\" from __future__ import print_function import os import sys import logging from framework . dependency_check import verify_dependencies verify_dependencies ( os . path . dirname ( os . path . abspath ( sys . argv [ ] ) ) or '' ) from framework . core import Core from framework . dependency_management . component_initialiser import ComponentInitialiser , DatabaseNotRunningException from framework . dependency_management . dependency_resolver import ServiceLocator from framework import update from framework . lib . cli_options import usage , parse_options , parse_update_options def banner ( ) : print ( \"\"\"\"\"\" ) def get_plugins_from_arg ( arg ) : plugins = arg . split ( '' ) plugin_groups = ServiceLocator . get_component ( \"\" ) . GetGroupsForPlugins ( plugins ) if len ( plugin_groups ) > : usage ( \"\" + str ( plugin_groups ) + \"\" ) return [ plugins , plugin_groups ] def process_options ( user_args ) : try : db_plugin = ServiceLocator . get_component ( \"\" ) valid_groups = db_plugin . GetAllGroups ( ) valid_types = db_plugin . GetAllTypes ( ) + [ '' , '' ] arg = parse_options ( user_args , valid_groups , valid_types ) except KeyboardInterrupt as e : usage ( \"\" + e ) profiles = { } plugin_group = arg . PluginGroup ", "answer": "if arg . CustomProfile :"}, {"prompt": " def main ( ) : ", "answer": "print ( \"\" )"}, {"prompt": " '''''' import unittest from certfuzz . scoring . multiarmed_bandit . arms import errors class Test ( unittest . TestCase ) : def setUp ( self ) : pass def tearDown ( self ) : pass def testName ( self ) : ", "answer": "pass"}, {"prompt": " from . outgoing import OutgoingMessage ", "answer": "class ErrorMessage ( OutgoingMessage ) :"}, {"prompt": " from django . template . response import TemplateResponse from enhanced_cbv . utils import fetch_resources , UnicodeWriter try : from cStringIO import StringIO except ImportError : from StringIO import StringIO class PDFTemplateResponse ( TemplateResponse ) : import logging class PisaNullHandler ( logging . Handler ) : def emit ( self , record ) : pass logging . getLogger ( \"\" ) . addHandler ( PisaNullHandler ( ) ) def __init__ ( self , request , template , context = None , mimetype = '' , status = None , content_type = None , current_app = None , filename = None ) : \"\"\"\"\"\" self . filename = filename super ( PDFTemplateResponse , self ) . __init__ ( request , template , context , mimetype , status , content_type ) def render ( self ) : \"\"\"\"\"\" import xhtml2pdf . pisa as pisa if not self . _is_rendered : buffer = StringIO ( ) pisa . CreatePDF ( self . rendered_content , buffer , link_callback = fetch_resources ) pdf = buffer . getvalue ( ) buffer . close ( ) self . write ( pdf ) self [ '' ] = '' % ( self . filename , ) self . _is_rendered = True for post_callback in self . _post_render_callbacks : post_callback ( self ) return self class CSVTemplateResponse ( TemplateResponse ) : def __init__ ( self , request , template , context = None , content_type = '' , status = None , current_app = None , using = None , filename = None , rows = None , writer_kwargs = None ) : \"\"\"\"\"\" self . filename = filename self . rows = rows if writer_kwargs : self . writer_kwargs = writer_kwargs else : self . writer_kwargs = { } ", "answer": "super ( CSVTemplateResponse , self ) . __init__ ("}, {"prompt": " from datetime import datetime , timedelta from django . test import TestCase from . . models import Report , Fix from . . settings import CONFIG def create_fix ( ** kwargs ) : kwargs [ '' ] = kwargs [ '' ] = Report . objects . create ( url = '' ) return Fix . objects . create ( ** kwargs ) class ReportTestCase ( TestCase ) : def setUp ( self ) : expiration_days = CONFIG [ '' ] self . report1 = Report . objects . create ( url = '' ) expired_datetime = datetime . now ( ) - timedelta ( days = expiration_days + ) self . report2 = Report . objects . create ( url = '' , created_on = expired_datetime ) def test_expired ( self ) : self . assertFalse ( self . report1 . expired ( ) ) self . assertTrue ( self . report2 . expired ( ) ) def test_delete_expired ( self ) : Report . objects . delete_expired ( ) qs = Report . objects . all ( ) self . assertEqual ( qs . count ( ) , ) self . assertEqual ( qs [ ] . pk , ) class FixTestCase ( TestCase ) : def setUp ( self ) : self . fix = create_fix ( description = '' ) def test_caches_description_html ( self ) : self . assertEqual ( self . fix . description_html , '' ) ", "answer": "def test_updates_description_html ( self ) :"}, {"prompt": " \"\"\"\"\"\" from pyesgf . search import SearchConnection , not_equals from . config import TEST_SERVICE def test_context_freetext ( ) : conn = SearchConnection ( TEST_SERVICE ) context = conn . new_context ( query = \"\" ) assert context . freetext_constraint == \"\" def test_context_facets1 ( ) : conn = SearchConnection ( TEST_SERVICE ) context = conn . new_context ( project = '' ) assert context . facet_constraints [ '' ] == '' def test_context_facets1 ( ) : conn = SearchConnection ( TEST_SERVICE ) context = conn . new_context ( project = '' ) context2 = context . constrain ( model = \"\" ) assert context2 . facet_constraints [ '' ] == '' assert context2 . facet_constraints [ '' ] == '' def test_context_facets_multivalue ( ) : conn = SearchConnection ( TEST_SERVICE ) context = conn . new_context ( project = '' ) context2 = context . constrain ( model = [ '' , '' ] ) assert context2 . hit_count > assert context2 . facet_constraints [ '' ] == '' assert sorted ( context2 . facet_constraints . getall ( '' ) ) == [ '' , '' ] def test_context_facet_multivalue2 ( ) : conn = SearchConnection ( TEST_SERVICE ) context = conn . new_context ( project = '' , model = '' ) assert context . facet_constraints . getall ( '' ) == [ '' ] context2 = context . constrain ( model = [ '' , '' ] ) assert sorted ( context2 . facet_constraints . getall ( '' ) ) == [ '' , '' ] def test_context_facet_multivalue3 ( ) : conn = SearchConnection ( TEST_SERVICE ) ctx = conn . new_context ( project = '' , query = '' , experiment = '' ) hits1 = ctx . hit_count assert hits1 > ctx2 = conn . new_context ( project = '' , query = '' , experiment = [ '' , '' ] ) hits2 = ctx2 . hit_count assert hits2 > hits1 def test_context_facet_options ( ) : conn = SearchConnection ( TEST_SERVICE ) context = conn . new_context ( project = '' , model = '' , ensemble = '' , experiment = '' , realm = '' ) assert context . get_facet_options ( ) . keys ( ) == [ '' , '' , '' , '' , '' , '' ] def test_context_facets3 ( ) : conn = SearchConnection ( TEST_SERVICE ) context = conn . new_context ( project = '' ) context2 = context . constrain ( model = \"\" ) results = context2 . search ( ) result = results [ ] assert result . json [ '' ] == [ '' ] assert result . json [ '' ] == [ '' ] def test_facet_count ( ) : conn = SearchConnection ( TEST_SERVICE ) context = conn . new_context ( project = '' ) context2 = context . constrain ( model = \"\" ) counts = context2 . facet_counts assert counts [ '' ] . keys ( ) == [ '' ] assert counts [ '' ] . keys ( ) == [ '' ] def test_distrib ( ) : conn = SearchConnection ( TEST_SERVICE , distrib = False ) context = conn . new_context ( project = '' ) count1 = context . hit_count conn2 = SearchConnection ( TEST_SERVICE , distrib = True ) context = conn2 . new_context ( project = '' ) count2 = context . hit_count assert count1 < count2 def test_constrain ( ) : conn = SearchConnection ( TEST_SERVICE ) context = conn . new_context ( project = '' ) count1 = context . hit_count context = context . constrain ( model = \"\" ) count2 = context . hit_count assert count1 > count2 def test_constrain_freetext ( ) : conn = SearchConnection ( TEST_SERVICE ) context = conn . new_context ( project = '' , query = '' ) assert context . freetext_constraint == '' context = context . constrain ( experiment = '' ) assert context . freetext_constraint == '' def test_constrain_regression1 ( ) : conn = SearchConnection ( TEST_SERVICE ) context = conn . new_context ( project = '' , model = '' ) assert '' not in context . facet_constraints context2 = context . constrain ( experiment = '' ) assert '' not in context . facet_constraints def test_negative_facet ( ) : conn = SearchConnection ( TEST_SERVICE ) context = conn . new_context ( project = '' , model = '' ) hits1 = context . hit_count print context . facet_counts [ '' ] context2 = context . constrain ( experiment = '' ) hits2 = context2 . hit_count context3 = context . constrain ( experiment = not_equals ( '' ) ) hits3 = context3 . hit_count assert hits1 == hits2 + hits3 def test_replica ( ) : conn = SearchConnection ( TEST_SERVICE ) ", "answer": "context = conn . new_context ("}, {"prompt": " \"\"\"\"\"\" import os _original_os_urandom = os . urandom def os_urandom_replacement ( n ) : raise NotImplementedError os . urandom = os_urandom_replacement import random os . urandom = _original_os_urandom random . _urandom = _original_os_urandom import BaseHTTPServer import Bastion import CGIHTTPServer import ConfigParser import Cookie import DocXMLRPCServer import HTMLParser import MimeWriter import Queue import SimpleHTTPServer import SimpleXMLRPCServer import SocketServer import StringIO import UserDict import UserList import UserString import aifc import anydbm import atexit import audiodev import base64 import bdb import binhex import bisect import bz2 import calendar import cgi import cgitb import chunk import cmd import code import codecs import codeop import colorsys import commands import cookielib import copy import copy_reg import csv import datetime import difflib import dircache import dis import doctest import dumbdbm import filecmp import fileinput import fnmatch import formatter import fpformat import ftplib import getopt import getpass import gettext import glob import gzip import heapq import hmac import htmlentitydefs import htmllib import httplib import imaplib import imghdr import imputil import inspect import keyword import linecache import locale import logging import macpath import macurl2path import mailbox import mailcap import markupbase import math import md5 import mhlib import mimetools import mimetypes import modulefinder import multifile import mutex import netrc import new import nntplib import ntpath import nturl2path import opcode import optparse import os2emxpath import pdb import pickle import pickletools import pipes import pkgutil import popen2 import poplib import posixpath import pprint import profile import pstats import pyclbr import pydoc import quopri import re import repr import rfc822 import robotparser import sched import sets import sgmllib import sha import shelve import shlex import shutil import site import smtplib import sndhdr import socket import stat import statvfs import string import stringold import stringprep import struct import sunau import sunaudio import symbol import sys import tabnanny import tarfile import telnetlib import tempfile import textwrap import time import timeit import toaiff import token import tokenize import trace import traceback import types import unittest import urllib import urllib2 import urlparse import uu import uuid import warnings import wave import weakref import whichdb ", "answer": "import xdrlib"}, {"prompt": " \"\"\"\"\"\" from nova . api . openstack import extensions from nova . api . openstack import wsgi authorize = extensions . soft_extension_authorizer ( '' , '' ) class ExtendedStatusController ( wsgi . Controller ) : def __init__ ( self , * args , ** kwargs ) : ", "answer": "super ( ExtendedStatusController , self ) . __init__ ( * args , ** kwargs )"}, {"prompt": " import time from random import randint ", "answer": "from tests . utils . benchmark import Benchmark , BenchmarkData"}, {"prompt": " \"\"\"\"\"\" from . no_load import NoLoadScenario from . read_request_load import read_request_load_scenario from . write_request_load import ( write_request_load_scenario , DatasetCreationTimeout , ) from . _request_load import ( RequestRateTooLow , RequestRateNotReached , RequestOverload , NoNodesFound , RequestScenarioAlreadyStarted , ) __all__ = [ ", "answer": "'' ,"}, {"prompt": " \"\"\"\"\"\" from __future__ import ( absolute_import , division , print_function , unicode_literals ) import logging from os . path import abspath , dirname , join , realpath , relpath from sys import path import pytest logger = logging . getLogger ( __name__ ) test_dir = realpath ( dirname ( __file__ ) ) ", "answer": "src_dir = abspath ( join ( test_dir , '' ) )"}, {"prompt": " import rospy , actionlib from control_msgs . msg import ( FollowJointTrajectoryAction , FollowJointTrajectoryGoal ) from trajectory_msgs . msg import JointTrajectory , JointTrajectoryPoint arm_joint_names = [ \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ] arm_intermediate_positions = [ , , - , , , , ] arm_joint_positions = [ , , - , , , , ] if __name__ == \"\" : rospy . init_node ( \"\" ) arm_client = actionlib . SimpleActionClient ( \"\" , FollowJointTrajectoryAction ) ", "answer": "arm_client . wait_for_server ( )"}, {"prompt": " import nova . scheduler from nova . scheduler . filters import abstract_filter class AllHostsFilter ( abstract_filter . AbstractHostFilter ) : \"\"\"\"\"\" def instance_type_to_filter ( self , instance_type ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " from django . db . backends . postgresql . base import quote_name def get_table_list ( cursor ) : \"\" cursor . execute ( \"\"\"\"\"\" ) return [ row [ ] for row in cursor . fetchall ( ) ] def get_table_description ( cursor , table_name ) : \"\" cursor . execute ( \"\" % quote_name ( table_name ) ) return cursor . description def get_relations ( cursor , table_name ) : \"\"\"\"\"\" cursor . execute ( \"\"\"\"\"\" , [ table_name ] ) relations = { } for row in cursor . fetchall ( ) : try : ", "answer": "relations [ int ( row [ ] [ : - ] ) - ] = ( int ( row [ ] [ : - ] ) - , row [ ] )"}, {"prompt": " from __future__ import unicode_literals import copy import datetime from django . db import models from django . utils . functional import curry from django . utils . translation import ugettext_lazy as _ from django . conf import settings from audit_log . models . fields import LastUserField from audit_log import settings as local_settings try : from django . utils . timezone import now as datetime_now assert datetime_now except ImportError : import datetime datetime_now = datetime . datetime . now class LogEntryObjectDescriptor ( object ) : def __init__ ( self , model ) : self . model = model def __get__ ( self , instance , owner ) : kwargs = dict ( ( f . attname , getattr ( instance , f . attname ) ) for f in self . model . _meta . fields if hasattr ( instance , f . attname ) ) return self . model ( ** kwargs ) class AuditLogManager ( models . Manager ) : def __init__ ( self , model , attname , instance = None , ) : super ( AuditLogManager , self ) . __init__ ( ) self . model = model self . instance = instance self . attname = attname if instance is not None and not hasattr ( instance , '' % attname ) : setattr ( instance , '' % attname , True ) def enable_tracking ( self ) : if self . instance is None : raise ValueError ( \"\" \"\" ) setattr ( self . instance , '' % self . attname , True ) def disable_tracking ( self ) : if self . instance is None : raise ValueError ( \"\" \"\" ) setattr ( self . instance , '' % self . attname , False ) def is_tracking_enabled ( self ) : if local_settings . DISABLE_AUDIT_LOG : return False if self . instance is None : raise ValueError ( \"\" \"\" ) return getattr ( self . instance , '' % self . attname ) def get_queryset ( self ) : if self . instance is None : return super ( AuditLogManager , self ) . get_queryset ( ) f = { self . instance . _meta . pk . name : self . instance . pk } return super ( AuditLogManager , self ) . get_queryset ( ) . filter ( ** f ) class AuditLogDescriptor ( object ) : def __init__ ( self , model , manager_class , attname ) : self . model = model self . manager_class = manager_class self . attname = attname def __get__ ( self , instance , owner ) : if instance is None : return self . manager_class ( self . model , self . attname ) return self . manager_class ( self . model , self . attname , instance ) class AuditLog ( object ) : manager_class = AuditLogManager def __init__ ( self , exclude = [ ] ) : self . _exclude = exclude def contribute_to_class ( self , cls , name ) : self . manager_name = name models . signals . class_prepared . connect ( self . finalize , sender = cls ) def create_log_entry ( self , instance , action_type ) : manager = getattr ( instance , self . manager_name ) attrs = { } for field in instance . _meta . fields : if field . attname not in self . _exclude : attrs [ field . attname ] = getattr ( instance , field . attname ) manager . create ( action_type = action_type , ** attrs ) def post_save ( self , instance , created , ** kwargs ) : if getattr ( instance , self . manager_name ) . is_tracking_enabled ( ) : self . create_log_entry ( instance , created and '' or '' ) def post_delete ( self , instance , ** kwargs ) : if getattr ( instance , self . manager_name ) . is_tracking_enabled ( ) : self . create_log_entry ( instance , '' ) def finalize ( self , sender , ** kwargs ) : log_entry_model = self . create_log_entry_model ( sender ) models . signals . post_save . connect ( self . post_save , sender = sender , weak = False ) models . signals . post_delete . connect ( self . post_delete , sender = sender , weak = False ) descriptor = AuditLogDescriptor ( log_entry_model , self . manager_class , self . manager_name ) setattr ( sender , self . manager_name , descriptor ) def copy_fields ( self , model ) : \"\"\"\"\"\" fields = { '' : model . __module__ } for field in model . _meta . fields : if not field . name in self . _exclude : field = copy . deepcopy ( field ) if isinstance ( field , models . AutoField ) : field . __class__ = models . IntegerField if field . primary_key : field . serialize = True if isinstance ( field , models . OneToOneField ) : ", "answer": "field . __class__ = models . ForeignKey"}, {"prompt": " import pyglet . app ", "answer": "from pycraft . window import Window"}, {"prompt": " import os import sys import textwrap import pytest from tests . lib import ( assert_all_changes , pyversion , _create_test_package , _change_test_package_version , ) from tests . lib . local_repos import local_checkout def test_no_upgrade_unless_requested ( script ) : \"\"\"\"\"\" script . pip ( '' , '' , expect_error = True ) result = script . pip ( '' , '' , expect_error = True ) assert not result . files_created , ( '' ) @ pytest . mark . network def test_upgrade_to_specific_version ( script ) : \"\"\"\"\"\" script . pip ( '' , '' , expect_error = True ) result = script . pip ( '' , '' , expect_error = True ) assert result . files_created , ( '' ) assert ( script . site_packages / '' % pyversion in result . files_deleted ) assert ( script . site_packages / '' % pyversion in result . files_created ) @ pytest . mark . network def test_upgrade_if_requested ( script ) : \"\"\"\"\"\" script . pip ( '' , '' , expect_error = True ) result = script . pip ( '' , '' , '' , expect_error = True ) ", "answer": "assert result . files_created , ''"}, {"prompt": " from __future__ import print_function from builtins import object import re import difflib COLUMN_NAMES = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' } class Pin ( object ) : pass DEFAULT_PIN = Pin ( ) DEFAULT_PIN . num = None DEFAULT_PIN . name = '' DEFAULT_PIN . type = '' DEFAULT_PIN . style = '' DEFAULT_PIN . unit = DEFAULT_PIN . side = '' def num_row_elements ( row ) : '''''' try : rowset = set ( row ) rowset . discard ( '' ) return len ( rowset ) except TypeError : return def get_nonblank_row ( csv_reader ) : '''''' for row in csv_reader : if num_row_elements ( row ) > : return row return None def get_part_num ( csv_reader ) : '''''' part_num = get_nonblank_row ( csv_reader ) try : part_num = set ( part_num ) part_num . discard ( '' ) return part_num . pop ( ) except TypeError : return None def find_closest_match ( name , name_dict , fuzzy_match , threshold = ) : '''''' scrubber = re . compile ( '' ) name = scrubber . sub ( '' , name ) . lower ( ) if fuzzy_match == False : return name_dict [ name ] match = difflib . get_close_matches ( name , list ( name_dict . keys ( ) ) , , threshold ) [ ] return name_dict [ match ] def clean_headers ( headers ) : '''''' return [ find_closest_match ( h , COLUMN_NAMES , True ) for h in headers ] def issue ( msg , level = '' ) : if level == '' : print ( '' . format ( msg ) ) elif level == '' : print ( '' . format ( msg ) ) raise Exception ( '' ) else : ", "answer": "print ( msg )"}, {"prompt": " from mock import patch from nose . tools import istest from provy . more . debian import ApacheRole , AptitudeRole from tests . unit . tools . helpers import ProvyTestCase class ApacheRoleTest ( ProvyTestCase ) : def setUp ( self ) : super ( ApacheRoleTest , self ) . setUp ( ) self . role = ApacheRole ( prov = None , context = { } ) @ istest def installs_necessary_packages_to_provision ( self ) : with self . using_stub ( AptitudeRole ) as aptitude : self . role . provision ( ) aptitude . ensure_package_installed . assert_called_with ( '' ) @ istest def ensures_module_is_installed_and_enabled ( self ) : with self . using_stub ( AptitudeRole ) as aptitude , self . execute_mock ( ) as execute : self . role . ensure_mod ( '' ) aptitude . ensure_package_installed . assert_called_with ( '' ) execute . assert_called_with ( '' , sudo = True ) self . assertTrue ( self . role . must_restart ) @ istest def ensures_site_is_available_from_template ( self ) : with self . execute_mock ( ) , self . mock_role_method ( '' ) as update_file , self . mock_role_method ( '' ) : self . role . create_site ( '' , template = '' ) update_file . assert_called_with ( '' , '' , options = { } , sudo = True ) self . assertTrue ( self . role . must_restart ) @ istest def ensures_site_is_available_from_template_and_options ( self ) : with self . execute_mock ( ) , self . mock_role_method ( '' ) as update_file , self . mock_role_method ( '' ) : self . role . create_site ( '' , template = '' , options = { '' : '' } ) update_file . assert_called_with ( '' , '' , options = { '' : '' } , sudo = True ) self . assertTrue ( self . role . must_restart ) @ istest def ensures_that_a_website_is_enabled ( self ) : with self . mock_role_method ( '' ) as remote_symlink : self . role . ensure_site_enabled ( '' ) remote_symlink . assert_called_with ( from_file = '' , to_file = '' , sudo = True ) self . assertTrue ( self . role . must_restart ) @ istest def ensures_that_a_website_is_disabled ( self ) : with self . mock_role_method ( '' ) as remove_file : self . role . ensure_site_disabled ( '' ) remove_file . assert_called_with ( '' , sudo = True ) self . assertTrue ( self . role . must_restart ) @ istest def can_be_restarted ( self ) : with self . execute_mock ( ) as execute : self . role . restart ( ) execute . assert_called_with ( '' , sudo = True ) @ istest def ensures_that_it_must_be_restarted ( self ) : self . assertFalse ( self . role . must_restart ) ", "answer": "self . role . ensure_restart ( )"}, {"prompt": " \"\"\"\"\"\" import os import spf import sys def main ( ) : if len ( sys . argv ) != : print ( '' + os . path . basename ( __file__ ) + '' ) sys . exit ( ) result , explanation = spf . check2 ( sys . argv [ ] , sys . argv [ ] , sys . argv [ ] ) print ( '' + os . path . basename ( __file__ ) + '' + result + '' + explanation + '' ) ", "answer": "if result == '' :"}, {"prompt": " try : import urllib . parse import urllib . request import urllib . error except ImportError : import urllib2 import urllib import json class MesoPyError ( Exception ) : def __init__ ( self , error_message ) : self . error_message = error_message def __str__ ( self ) : r\"\"\"\"\"\" return repr ( self . error_message ) class Meso ( object ) : def __init__ ( self , token ) : ", "answer": "r\"\"\"\"\"\""}, {"prompt": " from django . conf . urls import patterns , include , url urlpatterns = patterns ( ", "answer": "'' ,"}, {"prompt": " class SimpleBunch ( dict ) : \"\"\"\"\"\" ", "answer": "def __init__ ( self , ** kwargs ) :"}, {"prompt": " from arcs import Arcs from utils import point_compare , is_point , Strut , mysterious_line_test class Line : def __init__ ( self , Q ) : self . arcs = Arcs ( Q ) def arc ( self , current_arc , last = False ) : n = len ( current_arc ) if last and not len ( self . line_arcs ) and n == : point = current_arc [ ] index = self . arcs . get_index ( point ) if len ( index ) : self . line_arcs . append ( index [ ] ) else : index . append ( self . arcs . length ) self . line_arcs . append ( index [ ] ) self . arcs . push ( current_arc ) elif n > : self . line_arcs . append ( self . arcs . check ( current_arc ) ) def line ( self , points , opened ) : self . line_arcs = [ ] ; n = len ( points ) current_arc = Strut ( ) k = p = False t = False if not opened : points . pop ( ) n -= while k < n : t = self . arcs . peak ( points [ k ] ) if opened : break if p and not mysterious_line_test ( p , t ) : tInP = all ( map ( lambda line : line in p , t ) ) pInT = all ( map ( lambda line : line in t , p ) ) if tInP and not pInT : k -= break p = t k += if k == n and isinstance ( p , list ) and len ( p ) > : point0 = points [ ] i = k = while i < n : point = points [ i ] ; if point_compare ( point0 , point ) > : point0 = point k = i i += ", "answer": "i = - "}, {"prompt": " \"\"\"\"\"\" import copy import mock from oslo_context import context as o_context from oslo_context import fixture as o_fixture from nova . compute import flavors from nova . compute import task_states from nova . compute import vm_states from nova import context from nova import exception from nova import notifications from nova import objects from nova . objects import base as obj_base from nova import test from nova . tests . unit import fake_network from nova . tests . unit import fake_notifier class NotificationsTestCase ( test . TestCase ) : def setUp ( self ) : super ( NotificationsTestCase , self ) . setUp ( ) self . fixture = self . useFixture ( o_fixture . ClearRequestContext ( ) ) self . net_info = fake_network . fake_get_instance_nw_info ( self , , ) def fake_get_nw_info ( cls , ctxt , instance ) : self . assertTrue ( ctxt . is_admin ) return self . net_info self . stub_out ( '' , fake_get_nw_info ) fake_network . set_stub_network_methods ( self ) fake_notifier . stub_notifier ( self . stubs ) self . addCleanup ( fake_notifier . reset ) self . flags ( compute_driver = '' , network_manager = '' , notify_on_state_change = \"\" , host = '' ) self . flags ( api_servers = [ '' ] , group = '' ) self . user_id = '' self . project_id = '' self . context = context . RequestContext ( self . user_id , self . project_id ) self . instance = self . _wrapped_create ( ) self . decorated_function_called = False def _wrapped_create ( self , params = None ) : instance_type = flavors . get_flavor_by_name ( '' ) inst = objects . Instance ( image_ref = , user_id = self . user_id , project_id = self . project_id , instance_type_id = instance_type [ '' ] , root_gb = , ephemeral_gb = , access_ip_v4 = '' , access_ip_v6 = '' , display_name = '' , hostname = '' , node = '' , system_metadata = { } ) inst . _context = self . context if params : inst . update ( params ) inst . flavor = instance_type inst . create ( ) return inst def test_send_api_fault_disabled ( self ) : self . flags ( notify_api_faults = False ) notifications . send_api_fault ( \"\" , , None ) self . assertEqual ( , len ( fake_notifier . NOTIFICATIONS ) ) def test_send_api_fault ( self ) : self . flags ( notify_api_faults = True ) exception = None try : raise test . TestingException ( \"\" ) except test . TestingException as e : exception = e notifications . send_api_fault ( \"\" , , exception ) self . assertEqual ( , len ( fake_notifier . NOTIFICATIONS ) ) n = fake_notifier . NOTIFICATIONS [ ] self . assertEqual ( n . priority , '' ) self . assertEqual ( n . event_type , '' ) self . assertEqual ( n . payload [ '' ] , '' ) self . assertEqual ( n . payload [ '' ] , ) self . assertIsNotNone ( n . payload [ '' ] ) def test_send_api_fault_fresh_context ( self ) : self . flags ( notify_api_faults = True ) exception = None try : raise test . TestingException ( \"\" ) except test . TestingException as e : exception = e ctxt = context . RequestContext ( overwrite = True ) notifications . send_api_fault ( \"\" , , exception ) self . assertEqual ( , len ( fake_notifier . NOTIFICATIONS ) ) n = fake_notifier . NOTIFICATIONS [ ] self . assertEqual ( n . priority , '' ) self . assertEqual ( n . event_type , '' ) self . assertEqual ( n . payload [ '' ] , '' ) self . assertEqual ( n . payload [ '' ] , ) self . assertIsNotNone ( n . payload [ '' ] ) self . assertEqual ( ctxt , n . context ) def test_send_api_fault_fake_context ( self ) : self . flags ( notify_api_faults = True ) exception = None try : raise test . TestingException ( \"\" ) except test . TestingException as e : exception = e ctxt = o_context . get_current ( ) self . assertIsNotNone ( ctxt ) notifications . send_api_fault ( \"\" , , exception ) self . assertEqual ( , len ( fake_notifier . NOTIFICATIONS ) ) n = fake_notifier . NOTIFICATIONS [ ] self . assertEqual ( n . priority , '' ) self . assertEqual ( n . event_type , '' ) self . assertEqual ( n . payload [ '' ] , '' ) self . assertEqual ( n . payload [ '' ] , ) self . assertIsNotNone ( n . payload [ '' ] ) self . assertIsNotNone ( n . context ) self . assertEqual ( ctxt , n . context ) def test_send_api_fault_admin_context ( self ) : self . flags ( notify_api_faults = True ) exception = None try : raise test . TestingException ( \"\" ) except test . TestingException as e : exception = e self . fixture . _remove_cached_context ( ) self . assertIsNone ( o_context . get_current ( ) ) notifications . send_api_fault ( \"\" , , exception ) self . assertEqual ( , len ( fake_notifier . NOTIFICATIONS ) ) n = fake_notifier . NOTIFICATIONS [ ] self . assertEqual ( n . priority , '' ) self . assertEqual ( n . event_type , '' ) self . assertEqual ( n . payload [ '' ] , '' ) self . assertEqual ( n . payload [ '' ] , ) self . assertIsNotNone ( n . payload [ '' ] ) self . assertIsNotNone ( n . context ) self . assertTrue ( n . context . is_admin ) def test_notif_disabled ( self ) : self . flags ( notify_on_state_change = None ) old = copy . copy ( self . instance ) self . instance . vm_state = vm_states . ACTIVE old_vm_state = old [ '' ] new_vm_state = self . instance . vm_state old_task_state = old [ '' ] new_task_state = self . instance . task_state notifications . send_update_with_states ( self . context , self . instance , old_vm_state , new_vm_state , old_task_state , new_task_state , verify_states = True ) notifications . send_update ( self . context , old , self . instance ) self . assertEqual ( , len ( fake_notifier . NOTIFICATIONS ) ) def test_task_notif ( self ) : self . flags ( notify_on_state_change = \"\" ) old = copy . copy ( self . instance ) self . instance . task_state = task_states . SPAWNING old_vm_state = old [ '' ] new_vm_state = self . instance . vm_state old_task_state = old [ '' ] new_task_state = self . instance . task_state notifications . send_update_with_states ( self . context , self . instance , old_vm_state , new_vm_state , old_task_state , new_task_state , verify_states = True ) self . assertEqual ( , len ( fake_notifier . NOTIFICATIONS ) ) self . flags ( notify_on_state_change = \"\" ) notifications . send_update ( self . context , old , self . instance ) self . assertEqual ( , len ( fake_notifier . NOTIFICATIONS ) ) def test_send_no_notif ( self ) : old_vm_state = self . instance . vm_state new_vm_state = self . instance . vm_state old_task_state = self . instance . task_state new_task_state = self . instance . task_state notifications . send_update_with_states ( self . context , self . instance , old_vm_state , new_vm_state , old_task_state , new_task_state , service = \"\" , host = None , verify_states = True ) self . assertEqual ( , len ( fake_notifier . NOTIFICATIONS ) ) def test_send_on_vm_change ( self ) : old = obj_base . obj_to_primitive ( self . instance ) old [ '' ] = None self . instance . vm_state = vm_states . ACTIVE notifications . send_update ( self . context , old , self . instance ) self . assertEqual ( , len ( fake_notifier . NOTIFICATIONS ) ) notif = fake_notifier . NOTIFICATIONS [ ] self . assertEqual ( '' , notif . publisher_id ) def test_send_on_task_change ( self ) : old = obj_base . obj_to_primitive ( self . instance ) old [ '' ] = None self . instance . task_state = task_states . SPAWNING notifications . send_update ( self . context , old , self . instance ) self . assertEqual ( , len ( fake_notifier . NOTIFICATIONS ) ) def test_no_update_with_states ( self ) : notifications . send_update_with_states ( self . context , self . instance , vm_states . BUILDING , vm_states . BUILDING , task_states . SPAWNING , task_states . SPAWNING , verify_states = True ) self . assertEqual ( , len ( fake_notifier . NOTIFICATIONS ) ) def test_vm_update_with_states ( self ) : notifications . send_update_with_states ( self . context , self . instance , vm_states . BUILDING , vm_states . ACTIVE , task_states . SPAWNING , task_states . SPAWNING , verify_states = True ) self . assertEqual ( , len ( fake_notifier . NOTIFICATIONS ) ) notif = fake_notifier . NOTIFICATIONS [ ] payload = notif . payload access_ip_v4 = str ( self . instance . access_ip_v4 ) access_ip_v6 = str ( self . instance . access_ip_v6 ) display_name = self . instance . display_name hostname = self . instance . hostname node = self . instance . node self . assertEqual ( vm_states . BUILDING , payload [ \"\" ] ) self . assertEqual ( vm_states . ACTIVE , payload [ \"\" ] ) self . assertEqual ( task_states . SPAWNING , payload [ \"\" ] ) self . assertEqual ( task_states . SPAWNING , payload [ \"\" ] ) self . assertEqual ( payload [ \"\" ] , access_ip_v4 ) self . assertEqual ( payload [ \"\" ] , access_ip_v6 ) self . assertEqual ( payload [ \"\" ] , display_name ) self . assertEqual ( payload [ \"\" ] , hostname ) self . assertEqual ( payload [ \"\" ] , node ) def test_task_update_with_states ( self ) : self . flags ( notify_on_state_change = \"\" ) notifications . send_update_with_states ( self . context , self . instance , vm_states . BUILDING , vm_states . BUILDING , task_states . SPAWNING , None , verify_states = True ) self . assertEqual ( , len ( fake_notifier . NOTIFICATIONS ) ) notif = fake_notifier . NOTIFICATIONS [ ] payload = notif . payload access_ip_v4 = str ( self . instance . access_ip_v4 ) access_ip_v6 = str ( self . instance . access_ip_v6 ) display_name = self . instance . display_name hostname = self . instance . hostname self . assertEqual ( vm_states . BUILDING , payload [ \"\" ] ) self . assertEqual ( vm_states . BUILDING , payload [ \"\" ] ) self . assertEqual ( task_states . SPAWNING , payload [ \"\" ] ) self . assertIsNone ( payload [ \"\" ] ) self . assertEqual ( payload [ \"\" ] , access_ip_v4 ) self . assertEqual ( payload [ \"\" ] , access_ip_v6 ) self . assertEqual ( payload [ \"\" ] , display_name ) self . assertEqual ( payload [ \"\" ] , hostname ) def test_update_no_service_name ( self ) : notifications . send_update_with_states ( self . context , self . instance , vm_states . BUILDING , vm_states . BUILDING , task_states . SPAWNING , None ) self . assertEqual ( , len ( fake_notifier . NOTIFICATIONS ) ) notif = fake_notifier . NOTIFICATIONS [ ] self . assertEqual ( '' , notif . publisher_id ) def test_update_with_service_name ( self ) : notifications . send_update_with_states ( self . context , self . instance , vm_states . BUILDING , vm_states . BUILDING , task_states . SPAWNING , None , service = \"\" ) self . assertEqual ( , len ( fake_notifier . NOTIFICATIONS ) ) notif = fake_notifier . NOTIFICATIONS [ ] self . assertEqual ( '' , notif . publisher_id ) def test_update_with_host_name ( self ) : notifications . send_update_with_states ( self . context , self . instance , vm_states . BUILDING , vm_states . BUILDING , task_states . SPAWNING , None , host = \"\" ) self . assertEqual ( , len ( fake_notifier . NOTIFICATIONS ) ) notif = fake_notifier . NOTIFICATIONS [ ] self . assertEqual ( '' , notif . publisher_id ) def test_payload_has_fixed_ip_labels ( self ) : info = notifications . info_from_instance ( self . context , self . instance , self . net_info , None ) self . assertIn ( \"\" , info ) self . assertEqual ( info [ \"\" ] [ ] [ \"\" ] , \"\" ) def test_payload_has_vif_mac_address ( self ) : info = notifications . info_from_instance ( self . context , self . instance , self . net_info , None ) self . assertIn ( \"\" , info ) self . assertEqual ( self . net_info [ ] [ '' ] , info [ \"\" ] [ ] [ \"\" ] ) def test_payload_has_cell_name_empty ( self ) : info = notifications . info_from_instance ( self . context , self . instance , self . net_info , None ) self . assertIn ( \"\" , info ) self . assertIsNone ( self . instance . cell_name ) self . assertEqual ( \"\" , info [ \"\" ] ) def test_payload_has_cell_name ( self ) : self . instance . cell_name = \"\" info = notifications . info_from_instance ( self . context , self . instance , self . net_info , None ) self . assertIn ( \"\" , info ) self . assertEqual ( \"\" , info [ \"\" ] ) def test_payload_has_progress_empty ( self ) : info = notifications . info_from_instance ( self . context , self . instance , self . net_info , None ) self . assertIn ( \"\" , info ) self . assertIsNone ( self . instance . progress ) self . assertEqual ( \"\" , info [ \"\" ] ) def test_payload_has_progress ( self ) : self . instance . progress = info = notifications . info_from_instance ( self . context , self . instance , self . net_info , None ) self . assertIn ( \"\" , info ) self . assertEqual ( , info [ \"\" ] ) def test_send_access_ip_update ( self ) : notifications . send_update ( self . context , self . instance , self . instance ) self . assertEqual ( , len ( fake_notifier . NOTIFICATIONS ) ) notif = fake_notifier . NOTIFICATIONS [ ] payload = notif . payload access_ip_v4 = str ( self . instance . access_ip_v4 ) access_ip_v6 = str ( self . instance . access_ip_v6 ) self . assertEqual ( payload [ \"\" ] , access_ip_v4 ) self . assertEqual ( payload [ \"\" ] , access_ip_v6 ) def test_send_name_update ( self ) : param = { \"\" : \"\" } new_name_inst = self . _wrapped_create ( params = param ) notifications . send_update ( self . context , self . instance , new_name_inst ) self . assertEqual ( , len ( fake_notifier . NOTIFICATIONS ) ) notif = fake_notifier . NOTIFICATIONS [ ] payload = notif . payload old_display_name = self . instance . display_name new_display_name = new_name_inst . display_name self . assertEqual ( payload [ \"\" ] , old_display_name ) self . assertEqual ( payload [ \"\" ] , new_display_name ) def test_send_no_state_change ( self ) : called = [ False ] def sending_no_state_change ( context , instance , ** kwargs ) : called [ ] = True self . stub_out ( '' , sending_no_state_change ) notifications . send_update ( self . context , self . instance , self . instance ) self . assertTrue ( called [ ] ) def test_fail_sending_update ( self ) : def fail_sending ( context , instance , ** kwargs ) : raise Exception ( '' ) self . stub_out ( '' , fail_sending ) notifications . send_update ( self . context , self . instance , self . instance ) self . assertEqual ( , len ( fake_notifier . NOTIFICATIONS ) ) @ mock . patch . object ( notifications . LOG , '' ) def test_fail_sending_update_instance_not_found ( self , mock_log_exception ) : notfound = exception . InstanceNotFound ( instance_id = self . instance . uuid ) with mock . patch . object ( notifications , '' , side_effect = notfound ) : notifications . send_update ( self . context , self . instance , self . instance ) self . assertEqual ( , len ( fake_notifier . NOTIFICATIONS ) ) self . assertEqual ( , mock_log_exception . call_count ) @ mock . patch . object ( notifications . LOG , '' ) def test_fail_send_update_with_states_inst_not_found ( self , mock_log_exception ) : notfound = exception . InstanceNotFound ( instance_id = self . instance . uuid ) with mock . patch . object ( notifications , '' , side_effect = notfound ) : notifications . send_update_with_states ( self . context , self . instance , vm_states . BUILDING , vm_states . ERROR , task_states . NETWORKING , new_task_state = None ) self . assertEqual ( , len ( fake_notifier . NOTIFICATIONS ) ) self . assertEqual ( , mock_log_exception . call_count ) def _decorated_function ( self , arg1 , arg2 ) : self . decorated_function_called = True def test_notify_decorator ( self ) : func_name = self . _decorated_function . __name__ self . _decorated_function = notifications . notify_decorator ( func_name , self . _decorated_function ) ctxt = o_context . RequestContext ( ) self . _decorated_function ( , ctxt ) self . assertEqual ( , len ( fake_notifier . NOTIFICATIONS ) ) n = fake_notifier . NOTIFICATIONS [ ] self . assertEqual ( n . priority , '' ) self . assertEqual ( n . event_type , func_name ) self . assertEqual ( n . context , ctxt ) self . assertTrue ( self . decorated_function_called ) class NotificationsFormatTestCase ( test . NoDBTestCase ) : def test_state_computation ( self ) : instance = { '' : mock . sentinel . vm_state , '' : mock . sentinel . task_state } states = notifications . _compute_states_payload ( instance ) self . assertEqual ( mock . sentinel . vm_state , states [ '' ] ) self . assertEqual ( mock . sentinel . vm_state , states [ '' ] ) self . assertEqual ( mock . sentinel . task_state , states [ '' ] ) self . assertEqual ( mock . sentinel . task_state , states [ '' ] ) states = notifications . _compute_states_payload ( instance , old_vm_state = mock . sentinel . old_vm_state , ) self . assertEqual ( mock . sentinel . vm_state , states [ '' ] ) self . assertEqual ( mock . sentinel . old_vm_state , states [ '' ] ) self . assertEqual ( mock . sentinel . task_state , states [ '' ] ) self . assertEqual ( mock . sentinel . task_state , states [ '' ] ) ", "answer": "states = notifications . _compute_states_payload ("}, {"prompt": " from __future__ import print_function from builtins import str from builtins import range import pyGPs from pyGPs . Validation import valid import numpy as np print ( '' ) print ( '' ) data_source = \"\" x = [ ] y = [ ] with open ( data_source ) as f : for index , line in enumerate ( f ) : feature = line . split ( '' ) ", "answer": "attr = feature [ : - ]"}, {"prompt": " import collections import six from magnumclient . common import cliutils from magnumclient . common import utils from magnumclient import exceptions as exc from magnumclient . tests import utils as test_utils class CommonFiltersTest ( test_utils . BaseTestCase ) : def test_limit ( self ) : result = utils . common_filters ( limit = ) self . assertEqual ( [ '' ] , result ) def test_limit_0 ( self ) : result = utils . common_filters ( limit = ) self . assertEqual ( [ '' ] , result ) def test_limit_negative_number ( self ) : result = utils . common_filters ( limit = - ) self . assertEqual ( [ '' ] , result ) def test_other ( self ) : for key in ( '' , '' , '' ) : result = utils . common_filters ( ** { key : '' } ) self . assertEqual ( [ '' % key ] , result ) class SplitAndDeserializeTest ( test_utils . BaseTestCase ) : def test_split_and_deserialize ( self ) : ret = utils . split_and_deserialize ( '' ) ", "answer": "self . assertEqual ( ( '' , '' ) , ret )"}, {"prompt": " import select import logging import time import socket import cPickle as pickle from multiprocessing import Process , Pipe from functools import partial try : import errno except ImportError : errno = None EINTR = getattr ( errno , '' , ) import monocle from monocle import _o , Return , launch from monocle . core import Callback from monocle . stack . network import add_service , Client from monocle . stack . multiprocess import PipeChannel , SocketChannel , get_conn , make_subchannels , Service log = logging . getLogger ( \"\" ) subproc_formatter = logging . Formatter ( \"\" ) @ _o def log_receive ( chan ) : root = logging . getLogger ( '' ) while True : levelno , msg = yield chan . recv ( ) for h in root . handlers : h . old_formatter = h . formatter h . setFormatter ( subproc_formatter ) log . log ( levelno , msg ) for h in root . handlers : h . setFormatter ( h . old_formatter ) class SyncSockChannel ( object ) : def __init__ ( self , sock ) : self . sock = sock def _sendall ( self , data ) : while data : try : r = self . sock . send ( data ) except socket . error , e : if e . args [ ] == EINTR : continue raise data = data [ r : ] def _recv ( self , count ) : result = \"\" while count : try : data = self . sock . recv ( min ( count , ) ) except socket . error , e : if e . args [ ] == EINTR : continue raise else : count -= len ( data ) result += data return result def send ( self , value ) : p = pickle . dumps ( value ) self . _sendall ( str ( len ( p ) ) ) self . _sendall ( \"\" ) self . _sendall ( p ) def recv ( self ) : l = \"\" while True : x = self . _recv ( ) if x == \"\" : break l += x l = int ( l ) p = self . _recv ( l ) try : value = pickle . loads ( p ) except Exception : log . exception ( \"\" , p ) raise return value def poll ( self ) : r , w , x = select . select ( [ self . sock ] , [ ] , [ self . sock ] , ) if r + x : log . info ( \"\" ) return True else : return False class SockChannelHandler ( logging . Handler ) : def __init__ ( self , sock ) : logging . Handler . __init__ ( self ) self . sock = sock def setFormatter ( self , formatter ) : self . formatter = formatter def send ( self , record ) : if record . args and isinstance ( record . args , tuple ) : args = record . args new_args = [ ] for arg in args : if isinstance ( arg , str ) : new_args . append ( arg . decode ( '' , '' ) ) else : new_args . append ( arg ) record . args = tuple ( new_args ) self . sock . send ( ( record . levelno , self . formatter . format ( record ) ) ) def emit ( self , record ) : try : self . send ( record ) except ( KeyboardInterrupt , SystemExit ) : raise except : self . handleError ( record ) def close ( self ) : logging . Handler . close ( self ) class SyncSockSubchan ( object ) : def __init__ ( self , chan , subchan ) : self . chan = chan self . subchan = subchan def send ( self , value ) : return self . chan . send ( { '' : self . subchan , '' : value } ) def recv ( self ) : value = self . chan . recv ( ) assert value [ '' ] == self . subchan return value [ '' ] def poll ( self ) : return self . chan . poll ( ) def _wrapper_with_sockets ( target , port , * args , ** kwargs ) : sock = socket . socket ( ) while True : try : sock . connect ( ( '' , port ) ) except Exception , e : print \"\" , port , type ( e ) , str ( e ) time . sleep ( ) sock . close ( ) sock = socket . socket ( ) else : break ", "answer": "try :"}, {"prompt": " \"\"\"\"\"\" import json import unittest from cloudcafe . compute . common . models . metadata import Metadata , MetadataItem class MetadataModelTest ( unittest . TestCase ) : @ classmethod def setUpClass ( cls ) : cls . metadata = Metadata ( ) cls . metadata [ '' ] = '' cls . expected_xml = ( '' '' '' '' ) cls . expected_json = json . dumps ( { '' : { '' : '' } } ) def test_metadata_xml_serialization ( self ) : serialized_metadata = self . metadata . serialize ( '' ) self . assertEqual ( serialized_metadata , self . expected_xml ) def test_metadata_xml_deserialization ( self ) : metadata = Metadata . deserialize ( self . expected_xml , '' ) self . assertIsNotNone ( metadata ) self . assertEqual ( metadata . get ( '' ) , '' ) def test_metadata_json_serialization ( self ) : serialized_metadata = self . metadata . serialize ( '' ) self . assertEqual ( serialized_metadata , self . expected_json ) def test_metadata_json_deserialization ( self ) : metadata = Metadata . deserialize ( self . expected_json , '' ) self . assertIsNotNone ( metadata ) self . assertEqual ( metadata . get ( '' ) , '' ) class MetadataItemModelTest ( unittest . TestCase ) : @ classmethod def setUpClass ( cls ) : ", "answer": "cls . meta_item = MetadataItem ( )"}, {"prompt": " import base64 import re from oslo_config import cfg from oslo_log import log as logging import oslo_messaging as messaging from oslo_utils import strutils from oslo_utils import timeutils from oslo_utils import uuidutils import six import stevedore import webob from webob import exc from nova . api . openstack import api_version_request from nova . api . openstack import common from nova . api . openstack . compute . schemas import servers as schema_servers from nova . api . openstack . compute . views import servers as views_servers from nova . api . openstack import extensions from nova . api . openstack import wsgi from nova . api import validation from nova import compute from nova . compute import flavors from nova import exception from nova . i18n import _ from nova . i18n import _LW from nova . image import glance from nova import objects from nova import utils ALIAS = '' CONF = cfg . CONF CONF . import_opt ( '' , '' ) CONF . import_opt ( '' , '' ) CONF . import_opt ( '' , '' , group = '' ) CONF . import_opt ( '' , '' , group = '' ) LOG = logging . getLogger ( __name__ ) authorize = extensions . os_compute_authorizer ( ALIAS ) class ServersController ( wsgi . Controller ) : \"\"\"\"\"\" EXTENSION_CREATE_NAMESPACE = '' EXTENSION_REBUILD_NAMESPACE = '' EXTENSION_UPDATE_NAMESPACE = '' EXTENSION_RESIZE_NAMESPACE = '' _view_builder_class = views_servers . ViewBuilderV21 schema_server_create = schema_servers . base_create schema_server_update = schema_servers . base_update schema_server_rebuild = schema_servers . base_rebuild schema_server_resize = schema_servers . base_resize schema_server_create_v20 = schema_servers . base_create_v20 schema_server_update_v20 = schema_servers . base_update_v20 schema_server_rebuild_v20 = schema_servers . base_rebuild_v20 schema_server_create_v219 = schema_servers . base_create_v219 schema_server_update_v219 = schema_servers . base_update_v219 schema_server_rebuild_v219 = schema_servers . base_rebuild_v219 @ staticmethod def _add_location ( robj ) : if '' not in robj . obj : return robj link = [ l for l in robj . obj [ '' ] [ '' ] if l [ '' ] == '' ] if link : robj [ '' ] = utils . utf8 ( link [ ] [ '' ] ) return robj def __init__ ( self , ** kwargs ) : def _check_load_extension ( required_function ) : def should_load_extension ( ext ) : whitelist = CONF . osapi_v21 . extensions_whitelist blacklist = CONF . osapi_v21 . extensions_blacklist if not whitelist : if ext . obj . alias in blacklist : return False else : return True else : if ext . obj . alias in whitelist : if ext . obj . alias in blacklist : LOG . warning ( _LW ( \"\" \"\" ) , ext . obj . alias ) return False else : return True else : return False def check_load_extension ( ext ) : if isinstance ( ext . obj , extensions . V21APIExtensionBase ) : if hasattr ( ext . obj , required_function ) : LOG . debug ( '' '' , { '' : ext . obj . alias , '' : required_function } ) return should_load_extension ( ext ) else : LOG . debug ( '' , { '' : ext . obj . alias , '' : required_function } ) return False else : return False return check_load_extension self . extension_info = kwargs . pop ( '' ) super ( ServersController , self ) . __init__ ( ** kwargs ) self . compute_api = compute . API ( skip_policy_check = True ) self . create_extension_manager = stevedore . enabled . EnabledExtensionManager ( namespace = self . EXTENSION_CREATE_NAMESPACE , check_func = _check_load_extension ( '' ) , invoke_on_load = True , invoke_kwds = { \"\" : self . extension_info } , propagate_map_exceptions = True ) if not list ( self . create_extension_manager ) : LOG . debug ( \"\" ) self . rebuild_extension_manager = stevedore . enabled . EnabledExtensionManager ( namespace = self . EXTENSION_REBUILD_NAMESPACE , check_func = _check_load_extension ( '' ) , invoke_on_load = True , invoke_kwds = { \"\" : self . extension_info } , propagate_map_exceptions = True ) if not list ( self . rebuild_extension_manager ) : LOG . debug ( \"\" ) self . update_extension_manager = stevedore . enabled . EnabledExtensionManager ( namespace = self . EXTENSION_UPDATE_NAMESPACE , check_func = _check_load_extension ( '' ) , invoke_on_load = True , invoke_kwds = { \"\" : self . extension_info } , propagate_map_exceptions = True ) if not list ( self . update_extension_manager ) : LOG . debug ( \"\" ) self . resize_extension_manager = stevedore . enabled . EnabledExtensionManager ( namespace = self . EXTENSION_RESIZE_NAMESPACE , check_func = _check_load_extension ( '' ) , invoke_on_load = True , invoke_kwds = { \"\" : self . extension_info } , propagate_map_exceptions = True ) if not list ( self . resize_extension_manager ) : LOG . debug ( \"\" ) self . create_schema_manager = stevedore . enabled . EnabledExtensionManager ( namespace = self . EXTENSION_CREATE_NAMESPACE , check_func = _check_load_extension ( '' ) , invoke_on_load = True , invoke_kwds = { \"\" : self . extension_info } , propagate_map_exceptions = True ) if list ( self . create_schema_manager ) : self . create_schema_manager . map ( self . _create_extension_schema , self . schema_server_create_v219 , '' ) self . create_schema_manager . map ( self . _create_extension_schema , self . schema_server_create , '' ) self . create_schema_manager . map ( self . _create_extension_schema , self . schema_server_create_v20 , '' ) else : LOG . debug ( \"\" ) self . update_schema_manager = stevedore . enabled . EnabledExtensionManager ( namespace = self . EXTENSION_UPDATE_NAMESPACE , check_func = _check_load_extension ( '' ) , invoke_on_load = True , invoke_kwds = { \"\" : self . extension_info } , propagate_map_exceptions = True ) if list ( self . update_schema_manager ) : self . update_schema_manager . map ( self . _update_extension_schema , self . schema_server_update_v219 , '' ) self . update_schema_manager . map ( self . _update_extension_schema , self . schema_server_update , '' ) self . update_schema_manager . map ( self . _update_extension_schema , self . schema_server_update_v20 , '' ) else : LOG . debug ( \"\" ) self . rebuild_schema_manager = stevedore . enabled . EnabledExtensionManager ( namespace = self . EXTENSION_REBUILD_NAMESPACE , check_func = _check_load_extension ( '' ) , invoke_on_load = True , invoke_kwds = { \"\" : self . extension_info } , propagate_map_exceptions = True ) if list ( self . rebuild_schema_manager ) : self . rebuild_schema_manager . map ( self . _rebuild_extension_schema , self . schema_server_rebuild_v219 , '' ) self . rebuild_schema_manager . map ( self . _rebuild_extension_schema , self . schema_server_rebuild , '' ) self . rebuild_schema_manager . map ( self . _rebuild_extension_schema , self . schema_server_rebuild_v20 , '' ) else : LOG . debug ( \"\" ) self . resize_schema_manager = stevedore . enabled . EnabledExtensionManager ( namespace = self . EXTENSION_RESIZE_NAMESPACE , check_func = _check_load_extension ( '' ) , invoke_on_load = True , invoke_kwds = { \"\" : self . extension_info } , propagate_map_exceptions = True ) if list ( self . resize_schema_manager ) : self . resize_schema_manager . map ( self . _resize_extension_schema , self . schema_server_resize , '' ) else : LOG . debug ( \"\" ) @ extensions . expected_errors ( ( , ) ) def index ( self , req ) : \"\"\"\"\"\" context = req . environ [ '' ] authorize ( context , action = \"\" ) try : servers = self . _get_servers ( req , is_detail = False ) except exception . Invalid as err : raise exc . HTTPBadRequest ( explanation = err . format_message ( ) ) return servers @ extensions . expected_errors ( ( , ) ) def detail ( self , req ) : \"\"\"\"\"\" context = req . environ [ '' ] authorize ( context , action = \"\" ) try : servers = self . _get_servers ( req , is_detail = True ) except exception . Invalid as err : raise exc . HTTPBadRequest ( explanation = err . format_message ( ) ) return servers def _get_servers ( self , req , is_detail ) : \"\"\"\"\"\" search_opts = { } search_opts . update ( req . GET ) context = req . environ [ '' ] remove_invalid_options ( context , search_opts , self . _get_server_search_options ( req ) ) search_opts . pop ( '' , None ) if '' in req . GET . keys ( ) : statuses = req . GET . getall ( '' ) states = common . task_and_vm_state_from_status ( statuses ) vm_state , task_state = states if not vm_state and not task_state : return { '' : [ ] } search_opts [ '' ] = vm_state if '' not in task_state : search_opts [ '' ] = task_state if '' in search_opts : try : parsed = timeutils . parse_isotime ( search_opts [ '' ] ) except ValueError : msg = _ ( '' ) raise exc . HTTPBadRequest ( explanation = msg ) search_opts [ '' ] = parsed if '' not in search_opts : if '' not in search_opts : search_opts [ '' ] = False else : search_opts [ '' ] = strutils . bool_from_string ( search_opts [ '' ] , default = False ) if search_opts . get ( \"\" ) == [ '' ] : if context . is_admin : search_opts [ '' ] = True else : msg = _ ( \"\" ) raise exc . HTTPForbidden ( explanation = msg ) all_tenants = common . is_all_tenants ( search_opts ) search_opts . pop ( '' , None ) elevated = None if all_tenants : if is_detail : authorize ( context , action = \"\" ) else : authorize ( context , action = \"\" ) elevated = context . elevated ( ) else : if context . project_id : search_opts [ '' ] = context . project_id else : search_opts [ '' ] = context . user_id limit , marker = common . get_limit_and_marker ( req ) sort_keys , sort_dirs = common . get_sort_params ( req . params ) expected_attrs = [ '' ] if is_detail : expected_attrs = self . _view_builder . get_show_expected_attrs ( expected_attrs ) try : instance_list = self . compute_api . get_all ( elevated or context , search_opts = search_opts , limit = limit , marker = marker , want_objects = True , expected_attrs = expected_attrs , sort_keys = sort_keys , sort_dirs = sort_dirs ) except exception . MarkerNotFound : msg = _ ( '' ) % marker raise exc . HTTPBadRequest ( explanation = msg ) except exception . FlavorNotFound : LOG . debug ( \"\" , search_opts [ '' ] ) instance_list = objects . InstanceList ( ) if is_detail : instance_list . _context = context instance_list . fill_faults ( ) response = self . _view_builder . detail ( req , instance_list ) else : response = self . _view_builder . index ( req , instance_list ) req . cache_db_instances ( instance_list ) return response def _get_server ( self , context , req , instance_uuid , is_detail = False ) : \"\"\"\"\"\" expected_attrs = [ '' , '' , '' ] if is_detail : expected_attrs = self . _view_builder . get_show_expected_attrs ( expected_attrs ) instance = common . get_instance ( self . compute_api , context , instance_uuid , expected_attrs = expected_attrs ) req . cache_db_instance ( instance ) return instance def _get_requested_networks ( self , requested_networks ) : \"\"\"\"\"\" networks = [ ] network_uuids = [ ] for network in requested_networks : request = objects . NetworkRequest ( ) try : request . address = network . get ( '' , None ) request . port_id = network . get ( '' , None ) if request . port_id : request . network_id = None if not utils . is_neutron ( ) : msg = _ ( \"\" ) raise exc . HTTPBadRequest ( explanation = msg ) if request . address is not None : msg = _ ( \"\" \"\" \"\" ) % { \"\" : request . address , \"\" : request . port_id } raise exc . HTTPBadRequest ( explanation = msg ) else : request . network_id = network [ '' ] if ( not request . port_id and not uuidutils . is_uuid_like ( request . network_id ) ) : br_uuid = request . network_id . split ( '' , ) [ - ] if not uuidutils . is_uuid_like ( br_uuid ) : msg = _ ( \"\" \"\" \"\" ) % request . network_id raise exc . HTTPBadRequest ( explanation = msg ) if ( not utils . is_neutron ( ) and request . network_id and request . network_id in network_uuids ) : expl = ( _ ( \"\" \"\" ) % request . network_id ) raise exc . HTTPBadRequest ( explanation = expl ) network_uuids . append ( request . network_id ) networks . append ( request ) except KeyError as key : expl = _ ( '' ) % key raise exc . HTTPBadRequest ( explanation = expl ) except TypeError : expl = _ ( '' ) raise exc . HTTPBadRequest ( explanation = expl ) return objects . NetworkRequestList ( objects = networks ) B64_REGEX = re . compile ( '' '' '' ) def _decode_base64 ( self , data ) : data = re . sub ( r'' , '' , data ) if not self . B64_REGEX . match ( data ) : return None try : return base64 . b64decode ( data ) except TypeError : return None @ extensions . expected_errors ( ) def show ( self , req , id ) : \"\"\"\"\"\" context = req . environ [ '' ] authorize ( context , action = \"\" ) instance = self . _get_server ( context , req , id , is_detail = True ) return self . _view_builder . show ( req , instance ) @ wsgi . response ( ) @ extensions . expected_errors ( ( , , , ) ) @ validation . schema ( schema_server_create_v20 , '' , '' ) @ validation . schema ( schema_server_create , '' , '' ) @ validation . schema ( schema_server_create_v219 , '' ) def create ( self , req , body ) : \"\"\"\"\"\" context = req . environ [ '' ] server_dict = body [ '' ] password = self . _get_server_admin_password ( server_dict ) name = common . normalize_name ( server_dict [ '' ] ) if api_version_request . is_supported ( req , min_version = '' ) : if '' in server_dict : description = server_dict [ '' ] else : description = None else : description = name create_kwargs = { } if list ( self . create_extension_manager ) : self . create_extension_manager . map ( self . _create_extension_point , server_dict , create_kwargs , body ) availability_zone = create_kwargs . pop ( \"\" , None ) target = { '' : context . project_id , '' : context . user_id , '' : availability_zone } authorize ( context , target , '' ) parse_az = self . compute_api . parse_availability_zone availability_zone , host , node = parse_az ( context , availability_zone ) if host or node : authorize ( context , { } , '' ) block_device_mapping = create_kwargs . get ( \"\" ) if block_device_mapping : authorize ( context , target , '' ) image_uuid = self . _image_from_req_data ( server_dict , create_kwargs ) return_reservation_id = create_kwargs . pop ( '' , False ) requested_networks = None if ( '' in self . extension_info . get_extensions ( ) or utils . is_neutron ( ) ) : requested_networks = server_dict . get ( '' ) if requested_networks is not None : requested_networks = self . _get_requested_networks ( requested_networks ) if requested_networks and len ( requested_networks ) : authorize ( context , target , '' ) try : flavor_id = self . _flavor_id_from_req_data ( body ) except ValueError : msg = _ ( \"\" ) raise exc . HTTPBadRequest ( explanation = msg ) try : inst_type = flavors . get_flavor_by_flavor_id ( flavor_id , ctxt = context , read_deleted = \"\" ) ( instances , resv_id ) = self . compute_api . create ( context , inst_type , image_uuid , display_name = name , display_description = description , availability_zone = availability_zone , forced_host = host , forced_node = node , metadata = server_dict . get ( '' , { } ) , admin_password = password , requested_networks = requested_networks , check_server_group_quota = True , ** create_kwargs ) except ( exception . QuotaError , exception . PortLimitExceeded ) as error : raise exc . HTTPForbidden ( explanation = error . format_message ( ) ) except exception . ImageNotFound : msg = _ ( \"\" ) raise exc . HTTPBadRequest ( explanation = msg ) except exception . FlavorNotFound : msg = _ ( \"\" ) raise exc . HTTPBadRequest ( explanation = msg ) except exception . KeypairNotFound : msg = _ ( \"\" ) raise exc . HTTPBadRequest ( explanation = msg ) except exception . ConfigDriveInvalidValue : msg = _ ( \"\" ) raise exc . HTTPBadRequest ( explanation = msg ) except exception . ExternalNetworkAttachForbidden as error : raise exc . HTTPForbidden ( explanation = error . format_message ( ) ) except messaging . RemoteError as err : msg = \"\" % { '' : err . exc_type , '' : err . value } raise exc . HTTPBadRequest ( explanation = msg ) except UnicodeDecodeError as error : msg = \"\" % error raise exc . HTTPBadRequest ( explanation = msg ) except ( exception . ImageNotActive , exception . ImageBadRequest , exception . FixedIpNotFoundForAddress , exception . FlavorDiskTooSmall , exception . FlavorMemoryTooSmall , exception . InvalidMetadata , exception . InvalidRequest , exception . InvalidVolume , exception . MultiplePortsNotApplicable , exception . InvalidFixedIpAndMaxCountRequest , exception . InstanceUserDataMalformed , exception . InstanceUserDataTooLarge , exception . PortNotFound , exception . FixedIpAlreadyInUse , exception . SecurityGroupNotFound , exception . PortRequiresFixedIP , exception . NetworkRequiresSubnet , exception . NetworkNotFound , exception . NetworkDuplicated , exception . InvalidBDM , exception . InvalidBDMSnapshot , exception . InvalidBDMVolume , exception . InvalidBDMImage , exception . InvalidBDMBootSequence , exception . InvalidBDMLocalsLimit , exception . InvalidBDMVolumeNotBootable , exception . InvalidBDMEphemeralSize , exception . InvalidBDMFormat , exception . InvalidBDMSwapSize , exception . AutoDiskConfigDisabledByImage , exception . ImageNUMATopologyIncomplete , exception . ImageNUMATopologyForbidden , exception . ImageNUMATopologyAsymmetric , exception . ImageNUMATopologyCPUOutOfRange , exception . ImageNUMATopologyCPUDuplicates , exception . ImageNUMATopologyCPUsUnassigned , exception . ImageNUMATopologyMemoryOutOfRange , exception . InstanceGroupNotFound ) as error : raise exc . HTTPBadRequest ( explanation = error . format_message ( ) ) except ( exception . PortInUse , exception . InstanceExists , exception . NetworkAmbiguous , exception . NoUniqueMatch ) as error : raise exc . HTTPConflict ( explanation = error . format_message ( ) ) if return_reservation_id : return wsgi . ResponseObject ( { '' : resv_id } ) req . cache_db_instances ( instances ) server = self . _view_builder . create ( req , instances [ ] ) if CONF . enable_instance_password : server [ '' ] [ '' ] = password robj = wsgi . ResponseObject ( server ) return self . _add_location ( robj ) def _create_extension_point ( self , ext , server_dict , create_kwargs , req_body ) : handler = ext . obj LOG . debug ( \"\" , ext . obj ) handler . server_create ( server_dict , create_kwargs , req_body ) def _rebuild_extension_point ( self , ext , rebuild_dict , rebuild_kwargs ) : handler = ext . obj LOG . debug ( \"\" , ext . obj ) handler . server_rebuild ( rebuild_dict , rebuild_kwargs ) def _resize_extension_point ( self , ext , resize_dict , resize_kwargs ) : handler = ext . obj LOG . debug ( \"\" , ext . obj ) handler . server_resize ( resize_dict , resize_kwargs ) def _update_extension_point ( self , ext , update_dict , update_kwargs ) : handler = ext . obj LOG . debug ( \"\" , ext . obj ) handler . server_update ( update_dict , update_kwargs ) def _create_extension_schema ( self , ext , create_schema , version ) : handler = ext . obj LOG . debug ( \"\" , ext . obj ) schema = handler . get_server_create_schema ( version ) if ext . obj . name == '' : create_schema [ '' ] . update ( schema ) else : create_schema [ '' ] [ '' ] [ '' ] . update ( schema ) def _update_extension_schema ( self , ext , update_schema , version ) : handler = ext . obj LOG . debug ( \"\" , ext . obj ) schema = handler . get_server_update_schema ( version ) update_schema [ '' ] [ '' ] [ '' ] . update ( schema ) def _rebuild_extension_schema ( self , ext , rebuild_schema , version ) : handler = ext . obj LOG . debug ( \"\" , ext . obj ) schema = handler . get_server_rebuild_schema ( version ) rebuild_schema [ '' ] [ '' ] [ '' ] . update ( schema ) def _resize_extension_schema ( self , ext , resize_schema , version ) : handler = ext . obj LOG . debug ( \"\" , ext . obj ) schema = handler . get_server_resize_schema ( version ) resize_schema [ '' ] [ '' ] [ '' ] . update ( schema ) def _delete ( self , context , req , instance_uuid ) : authorize ( context , action = '' ) instance = self . _get_server ( context , req , instance_uuid ) if CONF . reclaim_instance_interval : try : self . compute_api . soft_delete ( context , instance ) except exception . InstanceInvalidState : self . compute_api . delete ( context , instance ) else : self . compute_api . delete ( context , instance ) @ extensions . expected_errors ( ( , ) ) @ validation . schema ( schema_server_update_v20 , '' , '' ) @ validation . schema ( schema_server_update , '' , '' ) @ validation . schema ( schema_server_update_v219 , '' ) def update ( self , req , id , body ) : \"\"\"\"\"\" ctxt = req . environ [ '' ] update_dict = { } authorize ( ctxt , action = '' ) if '' in body [ '' ] : update_dict [ '' ] = common . normalize_name ( body [ '' ] [ '' ] ) if '' in body [ '' ] : update_dict [ '' ] = body [ '' ] [ '' ] if list ( self . update_extension_manager ) : self . update_extension_manager . map ( self . _update_extension_point , body [ '' ] , update_dict ) instance = self . _get_server ( ctxt , req , id , is_detail = True ) try : instance . update ( update_dict ) instance . save ( ) return self . _view_builder . show ( req , instance , extend_address = False ) ", "answer": "except exception . InstanceNotFound :"}, {"prompt": " from __future__ import absolute_import , division , print_function , unicode_literals \"\"\"\"\"\" import math , random , time import demo import pi3d LOGGER = pi3d . Log . logger ( __name__ ) LOGGER . info ( \"\" \"\" \"\" \"\" \"\" ) DISPLAY = pi3d . Display . create ( w = , h = ) DISPLAY . set_background ( , , , ) pi3d . Light ( lightpos = ( , - , - ) , lightcol = ( , , ) , lightamb = ( , , ) ) shader = pi3d . Shader ( \"\" ) flatsh = pi3d . Shader ( \"\" ) tree2img = pi3d . Texture ( \"\" ) tree1img = pi3d . Texture ( \"\" ) hb2img = pi3d . Texture ( \"\" ) bumpimg = pi3d . Texture ( \"\" ) reflimg = pi3d . Texture ( \"\" ) ", "answer": "rockimg = pi3d . Texture ( \"\" )"}, {"prompt": " import copy from django . forms . utils import flatatt class HTMLElement ( object ) : \"\"\"\"\"\" def __init__ ( self ) : self . attrs = getattr ( self , \"\" , { } ) self . classes = getattr ( self , \"\" , [ ] ) def get_default_classes ( self ) : \"\"\"\"\"\" ", "answer": "return [ ]"}, {"prompt": " \"\"\"\"\"\" ", "answer": "from core . common import retrieve_content"}, {"prompt": " from __future__ import absolute_import , unicode_literals from django . test import TestCase from django . test . utils import override_settings from wagtail . contrib . wagtailfrontendcache . backends import ( BaseBackend , CloudflareBackend , HTTPBackend ) from wagtail . contrib . wagtailfrontendcache . utils import get_backends from wagtail . tests . testapp . models import EventIndex from wagtail . wagtailcore . models import Page class TestBackendConfiguration ( TestCase ) : def test_default ( self ) : backends = get_backends ( ) self . assertEqual ( len ( backends ) , ) def test_varnish ( self ) : backends = get_backends ( backend_settings = { '' : { '' : '' , '' : '' , } , } ) self . assertEqual ( set ( backends . keys ( ) ) , set ( [ '' ] ) ) self . assertIsInstance ( backends [ '' ] , HTTPBackend ) self . assertEqual ( backends [ '' ] . cache_scheme , '' ) self . assertEqual ( backends [ '' ] . cache_netloc , '' ) def test_cloudflare ( self ) : backends = get_backends ( backend_settings = { '' : { '' : '' , '' : '' , '' : '' , } , } ) self . assertEqual ( set ( backends . keys ( ) ) , set ( [ '' ] ) ) self . assertIsInstance ( backends [ '' ] , CloudflareBackend ) self . assertEqual ( backends [ '' ] . cloudflare_email , '' ) self . assertEqual ( backends [ '' ] . cloudflare_token , '' ) def test_multiple ( self ) : backends = get_backends ( backend_settings = { '' : { '' : '' , '' : '' , } , '' : { '' : '' , '' : '' , '' : '' , } } ) ", "answer": "self . assertEqual ( set ( backends . keys ( ) ) , set ( [ '' , '' ] ) )"}, {"prompt": " from __future__ import absolute_import , print_function , unicode_literals from cms . utils import get_language_list from django . contrib . sitemaps import Sitemap from parler . utils . context import smart_override from . . models import Post from . . settings import get_setting class BlogSitemap ( Sitemap ) : ", "answer": "def priority ( self , obj ) :"}, {"prompt": " import sys from django . conf import settings from django . core . exceptions import ImproperlyConfigured class Settings ( object ) : def __init__ ( self , ** kwargs ) : self . defaults = kwargs def __getattr__ ( self , key ) : return getattr ( settings , '' % key , self . defaults [ key ] ) up_settings = Settings ( REGISTRATION_FORM = '' , DOUBLE_CHECK_EMAIL = False , CHECK_UNIQUE_EMAIL = False , DOUBLE_CHECK_PASSWORD = False , REGISTRATION_FULLNAME = False , REGISTRATION_REDIRECT = '' , EMAIL_ONLY = False , AUTO_LOGIN = False , USE_ACCOUNT_VERIFICATION = False , ACCOUNT_VERIFICATION_DAYS = , USE_EMAIL_VERIFICATION = False , EMAIL_VERIFICATION_DAYS = , ", "answer": "EMAIL_VERIFICATION_DONE_URL = '' ,"}, {"prompt": " import re xpath_tokenizer = re . compile ( \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" ) . findall def prepare_tag ( next , token ) : tag = token [ ] def select ( context , result ) : for elem in result : for e in elem : if e . tag == tag : yield e return select def prepare_star ( next , token ) : def select ( context , result ) : for elem in result : for e in elem : yield e return select def prepare_dot ( next , token ) : def select ( context , result ) : for elem in result : yield elem return select def prepare_iter ( next , token ) : token = next ( ) if token [ ] == \"\" : tag = \"\" elif not token [ ] : tag = token [ ] else : raise SyntaxError def select ( context , result ) : for elem in result : for e in elem . iter ( tag ) : if e is not elem : yield e return select def prepare_dot_dot ( next , token ) : def select ( context , result ) : parent_map = context . parent_map if parent_map is None : context . parent_map = parent_map = { } for p in context . root . iter ( ) : for e in p : parent_map [ e ] = p for elem in result : if elem in parent_map : yield parent_map [ elem ] return select def prepare_predicate ( next , token ) : token = next ( ) if token [ ] == \"\" : token = next ( ) if token [ ] : raise SyntaxError ( \"\" ) key = token [ ] token = next ( ) if token [ ] == \"\" : def select ( context , result ) : for elem in result : ", "answer": "if elem . get ( key ) is not None :"}, {"prompt": " import unittest import easypost from constants import API_KEY as api_key easypost . api_key = api_key class UserTests ( unittest . TestCase ) : def test_child_user_create ( self ) : easypost . api_key = \"\" child_user = easypost . User . create ( name = '' , password = '' , password_confirmation = '' , ) child_id = child_user . id assert child_id is not None retrieved_user = easypost . User . retrieve ( child_id ) assert retrieved_user . id == child_id ", "answer": "assert retrieved_user . name == ''"}, {"prompt": " import unittest from datetime import datetime , timedelta import os import signal import time from threading import Thread from rq import Queue from rq . compat import as_text from rq . job import Job import warnings from rq_scheduler import Scheduler from rq_scheduler . utils import to_unix , from_unix , get_next_scheduled_time from tests import RQTestCase def say_hello ( name = None ) : \"\"\"\"\"\" if name is None : name = '' return '' % ( name , ) def tl ( l ) : return [ as_text ( i ) for i in l ] def simple_addition ( x , y , z ) : return x + y + z class TestScheduler ( RQTestCase ) : def setUp ( self ) : super ( TestScheduler , self ) . setUp ( ) self . scheduler = Scheduler ( connection = self . testconn ) def test_birth_and_death_registration ( self ) : \"\"\"\"\"\" key = Scheduler . scheduler_key self . assertNotIn ( key , tl ( self . testconn . keys ( '' ) ) ) scheduler = Scheduler ( connection = self . testconn , interval = ) scheduler . register_birth ( ) self . assertIn ( key , tl ( self . testconn . keys ( '' ) ) ) self . assertEqual ( self . testconn . ttl ( key ) , ) self . assertFalse ( self . testconn . hexists ( key , '' ) ) self . assertRaises ( ValueError , scheduler . register_birth ) scheduler . register_death ( ) self . assertTrue ( self . testconn . hexists ( key , '' ) ) def test_create_job ( self ) : \"\"\"\"\"\" job = self . scheduler . _create_job ( say_hello , args = ( ) , kwargs = { } ) job_from_queue = Job . fetch ( job . id , connection = self . testconn ) self . assertEqual ( job , job_from_queue ) self . assertEqual ( job_from_queue . func , say_hello ) def test_create_job_with_ttl ( self ) : \"\"\"\"\"\" job = self . scheduler . _create_job ( say_hello , ttl = , args = ( ) , kwargs = { } ) job_from_queue = Job . fetch ( job . id , connection = self . testconn ) self . assertEqual ( , job_from_queue . ttl ) def test_create_job_with_id ( self ) : \"\"\"\"\"\" job = self . scheduler . _create_job ( say_hello , id = '' , args = ( ) , kwargs = { } ) job_from_queue = Job . fetch ( job . id , connection = self . testconn ) self . assertEqual ( '' , job_from_queue . id ) def test_create_job_with_description ( self ) : \"\"\"\"\"\" job = self . scheduler . _create_job ( say_hello , description = '' , args = ( ) , kwargs = { } ) job_from_queue = Job . fetch ( job . id , connection = self . testconn ) self . assertEqual ( '' , job_from_queue . description ) def test_job_not_persisted_if_commit_false ( self ) : \"\"\"\"\"\" job = self . scheduler . _create_job ( say_hello , commit = False ) self . assertEqual ( self . testconn . hgetall ( job . key ) , { } ) def test_create_scheduled_job ( self ) : \"\"\"\"\"\" scheduled_time = datetime . utcnow ( ) job = self . scheduler . enqueue_at ( scheduled_time , say_hello ) self . assertEqual ( job , Job . fetch ( job . id , connection = self . testconn ) ) self . assertIn ( job . id , tl ( self . testconn . zrange ( self . scheduler . scheduled_jobs_key , , ) ) ) self . assertEqual ( self . testconn . zscore ( self . scheduler . scheduled_jobs_key , job . id ) , to_unix ( scheduled_time ) ) def test_enqueue_in ( self ) : \"\"\"\"\"\" right_now = datetime . utcnow ( ) time_delta = timedelta ( minutes = ) job = self . scheduler . enqueue_in ( time_delta , say_hello ) self . assertIn ( job . id , tl ( self . testconn . zrange ( self . scheduler . scheduled_jobs_key , , ) ) ) self . assertEqual ( self . testconn . zscore ( self . scheduler . scheduled_jobs_key , job . id ) , to_unix ( right_now + time_delta ) ) time_delta = timedelta ( hours = ) job = self . scheduler . enqueue_in ( time_delta , say_hello ) self . assertEqual ( self . testconn . zscore ( self . scheduler . scheduled_jobs_key , job . id ) , to_unix ( right_now + time_delta ) ) def test_get_jobs ( self ) : \"\"\"\"\"\" now = datetime . utcnow ( ) job = self . scheduler . enqueue_at ( now , say_hello ) self . assertIn ( job , self . scheduler . get_jobs ( now ) ) future_time = now + timedelta ( hours = ) job = self . scheduler . enqueue_at ( future_time , say_hello ) ", "answer": "self . assertIn ( job , self . scheduler . get_jobs ( timedelta ( hours = , seconds = ) ) )"}, {"prompt": " from BaseDC import * from BaseIP import * ", "answer": "from DCIPUtils import *"}, {"prompt": " from google . appengine . api import images from django import forms from app . models . upload import UploadModel ", "answer": "class UploadForm ( forms . ModelForm ) :"}, {"prompt": " import inspect from django . core . cache import cache from django . conf import settings from django . contrib . auth . models import User , AnonymousUser from django . db import models from django . contrib . contenttypes import generic from django . db . models . base import Model , ModelBase from django . contrib . contenttypes . models import ContentType from django . utils . translation import ugettext_lazy as _ from django . shortcuts import render_to_response from django . template import RequestContext from django . http import Http404 , HttpResponseRedirect from django . db . models import Q from django . core . paginator import Paginator , InvalidPage from django . template . loader import render_to_string from zorna . account . models import UserGroup from zorna import defines ACL_USERS_PERMISSIONS_CACHE = u\"\" ACL_GROUPS_PERMISSIONS_CACHE = u\"\" ACL_MODEL_CACHE = u\"\" def get_acl_for_model ( object ) : \"\"\"\"\"\" if inspect . isclass ( object ) : model = object else : model = object . __class__ permclass = type ( '' , ( BaseACL , ) , { '' : model } ) return permclass ( ) def register_acl_for_model ( model , verbs ) : content_type = ContentType . objects . get_for_model ( model ) amc = cache . get ( ACL_MODEL_CACHE ) if amc is None : amc = { } try : return amc [ content_type . pk ] except : perms = [ ] for k , v in verbs . iteritems ( ) : try : perm = ACLVerbPermission . objects . get ( codename = k , content_type = content_type ) except ACLVerbPermission . DoesNotExist : perm = ACLVerbPermission . objects . create ( name = v , content_type = content_type , codename = k ) perms . append ( perm ) amc [ content_type . pk ] = perms cache . set ( ACL_MODEL_CACHE , amc ) return amc [ content_type . pk ] def get_allowed_objects ( user , model , permission ) : if type ( permission ) is list : ao = set ( [ ] ) for perm in permission : ao = ao . union ( set ( ACLPermission . objects . get_acl_objects_by_model ( user , model , perm ) ) ) return list ( ao ) else : return ACLPermission . objects . get_acl_objects_by_model ( user , model , permission ) def get_acl_by_object ( object , permission ) : \"\"\"\"\"\" return ACLPermission . objects . get_acl_by_object ( object , permission ) def get_acl_groups_by_object ( object , permission ) : \"\"\"\"\"\" return ACLPermission . objects . get_acl_groups_by_object ( object , permission ) def get_acl_users_by_object ( object , permission ) : \"\"\"\"\"\" return ACLPermission . objects . get_acl_users_by_object ( object , permission ) class ACLVerbPermission ( models . Model ) : name = models . CharField ( _ ( '' ) , max_length = ) content_type = models . ForeignKey ( ContentType ) codename = models . CharField ( _ ( '' ) , max_length = ) class Meta : verbose_name = _ ( '' ) verbose_name_plural = _ ( '' ) unique_together = ( ( '' , '' ) , ) ordering = ( '' , '' , '' ) db_table = settings . TABLE_PREFIX + \"\" def __unicode__ ( self ) : return u\"\" % ( unicode ( self . content_type . app_label ) , unicode ( self . codename ) ) class ACLPermissionManager ( models . Manager ) : cache_childs_groups = { } def copy_permissions ( self , obj_source , perm_source , obj_target , perm_target ) : ct_src = ContentType . objects . get_for_model ( obj_source ) ct_target = ContentType . objects . get_for_model ( obj_target ) self . filter ( object_id = obj_target . pk , content_type = ct_target , permission__codename = perm_target ) . delete ( ) perms = self . filter ( object_id = obj_source . pk , content_type = ct_src , permission__codename = perm_source ) check = get_acl_for_model ( obj_target ) for p in perms : if p . user : check . add_perm ( perm_target , obj_target , p . user , p . acltype ) else : check . add_perm ( perm_target , obj_target , p . group , p . acltype ) def cache_acl_groups ( self , object ) : acl_groups_permissions = cache . get ( ACL_GROUPS_PERMISSIONS_CACHE ) if acl_groups_permissions is None : acl_groups_permissions = { } ct = ContentType . objects . get_for_model ( object ) acl_groups_permissions [ ct . pk ] = { } acl_groups_permissions [ ct . pk ] [ object . id ] = { } perms = self . filter ( group__isnull = False , object_id = object . pk , content_type = ct ) . values ( '' , '' , '' , '' , '' ) . order_by ( '' ) for p in perms : try : groups = acl_groups_permissions [ ct . pk ] [ object . id ] [ p [ '' ] ] except : groups = acl_groups_permissions [ ct . pk ] [ object . id ] [ p [ '' ] ] = [ ] if p [ '' ] > defines . ZORNA_GROUP_REGISTERED : if p [ '' ] == defines . ZORNA_PERMISSIONS_DENY_CHILDS or p [ '' ] == defines . ZORNA_PERMISSIONS_ALLOW_CHILDS : if p [ '' ] not in self . cache_childs_groups : self . cache_childs_groups [ p [ '' ] ] = UserGroup . objects . get ( pk = p [ '' ] ) . get_descendants ( True ) childs = self . cache_childs_groups [ p [ '' ] ] childs_id = [ g . pk for g in childs ] if p [ '' ] == defines . ZORNA_PERMISSIONS_DENY_CHILDS : groups = [ groups - childs_id for groups , childs_id in zip ( groups , childs_id ) ] else : groups . extend ( childs_id ) elif p [ '' ] == defines . ZORNA_PERMISSIONS_ALLOW : groups . append ( p [ '' ] ) else : groups = [ g for g in groups if g != p [ '' ] ] else : if p [ '' ] == defines . ZORNA_PERMISSIONS_ALLOW or p [ '' ] == defines . ZORNA_PERMISSIONS_ALLOW_CHILDS : groups . append ( p [ '' ] ) else : groups = [ g for g in groups if g != p [ '' ] ] acl_groups_permissions [ ct . pk ] [ object . id ] [ p [ '' ] ] = groups cache . set ( ACL_GROUPS_PERMISSIONS_CACHE , acl_groups_permissions ) return acl_groups_permissions def get_acl_groups_by_object ( self , object , permission ) : \"\"\"\"\"\" ct = ContentType . objects . get_for_model ( object ) acl_groups_permissions = cache . get ( ACL_GROUPS_PERMISSIONS_CACHE ) if acl_groups_permissions is None : acl_groups_permissions = self . cache_acl_groups ( object ) else : try : acl_groups_permissions [ ct . pk ] [ object . pk ] except KeyError : acl_groups_permissions = self . cache_acl_groups ( object ) try : return acl_groups_permissions [ ct . pk ] [ object . id ] [ permission ] except : return [ ] def get_acl_by_object ( self , object , permission ) : \"\"\"\"\"\" allowed_groups = self . get_acl_groups_by_object ( object , permission ) if defines . ZORNA_GROUP_PUBLIC in allowed_groups or defines . ZORNA_GROUP_REGISTERED in allowed_groups : members = User . objects . filter ( is_active = ) . order_by ( '' , '' ) else : ct = ContentType . objects . get_for_model ( object ) members = User . objects . filter ( Q ( user_profile__groups__in = allowed_groups ) | Q ( aclpermission__permission__codename = permission , aclpermission__content_type = ct , aclpermission__object_id = object . pk ) ) . distinct ( ) . order_by ( '' , '' ) return members def get_acl_users_by_object ( self , object , permission ) : \"\"\"\"\"\" ct = ContentType . objects . get_for_model ( object ) members = User . objects . filter ( Q ( aclpermission__permission__codename = permission , aclpermission__content_type = ct , aclpermission__object_id = object . pk ) ) . distinct ( ) . order_by ( '' , '' ) return members def get_acl_objects_by_model ( self , user , model , permission ) : \"\"\"\"\"\" contenttype = ContentType . objects . get_for_model ( model ) ret = [ ] user_id = if user . is_anonymous ( ) else user . id acl_users_permissions = cache . get ( ACL_USERS_PERMISSIONS_CACHE ) if acl_users_permissions is None : acl_users_permissions = self . cache_user_permissions ( user ) else : try : acl_users_permissions [ user_id ] except KeyError : acl_users_permissions = self . cache_user_permissions ( user ) try : for obj , perm in acl_users_permissions [ user_id ] [ contenttype . id ] . iteritems ( ) : try : if perm [ permission ] : ret . append ( obj ) except : pass except : pass return ret def cache_user_permissions ( self , user ) : acl_users_permissions = cache . get ( ACL_USERS_PERMISSIONS_CACHE ) if acl_users_permissions is None : acl_users_permissions = { } if user . is_anonymous ( ) : user_id = ", "answer": "user_groups = [ ]"}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import , division , print_function , unicode_literals import os import logging logging . basicConfig ( ) from django . conf import settings from django . conf . urls import patterns , url from django . core . wsgi import get_wsgi_application from django . utils . timezone import now as tznow basename = os . path . splitext ( os . path . basename ( __file__ ) ) [ ] def rel ( * path ) : return os . path . abspath ( os . path . join ( os . path . dirname ( __file__ ) , * path ) ) . replace ( \"\" , \"\" ) if not settings . configured : settings . configure ( DEBUG = True , TIMEZONE = \"\" , INSTALLED_APPS = [ \"\" ] , TEMPLATE_DIRS = [ rel ( \"\" , \"\" ) ] , STATIC_ROOT = os . path . abspath ( rel ( \"\" , \"\" ) ) , ROOT_URLCONF = basename , WSGI_APPLICATION = \"\" . format ( basename ) , ) from easy_pdf . views import PDFTemplateView class HelloPDFView ( PDFTemplateView ) : template_name = \"\" def get_context_data ( self , ** kwargs ) : return super ( HelloPDFView , self ) . get_context_data ( pagesize = \"\" , title = \"\" , today = tznow ( ) , ** kwargs ) urlpatterns = patterns ( \"\" , url ( r\"\" , HelloPDFView . as_view ( ) ) ) application = get_wsgi_application ( ) if __name__ == \"\" : from django . core . management import call_command ", "answer": "call_command ( \"\" , \"\" ) "}, {"prompt": " import sys import os on_rtd = os . environ . get ( '' , None ) == '' sys . path . insert ( , os . path . abspath ( '' ) ) extensions = [ '' , '' , '' , '' , ] autodoc_member_order = '' templates_path = [ '' ] source_suffix = '' master_doc = '' project = u'' ", "answer": "copyright = u''"}, {"prompt": " import unittest from swift . common . swob import Request , HTTPUnauthorized from swift . common . middleware import container_quotas class FakeCache ( object ) : def __init__ ( self , val ) : if '' not in val : val [ '' ] = self . val = val def get ( self , * args ) : return self . val class FakeApp ( object ) : def __init__ ( self ) : pass def __call__ ( self , env , start_response ) : start_response ( '' , [ ] ) return [ ] class FakeMissingApp ( object ) : def __init__ ( self ) : pass def __call__ ( self , env , start_response ) : start_response ( '' , [ ] ) return [ ] def start_response ( * args ) : pass class TestContainerQuotas ( unittest . TestCase ) : def test_split_path_empty_container_path_segment ( self ) : app = container_quotas . ContainerQuotaMiddleware ( FakeApp ( ) , { } ) req = Request . blank ( '' , environ = { '' : '' , '' : { '' : '' } } ) res = req . get_response ( app ) self . assertEqual ( res . status_int , ) def test_not_handled ( self ) : app = container_quotas . ContainerQuotaMiddleware ( FakeApp ( ) , { } ) req = Request . blank ( '' , environ = { '' : '' } ) res = req . get_response ( app ) self . assertEqual ( res . status_int , ) app = container_quotas . ContainerQuotaMiddleware ( FakeApp ( ) , { } ) req = Request . blank ( '' , environ = { '' : '' } ) res = req . get_response ( app ) self . assertEqual ( res . status_int , ) def test_no_quotas ( self ) : app = container_quotas . ContainerQuotaMiddleware ( FakeApp ( ) , { } ) req = Request . blank ( '' , environ = { '' : '' , '' : FakeCache ( { } ) , '' : '' } ) res = req . get_response ( app ) self . assertEqual ( res . status_int , ) def test_exceed_bytes_quota ( self ) : app = container_quotas . ContainerQuotaMiddleware ( FakeApp ( ) , { } ) cache = FakeCache ( { '' : , '' : { '' : '' } } ) req = Request . blank ( '' , environ = { '' : '' , '' : cache , '' : '' } ) res = req . get_response ( app ) self . assertEqual ( res . status_int , ) self . assertEqual ( res . body , '' ) def test_exceed_bytes_quota_copy_from ( self ) : app = container_quotas . ContainerQuotaMiddleware ( FakeApp ( ) , { } ) cache = FakeCache ( { '' : , '' : { '' : '' } } ) req = Request . blank ( '' , environ = { '' : '' , '' : { '' : } , '' : cache } , headers = { '' : '' } ) res = req . get_response ( app ) self . assertEqual ( res . status_int , ) self . assertEqual ( res . body , '' ) def test_exceed_bytes_quota_copy_verb ( self ) : app = container_quotas . ContainerQuotaMiddleware ( FakeApp ( ) , { } ) cache = FakeCache ( { '' : , '' : { '' : '' } } ) req = Request . blank ( '' , environ = { '' : '' , '' : { '' : } , '' : cache } , headers = { '' : '' } ) res = req . get_response ( app ) self . assertEqual ( res . status_int , ) self . assertEqual ( res . body , '' ) def test_not_exceed_bytes_quota ( self ) : app = container_quotas . ContainerQuotaMiddleware ( FakeApp ( ) , { } ) cache = FakeCache ( { '' : , '' : { '' : '' } } ) req = Request . blank ( '' , environ = { '' : '' , '' : cache , '' : '' } ) res = req . get_response ( app ) self . assertEqual ( res . status_int , ) def test_not_exceed_bytes_quota_copy_from ( self ) : app = container_quotas . ContainerQuotaMiddleware ( FakeApp ( ) , { } ) cache = FakeCache ( { '' : , '' : { '' : '' } } ) req = Request . blank ( '' , environ = { '' : '' , '' : { '' : } , '' : cache } , headers = { '' : '' } ) res = req . get_response ( app ) self . assertEqual ( res . status_int , ) def test_not_exceed_bytes_quota_copy_verb ( self ) : app = container_quotas . ContainerQuotaMiddleware ( FakeApp ( ) , { } ) cache = FakeCache ( { '' : , '' : { '' : '' } } ) req = Request . blank ( '' , environ = { '' : '' , '' : { '' : } , '' : cache } , headers = { '' : '' } ) res = req . get_response ( app ) self . assertEqual ( res . status_int , ) def test_bytes_quota_copy_from_no_src ( self ) : app = container_quotas . ContainerQuotaMiddleware ( FakeApp ( ) , { } ) cache = FakeCache ( { '' : , '' : { '' : '' } } ) req = Request . blank ( '' , environ = { '' : '' , '' : { '' : } , '' : cache } , headers = { '' : '' } ) res = req . get_response ( app ) self . assertEqual ( res . status_int , ) def test_bytes_quota_copy_from_bad_src ( self ) : app = container_quotas . ContainerQuotaMiddleware ( FakeApp ( ) , { } ) cache = FakeCache ( { '' : , '' : { '' : '' } } ) req = Request . blank ( '' , environ = { '' : '' , '' : cache } , headers = { '' : '' } ) res = req . get_response ( app ) self . assertEqual ( res . status_int , ) def test_bytes_quota_copy_verb_no_src ( self ) : app = container_quotas . ContainerQuotaMiddleware ( FakeApp ( ) , { } ) cache = FakeCache ( { '' : , '' : { '' : '' } } ) req = Request . blank ( '' , environ = { '' : '' , '' : { '' : } , '' : cache } , headers = { '' : '' } ) res = req . get_response ( app ) self . assertEqual ( res . status_int , ) def test_exceed_counts_quota ( self ) : app = container_quotas . ContainerQuotaMiddleware ( FakeApp ( ) , { } ) cache = FakeCache ( { '' : , '' : { '' : '' } } ) req = Request . blank ( '' , environ = { '' : '' , '' : cache , '' : '' } ) res = req . get_response ( app ) self . assertEqual ( res . status_int , ) self . assertEqual ( res . body , '' ) def test_exceed_counts_quota_copy_from ( self ) : app = container_quotas . ContainerQuotaMiddleware ( FakeApp ( ) , { } ) cache = FakeCache ( { '' : , '' : { '' : '' } } ) req = Request . blank ( '' , environ = { '' : '' , '' : { '' : } , '' : cache } , headers = { '' : '' } ) res = req . get_response ( app ) self . assertEqual ( res . status_int , ) self . assertEqual ( res . body , '' ) def test_exceed_counts_quota_copy_verb ( self ) : app = container_quotas . ContainerQuotaMiddleware ( FakeApp ( ) , { } ) cache = FakeCache ( { '' : , '' : { '' : '' } } ) req = Request . blank ( '' , environ = { '' : '' , '' : cache } , headers = { '' : '' } ) res = req . get_response ( app ) self . assertEqual ( res . status_int , ) self . assertEqual ( res . body , '' ) def test_exceed_counts_quota_copy_cross_account_verb ( self ) : app = container_quotas . ContainerQuotaMiddleware ( FakeApp ( ) , { } ) a_c_cache = { '' : '' , '' : { '' : '' } , '' : , '' : } a2_c_cache = { '' : '' , '' : { '' : '' } , '' : , '' : } req = Request . blank ( '' , environ = { '' : '' , '' : a_c_cache , '' : a2_c_cache } , headers = { '' : '' , '' : '' } ) res = req . get_response ( app ) self . assertEqual ( res . status_int , ) self . assertEqual ( res . body , '' ) def test_exceed_counts_quota_copy_cross_account_PUT_verb ( self ) : app = container_quotas . ContainerQuotaMiddleware ( FakeApp ( ) , { } ) a_c_cache = { '' : '' , '' : { '' : '' } , '' : , '' : } a2_c_cache = { '' : '' , '' : { '' : '' } , '' : , '' : } req = Request . blank ( '' , environ = { '' : '' , '' : a_c_cache , '' : a2_c_cache } , headers = { '' : '' , '' : '' } ) res = req . get_response ( app ) self . assertEqual ( res . status_int , ) self . assertEqual ( res . body , '' ) def test_not_exceed_counts_quota ( self ) : app = container_quotas . ContainerQuotaMiddleware ( FakeApp ( ) , { } ) cache = FakeCache ( { '' : , '' : { '' : '' } } ) req = Request . blank ( '' , environ = { '' : '' , '' : cache , '' : '' } ) res = req . get_response ( app ) self . assertEqual ( res . status_int , ) def test_not_exceed_counts_quota_copy_from ( self ) : app = container_quotas . ContainerQuotaMiddleware ( FakeApp ( ) , { } ) cache = FakeCache ( { '' : , '' : { '' : '' } } ) req = Request . blank ( '' , environ = { '' : '' , '' : cache } , headers = { '' : '' } ) res = req . get_response ( app ) ", "answer": "self . assertEqual ( res . status_int , )"}, {"prompt": " import sys from os . path import basename from django . core . management . base import BaseCommand ", "answer": "from django . template import Template , Context"}, {"prompt": " \"\"\"\"\"\" import configparser import os import platform if platform . system ( ) == \"\" : config_folder = os . path . join ( os . path . expandvars ( \"\" ) , \"\" ) elif platform . system ( ) == \"\" : config_folder = os . path . expanduser ( \"\" ) else : config_folder = os . path . expanduser ( \"\" ) if not os . path . isdir ( config_folder ) : os . mkdir ( config_folder ) STARCHEAT_VERSION = \"\" STARCHEAT_VERSION_TAG = \"\" CONFIG_VERSION = ini_file = os . path . join ( config_folder , \"\" ) class Config ( object ) : def __init__ ( self ) : self . config = configparser . ConfigParser ( ) self . config_folder = config_folder self . ini_file = ini_file self . CONFIG_VERSION = CONFIG_VERSION def read ( self , option ) : self . config . read ( self . ini_file ) return self . config [ \"\" ] [ option ] def has_key ( self , option ) : self . config . read ( self . ini_file ) if \"\" in self . config : return option in self . config [ \"\" ] else : return False def set ( self , option , value ) : self . config . read ( ini_file ) self . config [ \"\" ] [ option ] = value self . config . write ( open ( ini_file , \"\" ) ) def create_config ( self , starbound_folder = None ) : if starbound_folder is None : starbound_folder = self . detect_starbound_folder ( ) storage_folder = \"\" assets_folder = os . path . join ( starbound_folder , \"\" ) player_folder = os . path . join ( starbound_folder , storage_folder , \"\" ) mods_folder = os . path . join ( starbound_folder , storage_folder , \"\" ) backup_folder = os . path . join ( config_folder , \"\" ) pak_hash = \"\" check_updates = \"\" assets_db = os . path . join ( config_folder , \"\" ) defaults = { \"\" : starbound_folder , \"\" : assets_folder , \"\" : player_folder , \"\" : mods_folder , \"\" : backup_folder , \"\" : pak_hash , \"\" : assets_db , \"\" : check_updates , \"\" : CONFIG_VERSION } self . config [ \"\" ] = defaults self . config . write ( open ( ini_file , \"\" ) ) if not os . path . isdir ( backup_folder ) : os . mkdir ( backup_folder ) def remove_config ( self ) : \"\"\"\"\"\" try : os . remove ( ini_file ) except FileNotFoundError : pass def detect_starbound_folder ( self ) : known_locations = [ '' , '' , os . path . expanduser ( \"\" ) , os . path . expanduser ( \"\" ) , os . path . expanduser ( \"\" ) ] if platform . system ( ) == \"\" : import winreg try : key = \"\" if platform . machine ( ) . endswith ( '' ) : key = \"\" starbound_uninstall = winreg . OpenKey ( winreg . HKEY_LOCAL_MACHINE , key ) starbound_path = winreg . QueryValueEx ( starbound_uninstall , \"\" ) [ ] known_locations . append ( os . path . normpath ( starbound_path ) ) starbound_uninstall . Close ( ) except OSError : pass try : steam = winreg . OpenKey ( winreg . HKEY_CURRENT_USER , \"\" ) steam_path = os . path . normpath ( winreg . QueryValueEx ( steam , \"\" ) [ ] ) known_locations . append ( os . path . join ( steam_path , \"\" , \"\" , \"\" ) ) steam . Close ( ) except OSError : pass ", "answer": "for path in known_locations :"}, {"prompt": " import unittest from six . moves . urllib . parse import urlparse from scrapy . http import Request from scrapy . utils . httpobj import urlparse_cached ", "answer": "class HttpobjUtilsTest ( unittest . TestCase ) :"}, {"prompt": " import os , sys import dgitcore from dgitcore import datasets , plugins , config from dgitcore . config import get_config __all__ = [ '' , '' ] ", "answer": "def api_call_action ( func ) :"}, {"prompt": " \"\"\"\"\"\" import asyncio from functools import partial from pulsar . apps import http from pulsar . apps . wsgi import HttpServerResponse __all__ = [ '' ] class DummyTransport ( asyncio . Transport ) : \"\"\"\"\"\" def __init__ ( self , client , connnection ) : self . client = client self . connection = connnection def write ( self , data ) : \"\"\"\"\"\" ", "answer": "self . connection . data_received ( data )"}, {"prompt": " from __future__ import unicode_literals from django . core . files import File from django . core . urlresolvers import reverse from acls . models import AccessControlList from user_management . tests . literals import ( TEST_USER_PASSWORD , TEST_USER_USERNAME ) from . . links import ( link_document_version_download , link_document_version_revert ) from . . permissions import ( permission_document_download , permission_document_version_revert ) from . literals import TEST_SMALL_DOCUMENT_PATH from . test_views import GenericDocumentViewTestCase class DocumentsLinksTestCase ( GenericDocumentViewTestCase ) : def test_document_version_revert_link_no_permission ( self ) : with open ( TEST_SMALL_DOCUMENT_PATH ) as file_object : self . document . new_version ( file_object = File ( file_object ) ) self . assertTrue ( self . document . versions . count ( ) , ) self . login ( username = TEST_USER_USERNAME , password = TEST_USER_PASSWORD ) self . add_test_view ( test_object = self . document . versions . first ( ) ) context = self . get_test_view ( ) resolved_link = link_document_version_revert . resolve ( context = context ) self . assertEqual ( resolved_link , None ) def test_document_version_revert_link_with_permission ( self ) : with open ( TEST_SMALL_DOCUMENT_PATH ) as file_object : self . document . new_version ( file_object = File ( file_object ) ) self . assertTrue ( self . document . versions . count ( ) , ) self . login ( username = TEST_USER_USERNAME , password = TEST_USER_PASSWORD ) acl = AccessControlList . objects . create ( content_object = self . document , role = self . role ) acl . permissions . add ( permission_document_version_revert . stored_permission ) self . add_test_view ( test_object = self . document . versions . first ( ) ) context = self . get_test_view ( ) resolved_link = link_document_version_revert . resolve ( context = context ) self . assertNotEqual ( resolved_link , None ) self . assertEqual ( resolved_link . url , reverse ( ", "answer": "'' ,"}, {"prompt": " \"\"\"\"\"\" def read_zt_byte_strings ( fobj , n_strings = , bufsize = ) : \"\"\"\"\"\" byte_strings = [ ] trailing = b'' while True : buf = fobj . read ( bufsize ) eof = len ( buf ) < bufsize zt_strings = buf . split ( b'' ) if len ( zt_strings ) > : byte_strings += [ trailing + zt_strings [ ] ] + zt_strings [ : - ] trailing = zt_strings [ - ] else : trailing += zt_strings [ ] n_found = len ( byte_strings ) if eof or n_found >= n_strings : break if n_found < n_strings : raise ValueError ( '' . format ( ", "answer": "n_strings , n_found ) )"}, {"prompt": " from __future__ import unicode_literals ", "answer": "TEST_WORKFLOW_LABEL = ''"}, {"prompt": " import numpy as np np . random . seed ( ) np . seterr ( over = \"\" ) import matplotlib . pyplot as plt from pybasicbayes . util . general import ibincount from pybasicbayes . util . text import progprint_xrange import pyhawkes . models reload ( pyhawkes . models ) K = B = dt = dt_max = T = network_hypers = { '' : , '' : , '' : } dt_model = pyhawkes . models . DiscreteTimeNetworkHawkesModelSpikeAndSlab ( K = K , dt = dt , dt_max = dt_max , B = B , network_hypers = network_hypers ) assert dt_model . check_stability ( ) S_dt , _ = dt_model . generate ( T = int ( np . ceil ( T / dt ) ) , keep = False ) print \"\" , S_dt . sum ( ) , \"\" print \"\" , dt_model . heldout_log_likelihood ( S_dt ) S_ct = dt * np . concatenate ( [ ibincount ( S ) for S in S_dt . T ] ) . astype ( float ) S_ct += dt * np . random . rand ( * S_ct . shape ) assert np . all ( S_ct < T ) C_ct = np . concatenate ( [ k * np . ones ( S . sum ( ) ) for k , S in enumerate ( S_dt . T ) ] ) . astype ( int ) perm = np . argsort ( S_ct ) S_ct = S_ct [ perm ] C_ct = C_ct [ perm ] ct_model = pyhawkes . models . ContinuousTimeNetworkHawkesModel ( K , dt_max = , network_hypers = network_hypers ) ct_model . add_data ( S_ct , C_ct , T ) ct_model . bias_model . lambda0 = dt_model . bias_model . lambda0 ct_model . weight_model . A = dt_model . weight_model . A ct_model . weight_model . W = dt_model . weight_model . W print \"\" , ct_model . heldout_log_likelihood ( S_ct , C_ct , T ) ct_lls = [ ct_model . log_likelihood ( ) ] N_samples = for itr in progprint_xrange ( N_samples , perline = ) : ct_model . resample_model ( ) ct_lls . append ( ct_model . log_likelihood ( ) ) ", "answer": "assert np . all ( ct_model . weight_model . A == )"}, {"prompt": " import abc from datetime import datetime from functools import reduce import operator from django . db import models from django . db . models . base import ModelBase from django . db . models import query import jsonfield import six from devops . error import DevopsError from devops . helpers . helpers import deepgetattr from devops . helpers import loader def choices ( * args , ** kwargs ) : defaults = { '' : , '' : False } defaults . update ( kwargs ) defaults . update ( choices = list ( zip ( args , args ) ) ) return models . CharField ( ** defaults ) class BaseModel ( models . Model ) : class Meta ( object ) : abstract = True created = models . DateTimeField ( default = datetime . utcnow ) class ParamedModelType ( ModelBase ) : \"\"\"\"\"\" def __new__ ( cls , name , bases , attrs ) : super_new = super ( ParamedModelType , cls ) . __new__ if name != '' and name != '' : parents = reduce ( operator . add , map ( lambda a : a . __mro__ , bases ) ) if ParamedModel not in bases and ParamedModel in parents : if '' not in attrs : attrs [ '' ] = type ( '' , ( object , ) , { } ) Meta = attrs [ '' ] Meta . proxy = True new_class = super_new ( cls , name , bases , attrs ) new_class . _param_field_names = [ ] for attr_name in attrs : attr = attrs [ attr_name ] if isinstance ( attr , ParamFieldBase ) : attr . set_param_key ( attr_name ) new_class . _param_field_names . append ( attr_name ) return new_class def __call__ ( cls , * args , ** kwargs ) : kwargs_for_params = { } defined_params = cls . get_defined_params ( ) for param in defined_params : if param in kwargs : kwargs_for_params [ param ] = kwargs . pop ( param ) obj = super ( ParamedModelType , cls ) . __call__ ( * args , ** kwargs ) if obj . _class : Cls = loader . load_class ( obj . _class ) obj . __class__ = Cls for param in kwargs_for_params : setattr ( obj , param , kwargs_for_params [ param ] ) return obj @ six . add_metaclass ( abc . ABCMeta ) class ParamFieldBase ( object ) : \"\"\"\"\"\" def __init__ ( self ) : ", "answer": "self . param_key = None"}, {"prompt": " \"\"\"\"\"\" import os import sys from Bcfg2 . Client . Tools . POSIX . base import POSIXTool class POSIXNonexistent ( POSIXTool ) : \"\"\"\"\"\" __req__ = [ '' ] def verify ( self , entry , _ ) : if os . path . lexists ( entry . get ( '' ) ) : self . logger . debug ( \"\" % entry . get ( \"\" ) ) return False return True def install ( self , entry ) : ename = entry . get ( '' ) recursive = entry . get ( '' , '' ) . lower ( ) == '' if recursive : for struct in self . config . getchildren ( ) : ", "answer": "for el in struct . getchildren ( ) :"}, {"prompt": " \"\"\"\"\"\" __author__ = '' import time import unittest from functools import partial from viewfinder . backend . base . testing import async_test from viewfinder . backend . db . episode import Episode from viewfinder . backend . db . photo import Photo from viewfinder . backend . db . post import Post from base_test import DBBaseTestCase class PostTestCase ( DBBaseTestCase ) : def testPostIdConstruction ( self ) : \"\"\"\"\"\" def _RoundTripPostId ( original_episode_id , original_photo_id ) : post_id = Post . ConstructPostId ( original_episode_id , original_photo_id ) new_episode_id , new_photo_id = Post . DeconstructPostId ( post_id ) self . assertEqual ( original_episode_id , new_episode_id ) self . assertEqual ( original_photo_id , new_photo_id ) _RoundTripPostId ( Episode . ConstructEpisodeId ( time . time ( ) , , ) , Photo . ConstructPhotoId ( time . time ( ) , , ) ) _RoundTripPostId ( Episode . ConstructEpisodeId ( time . time ( ) , , ( , '' ) ) , Photo . ConstructPhotoId ( time . time ( ) , , ( , '' ) ) ) _RoundTripPostId ( Episode . ConstructEpisodeId ( time . time ( ) , , ( , None ) ) , Photo . ConstructPhotoId ( time . time ( ) , , ( , None ) ) ) _RoundTripPostId ( Episode . ConstructEpisodeId ( time . time ( ) , , ( , '' ) ) , Photo . ConstructPhotoId ( time . time ( ) , , ( , '' ) ) ) def testPostIdOrdering ( self ) : \"\"\"\"\"\" def _Compare ( episode_id1 , photo_id1 , episode_id2 , photo_id2 ) : result = cmp ( episode_id1 , episode_id2 ) if result == : result = cmp ( photo_id1 , photo_id2 ) post_id1 = Post . ConstructPostId ( episode_id1 , photo_id1 ) post_id2 = Post . ConstructPostId ( episode_id2 , photo_id2 ) self . assertEqual ( cmp ( post_id1 , post_id2 ) , result ) timestamp = time . time ( ) episode_id1 = Episode . ConstructEpisodeId ( timestamp , , ( , None ) ) episode_id2 = Episode . ConstructEpisodeId ( timestamp , , ( , None ) ) photo_id1 = Photo . ConstructPhotoId ( timestamp , , ) photo_id2 = Photo . ConstructPhotoId ( timestamp , , ) _Compare ( episode_id1 , photo_id1 , episode_id2 , photo_id2 ) episode_id1 = Episode . ConstructEpisodeId ( timestamp , , ) episode_id2 = Episode . ConstructEpisodeId ( timestamp , , ) photo_id1 = Photo . ConstructPhotoId ( timestamp , , ( , None ) ) photo_id2 = Photo . ConstructPhotoId ( timestamp , , ( , None ) ) _Compare ( episode_id1 , photo_id1 , episode_id2 , photo_id2 ) episode_id1 = Episode . ConstructEpisodeId ( timestamp , , ) episode_id2 = Episode . ConstructEpisodeId ( timestamp , , ) photo_id1 = Photo . ConstructPhotoId ( timestamp , , ) photo_id2 = Photo . ConstructPhotoId ( timestamp , , ) _Compare ( episode_id1 , photo_id1 , episode_id2 , photo_id2 ) episode_id1 = Episode . ConstructEpisodeId ( timestamp , , ) episode_id2 = Episode . ConstructEpisodeId ( timestamp , , ) photo_id1 = Photo . ConstructPhotoId ( timestamp , , ) photo_id2 = Photo . ConstructPhotoId ( timestamp , , ) _Compare ( episode_id1 , photo_id1 , episode_id2 , photo_id2 ) episode_id1 = Episode . ConstructEpisodeId ( , , ) episode_id2 = Episode . ConstructEpisodeId ( , , ) photo_id1 = Photo . ConstructPhotoId ( , , ( , None ) ) ", "answer": "photo_id2 = Photo . ConstructPhotoId ( , , ( , None ) )"}, {"prompt": " \"\"\"\"\"\" from pyproct . driver . observer . accumulativeObserver import AccumulativeObserver class Observable ( object ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " import abc import collections import datetime import fnmatch import json import logging import six import time import uuid from notabene import kombu_driver as driver import requests logger = logging . getLogger ( __name__ ) @ six . add_metaclass ( abc . ABCMeta ) class PipelineHandlerBase ( object ) : \"\"\"\"\"\" def __init__ ( self , ** kw ) : \"\"\"\"\"\" @ abc . abstractmethod def handle_events ( self , events , env ) : \"\"\"\"\"\" @ abc . abstractmethod def commit ( self ) : \"\"\"\"\"\" @ abc . abstractmethod def rollback ( self ) : \"\"\"\"\"\" class LoggingHandler ( PipelineHandlerBase ) : def handle_events ( self , events , env ) : emsg = '' . join ( \"\" % ( event [ '' ] , event [ '' ] ) for event in events ) logger . info ( \"\" % ( len ( events ) , emsg ) ) return events def commit ( self ) : pass def rollback ( self ) : pass class NotabeneException ( Exception ) : pass class ConnectionManager ( object ) : def __init__ ( self ) : self . pool = { } def _extract_params ( self , kw ) : host = kw . get ( '' , '' ) user = kw . get ( '' , '' ) password = kw . get ( '' , '' ) port = kw . get ( '' , ) vhost = kw . get ( '' , '' ) library = kw . get ( '' , '' ) exchange_name = kw . get ( '' ) exchange_type = kw . get ( '' , '' ) if exchange_name is None : raise NotabeneException ( \"\" ) connection_dict = { '' : host , '' : port , '' : user , '' : password , '' : library , '' : vhost } connection_tuple = tuple ( sorted ( connection_dict . items ( ) ) ) exchange_dict = { '' : exchange_name , '' : exchange_type } exchange_tuple = tuple ( sorted ( exchange_dict . items ( ) ) ) return ( connection_dict , connection_tuple , exchange_dict , exchange_tuple ) def get_connection ( self , properties , queue_name ) : ( connection_dict , connection_tuple , exchange_dict , exchange_tuple ) = self . _extract_params ( properties ) connection_info = self . pool . get ( connection_tuple ) if connection_info is None : connection = driver . create_connection ( connection_dict [ '' ] , connection_dict [ '' ] , connection_dict [ '' ] , connection_dict [ '' ] , connection_dict [ '' ] , connection_dict [ '' ] ) connection_info = ( connection , { } ) self . pool [ connection_tuple ] = connection_info connection , exchange_pool = connection_info ", "answer": "exchange = exchange_pool . get ( exchange_tuple )"}, {"prompt": " import math import os import random import imp common = imp . load_source ( \"\" , \"\" ) def insert ( original , new , pos ) : return original [ : pos ] + str ( new ) + original [ pos : ] def generate ( full_path ) : try : chosen = random . sample ( set ( common . strings ) , ) changed = chosen orig = chosen for i in range ( ) : output = chosen [ i ] + \"\" f = open ( full_path + os . sep + \"\" + str ( i ) + \"\" , \"\" ) f . write ( \"\" % output ) f . close ( ) for b in range ( ) : changed [ i ] = insert ( changed [ i ] , random . randint ( , ) , random . randint ( , len ( changed [ i ] ) - ) ) name = changed [ i ] f = open ( full_path + os . sep + \"\" + str ( i ) + \"\" , \"\" ) f . write ( \"\" % name ) f . close ( ) ", "answer": "return "}, {"prompt": " '''''' import re from resources . lib . libraries import client ", "answer": "from resources . lib . libraries import jsunpack"}, {"prompt": " \"\"\"\"\"\" from Tkinter import * import tkMessageBox , tkColorChooser , tkFont import string , copy from configHandler import idleConf from dynOptionMenuWidget import DynOptionMenu from tabpage import TabPageSet from keybindingDialog import GetKeysDialog from configSectionNameDialog import GetCfgSectionNameDialog from configHelpSourceEdit import GetHelpSourceDialog class ConfigDialog ( Toplevel ) : def __init__ ( self , parent , title ) : Toplevel . __init__ ( self , parent ) self . configure ( borderwidth = ) self . geometry ( \"\" % ( parent . winfo_rootx ( ) + , parent . winfo_rooty ( ) + ) ) self . themeElements = { '' : ( '' , '' ) , '' : ( '' , '' ) , '' : ( '' , '' ) , '' : ( '' , '' ) , '' : ( '' , '' ) , '' : ( '' , '' ) , '' : ( '' , '' ) , '' : ( '' , '' ) , '' : ( '' , '' ) , '' : ( '' , '' ) , '' : ( '' , '' ) , '' : ( '' , '' ) , '' : ( '' , '' ) , } self . ResetChangedItems ( ) self . CreateWidgets ( ) self . resizable ( height = FALSE , width = FALSE ) self . transient ( parent ) self . grab_set ( ) self . protocol ( \"\" , self . Cancel ) self . parent = parent self . tabPages . focus_set ( ) self . LoadConfigs ( ) self . AttachVarCallbacks ( ) self . wait_window ( ) def CreateWidgets ( self ) : self . tabPages = TabPageSet ( self , pageNames = [ '' , '' , '' , '' ] ) self . tabPages . ChangePage ( ) frameActionButtons = Frame ( self ) self . buttonHelp = Button ( frameActionButtons , text = '' , command = self . Help , takefocus = FALSE ) self . buttonOk = Button ( frameActionButtons , text = '' , command = self . Ok , takefocus = FALSE ) self . buttonApply = Button ( frameActionButtons , text = '' , command = self . Apply , takefocus = FALSE ) self . buttonCancel = Button ( frameActionButtons , text = '' , command = self . Cancel , takefocus = FALSE ) self . CreatePageFontTab ( ) self . CreatePageHighlight ( ) self . CreatePageKeys ( ) self . CreatePageGeneral ( ) self . buttonHelp . pack ( side = RIGHT , padx = , pady = ) self . buttonOk . pack ( side = LEFT , padx = , pady = ) self . buttonApply . pack ( side = LEFT , padx = , pady = ) self . buttonCancel . pack ( side = LEFT , padx = , pady = ) frameActionButtons . pack ( side = BOTTOM ) self . tabPages . pack ( side = TOP , expand = TRUE , fill = BOTH ) def CreatePageFontTab ( self ) : self . fontSize = StringVar ( self ) self . fontBold = BooleanVar ( self ) self . fontName = StringVar ( self ) self . spaceNum = IntVar ( self ) self . editFont = tkFont . Font ( self , ( '' , , '' ) ) frame = self . tabPages . pages [ '' ] [ '' ] frameFont = Frame ( frame , borderwidth = , relief = GROOVE ) frameIndent = Frame ( frame , borderwidth = , relief = GROOVE ) labelFontTitle = Label ( frameFont , text = '' ) frameFontName = Frame ( frameFont ) frameFontParam = Frame ( frameFont ) labelFontNameTitle = Label ( frameFontName , justify = LEFT , text = '' ) self . listFontName = Listbox ( frameFontName , height = , takefocus = FALSE , exportselection = FALSE ) self . listFontName . bind ( '' , self . OnListFontButtonRelease ) scrollFont = Scrollbar ( frameFontName ) scrollFont . config ( command = self . listFontName . yview ) self . listFontName . config ( yscrollcommand = scrollFont . set ) labelFontSizeTitle = Label ( frameFontParam , text = '' ) self . optMenuFontSize = DynOptionMenu ( frameFontParam , self . fontSize , None , command = self . SetFontSample ) checkFontBold = Checkbutton ( frameFontParam , variable = self . fontBold , onvalue = , offvalue = , text = '' , command = self . SetFontSample ) frameFontSample = Frame ( frameFont , relief = SOLID , borderwidth = ) self . labelFontSample = Label ( frameFontSample , text = '' , justify = LEFT , font = self . editFont ) frameIndentSize = Frame ( frameIndent ) labelSpaceNumTitle = Label ( frameIndentSize , justify = LEFT , text = '' ) self . scaleSpaceNum = Scale ( frameIndentSize , variable = self . spaceNum , label = '' , orient = '' , tickinterval = , from_ = , to = ) frameFont . pack ( side = LEFT , padx = , pady = , expand = TRUE , fill = BOTH ) frameIndent . pack ( side = LEFT , padx = , pady = , fill = Y ) labelFontTitle . pack ( side = TOP , anchor = W , padx = , pady = ) frameFontName . pack ( side = TOP , padx = , pady = , fill = X ) frameFontParam . pack ( side = TOP , padx = , pady = , fill = X ) labelFontNameTitle . pack ( side = TOP , anchor = W ) self . listFontName . pack ( side = LEFT , expand = TRUE , fill = X ) scrollFont . pack ( side = LEFT , fill = Y ) labelFontSizeTitle . pack ( side = LEFT , anchor = W ) self . optMenuFontSize . pack ( side = LEFT , anchor = W ) checkFontBold . pack ( side = LEFT , anchor = W , padx = ) frameFontSample . pack ( side = TOP , padx = , pady = , expand = TRUE , fill = BOTH ) self . labelFontSample . pack ( expand = TRUE , fill = BOTH ) frameIndentSize . pack ( side = TOP , padx = , pady = , fill = BOTH ) labelSpaceNumTitle . pack ( side = TOP , anchor = W , padx = ) self . scaleSpaceNum . pack ( side = TOP , padx = , fill = X ) return frame def CreatePageHighlight ( self ) : self . builtinTheme = StringVar ( self ) self . customTheme = StringVar ( self ) self . fgHilite = BooleanVar ( self ) self . colour = StringVar ( self ) self . fontName = StringVar ( self ) self . themeIsBuiltin = BooleanVar ( self ) self . highlightTarget = StringVar ( self ) frame = self . tabPages . pages [ '' ] [ '' ] frameCustom = Frame ( frame , borderwidth = , relief = GROOVE ) frameTheme = Frame ( frame , borderwidth = , relief = GROOVE ) self . textHighlightSample = Text ( frameCustom , relief = SOLID , borderwidth = , font = ( '' , , '' ) , cursor = '' , width = , height = , takefocus = FALSE , highlightthickness = , wrap = NONE ) text = self . textHighlightSample text . bind ( '' , lambda e : '' ) text . bind ( '' , lambda e : '' ) textAndTags = ( ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( \"\" , '' ) , ( '' , '' ) , ( \"\" , '' ) , ( '' , '' ) , ( \"\" , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) , ( '' , '' ) ) for txTa in textAndTags : text . insert ( END , txTa [ ] , txTa [ ] ) for element in self . themeElements . keys ( ) : text . tag_bind ( self . themeElements [ element ] [ ] , '' , lambda event , elem = element : event . widget . winfo_toplevel ( ) . highlightTarget . set ( elem ) ) text . config ( state = DISABLED ) self . frameColourSet = Frame ( frameCustom , relief = SOLID , borderwidth = ) frameFgBg = Frame ( frameCustom ) labelCustomTitle = Label ( frameCustom , text = '' ) buttonSetColour = Button ( self . frameColourSet , text = '' , command = self . GetColour , highlightthickness = ) self . optMenuHighlightTarget = DynOptionMenu ( self . frameColourSet , self . highlightTarget , None , highlightthickness = ) self . radioFg = Radiobutton ( frameFgBg , variable = self . fgHilite , value = , text = '' , command = self . SetColourSampleBinding ) self . radioBg = Radiobutton ( frameFgBg , variable = self . fgHilite , value = , text = '' , command = self . SetColourSampleBinding ) self . fgHilite . set ( ) buttonSaveCustomTheme = Button ( frameCustom , text = '' , command = self . SaveAsNewTheme ) labelThemeTitle = Label ( frameTheme , text = '' ) labelTypeTitle = Label ( frameTheme , text = '' ) self . radioThemeBuiltin = Radiobutton ( frameTheme , variable = self . themeIsBuiltin , value = , command = self . SetThemeType , text = '' ) self . radioThemeCustom = Radiobutton ( frameTheme , variable = self . themeIsBuiltin , value = , command = self . SetThemeType , text = '' ) self . optMenuThemeBuiltin = DynOptionMenu ( frameTheme , self . builtinTheme , None , command = None ) self . optMenuThemeCustom = DynOptionMenu ( frameTheme , self . customTheme , None , command = None ) self . buttonDeleteCustomTheme = Button ( frameTheme , text = '' , command = self . DeleteCustomTheme ) frameCustom . pack ( side = LEFT , padx = , pady = , expand = TRUE , fill = BOTH ) frameTheme . pack ( side = LEFT , padx = , pady = , fill = Y ) labelCustomTitle . pack ( side = TOP , anchor = W , padx = , pady = ) self . frameColourSet . pack ( side = TOP , padx = , pady = , expand = TRUE , fill = X ) frameFgBg . pack ( side = TOP , padx = , pady = ) self . textHighlightSample . pack ( side = TOP , padx = , pady = , expand = TRUE , fill = BOTH ) buttonSetColour . pack ( side = TOP , expand = TRUE , fill = X , padx = , pady = ) self . optMenuHighlightTarget . pack ( side = TOP , expand = TRUE , fill = X , padx = , pady = ) self . radioFg . pack ( side = LEFT , anchor = E ) self . radioBg . pack ( side = RIGHT , anchor = W ) buttonSaveCustomTheme . pack ( side = BOTTOM , fill = X , padx = , pady = ) labelThemeTitle . pack ( side = TOP , anchor = W , padx = , pady = ) labelTypeTitle . pack ( side = TOP , anchor = W , padx = , pady = ) self . radioThemeBuiltin . pack ( side = TOP , anchor = W , padx = ) self . radioThemeCustom . pack ( side = TOP , anchor = W , padx = , pady = ) self . optMenuThemeBuiltin . pack ( side = TOP , fill = X , padx = , pady = ) self . optMenuThemeCustom . pack ( side = TOP , fill = X , anchor = W , padx = , pady = ) self . buttonDeleteCustomTheme . pack ( side = TOP , fill = X , padx = , pady = ) return frame def CreatePageKeys ( self ) : self . bindingTarget = StringVar ( self ) self . builtinKeys = StringVar ( self ) self . customKeys = StringVar ( self ) self . keysAreBuiltin = BooleanVar ( self ) self . keyBinding = StringVar ( self ) frame = self . tabPages . pages [ '' ] [ '' ] frameCustom = Frame ( frame , borderwidth = , relief = GROOVE ) frameKeySets = Frame ( frame , borderwidth = , relief = GROOVE ) frameTarget = Frame ( frameCustom ) labelCustomTitle = Label ( frameCustom , text = '' ) labelTargetTitle = Label ( frameTarget , text = '' ) scrollTargetY = Scrollbar ( frameTarget ) scrollTargetX = Scrollbar ( frameTarget , orient = HORIZONTAL ) self . listBindings = Listbox ( frameTarget , takefocus = FALSE , exportselection = FALSE ) self . listBindings . bind ( '' , self . KeyBindingSelected ) scrollTargetY . config ( command = self . listBindings . yview ) scrollTargetX . config ( command = self . listBindings . xview ) self . listBindings . config ( yscrollcommand = scrollTargetY . set ) self . listBindings . config ( xscrollcommand = scrollTargetX . set ) self . buttonNewKeys = Button ( frameCustom , text = '' , command = self . GetNewKeys , state = DISABLED ) buttonSaveCustomKeys = Button ( frameCustom , text = '' , command = self . SaveAsNewKeySet ) labelKeysTitle = Label ( frameKeySets , text = '' ) labelTypeTitle = Label ( frameKeySets , text = '' ) self . radioKeysBuiltin = Radiobutton ( frameKeySets , variable = self . keysAreBuiltin , value = , command = self . SetKeysType , text = '' ) self . radioKeysCustom = Radiobutton ( frameKeySets , variable = self . keysAreBuiltin , value = , command = self . SetKeysType , text = '' ) self . optMenuKeysBuiltin = DynOptionMenu ( frameKeySets , self . builtinKeys , None , command = None ) self . optMenuKeysCustom = DynOptionMenu ( frameKeySets , self . customKeys , None , command = None ) self . buttonDeleteCustomKeys = Button ( frameKeySets , text = '' , command = self . DeleteCustomKeys ) frameCustom . pack ( side = LEFT , padx = , pady = , expand = TRUE , fill = BOTH ) frameKeySets . pack ( side = LEFT , padx = , pady = , fill = Y ) labelCustomTitle . pack ( side = TOP , anchor = W , padx = , pady = ) buttonSaveCustomKeys . pack ( side = BOTTOM , fill = X , padx = , pady = ) self . buttonNewKeys . pack ( side = BOTTOM , fill = X , padx = , pady = ) frameTarget . pack ( side = LEFT , padx = , pady = , expand = TRUE , fill = BOTH ) frameTarget . columnconfigure ( , weight = ) frameTarget . rowconfigure ( , weight = ) labelTargetTitle . grid ( row = , column = , columnspan = , sticky = W ) self . listBindings . grid ( row = , column = , sticky = NSEW ) scrollTargetY . grid ( row = , column = , sticky = NS ) scrollTargetX . grid ( row = , column = , sticky = EW ) labelKeysTitle . pack ( side = TOP , anchor = W , padx = , pady = ) labelTypeTitle . pack ( side = TOP , anchor = W , padx = , pady = ) self . radioKeysBuiltin . pack ( side = TOP , anchor = W , padx = ) self . radioKeysCustom . pack ( side = TOP , anchor = W , padx = , pady = ) self . optMenuKeysBuiltin . pack ( side = TOP , fill = X , padx = , pady = ) self . optMenuKeysCustom . pack ( side = TOP , fill = X , anchor = W , padx = , pady = ) self . buttonDeleteCustomKeys . pack ( side = TOP , fill = X , padx = , pady = ) return frame def CreatePageGeneral ( self ) : self . winWidth = StringVar ( self ) self . winHeight = StringVar ( self ) self . paraWidth = StringVar ( self ) self . startupEdit = IntVar ( self ) self . autoSave = IntVar ( self ) self . encoding = StringVar ( self ) self . userHelpBrowser = BooleanVar ( self ) self . helpBrowser = StringVar ( self ) frame = self . tabPages . pages [ '' ] [ '' ] frameRun = Frame ( frame , borderwidth = , relief = GROOVE ) frameSave = Frame ( frame , borderwidth = , relief = GROOVE ) frameWinSize = Frame ( frame , borderwidth = , relief = GROOVE ) frameParaSize = Frame ( frame , borderwidth = , relief = GROOVE ) frameEncoding = Frame ( frame , borderwidth = , relief = GROOVE ) frameHelp = Frame ( frame , borderwidth = , relief = GROOVE ) labelRunTitle = Label ( frameRun , text = '' ) labelRunChoiceTitle = Label ( frameRun , text = '' ) radioStartupEdit = Radiobutton ( frameRun , variable = self . startupEdit , value = , command = self . SetKeysType , text = \"\" ) radioStartupShell = Radiobutton ( frameRun , variable = self . startupEdit , value = , command = self . SetKeysType , text = '' ) labelSaveTitle = Label ( frameSave , text = '' ) labelRunSaveTitle = Label ( frameSave , text = '' ) radioSaveAsk = Radiobutton ( frameSave , variable = self . autoSave , value = , command = self . SetKeysType , text = \"\" ) radioSaveAuto = Radiobutton ( frameSave , variable = self . autoSave , value = , command = self . SetKeysType , text = '' ) labelWinSizeTitle = Label ( frameWinSize , text = '' + '' ) labelWinWidthTitle = Label ( frameWinSize , text = '' ) entryWinWidth = Entry ( frameWinSize , textvariable = self . winWidth , width = ) labelWinHeightTitle = Label ( frameWinSize , text = '' ) entryWinHeight = Entry ( frameWinSize , textvariable = self . winHeight , width = ) labelParaWidthTitle = Label ( frameParaSize , text = '' + '' ) entryParaWidth = Entry ( frameParaSize , textvariable = self . paraWidth , width = ) labelEncodingTitle = Label ( frameEncoding , text = \"\" ) radioEncLocale = Radiobutton ( frameEncoding , variable = self . encoding , value = \"\" , text = \"\" ) radioEncUTF8 = Radiobutton ( frameEncoding , variable = self . encoding , value = \"\" , text = \"\" ) radioEncNone = Radiobutton ( frameEncoding , variable = self . encoding , value = \"\" , text = \"\" ) frameHelpList = Frame ( frameHelp ) frameHelpListButtons = Frame ( frameHelpList ) labelHelpListTitle = Label ( frameHelpList , text = '' ) scrollHelpList = Scrollbar ( frameHelpList ) self . listHelp = Listbox ( frameHelpList , height = , takefocus = FALSE , exportselection = FALSE ) scrollHelpList . config ( command = self . listHelp . yview ) self . listHelp . config ( yscrollcommand = scrollHelpList . set ) self . listHelp . bind ( '' , self . HelpSourceSelected ) self . buttonHelpListEdit = Button ( frameHelpListButtons , text = '' , state = DISABLED , width = , command = self . HelpListItemEdit ) self . buttonHelpListAdd = Button ( frameHelpListButtons , text = '' , width = , command = self . HelpListItemAdd ) self . buttonHelpListRemove = Button ( frameHelpListButtons , text = '' , state = DISABLED , width = , command = self . HelpListItemRemove ) frameRun . pack ( side = TOP , padx = , pady = , fill = X ) frameSave . pack ( side = TOP , padx = , pady = , fill = X ) frameWinSize . pack ( side = TOP , padx = , pady = , fill = X ) frameParaSize . pack ( side = TOP , padx = , pady = , fill = X ) frameEncoding . pack ( side = TOP , padx = , pady = , fill = X ) frameHelp . pack ( side = TOP , padx = , pady = , expand = TRUE , fill = BOTH ) labelRunTitle . pack ( side = TOP , anchor = W , padx = , pady = ) labelRunChoiceTitle . pack ( side = LEFT , anchor = W , padx = , pady = ) radioStartupShell . pack ( side = RIGHT , anchor = W , padx = , pady = ) radioStartupEdit . pack ( side = RIGHT , anchor = W , padx = , pady = ) labelSaveTitle . pack ( side = TOP , anchor = W , padx = , pady = ) labelRunSaveTitle . pack ( side = LEFT , anchor = W , padx = , pady = ) radioSaveAuto . pack ( side = RIGHT , anchor = W , padx = , pady = ) radioSaveAsk . pack ( side = RIGHT , anchor = W , padx = , pady = ) labelWinSizeTitle . pack ( side = LEFT , anchor = W , padx = , pady = ) entryWinHeight . pack ( side = RIGHT , anchor = E , padx = , pady = ) labelWinHeightTitle . pack ( side = RIGHT , anchor = E , pady = ) entryWinWidth . pack ( side = RIGHT , anchor = E , padx = , pady = ) labelWinWidthTitle . pack ( side = RIGHT , anchor = E , pady = ) labelParaWidthTitle . pack ( side = LEFT , anchor = W , padx = , pady = ) entryParaWidth . pack ( side = RIGHT , anchor = E , padx = , pady = ) labelEncodingTitle . pack ( side = LEFT , anchor = W , padx = , pady = ) radioEncNone . pack ( side = RIGHT , anchor = E , pady = ) radioEncUTF8 . pack ( side = RIGHT , anchor = E , pady = ) radioEncLocale . pack ( side = RIGHT , anchor = E , pady = ) frameHelpListButtons . pack ( side = RIGHT , padx = , pady = , fill = Y ) frameHelpList . pack ( side = TOP , padx = , pady = , expand = TRUE , fill = BOTH ) labelHelpListTitle . pack ( side = TOP , anchor = W ) scrollHelpList . pack ( side = RIGHT , anchor = W , fill = Y ) self . listHelp . pack ( side = LEFT , anchor = E , expand = TRUE , fill = BOTH ) self . buttonHelpListEdit . pack ( side = TOP , anchor = W , pady = ) self . buttonHelpListAdd . pack ( side = TOP , anchor = W ) self . buttonHelpListRemove . pack ( side = TOP , anchor = W , pady = ) return frame def AttachVarCallbacks ( self ) : self . fontSize . trace_variable ( '' , self . VarChanged_fontSize ) self . fontName . trace_variable ( '' , self . VarChanged_fontName ) self . fontBold . trace_variable ( '' , self . VarChanged_fontBold ) self . spaceNum . trace_variable ( '' , self . VarChanged_spaceNum ) self . colour . trace_variable ( '' , self . VarChanged_colour ) self . builtinTheme . trace_variable ( '' , self . VarChanged_builtinTheme ) self . customTheme . trace_variable ( '' , self . VarChanged_customTheme ) self . themeIsBuiltin . trace_variable ( '' , self . VarChanged_themeIsBuiltin ) self . highlightTarget . trace_variable ( '' , self . VarChanged_highlightTarget ) self . keyBinding . trace_variable ( '' , self . VarChanged_keyBinding ) self . builtinKeys . trace_variable ( '' , self . VarChanged_builtinKeys ) self . customKeys . trace_variable ( '' , self . VarChanged_customKeys ) self . keysAreBuiltin . trace_variable ( '' , self . VarChanged_keysAreBuiltin ) self . winWidth . trace_variable ( '' , self . VarChanged_winWidth ) self . winHeight . trace_variable ( '' , self . VarChanged_winHeight ) self . paraWidth . trace_variable ( '' , self . VarChanged_paraWidth ) self . startupEdit . trace_variable ( '' , self . VarChanged_startupEdit ) self . autoSave . trace_variable ( '' , self . VarChanged_autoSave ) self . encoding . trace_variable ( '' , self . VarChanged_encoding ) def VarChanged_fontSize ( self , * params ) : value = self . fontSize . get ( ) self . AddChangedItem ( '' , '' , '' , value ) def VarChanged_fontName ( self , * params ) : value = self . fontName . get ( ) self . AddChangedItem ( '' , '' , '' , value ) def VarChanged_fontBold ( self , * params ) : value = self . fontBold . get ( ) self . AddChangedItem ( '' , '' , '' , value ) def VarChanged_spaceNum ( self , * params ) : value = self . spaceNum . get ( ) self . AddChangedItem ( '' , '' , '' , value ) def VarChanged_colour ( self , * params ) : self . OnNewColourSet ( ) def VarChanged_builtinTheme ( self , * params ) : value = self . builtinTheme . get ( ) self . AddChangedItem ( '' , '' , '' , value ) self . PaintThemeSample ( ) def VarChanged_customTheme ( self , * params ) : value = self . customTheme . get ( ) if value != '' : self . AddChangedItem ( '' , '' , '' , value ) self . PaintThemeSample ( ) def VarChanged_themeIsBuiltin ( self , * params ) : value = self . themeIsBuiltin . get ( ) self . AddChangedItem ( '' , '' , '' , value ) if value : self . VarChanged_builtinTheme ( ) else : self . VarChanged_customTheme ( ) def VarChanged_highlightTarget ( self , * params ) : self . SetHighlightTarget ( ) def VarChanged_keyBinding ( self , * params ) : value = self . keyBinding . get ( ) keySet = self . customKeys . get ( ) event = self . listBindings . get ( ANCHOR ) . split ( ) [ ] if idleConf . IsCoreBinding ( event ) : self . AddChangedItem ( '' , keySet , event , value ) else : extName = idleConf . GetExtnNameForEvent ( event ) extKeybindSection = extName + '' self . AddChangedItem ( '' , extKeybindSection , event , value ) def VarChanged_builtinKeys ( self , * params ) : value = self . builtinKeys . get ( ) self . AddChangedItem ( '' , '' , '' , value ) self . LoadKeysList ( value ) def VarChanged_customKeys ( self , * params ) : value = self . customKeys . get ( ) if value != '' : self . AddChangedItem ( '' , '' , '' , value ) self . LoadKeysList ( value ) def VarChanged_keysAreBuiltin ( self , * params ) : value = self . keysAreBuiltin . get ( ) self . AddChangedItem ( '' , '' , '' , value ) if value : self . VarChanged_builtinKeys ( ) else : self . VarChanged_customKeys ( ) def VarChanged_winWidth ( self , * params ) : value = self . winWidth . get ( ) self . AddChangedItem ( '' , '' , '' , value ) def VarChanged_winHeight ( self , * params ) : value = self . winHeight . get ( ) self . AddChangedItem ( '' , '' , '' , value ) def VarChanged_paraWidth ( self , * params ) : value = self . paraWidth . get ( ) self . AddChangedItem ( '' , '' , '' , value ) def VarChanged_startupEdit ( self , * params ) : value = self . startupEdit . get ( ) self . AddChangedItem ( '' , '' , '' , value ) def VarChanged_autoSave ( self , * params ) : value = self . autoSave . get ( ) self . AddChangedItem ( '' , '' , '' , value ) def VarChanged_encoding ( self , * params ) : value = self . encoding . get ( ) self . AddChangedItem ( '' , '' , '' , value ) def ResetChangedItems ( self ) : self . changedItems = { '' : { } , '' : { } , '' : { } , '' : { } } def AddChangedItem ( self , type , section , item , value ) : value = str ( value ) if not self . changedItems [ type ] . has_key ( section ) : self . changedItems [ type ] [ section ] = { } self . changedItems [ type ] [ section ] [ item ] = value def GetDefaultItems ( self ) : dItems = { '' : { } , '' : { } , '' : { } , '' : { } } for configType in dItems . keys ( ) : sections = idleConf . GetSectionList ( '' , configType ) for section in sections : dItems [ configType ] [ section ] = { } options = idleConf . defaultCfg [ configType ] . GetOptionList ( section ) for option in options : dItems [ configType ] [ section ] [ option ] = ( idleConf . defaultCfg [ configType ] . Get ( section , option ) ) return dItems def SetThemeType ( self ) : if self . themeIsBuiltin . get ( ) : self . optMenuThemeBuiltin . config ( state = NORMAL ) self . optMenuThemeCustom . config ( state = DISABLED ) self . buttonDeleteCustomTheme . config ( state = DISABLED ) else : self . optMenuThemeBuiltin . config ( state = DISABLED ) self . radioThemeCustom . config ( state = NORMAL ) self . optMenuThemeCustom . config ( state = NORMAL ) self . buttonDeleteCustomTheme . config ( state = NORMAL ) def SetKeysType ( self ) : if self . keysAreBuiltin . get ( ) : self . optMenuKeysBuiltin . config ( state = NORMAL ) self . optMenuKeysCustom . config ( state = DISABLED ) self . buttonDeleteCustomKeys . config ( state = DISABLED ) else : self . optMenuKeysBuiltin . config ( state = DISABLED ) self . radioKeysCustom . config ( state = NORMAL ) self . optMenuKeysCustom . config ( state = NORMAL ) self . buttonDeleteCustomKeys . config ( state = NORMAL ) def GetNewKeys ( self ) : listIndex = self . listBindings . index ( ANCHOR ) binding = self . listBindings . get ( listIndex ) bindName = binding . split ( ) [ ] if self . keysAreBuiltin . get ( ) : currentKeySetName = self . builtinKeys . get ( ) else : currentKeySetName = self . customKeys . get ( ) currentBindings = idleConf . GetCurrentKeySet ( ) if currentKeySetName in self . changedItems [ '' ] . keys ( ) : keySetChanges = self . changedItems [ '' ] [ currentKeySetName ] for event in keySetChanges . keys ( ) : currentBindings [ event ] = keySetChanges [ event ] . split ( ) currentKeySequences = currentBindings . values ( ) newKeys = GetKeysDialog ( self , '' , bindName , currentKeySequences ) . result if newKeys : if self . keysAreBuiltin . get ( ) : message = ( '' + '' ) newKeySet = self . GetNewKeysName ( message ) if not newKeySet : self . listBindings . select_set ( listIndex ) self . listBindings . select_anchor ( listIndex ) return else : self . CreateNewKeySet ( newKeySet ) self . listBindings . delete ( listIndex ) self . listBindings . insert ( listIndex , bindName + '' + newKeys ) self . listBindings . select_set ( listIndex ) self . listBindings . select_anchor ( listIndex ) self . keyBinding . set ( newKeys ) else : self . listBindings . select_set ( listIndex ) self . listBindings . select_anchor ( listIndex ) def GetNewKeysName ( self , message ) : usedNames = ( idleConf . GetSectionList ( '' , '' ) + idleConf . GetSectionList ( '' , '' ) ) newKeySet = GetCfgSectionNameDialog ( self , '' , message , usedNames ) . result return newKeySet def SaveAsNewKeySet ( self ) : newKeysName = self . GetNewKeysName ( '' ) if newKeysName : self . CreateNewKeySet ( newKeysName ) def KeyBindingSelected ( self , event ) : self . buttonNewKeys . config ( state = NORMAL ) def CreateNewKeySet ( self , newKeySetName ) : if self . keysAreBuiltin . get ( ) : prevKeySetName = self . builtinKeys . get ( ) else : prevKeySetName = self . customKeys . get ( ) prevKeys = idleConf . GetCoreKeys ( prevKeySetName ) newKeys = { } for event in prevKeys . keys ( ) : eventName = event [ : - ] binding = string . join ( prevKeys [ event ] ) newKeys [ eventName ] = binding if prevKeySetName in self . changedItems [ '' ] . keys ( ) : keySetChanges = self . changedItems [ '' ] [ prevKeySetName ] for event in keySetChanges . keys ( ) : newKeys [ event ] = keySetChanges [ event ] self . SaveNewKeySet ( newKeySetName , newKeys ) customKeyList = idleConf . GetSectionList ( '' , '' ) customKeyList . sort ( ) self . optMenuKeysCustom . SetMenu ( customKeyList , newKeySetName ) self . keysAreBuiltin . set ( ) self . SetKeysType ( ) def LoadKeysList ( self , keySetName ) : reselect = newKeySet = if self . listBindings . curselection ( ) : reselect = listIndex = self . listBindings . index ( ANCHOR ) keySet = idleConf . GetKeySet ( keySetName ) bindNames = keySet . keys ( ) bindNames . sort ( ) self . listBindings . delete ( , END ) for bindName in bindNames : key = string . join ( keySet [ bindName ] ) bindName = bindName [ : - ] if keySetName in self . changedItems [ '' ] . keys ( ) : if bindName in self . changedItems [ '' ] [ keySetName ] . keys ( ) : key = self . changedItems [ '' ] [ keySetName ] [ bindName ] self . listBindings . insert ( END , bindName + '' + key ) if reselect : self . listBindings . see ( listIndex ) self . listBindings . select_set ( listIndex ) self . listBindings . select_anchor ( listIndex ) def DeleteCustomKeys ( self ) : keySetName = self . customKeys . get ( ) if not tkMessageBox . askyesno ( '' , '' + '' % ( keySetName ) , parent = self ) : return idleConf . userCfg [ '' ] . remove_section ( keySetName ) if self . changedItems [ '' ] . has_key ( keySetName ) : del ( self . changedItems [ '' ] [ keySetName ] ) idleConf . userCfg [ '' ] . Save ( ) ", "answer": "itemList = idleConf . GetSectionList ( '' , '' )"}, {"prompt": " '''''' import os , sys , shutil import ConfigParser from bbox_core . bbox_config import BBoxConfig from utils . state_machine import StateMachine from utils import apk_utils , auxiliary_utils , zip_utils from bbox_core . bboxreporter import MsgException , BBoxReporter from bbox_core . bboxinstrumenter import BBoxInstrumenter , ApkCannotBeDecompiledException , Dex2JarConvertionError , EmmaCannotInstrumentException , Jar2DexConvertionError , IllegalArgumentException , ApktoolBuildException , SignApkException , AlignApkException from bbox_core . bboxexecutor import BBoxExecutor , ApkCannotBeInstalledException from logconfig import logger from string import rfind from utils . android_manifest import AndroidManifest from time import localtime import datetime from interfaces . emma_interface import EMMA_REPORT import time from six import iteritems RESULTS_RELATIVE_DIR = \"\" TMP_RELATIVE_DIR = \"\" DEVICE_REPORT_FOLDER_PATH = \"\" PARAMS_SECTION = \"\" STATE_UNINITIALIZED = \"\" STATE_APK_VALID = \"\" STATE_FOLDERS_CREATED = \"\" STATE_APK_DECOMPILED = \"\" STATE_DEX_CONVERTED_TO_JAR = \"\" STATE_JARS_INSTRUMENTED = \"\" STATE_JAR_CONVERTED_TO_DEX = \"\" STATE_MANIFEST_INSTRUMENTED = \"\" STATE_INSTRUMENTED_APK_BUILD = \"\" STATE_FINAL_INSTRUMENTED_APK_BUILD = \"\" STATE_INSTRUMENTED_APK_SIGNED = \"\" STATE_INSTRUMENTED_APK_ALIGNED = \"\" STATE_APK_INSTRUMENTED = \"\" STATE_VALID_SETTINGS_PROVIDED = \"\" STATE_APK_INSTALLED = \"\" STATE_APK_TEST_STARTED = \"\" STATE_APK_FINISHED_TESTING = \"\" STATES = [ ( STATE_UNINITIALIZED , STATE_APK_VALID ) , ( STATE_APK_VALID , STATE_FOLDERS_CREATED ) , ( STATE_FOLDERS_CREATED , STATE_APK_DECOMPILED ) , ( STATE_APK_DECOMPILED , STATE_DEX_CONVERTED_TO_JAR ) , ( STATE_DEX_CONVERTED_TO_JAR , STATE_JARS_INSTRUMENTED ) , ( STATE_JARS_INSTRUMENTED , STATE_JAR_CONVERTED_TO_DEX ) , ( STATE_JAR_CONVERTED_TO_DEX , STATE_MANIFEST_INSTRUMENTED ) , ( STATE_MANIFEST_INSTRUMENTED , STATE_INSTRUMENTED_APK_BUILD ) , ( STATE_INSTRUMENTED_APK_BUILD , STATE_FINAL_INSTRUMENTED_APK_BUILD ) , ( STATE_FINAL_INSTRUMENTED_APK_BUILD , STATE_INSTRUMENTED_APK_SIGNED ) , ( STATE_INSTRUMENTED_APK_SIGNED , STATE_INSTRUMENTED_APK_ALIGNED ) , ( STATE_INSTRUMENTED_APK_ALIGNED , STATE_APK_INSTRUMENTED ) , ( STATE_APK_INSTRUMENTED , STATE_APK_INSTALLED ) , ( STATE_VALID_SETTINGS_PROVIDED , STATE_APK_INSTALLED ) , ( STATE_APK_INSTRUMENTED , STATE_APK_TEST_STARTED ) , ( STATE_VALID_SETTINGS_PROVIDED , STATE_APK_TEST_STARTED ) , ( STATE_APK_INSTALLED , STATE_APK_TEST_STARTED ) , ( STATE_APK_TEST_STARTED , STATE_APK_FINISHED_TESTING ) , ] class BBoxCoverage : PREFIX_ONSTOP = \"\" ; PREFIX_ONERROR = \"\" ; '''''' def __init__ ( self , pathToBBoxConfigFile = \"\" ) : self . androidManifestFile = None self . instrumentedApk = None self . config = BBoxConfig ( pathToBBoxConfigFile ) self . bboxInstrumenter = BBoxInstrumenter ( self . config ) self . bboxExecutor = BBoxExecutor ( self . config ) self . bboxReporter = BBoxReporter ( self . config ) self . _bboxStateMachine = StateMachine ( states = STATES ) def getInstrumentedApk ( self ) : return self . instrumentedApk def getPackageName ( self ) : return self . packageName def instrumentApkForCoverage ( self , pathToOrigApk , resultsDir = None , tmpDir = None , removeApkTmpDirAfterInstr = True , copyApkToRes = True ) : '''''' self . _bboxStateMachine . start ( STATE_UNINITIALIZED ) valid = self . _checkProvidedApk ( pathToOrigApk ) if not valid : return False self . _bboxStateMachine . transitToState ( STATE_APK_VALID ) resultsRootDir = None if not resultsDir : resultsRootDir = os . path . join ( os . getcwd ( ) , RESULTS_RELATIVE_DIR ) else : resultsRootDir = os . path . abspath ( resultsDir ) tmpRootDir = None if not tmpDir : tmpRootDir = os . path . join ( os . getcwd ( ) , TMP_RELATIVE_DIR ) else : tmpRootDir = os . path . abspath ( tmpDir ) apkFileName = os . path . splitext ( os . path . basename ( pathToOrigApk ) ) [ ] self . apkTmpDir = self . _createDir ( tmpDir , apkFileName , False , True ) self . apkResultsDir = self . _createDir ( resultsRootDir , apkFileName , False , True ) self . coverageMetadataFolder = self . _createDir ( self . apkResultsDir , self . config . getCoverageMetadataRelativeDir ( ) , False , True ) self . runtimeReportsRootDir = self . _createDir ( self . apkResultsDir , self . config . getRuntimeReportsRelativeDir ( ) , False , True ) self . _bboxStateMachine . transitToState ( STATE_FOLDERS_CREATED ) if copyApkToRes : shutil . copy2 ( pathToOrigApk , self . apkResultsDir ) decompileDir = os . path . join ( self . apkTmpDir , self . config . getDecompiledApkRelativeDir ( ) ) success = self . _decompileApk ( self . bboxInstrumenter , pathToOrigApk , decompileDir ) if not success : return False self . _bboxStateMachine . transitToState ( STATE_APK_DECOMPILED ) dexFilesRelativePaths = self . _getDexFilePathsRelativeToDir ( decompileDir ) if not dexFilesRelativePaths : logger . error ( \"\" ) return False if \"\" not in dexFilesRelativePaths : logger . error ( \"\" ) return False rawJarFilesRootDir = os . path . join ( self . apkTmpDir , self . config . getTmpJarRelativeDir ( ) ) jarFilesRelativePaths = self . _convertDex2JarFiles ( converter = self . bboxInstrumenter , dexFilesRootDir = decompileDir , dexFilesRelativePaths = dexFilesRelativePaths , jarFilesRootDir = rawJarFilesRootDir , proceedOnError = True ) self . _bboxStateMachine . transitToState ( STATE_DEX_CONVERTED_TO_JAR ) if \"\" not in jarFilesRelativePaths : logger . error ( \"\" ) return False self . coverageMetadataFile = os . path . join ( self . coverageMetadataFolder , self . config . getCoverageMetadataFilename ( ) ) emmaInstrJarFilesRootDir = os . path . join ( self . apkTmpDir , self . config . getInstrumentedFilesRelativeDir ( ) ) emmaInstrJarFileRelativePaths = self . _instrFilesWithEmma ( instrumenter = self . bboxInstrumenter , jarFilesRootDir = rawJarFilesRootDir , jarFilesRelativePaths = jarFilesRelativePaths , instrJarsRootDir = emmaInstrJarFilesRootDir , coverageMetadataFile = self . coverageMetadataFile , proceedOnError = True ) self . _bboxStateMachine . transitToState ( STATE_JARS_INSTRUMENTED ) if \"\" not in emmaInstrJarFileRelativePaths : logger . error ( \"\" ) return False instrDexFilesRelativePaths = self . _convertJar2DexWithInstr ( converter = self . bboxInstrumenter , instrJarsRootDir = emmaInstrJarFilesRootDir , instrJarFilesRelativePaths = emmaInstrJarFileRelativePaths , finalDexFilesRootDir = decompileDir , proceedOnError = True ) self . _bboxStateMachine . transitToState ( STATE_JAR_CONVERTED_TO_DEX ) if \"\" not in instrDexFilesRelativePaths : logger . error ( \"\" ) return False uninstrumentedFiles = self . _getUnInstrFilesRelativePaths ( dexFilesRelativePaths , instrDexFilesRelativePaths ) if uninstrumentedFiles : logger . debug ( \"\" + str ( uninstrumentedFiles ) ) decompiledAndroidManifestPath = os . path . join ( decompileDir , \"\" ) success = self . _instrAndroidManifest ( self . bboxInstrumenter , decompiledAndroidManifestPath ) if not success : logger . error ( \"\" ) return False shutil . copy2 ( decompiledAndroidManifestPath , self . apkResultsDir ) self . androidManifestFile = os . path . join ( self . apkResultsDir , \"\" ) self . _bboxStateMachine . transitToState ( STATE_MANIFEST_INSTRUMENTED ) compiledApkFilePath = os . path . join ( self . apkResultsDir , \"\" % ( apkFileName , self . config . getInstrFileSuffix ( ) ) ) success = self . _compileApk ( self . bboxInstrumenter , decompileDir , compiledApkFilePath ) if not success : logger . error ( \"\" ) return False self . _bboxStateMachine . transitToState ( STATE_INSTRUMENTED_APK_BUILD ) compiledApkFilePathWithEmmaRes = os . path . join ( self . apkResultsDir , \"\" % ( apkFileName , self . config . getFinalInstrFileSuffix ( ) ) ) shutil . copy2 ( compiledApkFilePath , compiledApkFilePathWithEmmaRes ) self . _putAdditionalResources ( apk = compiledApkFilePathWithEmmaRes , resources = self . config . getEmmaResourcesDir ( ) ) self . _bboxStateMachine . transitToState ( STATE_FINAL_INSTRUMENTED_APK_BUILD ) signedApkFilePath = os . path . join ( self . apkResultsDir , \"\" % ( apkFileName , self . config . getSignedFileSuffix ( ) ) ) success = self . _signApk ( self . bboxInstrumenter , compiledApkFilePathWithEmmaRes , signedApkFilePath ) if not success : logger . error ( \"\" ) return False self . _bboxStateMachine . transitToState ( STATE_INSTRUMENTED_APK_SIGNED ) alignedApkFilePath = os . path . join ( self . apkResultsDir , \"\" % ( apkFileName , self . config . getAlignedFileSuffix ( ) ) ) success = self . _alignApk ( self . bboxInstrumenter , signedApkFilePath , alignedApkFilePath ) if not success : logger . error ( \"\" ) return False self . _bboxStateMachine . transitToState ( STATE_INSTRUMENTED_APK_ALIGNED ) if removeApkTmpDirAfterInstr : shutil . rmtree ( self . apkTmpDir ) self . instrumentedApk = alignedApkFilePath self . androidManifest = AndroidManifest ( self . androidManifestFile ) self . packageName = self . androidManifest . getInstrumentationTargetPackage ( ) self . runnerName = self . androidManifest . getInstrumentationRunnerName ( ) self . _bboxStateMachine . transitToState ( STATE_APK_INSTRUMENTED ) return True def _createDir ( self , root , directory , createNew = True , overwrite = False ) : resDir = os . path . join ( root , directory ) if createNew : i = while os . path . exists ( resDir ) : i += resDir = os . path . join ( root , \"\" % ( directory , i ) ) auxiliary_utils . mkdir ( path = resDir , mode = , overwrite = overwrite ) return resDir def _createFolder ( self , root , dirName , overwrite = False ) : resultDir = os . path . join ( root , dirName ) auxiliary_utils . mkdir ( path = resultDir , mode = , overwrite = overwrite ) return resultDir def _checkProvidedApk ( self , pathToApk ) : '''''' ( valid , error ) = apk_utils . checkInputApkFile ( pathToApk ) if not valid : logger . error ( \"\" % ( pathToApk , error ) ) return valid return valid def _decompileApk ( self , decompiler , apk , outputDir ) : try : decompiler . decompileApk ( apk , outputDir ) except ApkCannotBeDecompiledException as e : logger . error ( e . msg ) return False except : logger . error ( \"\" ) return False return True def _convertDex2JarFiles ( self , converter , dexFilesRootDir , dexFilesRelativePaths , jarFilesRootDir , proceedOnError = True ) : jarFilesRelativePaths = [ ] for dexFileRelativePath in dexFilesRelativePaths : dexFilePath = os . path . join ( dexFilesRootDir , dexFileRelativePath ) jarFileRelativePath = os . path . splitext ( dexFileRelativePath ) [ ] + \"\" jarFilePath = os . path . join ( jarFilesRootDir , jarFileRelativePath ) try : converter . convertDex2Jar ( dexFilePath , jarFilePath , overwrite = True ) except Dex2JarConvertionError as e : if proceedOnError : logger . warning ( \"\" ( dexFilePath , jarFilePath , e . msg ) ) continue else : raise jarFilesRelativePaths . append ( jarFileRelativePath ) return jarFilesRelativePaths def _instrFilesWithEmma ( self , instrumenter , jarFilesRootDir , jarFilesRelativePaths , instrJarsRootDir , coverageMetadataFile , proceedOnError = True ) : instrJarFilesRelativePaths = [ ] for jarFileRelativePath in jarFilesRelativePaths : jarFileAbsPath = os . path . join ( jarFilesRootDir , jarFileRelativePath ) instrJarRelativeDir = jarFileRelativePath [ : jarFileRelativePath . rfind ( \"\" ) + ] instrJarFullDir = os . path . join ( instrJarsRootDir , instrJarRelativeDir ) try : instrumenter . instrumentJarWithEmma ( jarFile = jarFileAbsPath , outputFolder = instrJarFullDir , emmaMetadataFile = coverageMetadataFile ) except EmmaCannotInstrumentException as e : if proceedOnError : logger . warning ( \"\" ( jarFileAbsPath , e . msg ) ) continue else : raise instrJarFilesRelativePaths . append ( jarFileRelativePath ) return instrJarFilesRelativePaths def _convertJar2DexWithInstr ( self , converter , instrJarsRootDir , instrJarFilesRelativePaths , finalDexFilesRootDir , proceedOnError ) : instrDexFilesRelativePaths = [ ] for jarFileRelativePath in instrJarFilesRelativePaths : jarFileAbsPath = os . path . join ( instrJarsRootDir , jarFileRelativePath ) dexFileRelativePath = os . path . splitext ( jarFileRelativePath ) [ ] + \"\" dexFileAbsPath = os . path . join ( finalDexFilesRootDir , dexFileRelativePath ) print \"\" + jarFileRelativePath try : withFiles = [ ] if jarFileRelativePath == \"\" : emmaDevicePath = os . path . join ( self . config . getEmmaDir ( ) , self . config . getEmmaDeviceJar ( ) ) withFiles . append ( self . config . getAndroidSpecificInstrumentationClassesPath ( ) ) withFiles . append ( emmaDevicePath ) converter . convertJar2Dex ( jarFile = jarFileAbsPath , dexFile = dexFileAbsPath , withFiles = withFiles , overwrite = True ) except Jar2DexConvertionError as e : if proceedOnError : logger . warning ( \"\" % ( jarFileAbsPath , e . msg ) ) continue else : raise instrDexFilesRelativePaths . append ( dexFileRelativePath ) return instrDexFilesRelativePaths def _getUnInstrFilesRelativePaths ( self , dexFilesRelativePaths , instrDexFilesRelativePaths ) : uninstrumentedFiles = [ ] for dexFileRelativePath in dexFilesRelativePaths : if dexFileRelativePath not in instrDexFilesRelativePaths : uninstrumentedFiles . append ( dexFileRelativePath ) return uninstrumentedFiles def _instrAndroidManifest ( self , instrumenter , initAndroidManifest , instrAndroidManifest = None , addSdCardPermission = True ) : success = True try : instrumenter . instrumentAndroidManifestFile ( initAndroidManifest , instrAndroidManifest , addSdCardPermission ) except IllegalArgumentException as e : logger . error ( \"\" % e . msg ) success = False except : logger . error ( \"\" ) success = False return success def _compileApk ( self , compiler , fromDir , apkPath ) : success = True try : compiler . buildApk ( fromDir , apkPath ) except ApktoolBuildException as e : logger . error ( \"\" % e . msg ) success = False except : logger . error ( \"\" ) success = False return success def _putAdditionalResources ( self , apk , resources ) : zip_utils . zipdir ( resources , apk ) def _signApk ( self , signer , unsignedApkFile , signedApkFile ) : success = True try : signer . signApk ( unsignedApkFile , signedApkFile ) except SignApkException as e : logger . error ( \"\" % e . msg ) success = False except : logger . error ( \"\" ) success = False return success def _alignApk ( self , aligner , unalignedApkFile , alignedApkFile ) : success = True try : aligner . alignApk ( unalignedApkFile , alignedApkFile ) except AlignApkException as e : logger . error ( \"\" % e . msg ) success = False except : logger . error ( \"\" ) success = False return success def _getDexFiles ( self , directory ) : dexFileNames = auxiliary_utils . searchFiles ( where = directory , extension = \"\" ) return dexFileNames def _getDexFilePathsRelativeToDir ( self , target ) : dexFileRelativePaths = auxiliary_utils . searchFilesRelativeToDir ( target = target , extension = \"\" ) return dexFileRelativePaths def initAlreadyInstrApkEnv ( self , pathToInstrApk , resultsDir , pathToInstrManifestFile = None ) : if not apk_utils . checkInputApkFile ( pathToInstrApk ) : logger . error ( \"\" % pathToInstrApk ) return if not os . path . isdir ( resultsDir ) : logger . error ( \"\" % resultsDir ) return coverageMetadataFolderPath = os . path . join ( resultsDir , self . config . getCoverageMetadataRelativeDir ( ) ) if not os . path . isdir ( coverageMetadataFolderPath ) : logger . error ( \"\" % resultsDir ) return self . coverageMetadataFolder = coverageMetadataFolderPath if self . config . getCoverageMetadataFilename ( ) not in os . listdir ( coverageMetadataFolderPath ) : logger . error ( \"\" % self . coverageMetadataFolder ) ", "answer": "return"}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import , unicode_literals import pytest import logging from osbs . conf import Configuration from osbs . api import OSBS from osbs . exceptions import OsbsException from tempfile import NamedTemporaryFile logger = logging . getLogger ( \"\" ) def test_missing_config ( ) : os_conf = Configuration ( conf_file = \"\" , conf_section = \"\" ) def test_no_config ( ) : os_conf = Configuration ( conf_file = None , openshift_uri = '' ) assert os_conf . get_openshift_oauth_api_uri ( ) == '' def test_missing_section ( ) : with NamedTemporaryFile ( ) as f : os_conf = Configuration ( conf_file = f . name , conf_section = \"\" ) def test_no_build_type ( ) : with NamedTemporaryFile ( mode = '' ) as f : f . write ( \"\"\"\"\"\" ) f . flush ( ) f . seek ( ) os_conf = Configuration ( conf_file = f . name , conf_section = \"\" ) assert os_conf . get_build_type ( ) is None def test_no_inputs ( ) : with NamedTemporaryFile ( mode = '' ) as f : f . write ( \"\"\"\"\"\" ) f . flush ( ) f . seek ( ) with pytest . raises ( OsbsException ) : os_conf = Configuration ( conf_file = f . name , conf_section = \"\" ) build_conf = Configuration ( conf_file = f . name , conf_section = \"\" ) osbs = OSBS ( os_conf , build_conf ) ", "answer": "osbs . create_build ( git_uri = \"\" ,"}, {"prompt": " import django_filters from datetime import date , timedelta from fec_alerts . models import new_filing from summary_data . models import Committee_Overlay , Authorized_Candidate_Committees , DistrictWeekly , District , Candidate_Overlay from formdata . models import SkedE from django . db . models import Q from summary_data . utils . weekly_update_utils import get_week_number class NFFilter ( django_filters . FilterSet ) : min_raised = django_filters . NumberFilter ( name = '' , lookup_type = '' ) min_spent = django_filters . NumberFilter ( name = '' , lookup_type = '' ) min_coh = django_filters . NumberFilter ( name = '' , lookup_type = '' ) filed_before = django_filters . DateFilter ( name = '' , lookup_type = '' ) filed_after = django_filters . DateFilter ( name = '' , lookup_type = '' ) class Meta : model = new_filing fields = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ] class COFilter ( django_filters . FilterSet ) : min_raised = django_filters . NumberFilter ( name = '' , lookup_type = '' ) min_spent = django_filters . NumberFilter ( name = '' , lookup_type = '' ) min_coh = django_filters . NumberFilter ( name = '' , lookup_type = '' ) class Meta : model = Committee_Overlay fields = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ] class OSFilter ( django_filters . FilterSet ) : min_ies = django_filters . NumberFilter ( name = '' , lookup_type = '' ) class Meta : model = Committee_Overlay fields = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ] class DistrictFilter ( django_filters . FilterSet ) : class Meta : model = District fields = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ] class CandidateFilter ( django_filters . FilterSet ) : class Meta : model = Candidate_Overlay fields = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ] class DWFilter ( django_filters . FilterSet ) : week_start = django_filters . NumberFilter ( name = '' , lookup_type = '' ) week_end = django_filters . NumberFilter ( name = '' , lookup_type = '' ) class Meta : model = DistrictWeekly fields = [ '' , '' , '' , '' ] class SkedEFilter ( django_filters . FilterSet ) : min_spent = django_filters . NumberFilter ( name = '' , lookup_type = '' ) class Meta : model = SkedE fields = ( '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ) def yearFilter ( queryset , querydict ) : try : year = int ( querydict [ '' ] ) queryset = queryset . filter ( Q ( coverage_from_date__gte = date ( year , , ) , coverage_to_date__lte = date ( year , , ) ) ) except ( KeyError , ValueError ) : pass return queryset def DWDistrictFilter ( queryset , querydict ) : try : district_list = querydict [ '' ] if district_list . find ( '' ) < : queryset = queryset . filter ( district__pk = district_list ) else : district_ids = district_list . split ( '' ) queryset = queryset . filter ( district__pk__in = district_ids ) except KeyError : pass return queryset def candidatedistrictFilter ( queryset , querydict ) : try : id = int ( querydict [ '' ] ) queryset = queryset . filter ( district__pk = id ) except ( KeyError , ValueError ) : pass return queryset def districtIDFilter ( queryset , querydict ) : try : id = int ( querydict [ '' ] ) queryset = queryset . filter ( pk = id ) except ( KeyError , ValueError ) : pass return queryset def weekFilter ( queryset , querydict ) : try : week = querydict [ '' ] if week . upper ( ) == \"\" : queryset = queryset . filter ( cycle_week_number = get_week_number ( date . today ( ) ) ) if week . upper ( ) == \"\" : queryset = queryset . filter ( cycle_week_number = get_week_number ( date . today ( ) ) - ) except KeyError : pass return queryset def periodTypeFilter ( queryset , querydict ) : try : period_type = querydict [ '' ] if period_type . startswith ( '' ) : if period_type == '' : queryset = queryset . filter ( coverage_from_date__month = , coverage_from_date__day = , coverage_to_date__month = , coverage_to_date__day = ) elif period_type == '' : queryset = queryset . filter ( coverage_from_date__month = , coverage_from_date__day = , coverage_to_date__month = , coverage_to_date__day = ) elif period_type == '' : queryset = queryset . filter ( coverage_from_date__month = , coverage_from_date__day = , coverage_to_date__month = , coverage_to_date__day = ) elif period_type == '' : queryset = queryset . filter ( coverage_from_date__month = , coverage_from_date__day = , coverage_to_date__month = , coverage_to_date__day = ) elif period_type . startswith ( '' ) : if period_type == '' : queryset = queryset . filter ( coverage_from_date__month = , coverage_from_date__day = , coverage_to_date__month = , coverage_to_date__day = ) elif period_type == '' : queryset = queryset . filter ( Q ( coverage_from_date__month = , coverage_from_date__day = , coverage_to_date__month = , coverage_to_date__day = ) | Q ( coverage_from_date__month = , coverage_from_date__day = , coverage_to_date__month = , coverage_to_date__day = ) ) elif period_type == '' : queryset = queryset . filter ( coverage_from_date__month = , coverage_from_date__day = , coverage_to_date__month = , coverage_to_date__day = ) elif period_type == '' : queryset = queryset . filter ( coverage_from_date__month = , coverage_from_date__day = , coverage_to_date__month = , coverage_to_date__day = ) elif period_type == '' : queryset = queryset . filter ( coverage_from_date__month = , coverage_from_date__day = , coverage_to_date__month = , coverage_to_date__day = ) elif period_type == '' : queryset = queryset . filter ( coverage_from_date__month = , coverage_from_date__day = , coverage_to_date__month = , coverage_to_date__day = ) elif period_type == '' : queryset = queryset . filter ( coverage_from_date__month = , coverage_from_date__day = , coverage_to_date__month = , coverage_to_date__day = ) elif period_type == '' : queryset = queryset . filter ( coverage_from_date__month = , coverage_from_date__day = , coverage_to_date__month = , coverage_to_date__day = ) elif period_type == '' : queryset = queryset . filter ( coverage_from_date__month = , coverage_from_date__day = , coverage_to_date__month = , coverage_to_date__day = ) elif period_type == '' : queryset = queryset . filter ( coverage_from_date__month = , coverage_from_date__day = , coverage_to_date__month = , coverage_to_date__day = ) elif period_type == '' : queryset = queryset . filter ( coverage_from_date__month = , coverage_from_date__day = , coverage_to_date__month = , coverage_to_date__day = ) elif period_type == '' : queryset = queryset . filter ( coverage_from_date__month = , coverage_from_date__day = , coverage_to_date__month = , coverage_to_date__day = ) elif period_type == '' : queryset = queryset . filter ( Q ( coverage_from_date = date ( , , ) , coverage_to_date = date ( , , ) ) ) elif period_type == '' : queryset = queryset . filter ( Q ( coverage_from_date = date ( , , ) , coverage_to_date = date ( , , ) ) ) elif period_type == '' : queryset = queryset . filter ( coverage_to_date = date ( , , ) ) elif period_type . startswith ( '' ) : if period_type == '' : queryset = queryset . filter ( coverage_from_date__month = , coverage_from_date__day = , coverage_to_date__month = , coverage_to_date__day = ) elif period_type == '' : queryset = queryset . filter ( coverage_from_date__month = , coverage_from_date__day = , coverage_to_date__month = , coverage_to_date__day = ) except KeyError : pass return queryset def reportTypeFilter ( queryset , querydict ) : try : report_type = querydict [ '' ] if report_type == '' : queryset = queryset . filter ( form_type__in = [ '' , '' , '' , '' , '' , '' , '' , '' , '' ] ) elif report_type == '' : queryset = queryset . filter ( form_type__in = [ '' , '' , '' , '' , '' , '' ] ) elif report_type == '' : queryset = queryset . filter ( form_type__in = [ '' , '' , '' ] ) elif report_type == '' : queryset = queryset . filter ( form_type__in = [ '' , '' , '' ] ) elif report_type == '' : queryset = queryset . filter ( form_type__in = [ '' , '' , '' ] ) elif report_type == '' : queryset = queryset . filter ( form_type__in = [ '' , '' , '' ] ) elif report_type == '' : queryset = queryset . filter ( form_type__in = [ '' , '' , '' ] ) elif report_type == '' : queryset = queryset . filter ( form_type__in = [ '' , '' , '' ] ) except KeyError : pass return queryset def orderingFilter ( queryset , querydict , fields ) : \"\"\"\"\"\" try : ordering = querydict [ '' ] if ordering . lstrip ( '' ) in fields : orderlist = [ ordering ] queryset = queryset . order_by ( * orderlist ) except KeyError : pass return queryset def committeeSearchSlow ( queryset , querydict ) : \"\"\"\"\"\" try : search_term = querydict [ '' ] ", "answer": "queryset = queryset . filter ( committee_name__icontains = search_term )"}, {"prompt": " import os import sys extensions = [ ] templates_path = [ '' ] source_suffix = '' master_doc = '' project = u'' copyright = u'' version = '' release = '' exclude_trees = [ ] pygments_style = '' html_theme = '' if os . environ . get ( '' ) else '' htmlhelp_basename = '' latex_documents = [ ( '' , '' , u'' , u'' , '' ) , ] latex_elements = { ", "answer": "'' : \"\" . join ( ("}, {"prompt": " import sys if sys . platform . startswith ( '' ) : from java . lang import Object , Class def unic ( item , * args ) : if isinstance ( item , Object ) and not isinstance ( item , Class ) : try : item = item . toString ( ) except : return _unrepresentable_object ( item ) return _unic ( item , * args ) elif sys . platform == '' : def unic ( item , * args ) : return _unic ( item , * args ) else : from unicodedata import normalize def unic ( item , * args ) : return normalize ( '' , _unic ( item , * args ) ) def _unic ( item , * args ) : try : return unicode ( item , * args ) ", "answer": "except UnicodeError :"}, {"prompt": " import os import logging import pkgutil import pkg_resources import ConfigParser import re import zc . buildout import config_enhance import subprocess import sys __ALL__ = [ \"\" , \"\" , \"\" ] EGG_URI_RE = re . compile ( \"\" ) LOG = logging . getLogger ( __name__ ) class PlatformVersions ( object ) : '''''' def __init__ ( self , buildout ) : '''''' self . buildout = buildout self . config_section = None self . source_section = None self . sources = None self . target_section = None self . platform_env_var = None def parse_config ( self ) : self . load_config_section_name ( ) self . load_platform_env_var ( ) self . load_source_section ( ) self . load_source_list ( ) self . load_target_section ( ) def load_platform_env_var ( self ) : if self . _config : platform_env_var = self . _config . get ( \"\" , None ) if platform_env_var : platform_env_var = platform_env_var . strip ( ) if len ( platform_env_var ) == : platform_env_var = None self . platform_env_var = platform_env_var def load_config_section_name ( self ) : self . config_section = self . buildout [ '' ] . get ( '' , '' ) try : self . _config = self . buildout [ self . config_section ] except : self . _config = None def load_source_section ( self ) : self . source_section = self . _get_platform ( ) def load_source_list ( self ) : source_list = [ ] if self . _config : source_str = self . _config . get ( '' , '' ) for name in source_str . split ( \"\" ) : name = name . strip ( ) if len ( name ) : source_list . append ( name ) for source in source_list : LOG . info ( \"\" , source ) self . sources = source_list else : self . sources = [ ] return source_list def load_target_section ( self ) : if '' in self . buildout [ '' ] : self . target_section = self . buildout [ '' ] [ '' ] else : self . target_section = '' def _get_platform_from_env ( self ) : platform_env = None if self . platform_env_var : platform_env = os . getenv ( self . platform_env_var , None ) if platform_env is not None and len ( platform_env ) > : LOG . debug ( \"\" , self . platform_env_var , platform_env ) else : LOG . debug ( \"\" , self . platform_env_var ) return platform_env def _get_platform_from_config ( self ) : if self . _config : platform_env = self . _config . get ( \"\" , None ) if platform_env : platform_env = platform_env . strip ( ) if len ( platform_env ) == : platform_env = None if platform_env is None : LOG . error ( \"\" , \"\" ) raise Exception ( \"\" ) else : LOG . info ( \"\" , self . config_section , \"\" , platform_env ) else : platform_env = None return platform_env def _get_platform ( self ) : '''''' platform_env = self . _get_platform_from_env ( ) if not platform_env : platform_env = self . _get_platform_from_config ( ) return platform_env def load_platform_versions ( self ) : new_versions = { } cp = ConfigParser . ConfigParser ( ) for file_name in self . sources : _load_config ( cp , file_name ) config_enhance . enhance ( cp ) if cp . has_section ( self . source_section ) : new_versions . update ( cp . items ( self . source_section ) ) else : LOG . warn ( \"\" , self . source_section ) LOG . warn ( \"\" ) for section in cp . sections ( ) : LOG . info ( \"\" , section ) return new_versions def load_develop_packages ( self ) : pkgs = [ ] if self . buildout is not None : buildout_section = self . buildout . get ( \"\" , None ) if buildout_section is not None : develop_str = buildout_section . get ( \"\" , None ) if develop_str is not None : develop_paths = [ vv for vv in develop_str . split ( ) if len ( vv ) ] if len ( develop_paths ) : develop_pkgs = lookup_develop_distributions ( develop_paths ) pkg_names = [ dd for dd in develop_pkgs ] pkgs . extend ( pkg_names ) if self . _config is not None : package_string = self . _config . get ( \"\" , None ) if package_string is not None : pkgs . extend ( [ ( vv . strip ( ) , None ) for vv in package_string . split ( ) ] ) return pkgs def load_composite_versions ( self ) : cur_versions = dict ( self . buildout [ self . target_section ] ) new_versions = self . load_platform_versions ( ) new_versions . update ( cur_versions ) for pkg in self . load_develop_packages ( ) : if pkg [ ] is None : LOG . info ( \"\" , pkg ) new_versions . pop ( pkg [ ] , None ) else : LOG . info ( \"\" , pkg [ ] , pkg [ ] ) new_versions [ pkg [ ] ] = pkg [ ] self . versions = new_versions return self . versions def apply_new_versions ( self ) : '''''' target = self . buildout [ self . target_section ] target . clear ( ) target . update ( self . versions ) zc . buildout . easy_install . default_versions ( self . versions ) for k , v in self . versions . iteritems ( ) : LOG . debug ( \"\" , k , v ) def apply_to_buildout ( self ) : self . parse_config ( ) self . load_composite_versions ( ) self . apply_new_versions ( ) def read_package_name_from_setup_py ( path ) : try : setup_py = os . path . join ( path , \"\" ) if os . path . exists ( setup_py ) : cmd = [ sys . executable , \"\" , \"\" , setup_py , \"\" , \"\" ] env = { \"\" : \"\" . join ( sys . path ) } proc = subprocess . Popen ( cmd , env = env , stdout = subprocess . PIPE ) result = proc . communicate ( ) vv = result [ ] if proc . returncode != : raise Exception ( \"\" % ( \"\" . join ( cmd ) , proc . returncode ) ) return parse_setup_py_version_output ( vv ) except ( Exception , IOError ) : LOG . exception ( \"\" , setup_py ) def parse_setup_py_version_output ( output ) : \"\"\"\"\"\" return tuple ( output . split ( ) [ - : ] ) ", "answer": "def read_package_name_from_pkg_resources ( path ) :"}, {"prompt": " \"\"\"\"\"\" import logging import sys import thread import threading import traceback from google . appengine . api . logservice import logservice from google . appengine . runtime import request_environment BACKGROUND_REQUEST_ID = '' class _BackgroundRequest ( object ) : \"\"\"\"\"\" def __init__ ( self ) : self . _ready_condition = threading . Condition ( ) self . _callable_ready = False self . _thread_id_ready = False def ProvideCallable ( self , target , args , kwargs ) : \"\"\"\"\"\" with self . _ready_condition : self . _target = target self . _args = args self . _kwargs = kwargs self . _callable_ready = True self . _ready_condition . notify ( ) while not self . _thread_id_ready : self . _ready_condition . wait ( ) return self . _thread_id def WaitForCallable ( self ) : \"\"\"\"\"\" with self . _ready_condition : self . _thread_id = thread . get_ident ( ) self . _thread_id_ready = True self . _ready_condition . notify ( ) while not self . _callable_ready : self . _ready_condition . wait ( ) return self . _target , self . _args , self . _kwargs class _BackgroundRequestsContainer ( object ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " \"\"\"\"\"\" from docutils import nodes , utils from docutils . parsers . rst import roles from sphinx import addnodes from sphinx . util import ws_re , caption_ref_re def sample_role ( name , rawtext , text , lineno , inliner , options = { } , content = [ ] ) : \"\"\"\"\"\" pass prefixed_roles = { '' : ( '' , '' ) , '' : ( '' , '' ) , } no_text_roles = [ '' , '' , ] def prefixed_role ( name , rawtext , text , lineno , inliner , options = { } , content = [ ] ) : prefix , baseuri = prefixed_roles [ name ] uri = baseuri + text display = utils . unescape ( text ) node = nodes . literal ( prefix , prefix ) ref = nodes . reference ( rawtext , display , refuri = uri , ** options ) node += ref return [ node ] , [ ] def url_role ( name , rawtext , text , lineno , inliner , options = { } , content = [ ] ) : uri = text display = '' node = nodes . literal ( '' , '' ) node += nodes . reference ( rawtext , name , refuri = uri , ** options ) ", "answer": "return [ node ] , [ ]"}, {"prompt": " from __future__ import ( absolute_import , division , generators , nested_scopes , print_function , unicode_literals , with_statement ) import os import unittest from contextlib import contextmanager from pants . base . build_file import BuildFile from pants . base . file_system_project_tree import FileSystemProjectTree from pants . build_graph . build_configuration import BuildConfiguration from pants . build_graph . build_file_aliases import BuildFileAliases , TargetMacro from pants . build_graph . target import Target from pants . util . contextutil import temporary_dir from pants . util . dirutil import touch class BuildConfigurationTest ( unittest . TestCase ) : def setUp ( self ) : self . build_configuration = BuildConfiguration ( ) def _register_aliases ( self , ** kwargs ) : self . build_configuration . register_aliases ( BuildFileAliases ( ** kwargs ) ) def test_register_bad ( self ) : ", "answer": "with self . assertRaises ( TypeError ) :"}, {"prompt": " import numpy as np from gym import utils from gym . envs . mujoco import mujoco_env class SwimmerEnv ( mujoco_env . MujocoEnv , utils . EzPickle ) : def __init__ ( self ) : mujoco_env . MujocoEnv . __init__ ( self , '' , ) utils . EzPickle . __init__ ( self ) self . ctrl_cost_coeff = self . finalize ( ) def _step ( self , a ) : xposbefore = self . model . data . qpos [ , ] self . do_simulation ( a , self . frame_skip ) xposafter = self . model . data . qpos [ , ] reward_fwd = ( xposafter - xposbefore ) / self . dt reward_ctrl = - self . ctrl_cost_coeff * np . square ( a ) . sum ( ) reward = reward_fwd + reward_ctrl ob = self . _get_obs ( ) return ob , reward , False , dict ( reward_fwd = reward_fwd , reward_ctrl = reward_ctrl ) def _get_obs ( self ) : qpos = self . model . data . qpos ", "answer": "qvel = self . model . data . qvel"}, {"prompt": " from openid . consumer import consumer from django . core . urlresolvers import reverse from allauth . utils import get_user_model from allauth . tests import TestCase , Mock , patch from . import views from . utils import AXAttribute class OpenIDTests ( TestCase ) : def test_discovery_failure ( self ) : \"\"\"\"\"\" resp = self . client . post ( reverse ( '' ) , dict ( openid = '' ) ) self . assertTrue ( '' in resp . context [ '' ] . errors ) def test_login ( self ) : resp = self . client . post ( reverse ( views . login ) , dict ( openid = '' ) ) assert '' in resp [ '' ] with patch ( '' '' ) as consumer_mock : ", "answer": "client = Mock ( )"}, {"prompt": " from __future__ import unicode_literals import logging import threading import spotify from spotify import ffi , lib , serialized , utils ", "answer": "__all__ = ["}, {"prompt": " \"\"\"\"\"\" _defaulttimeout = None import errno import jarray import string import struct import sys import threading import time import types import java . io . BufferedInputStream import java . io . BufferedOutputStream import java . io . InterruptedIOException import java . io . IOException import java . lang . String import java . lang . Exception import java . net . DatagramPacket import java . net . InetAddress import java . net . InetSocketAddress import java . net . Socket import java . net . BindException import java . net . ConnectException import java . net . NoRouteToHostException import java . net . PortUnreachableException import java . net . ProtocolException import java . net . SocketException import java . net . SocketTimeoutException import java . net . UnknownHostException import java . nio . ByteBuffer import java . nio . channels . DatagramChannel import java . nio . channels . ServerSocketChannel import java . nio . channels . SocketChannel import java . nio . channels . AlreadyConnectedException import java . nio . channels . AsynchronousCloseException import java . nio . channels . CancelledKeyException import java . nio . channels . ClosedByInterruptException import java . nio . channels . ClosedChannelException import java . nio . channels . ClosedSelectorException import java . nio . channels . ConnectionPendingException import java . nio . channels . IllegalBlockingModeException import java . nio . channels . IllegalSelectorException import java . nio . channels . NoConnectionPendingException import java . nio . channels . NonReadableChannelException import java . nio . channels . NonWritableChannelException import java . nio . channels . NotYetBoundException import java . nio . channels . NotYetConnectedException import java . nio . channels . UnresolvedAddressException import java . nio . channels . UnsupportedAddressTypeException import javax . net . ssl . SSLSocketFactory javax . net . ssl . SSLException javax . net . ssl . SSLHandshakeException javax . net . ssl . SSLKeyException javax . net . ssl . SSLPeerUnverifiedException javax . net . ssl . SSLProtocolException import org . python . core . io . DatagramSocketIO import org . python . core . io . ServerSocketIO import org . python . core . io . SocketIO from org . python . core . Py import newString as asPyString class error ( Exception ) : pass class herror ( error ) : pass class gaierror ( error ) : pass class timeout ( error ) : pass class sslerror ( error ) : pass ALL = None _exception_map = { ( java . io . IOException , ALL ) : lambda : error ( errno . ECONNRESET , '' ) , ( java . io . InterruptedIOException , ALL ) : lambda : timeout ( '' ) , ( java . net . BindException , ALL ) : lambda : error ( errno . EADDRINUSE , '' ) , ( java . net . ConnectException , ALL ) : lambda : error ( errno . ECONNREFUSED , '' ) , ( java . net . NoRouteToHostException , ALL ) : None , ( java . net . PortUnreachableException , ALL ) : None , ( java . net . ProtocolException , ALL ) : None , ( java . net . SocketException , ALL ) : None , ( java . net . SocketTimeoutException , ALL ) : lambda : timeout ( '' ) , ( java . net . UnknownHostException , ALL ) : lambda : gaierror ( errno . EGETADDRINFOFAILED , '' ) , ( java . nio . channels . AlreadyConnectedException , ALL ) : lambda : error ( errno . EISCONN , '' ) , ( java . nio . channels . AsynchronousCloseException , ALL ) : None , ( java . nio . channels . CancelledKeyException , ALL ) : None , ( java . nio . channels . ClosedByInterruptException , ALL ) : None , ( java . nio . channels . ClosedChannelException , ALL ) : lambda : error ( errno . EPIPE , '' ) , ( java . nio . channels . ClosedSelectorException , ALL ) : None , ( java . nio . channels . ConnectionPendingException , ALL ) : None , ( java . nio . channels . IllegalBlockingModeException , ALL ) : None , ( java . nio . channels . IllegalSelectorException , ALL ) : None , ( java . nio . channels . NoConnectionPendingException , ALL ) : None , ( java . nio . channels . NonReadableChannelException , ALL ) : None , ( java . nio . channels . NonWritableChannelException , ALL ) : None , ( java . nio . channels . NotYetBoundException , ALL ) : None , ( java . nio . channels . NotYetConnectedException , ALL ) : None , ( java . nio . channels . UnresolvedAddressException , ALL ) : lambda : gaierror ( errno . EGETADDRINFOFAILED , '' ) , ( java . nio . channels . UnsupportedAddressTypeException , ALL ) : None , ( javax . net . ssl . SSLException , ALL ) : lambda : sslerror ( - , '' ) , ( javax . net . ssl . SSLHandshakeException , ALL ) : lambda : sslerror ( - , '' ) , ( javax . net . ssl . SSLKeyException , ALL ) : lambda : sslerror ( - , '' ) , ( javax . net . ssl . SSLPeerUnverifiedException , ALL ) : lambda : sslerror ( - , '' ) , ( javax . net . ssl . SSLProtocolException , ALL ) : lambda : sslerror ( - , '' ) , } def would_block_error ( exc = None ) : return error ( errno . EWOULDBLOCK , '' ) def _map_exception ( exc , circumstance = ALL ) : mapped_exception = _exception_map . get ( ( exc . __class__ , circumstance ) ) if mapped_exception : exception = mapped_exception ( ) else : exception = error ( - , '' % exc ) exception . java_exception = exc return exception MODE_BLOCKING = '' MODE_NONBLOCKING = '' MODE_TIMEOUT = '' _permitted_modes = ( MODE_BLOCKING , MODE_NONBLOCKING , MODE_TIMEOUT ) SHUT_RD = SHUT_WR = SHUT_RDWR = AF_UNSPEC = AF_INET = AF_INET6 = AI_PASSIVE = AI_CANONNAME = SOCK_DGRAM = SOCK_STREAM = SOCK_RAW = SOCK_RDM = SOCK_SEQPACKET = SOL_SOCKET = IPPROTO_TCP = IPPROTO_UDP = SO_BROADCAST = SO_KEEPALIVE = SO_LINGER = SO_OOBINLINE = SO_RCVBUF = SO_REUSEADDR = SO_SNDBUF = SO_TIMEOUT = TCP_NODELAY = INADDR_ANY = \"\" INADDR_BROADCAST = \"\" SO_ACCEPTCONN = - SO_DEBUG = - SO_DONTROUTE = - SO_ERROR = - SO_EXCLUSIVEADDRUSE = - SO_RCVLOWAT = - SO_RCVTIMEO = - SO_REUSEPORT = - SO_SNDLOWAT = - SO_SNDTIMEO = - SO_TYPE = - SO_USELOOPBACK = - __all__ = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , ] def _constant_to_name ( const_value ) : sock_module = sys . modules [ '' ] try : for name in dir ( sock_module ) : if getattr ( sock_module , name ) is const_value : return name return \"\" finally : sock_module = None class _nio_impl : timeout = None mode = MODE_BLOCKING def getpeername ( self ) : return ( self . jsocket . getInetAddress ( ) . getHostAddress ( ) , self . jsocket . getPort ( ) ) def config ( self , mode , timeout ) : self . mode = mode if self . mode == MODE_BLOCKING : self . jchannel . configureBlocking ( ) if self . mode == MODE_NONBLOCKING : self . jchannel . configureBlocking ( ) if self . mode == MODE_TIMEOUT : self . jchannel . configureBlocking ( ) self . _timeout_millis = int ( timeout * ) self . jsocket . setSoTimeout ( self . _timeout_millis ) def getsockopt ( self , level , option ) : if self . options . has_key ( ( level , option ) ) : result = getattr ( self . jsocket , \"\" % self . options [ ( level , option ) ] ) ( ) if option == SO_LINGER : if result == - : enabled , linger_time = , else : enabled , linger_time = , result return struct . pack ( '' , enabled , linger_time ) return result else : raise error ( errno . ENOPROTOOPT , \"\" % ( _constant_to_name ( option ) , _constant_to_name ( level ) , str ( self . jsocket ) ) ) def setsockopt ( self , level , option , value ) : if self . options . has_key ( ( level , option ) ) : if option == SO_LINGER : values = struct . unpack ( '' , value ) self . jsocket . setSoLinger ( * values ) else : getattr ( self . jsocket , \"\" % self . options [ ( level , option ) ] ) ( value ) else : raise error ( errno . ENOPROTOOPT , \"\" % ( _constant_to_name ( option ) , _constant_to_name ( level ) , str ( self . jsocket ) ) ) def close ( self ) : self . jsocket . close ( ) def getchannel ( self ) : return self . jchannel def fileno ( self ) : return self . socketio class _client_socket_impl ( _nio_impl ) : options = { ( SOL_SOCKET , SO_KEEPALIVE ) : '' , ( SOL_SOCKET , SO_LINGER ) : '' , ( SOL_SOCKET , SO_OOBINLINE ) : '' , ( SOL_SOCKET , SO_RCVBUF ) : '' , ( SOL_SOCKET , SO_REUSEADDR ) : '' , ( SOL_SOCKET , SO_SNDBUF ) : '' , ( SOL_SOCKET , SO_TIMEOUT ) : '' , ( IPPROTO_TCP , TCP_NODELAY ) : '' , } def __init__ ( self , socket = None ) : if socket : self . jchannel = socket . getChannel ( ) self . host = socket . getInetAddress ( ) . getHostAddress ( ) self . port = socket . getPort ( ) else : self . jchannel = java . nio . channels . SocketChannel . open ( ) self . host = None self . port = None self . jsocket = self . jchannel . socket ( ) self . socketio = org . python . core . io . SocketIO ( self . jchannel , '' ) def bind ( self , host , port , reuse_addr ) : self . jsocket . setReuseAddress ( reuse_addr ) self . jsocket . bind ( java . net . InetSocketAddress ( host , port ) ) def connect ( self , host , port ) : self . host = host self . port = port if self . mode == MODE_TIMEOUT : self . jsocket . connect ( java . net . InetSocketAddress ( self . host , self . port ) , self . _timeout_millis ) else : self . jchannel . connect ( java . net . InetSocketAddress ( self . host , self . port ) ) def finish_connect ( self ) : return self . jchannel . finishConnect ( ) def _do_read_net ( self , buf ) : return self . jsocket . getInputStream ( ) . read ( buf ) def _do_read_nio ( self , buf ) : bytebuf = java . nio . ByteBuffer . wrap ( buf ) count = self . jchannel . read ( bytebuf ) return count def _do_write_net ( self , buf ) : self . jsocket . getOutputStream ( ) . write ( buf ) return len ( buf ) def _do_write_nio ( self , buf ) : bytebuf = java . nio . ByteBuffer . wrap ( buf ) count = self . jchannel . write ( bytebuf ) return count def read ( self , buf ) : if self . mode == MODE_TIMEOUT : return self . _do_read_net ( buf ) else : return self . _do_read_nio ( buf ) def write ( self , buf ) : if self . mode == MODE_TIMEOUT : return self . _do_write_net ( buf ) else : return self . _do_write_nio ( buf ) def shutdown ( self , how ) : if how in ( SHUT_RD , SHUT_RDWR ) : self . jsocket . shutdownInput ( ) if how in ( SHUT_WR , SHUT_RDWR ) : self . jsocket . shutdownOutput ( ) class _server_socket_impl ( _nio_impl ) : options = { ( SOL_SOCKET , SO_RCVBUF ) : '' , ( SOL_SOCKET , SO_REUSEADDR ) : '' , ( SOL_SOCKET , SO_TIMEOUT ) : '' , } def __init__ ( self , host , port , backlog , reuse_addr ) : self . jchannel = java . nio . channels . ServerSocketChannel . open ( ) self . jsocket = self . jchannel . socket ( ) if host : bindaddr = java . net . InetSocketAddress ( host , port ) else : bindaddr = java . net . InetSocketAddress ( port ) self . jsocket . setReuseAddress ( reuse_addr ) self . jsocket . bind ( bindaddr , backlog ) self . socketio = org . python . core . io . ServerSocketIO ( self . jchannel , '' ) def accept ( self ) : if self . mode in ( MODE_BLOCKING , MODE_NONBLOCKING ) : new_cli_chan = self . jchannel . accept ( ) if new_cli_chan != None : return _client_socket_impl ( new_cli_chan . socket ( ) ) else : return None else : new_cli_sock = self . jsocket . accept ( ) return _client_socket_impl ( new_cli_sock ) def shutdown ( self , how ) : pass class _datagram_socket_impl ( _nio_impl ) : options = { ( SOL_SOCKET , SO_BROADCAST ) : '' , ( SOL_SOCKET , SO_RCVBUF ) : '' , ( SOL_SOCKET , SO_REUSEADDR ) : '' , ( SOL_SOCKET , SO_SNDBUF ) : '' , ( SOL_SOCKET , SO_TIMEOUT ) : '' , } def __init__ ( self , port = None , address = None , reuse_addr = ) : self . jchannel = java . nio . channels . DatagramChannel . open ( ) self . jsocket = self . jchannel . socket ( ) if port is not None : if address is not None : local_address = java . net . InetSocketAddress ( address , port ) else : local_address = java . net . InetSocketAddress ( port ) self . jsocket . setReuseAddress ( reuse_addr ) self . jsocket . bind ( local_address ) self . socketio = org . python . core . io . DatagramSocketIO ( self . jchannel , '' ) def connect ( self , host , port ) : self . jchannel . connect ( java . net . InetSocketAddress ( host , port ) ) def disconnect ( self ) : \"\"\"\"\"\" self . jchannel . disconnect ( ) def shutdown ( self , how ) : pass def _do_send_net ( self , byte_array , socket_address , flags ) : num_bytes = len ( byte_array ) if self . jsocket . isConnected ( ) and socket_address is None : packet = java . net . DatagramPacket ( byte_array , num_bytes ) else : packet = java . net . DatagramPacket ( byte_array , num_bytes , socket_address ) self . jsocket . send ( packet ) return num_bytes def _do_send_nio ( self , byte_array , socket_address , flags ) : byte_buf = java . nio . ByteBuffer . wrap ( byte_array ) if self . jchannel . isConnected ( ) and socket_address is None : bytes_sent = self . jchannel . write ( byte_buf ) else : bytes_sent = self . jchannel . send ( byte_buf , socket_address ) return bytes_sent def sendto ( self , byte_array , host , port , flags ) : socket_address = java . net . InetSocketAddress ( host , port ) if self . mode == MODE_TIMEOUT : return self . _do_send_net ( byte_array , socket_address , flags ) else : return self . _do_send_nio ( byte_array , socket_address , flags ) def send ( self , byte_array , flags ) : if self . mode == MODE_TIMEOUT : return self . _do_send_net ( byte_array , None , flags ) else : return self . _do_send_nio ( byte_array , None , flags ) def _do_receive_net ( self , return_source_address , num_bytes , flags ) : byte_array = jarray . zeros ( num_bytes , '' ) packet = java . net . DatagramPacket ( byte_array , num_bytes ) self . jsocket . receive ( packet ) bytes_rcvd = packet . getLength ( ) if bytes_rcvd < num_bytes : byte_array = byte_array [ : bytes_rcvd ] return_data = byte_array . tostring ( ) if return_source_address : host = None if packet . getAddress ( ) : host = packet . getAddress ( ) . getHostAddress ( ) port = packet . getPort ( ) return return_data , ( host , port ) else : return return_data def _do_receive_nio ( self , return_source_address , num_bytes , flags ) : byte_array = jarray . zeros ( num_bytes , '' ) byte_buf = java . nio . ByteBuffer . wrap ( byte_array ) source_address = self . jchannel . receive ( byte_buf ) if source_address is None and not self . jchannel . isBlocking ( ) : raise would_block_error ( ) byte_buf . flip ( ) ; bytes_read = byte_buf . remaining ( ) if bytes_read < num_bytes : byte_array = byte_array [ : bytes_read ] return_data = byte_array . tostring ( ) if return_source_address : return return_data , ( source_address . getAddress ( ) . getHostAddress ( ) , source_address . getPort ( ) ) else : return return_data def recvfrom ( self , num_bytes , flags ) : if self . mode == MODE_TIMEOUT : return self . _do_receive_net ( , num_bytes , flags ) else : return self . _do_receive_nio ( , num_bytes , flags ) def recv ( self , num_bytes , flags ) : if self . mode == MODE_TIMEOUT : return self . _do_receive_net ( , num_bytes , flags ) else : return self . _do_receive_nio ( , num_bytes , flags ) has_ipv6 = False def _gethostbyaddr ( name ) : addresses = java . net . InetAddress . getAllByName ( gethostbyname ( name ) ) names = [ ] addrs = [ ] for addr in addresses : names . append ( asPyString ( addr . getHostName ( ) ) ) addrs . append ( asPyString ( addr . getHostAddress ( ) ) ) return ( names , addrs ) def getfqdn ( name = None ) : \"\"\"\"\"\" if not name : name = gethostname ( ) names , addrs = _gethostbyaddr ( name ) for a in names : if a . find ( \"\" ) >= : return a return name def gethostname ( ) : try : return asPyString ( java . net . InetAddress . getLocalHost ( ) . getHostName ( ) ) except java . lang . Exception , jlx : raise _map_exception ( jlx ) def gethostbyname ( name ) : try : return asPyString ( java . net . InetAddress . getByName ( name ) . getHostAddress ( ) ) except java . lang . Exception , jlx : raise _map_exception ( jlx ) def gethostbyaddr ( name ) : names , addrs = _gethostbyaddr ( name ) return ( names [ ] , names , addrs ) def getservbyname ( servicename , protocolname = None ) : raise NotImplementedError ( \"\" ) def getservbyport ( port , protocolname = None ) : raise NotImplementedError ( \"\" ) def getprotobyname ( protocolname = None ) : raise NotImplementedError ( \"\" ) def _realsocket ( family = AF_INET , type = SOCK_STREAM , protocol = ) : assert family == AF_INET , \"\" assert type in ( SOCK_DGRAM , SOCK_STREAM ) , \"\" if type == SOCK_STREAM : if protocol != : assert protocol == IPPROTO_TCP , \"\" return _tcpsocket ( ) else : if protocol != : assert protocol == IPPROTO_UDP , \"\" return _udpsocket ( ) def getaddrinfo ( host , port , family = AF_INET , socktype = None , proto = , flags = None ) : try : if not family in [ AF_INET , AF_INET6 , AF_UNSPEC ] : raise gaierror ( errno . EIO , '' ) filter_fns = [ ] filter_fns . append ( { AF_INET : lambda x : isinstance ( x , java . net . Inet4Address ) , AF_INET6 : lambda x : isinstance ( x , java . net . Inet6Address ) , AF_UNSPEC : lambda x : isinstance ( x , java . net . InetAddress ) , } [ family ] ) if host == \"\" : host = java . net . InetAddress . getLocalHost ( ) . getHostName ( ) passive_mode = flags is not None and flags & AI_PASSIVE canonname_mode = flags is not None and flags & AI_CANONNAME results = [ ] for a in java . net . InetAddress . getAllByName ( host ) : if len ( [ f for f in filter_fns if f ( a ) ] ) : family = { java . net . Inet4Address : AF_INET , java . net . Inet6Address : AF_INET6 } [ a . getClass ( ) ] if passive_mode and not canonname_mode : canonname = \"\" else : canonname = asPyString ( a . getCanonicalHostName ( ) ) if host is None and passive_mode and not canonname_mode : sockname = INADDR_ANY else : sockname = asPyString ( a . getHostAddress ( ) ) results . append ( ( family , socktype , proto , canonname , ( sockname , port ) ) ) return results except java . lang . Exception , jlx : raise _map_exception ( jlx ) def getnameinfo ( sock_addr , flags ) : raise NotImplementedError ( \"\" ) def getdefaulttimeout ( ) : return _defaulttimeout def _calctimeoutvalue ( value ) : if value is None : return None try : floatvalue = float ( value ) except : raise TypeError ( '' ) if floatvalue < : raise ValueError ( \"\" ) if floatvalue < : return return floatvalue def setdefaulttimeout ( timeout ) : global _defaulttimeout try : _defaulttimeout = _calctimeoutvalue ( timeout ) finally : _nonblocking_api_mixin . timeout = _defaulttimeout def htons ( x ) : return x def htonl ( x ) : return x def ntohs ( x ) : return x def ntohl ( x ) : return x def inet_pton ( family , ip_string ) : try : ia = java . net . InetAddress . getByName ( ip_string ) bytes = [ ] for byte in ia . getAddress ( ) : if byte < : bytes . append ( byte + ) else : bytes . append ( byte ) return \"\" . join ( [ chr ( byte ) for byte in bytes ] ) except java . lang . Exception , jlx : raise _map_exception ( jlx ) def inet_ntop ( family , packed_ip ) : try : jByteArray = jarray . array ( packed_ip , '' ) ia = java . net . InetAddress . getByAddress ( jByteArray ) return ia . getHostAddress ( ) except java . lang . Exception , jlx : raise _map_exception ( jlx ) def inet_aton ( ip_string ) : return inet_pton ( AF_INET , ip_string ) def inet_ntoa ( packed_ip ) : return inet_ntop ( AF_INET , packed_ip ) class _nonblocking_api_mixin : mode = MODE_BLOCKING reference_count = close_lock = threading . Lock ( ) def __init__ ( self ) : self . timeout = _defaulttimeout if self . timeout is not None : self . mode = MODE_TIMEOUT self . pending_options = { ( SOL_SOCKET , SO_REUSEADDR ) : , } def gettimeout ( self ) : return self . timeout def settimeout ( self , timeout ) : self . timeout = _calctimeoutvalue ( timeout ) if self . timeout is None : self . mode = MODE_BLOCKING elif self . timeout < : self . mode = MODE_NONBLOCKING else : self . mode = MODE_TIMEOUT self . _config ( ) def setblocking ( self , flag ) : if flag : self . mode = MODE_BLOCKING self . timeout = None else : self . mode = MODE_NONBLOCKING self . timeout = self . _config ( ) def getblocking ( self ) : return self . mode == MODE_BLOCKING def setsockopt ( self , level , optname , value ) : try : if self . sock_impl : self . sock_impl . setsockopt ( level , optname , value ) else : self . pending_options [ ( level , optname ) ] = value except java . lang . Exception , jlx : raise _map_exception ( jlx ) def getsockopt ( self , level , optname ) : try : if self . sock_impl : return self . sock_impl . getsockopt ( level , optname ) else : return self . pending_options . get ( ( level , optname ) , None ) except java . lang . Exception , jlx : raise _map_exception ( jlx ) def shutdown ( self , how ) : assert how in ( SHUT_RD , SHUT_WR , SHUT_RDWR ) if not self . sock_impl : raise error ( errno . ENOTCONN , \"\" ) try : self . sock_impl . shutdown ( how ) except java . lang . Exception , jlx : raise _map_exception ( jlx ) def close ( self ) : try : if self . sock_impl : self . sock_impl . close ( ) except java . lang . Exception , jlx : raise _map_exception ( jlx ) def _config ( self ) : assert self . mode in _permitted_modes if self . sock_impl : self . sock_impl . config ( self . mode , self . timeout ) for level , optname in self . pending_options . keys ( ) : if optname != SO_REUSEADDR : self . sock_impl . setsockopt ( level , optname , self . pending_options [ ( level , optname ) ] ) def getchannel ( self ) : if not self . sock_impl : return None return self . sock_impl . getchannel ( ) def fileno ( self ) : if not self . sock_impl : return None return self . sock_impl . fileno ( ) def _get_jsocket ( self ) : return self . sock_impl . jsocket def _unpack_address_tuple ( address_tuple ) : error_message = \"\" if not isinstance ( address_tuple , tuple ) or not isinstance ( address_tuple [ ] , basestring ) or not isinstance ( address_tuple [ ] , ( int , long ) ) : raise TypeError ( error_message ) hostname = address_tuple [ ] if isinstance ( hostname , unicode ) : hostname = hostname . encode ( ) hostname = hostname . strip ( ) return hostname , address_tuple [ ] class _tcpsocket ( _nonblocking_api_mixin ) : sock_impl = None istream = None ostream = None local_addr = None server = def __init__ ( self ) : _nonblocking_api_mixin . __init__ ( self ) def bind ( self , addr ) : assert not self . sock_impl assert not self . local_addr _unpack_address_tuple ( addr ) self . local_addr = addr def listen ( self , backlog ) : \"\" try : assert not self . sock_impl self . server = if self . local_addr : host , port = _unpack_address_tuple ( self . local_addr ) else : host , port = \"\" , self . sock_impl = _server_socket_impl ( host , port , backlog , self . pending_options [ ( SOL_SOCKET , SO_REUSEADDR ) ] ) self . _config ( ) except java . lang . Exception , jlx : raise _map_exception ( jlx ) def accept ( self ) : \"\" try : if not self . sock_impl : self . listen ( ) assert self . server new_sock = self . sock_impl . accept ( ) if not new_sock : raise would_block_error ( ) cliconn = _tcpsocket ( ) cliconn . pending_options [ ( SOL_SOCKET , SO_REUSEADDR ) ] = new_sock . jsocket . getReuseAddress ( ) cliconn . sock_impl = new_sock cliconn . _setup ( ) return cliconn , new_sock . getpeername ( ) except java . lang . Exception , jlx : raise _map_exception ( jlx ) def _get_host_port ( self , addr ) : host , port = _unpack_address_tuple ( addr ) if host == \"\" : host = java . net . InetAddress . getLocalHost ( ) return host , port def _do_connect ( self , addr ) : try : assert not self . sock_impl host , port = self . _get_host_port ( addr ) self . sock_impl = _client_socket_impl ( ) if self . local_addr : bind_host , bind_port = _unpack_address_tuple ( self . local_addr ) self . sock_impl . bind ( bind_host , bind_port , self . pending_options [ ( SOL_SOCKET , SO_REUSEADDR ) ] ) self . _config ( ) self . sock_impl . connect ( host , port ) except java . lang . Exception , jlx : raise _map_exception ( jlx ) def connect ( self , addr ) : \"\" self . _do_connect ( addr ) self . _setup ( ) def connect_ex ( self , addr ) : \"\" if not self . sock_impl : self . _do_connect ( addr ) if self . sock_impl . finish_connect ( ) : self . _setup ( ) if self . mode == MODE_NONBLOCKING : return errno . EISCONN return return errno . EINPROGRESS def _setup ( self ) : if self . mode != MODE_NONBLOCKING : self . istream = self . sock_impl . jsocket . getInputStream ( ) self . ostream = self . sock_impl . jsocket . getOutputStream ( ) def recv ( self , n ) : try : if not self . sock_impl : raise error ( errno . ENOTCONN , '' ) if self . sock_impl . jchannel . isConnectionPending ( ) : self . sock_impl . jchannel . finishConnect ( ) data = jarray . zeros ( n , '' ) m = self . sock_impl . read ( data ) if m == - : return \"\" elif m <= : if self . mode == MODE_NONBLOCKING : raise would_block_error ( ) return \"\" if m < n : data = data [ : m ] return data . tostring ( ) except java . lang . Exception , jlx : raise _map_exception ( jlx ) def recvfrom ( self , n ) : return self . recv ( n ) , None def send ( self , s ) : try : if not self . sock_impl : raise error ( errno . ENOTCONN , '' ) if self . sock_impl . jchannel . isConnectionPending ( ) : self . sock_impl . jchannel . finishConnect ( ) numwritten = self . sock_impl . write ( s ) if numwritten == and self . mode == MODE_NONBLOCKING : raise would_block_error ( ) return numwritten except java . lang . Exception , jlx : raise _map_exception ( jlx ) sendall = send def getsockname ( self ) : try : if not self . sock_impl : host , port = self . local_addr or ( \"\" , ) host = java . net . InetAddress . getByName ( host ) . getHostAddress ( ) else : if self . server : host = self . sock_impl . jsocket . getInetAddress ( ) . getHostAddress ( ) else : host = self . sock_impl . jsocket . getLocalAddress ( ) . getHostAddress ( ) port = self . sock_impl . jsocket . getLocalPort ( ) return ( host , port ) except java . lang . Exception , jlx : raise _map_exception ( jlx ) def getpeername ( self ) : try : assert self . sock_impl assert not self . server host = self . sock_impl . jsocket . getInetAddress ( ) . getHostAddress ( ) port = self . sock_impl . jsocket . getPort ( ) return ( host , port ) except java . lang . Exception , jlx : raise _map_exception ( jlx ) def close ( self ) : try : if self . istream : self . istream . close ( ) if self . ostream : self . ostream . close ( ) if self . sock_impl : self . sock_impl . close ( ) except java . lang . Exception , jlx : raise _map_exception ( jlx ) class _udpsocket ( _nonblocking_api_mixin ) : sock_impl = None addr = None def __init__ ( self ) : _nonblocking_api_mixin . __init__ ( self ) def bind ( self , addr ) : try : assert not self . sock_impl host , port = _unpack_address_tuple ( addr ) if host == \"\" : host = INADDR_ANY host_address = java . net . InetAddress . getByName ( host ) self . sock_impl = _datagram_socket_impl ( port , host_address , self . pending_options [ ( SOL_SOCKET , SO_REUSEADDR ) ] ) self . _config ( ) except java . lang . Exception , jlx : raise _map_exception ( jlx ) def _do_connect ( self , addr ) : try : host , port = _unpack_address_tuple ( addr ) assert not self . addr self . addr = addr if not self . sock_impl : self . sock_impl = _datagram_socket_impl ( ) self . _config ( ) self . sock_impl . connect ( host , port ) except java . lang . Exception , jlx : raise _map_exception ( jlx ) def connect ( self , addr ) : self . _do_connect ( addr ) def connect_ex ( self , addr ) : if not self . sock_impl : self . _do_connect ( addr ) return def sendto ( self , data , p1 , p2 = None ) : try : if not p2 : flags , addr = , p1 else : flags , addr = , p2 if not self . sock_impl : self . sock_impl = _datagram_socket_impl ( ) self . _config ( ) host , port = _unpack_address_tuple ( addr ) if host == \"\" : host = INADDR_BROADCAST byte_array = java . lang . String ( data ) . getBytes ( '' ) result = self . sock_impl . sendto ( byte_array , host , port , flags ) return result except java . lang . Exception , jlx : raise _map_exception ( jlx ) def send ( self , data , flags = None ) : if not self . addr : raise error ( errno . ENOTCONN , \"\" ) byte_array = java . lang . String ( data ) . getBytes ( '' ) return self . sock_impl . send ( byte_array , flags ) def recvfrom ( self , num_bytes , flags = None ) : \"\"\"\"\"\" try : if not self . sock_impl : self . sock_impl = _datagram_socket_impl ( ) self . _config ( ) return self . sock_impl . recvfrom ( num_bytes , flags ) except java . lang . Exception , jlx : raise _map_exception ( jlx ) def recv ( self , num_bytes , flags = None ) : if not self . sock_impl : raise error ( errno . ENOTCONN , \"\" ) try : return self . sock_impl . recv ( num_bytes , flags ) except java . lang . Exception , jlx : raise _map_exception ( jlx ) def getsockname ( self ) : try : assert self . sock_impl host = self . sock_impl . jsocket . getLocalAddress ( ) . getHostAddress ( ) port = self . sock_impl . jsocket . getLocalPort ( ) return ( host , port ) except java . lang . Exception , jlx : raise _map_exception ( jlx ) def getpeername ( self ) : try : assert self . sock host = self . sock_impl . jsocket . getInetAddress ( ) . getHostAddress ( ) port = self . sock_impl . jsocket . getPort ( ) return ( host , port ) ", "answer": "except java . lang . Exception , jlx :"}, {"prompt": " import re from speech_rest import main ", "answer": "def test_main ( resource , capsys ) :"}, {"prompt": " \"\"\"\"\"\" from __future__ import division import numpy as np from . . utils . validation import check_array , check_consistent_length from . . utils . validation import column_or_1d from . . externals . six import string_types import warnings __ALL__ = [ \"\" , \"\" , \"\" , \"\" , \"\" ] def _check_reg_targets ( y_true , y_pred , multioutput ) : \"\"\"\"\"\" check_consistent_length ( y_true , y_pred ) y_true = check_array ( y_true , ensure_2d = False ) y_pred = check_array ( y_pred , ensure_2d = False ) if y_true . ndim == : y_true = y_true . reshape ( ( - , ) ) if y_pred . ndim == : y_pred = y_pred . reshape ( ( - , ) ) if y_true . shape [ ] != y_pred . shape [ ] : raise ValueError ( \"\" \"\" . format ( y_true . shape [ ] , y_pred . shape [ ] ) ) n_outputs = y_true . shape [ ] multioutput_options = ( None , '' , '' , '' ) if multioutput not in multioutput_options : multioutput = check_array ( multioutput , ensure_2d = False ) if n_outputs == : raise ValueError ( \"\" \"\" ) elif n_outputs != len ( multioutput ) : raise ValueError ( ( \"\" \"\" ) % ( len ( multioutput ) , n_outputs ) ) y_type = '' if n_outputs == else '' return y_type , y_true , y_pred , multioutput def mean_absolute_error ( y_true , y_pred , sample_weight = None , multioutput = '' ) : \"\"\"\"\"\" y_type , y_true , y_pred , multioutput = _check_reg_targets ( y_true , y_pred , multioutput ) output_errors = np . average ( np . abs ( y_pred - y_true ) , weights = sample_weight , axis = ) if isinstance ( multioutput , string_types ) : if multioutput == '' : return output_errors elif multioutput == '' : multioutput = None return np . average ( output_errors , weights = multioutput ) def mean_squared_error ( y_true , y_pred , sample_weight = None , multioutput = '' ) : \"\"\"\"\"\" y_type , y_true , y_pred , multioutput = _check_reg_targets ( ", "answer": "y_true , y_pred , multioutput )"}, {"prompt": " xilinx_board_type = '' weblab_xilinx_experiment_port_number = xilinx_home = \"\" xilinx_impact_full_path = [ \"\" , \"\" ] xilinx_programmer_type = '' xilinx_device_to_send_commands = '' xilinx_jtag_blazer_jbmanager_svf2jsvf_full_path = [ \"\" , \"\" ] xilinx_jtag_blazer_jbmanager_target_full_path = [ \"\" , \"\" ] xilinx_jtag_blazer_device_ip_PLD = \"\" xilinx_http_device_ip_PLD = \"\" xilinx_http_device_port_PLD = xilinx_http_device_app_PLD = \"\" xilinx_batch_content_PLD = \"\"\"\"\"\" ", "answer": "pld_webcam_url = '''''' "}, {"prompt": " from __future__ import division , unicode_literals import re import json import copy from collections import OrderedDict , defaultdict import config import biblio from . messages import * from . htmlhelpers import * def transformDataBlocks ( doc , lines ) : inBlock = False blockTypes = { '' : transformPropdef , '' : transformDescdef , '' : transformElementdef , '' : transformArgumentdef , '' : transformRailroad , '' : transformBiblio , '' : transformAnchors , '' : transformLinkDefaults , '' : transformIgnoredSpecs , '' : transformInfo , '' : transformInclude , '' : transformPre } blockType = \"\" tagName = \"\" startLine = newLines = [ ] for ( i , line ) in enumerate ( lines ) : match = re . match ( r\"\" , line , re . I ) if match and not inBlock : inBlock = True startLine = i tagName = match . group ( ) typeMatch = re . search ( \"\" . join ( blockTypes . keys ( ) ) , match . group ( ) ) if typeMatch : blockType = typeMatch . group ( ) else : blockType = \"\" match = re . match ( r\"\" + tagName + \"\" , line , re . I ) if match and inBlock : inBlock = False if startLine == i : match = re . match ( r\"\" . format ( tagName ) , line , re . I ) repl = blockTypes [ blockType ] ( lines = [ match . group ( ) ] , tagName = tagName , firstLine = match . group ( ) , doc = doc ) newLines . extend ( repl ) newLines . append ( \"\" . format ( - len ( repl ) - ) ) newLines . append ( match . group ( ) ) elif re . match ( r\"\" , match . group ( ) ) : repl = blockTypes [ blockType ] ( lines = lines [ startLine + : i ] , tagName = tagName , firstLine = lines [ startLine ] , doc = doc ) newLines . extend ( repl ) newLines . append ( \"\" . format ( ( i - startLine ) - len ( repl ) - ) ) newLines . append ( match . group ( ) ) else : repl = blockTypes [ blockType ] ( lines = lines [ startLine + : i ] + [ match . group ( ) ] , tagName = tagName , firstLine = lines [ startLine ] , doc = doc ) newLines . extend ( repl ) newLines . append ( \"\" . format ( ( i - startLine ) - len ( repl ) - ) ) newLines . append ( match . group ( ) ) tagName = \"\" blockType = \"\" continue if inBlock : continue newLines . append ( line ) return newLines def transformPre ( lines , tagName , firstLine , ** kwargs ) : if len ( lines ) == : return [ firstLine , \"\" . format ( tagName ) ] if re . match ( r\"\" , lines [ - ] ) : lastLine = \"\" . format ( tagName ) lines = lines [ : - ] else : lastLine = \"\" . format ( tagName ) if len ( lines ) == : return [ firstLine , lastLine ] indent = float ( \"\" ) for ( i , line ) in enumerate ( lines ) : if line . strip ( ) == \"\" : continue lines [ i ] = lines [ i ] . replace ( \"\" , \"\" ) indent = min ( indent , len ( re . match ( r\"\" , lines [ i ] ) . group ( ) ) ) if indent == float ( \"\" ) : indent = for ( i , line ) in enumerate ( lines ) : if line . strip ( ) == \"\" : continue lines [ i ] = lines [ i ] [ indent : ] lines [ ] = firstLine . rstrip ( ) + lines [ ] lines . append ( lastLine ) return lines def transformPropdef ( lines , doc , firstLine , ** kwargs ) : attrs = OrderedDict ( ) parsedAttrs = parseDefBlock ( lines , \"\" ) forHint = \"\" if \"\" in parsedAttrs : forHint = \"\" . format ( parsedAttrs [ \"\" ] . split ( \"\" ) [ ] . strip ( ) ) if \"\" in firstLine or \"\" in parsedAttrs : attrs [ \"\" ] = None attrs [ \"\" ] = None ret = [ \"\" . format ( forHint = forHint ) ] elif \"\" in firstLine : attrs [ \"\" ] = None attrs [ \"\" ] = None for defaultKey in [ \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ] : attrs [ defaultKey ] = \"\" ret = [ \"\" . format ( forHint = forHint ) ] else : attrs [ \"\" ] = None attrs [ \"\" ] = None attrs [ \"\" ] = None attrs [ \"\" ] = \"\" attrs [ \"\" ] = None attrs [ \"\" ] = \"\" attrs [ \"\" ] = \"\" attrs [ \"\" ] = \"\" attrs [ \"\" ] = \"\" ret = [ \"\" . format ( forHint = forHint ) ] for key , val in attrs . items ( ) : if key in parsedAttrs or val is not None : if key in parsedAttrs : val = parsedAttrs [ key ] if key in ( \"\" , \"\" ) : ret . append ( \"\" . format ( key , val ) ) elif key == \"\" and val . lower ( ) == \"\" : ret . append ( \"\" ) else : ret . append ( \"\" . format ( key , val ) ) else : die ( \"\" , parsedAttrs . get ( \"\" , \"\" ) , key ) continue for key , val in parsedAttrs . items ( ) : if key in attrs : continue ret . append ( \"\" . format ( key , val ) ) ret . append ( \"\" ) return ret def transformDescdef ( lines , doc , firstLine , ** kwargs ) : vals = parseDefBlock ( lines , \"\" ) if \"\" in firstLine or \"\" in vals : requiredKeys = [ \"\" , \"\" ] ret = [ \"\" . format ( vals . get ( \"\" , \"\" ) ) ] if \"\" in firstLine : requiredKeys = [ \"\" , \"\" , \"\" ] ret = [ \"\" . format ( vals . get ( \"\" , \"\" ) ) ] else : requiredKeys = [ \"\" , \"\" , \"\" , \"\" ] ret = [ \"\" . format ( vals . get ( \"\" , \"\" ) ) ] for key in requiredKeys : if key == \"\" : ret . append ( \"\" . format ( key , vals . get ( key , '' ) ) ) elif key == \"\" : ret . append ( \"\" . format ( key , vals . get ( key , '' ) ) ) elif key in vals : ret . append ( \"\" . format ( key , vals . get ( key , '' ) ) ) else : die ( \"\" , vals . get ( \"\" , \"\" ) , key ) continue for key in vals . viewkeys ( ) - requiredKeys : ret . append ( \"\" . format ( key , vals [ key ] ) ) ret . append ( \"\" ) return ret def transformElementdef ( lines , doc , ** kwargs ) : attrs = OrderedDict ( ) parsedAttrs = parseDefBlock ( lines , \"\" ) if \"\" in parsedAttrs or \"\" in parsedAttrs : html = \"\" if \"\" in parsedAttrs : groups = [ x . strip ( ) for x in parsedAttrs [ \"\" ] . split ( \"\" ) ] for group in groups : html += \"\" . format ( group ) del parsedAttrs [ \"\" ] if \"\" in parsedAttrs : atts = [ x . strip ( ) for x in parsedAttrs [ \"\" ] . split ( \"\" ) ] for att in atts : html += \"\" . format ( att , parsedAttrs . get ( \"\" , \"\" ) ) html += \"\" parsedAttrs [ \"\" ] = html attrs [ \"\" ] = None attrs [ \"\" ] = None attrs [ \"\" ] = None attrs [ \"\" ] = None attrs [ \"\" ] = None attrs [ \"\" ] = None ret = [ \"\" ] for key , val in attrs . items ( ) : if key in parsedAttrs or val is not None : if key in parsedAttrs : val = parsedAttrs [ key ] if key == \"\" : ret . append ( \"\" ) ret . append ( '' . join ( \"\" . format ( x . strip ( ) ) for x in val . split ( \"\" ) ) ) elif key == \"\" : ret . append ( \"\" . format ( key ) ) ret . extend ( val . split ( \"\" ) ) elif key == \"\" : ret . append ( \"\" ) ret . append ( '' . join ( \"\" . format ( x . strip ( ) ) for x in val . split ( \"\" ) ) ) elif key == \"\" : ret . append ( \"\" ) ret . append ( '' . join ( \"\" . format ( x . strip ( ) ) for x in val . split ( \"\" ) ) ) else : ret . append ( \"\" . format ( key , val ) ) else : die ( \"\" , parsedAttrs . get ( \"\" , \"\" ) , key ) continue for key , val in parsedAttrs . items ( ) : if key in attrs : continue ret . append ( \"\" . format ( key , val ) ) ret . append ( \"\" ) return ret def transformArgumentdef ( lines , firstLine , ** kwargs ) : attrs = parseDefBlock ( lines , \"\" , capitalizeKeys = False ) el = parseHTML ( firstLine + \"\" ) [ ] if \"\" in el . attrib : forValue = el . get ( '' ) el . set ( \"\" , forValue ) if \"\" in forValue : interface , method = forValue . split ( \"\" ) else : die ( \"\" , forValue ) return removeAttr ( el , \"\" ) else : die ( \"\" ) return addClass ( el , \"\" ) rootAttrs = \"\" . join ( \"\" . format ( k , escapeAttr ( v ) ) for k , v in el . attrib . items ( ) ) lines = [ '''''' . format ( attrs = rootAttrs , interface = interface , method = method ) ] + [ '''''' . format ( param , desc ) for param , desc in attrs . items ( ) ] + [ '''''' ] return lines def parseDefBlock ( lines , type , capitalizeKeys = True ) : vals = OrderedDict ( ) lastKey = None for line in lines : match = re . match ( r\"\" , line ) if match is None : if lastKey is not None and ( line . strip ( ) == \"\" or re . match ( r\"\" , line ) ) : key = lastKey val = line . strip ( ) else : die ( \"\" , vals . get ( \"\" , \"\" ) , line , type ) continue else : key = match . group ( ) . strip ( ) if capitalizeKeys : key = key . capitalize ( ) lastKey = key val = match . group ( ) . strip ( ) if key in vals : vals [ key ] += \"\" + val else : vals [ key ] = val return vals def transformRailroad ( lines , doc , ** kwargs ) : import StringIO import railroadparser ret = [ \"\" ] doc . extraStyles [ '' ] = \"\" code = '' . join ( lines ) diagram = railroadparser . parse ( code ) temp = StringIO . StringIO ( ) diagram . writeSvg ( temp . write ) ret . append ( temp . getvalue ( ) ) temp . close ( ) ret . append ( \"\" ) return ret def transformBiblio ( lines , doc , ** kwargs ) : storage = defaultdict ( list ) biblio . processSpecrefBiblioFile ( '' . join ( lines ) , storage , order = ) for k , vs in storage . items ( ) : doc . refs . biblioKeys . add ( k ) doc . refs . biblios [ k ] . extend ( vs ) return [ ] def transformAnchors ( lines , doc , ** kwargs ) : anchors = parseInfoTree ( lines , doc . md . indent ) return processAnchors ( anchors , doc ) def processAnchors ( anchors , doc ) : for anchor in anchors : if \"\" not in anchor or len ( anchor [ '' ] ) != : die ( \"\" , config . printjson ( anchor ) ) continue if \"\" not in anchor or len ( anchor [ '' ] ) != : die ( \"\" , config . printjson ( anchor ) ) continue if \"\" not in anchor and \"\" not in anchor : die ( \"\" , config . printjson ( anchor ) ) continue if \"\" in anchor : urlPrefix = '' . join ( anchor [ '' ] ) else : urlPrefix = \"\" if \"\" in anchor : urlSuffix = anchor [ '' ] [ ] else : urlSuffix = config . simplifyText ( anchor [ '' ] [ ] ) url = urlPrefix + ( \"\" if \"\" in urlPrefix or \"\" in urlSuffix else \"\" ) + urlSuffix if anchor [ '' ] [ ] in config . lowercaseTypes : anchor [ '' ] [ ] = anchor [ '' ] [ ] . lower ( ) doc . refs . refs [ anchor [ '' ] [ ] ] . append ( { \"\" : anchor [ '' ] [ ] , \"\" : anchor [ '' ] [ ] , \"\" : url , \"\" : doc . md . shortname , \"\" : doc . md . level , \"\" : anchor . get ( '' , [ ] ) , \"\" : True , \"\" : \"\" , \"\" : anchor . get ( '' , [ '' ] ) [ ] } ) methodishStart = re . match ( r\"\" , anchor [ '' ] [ ] ) if methodishStart : arglessName = methodishStart . group ( ) + \"\" doc . refs . addMethodVariants ( anchor [ '' ] [ ] , anchor . get ( '' , [ ] ) , doc . md . shortname ) return [ ] def transformLinkDefaults ( lines , doc , ** kwargs ) : lds = parseInfoTree ( lines , doc . md . indent ) return processLinkDefaults ( lds , doc ) def processLinkDefaults ( lds , doc ) : for ld in lds : if len ( ld . get ( '' , [ ] ) ) != : ", "answer": "die ( \"\" , config . printjson ( ld ) )"}, {"prompt": " from __future__ import unicode_literals from django . db import models , migrations class Migration ( migrations . Migration ) : dependencies = [ ( '' , '' ) , ] operations = [ migrations . CreateModel ( name = '' , fields = [ ( '' , models . OneToOneField ( parent_link = True , auto_created = True , primary_key = True , serialize = False , to = '' ) ) , ] , options = { } , bases = ( '' , ) , ) , ", "answer": "] "}, {"prompt": " class NailgunNodeAdapter ( object ) : def __init__ ( self , node ) : self . node = node @ property def id ( self ) : return self . node . id @ property def name ( self ) : return self . node . name @ property def full_name ( self ) : return self . node . full_name ", "answer": "def get_node_spaces ( self ) :"}, {"prompt": " import datetime import errno import os import tempfile from django . conf import settings from django . contrib . sessions . backends . base import SessionBase , CreateError , VALID_KEY_CHARS from django . core . exceptions import SuspiciousOperation , ImproperlyConfigured from django . utils import timezone class SessionStore ( SessionBase ) : \"\"\"\"\"\" def __init__ ( self , session_key = None ) : self . storage_path = type ( self ) . _get_storage_path ( ) self . file_prefix = settings . SESSION_COOKIE_NAME super ( SessionStore , self ) . __init__ ( session_key ) @ classmethod def _get_storage_path ( cls ) : try : return cls . _storage_path except AttributeError : storage_path = getattr ( settings , \"\" , None ) if not storage_path : storage_path = tempfile . gettempdir ( ) if not os . path . isdir ( storage_path ) : raise ImproperlyConfigured ( \"\" \"\" \"\" % storage_path ) cls . _storage_path = storage_path return storage_path def _key_to_file ( self , session_key = None ) : \"\"\"\"\"\" if session_key is None : session_key = self . _get_or_create_session_key ( ) if not set ( session_key ) . issubset ( set ( VALID_KEY_CHARS ) ) : raise SuspiciousOperation ( \"\" ) return os . path . join ( self . storage_path , self . file_prefix + session_key ) def _last_modification ( self ) : \"\"\"\"\"\" modification = os . stat ( self . _key_to_file ( ) ) . st_mtime if settings . USE_TZ : modification = datetime . datetime . utcfromtimestamp ( modification ) modification = modification . replace ( tzinfo = timezone . utc ) else : modification = datetime . datetime . fromtimestamp ( modification ) return modification def load ( self ) : session_data = { } try : with open ( self . _key_to_file ( ) , \"\" ) as session_file : file_data = session_file . read ( ) if file_data : try : session_data = self . decode ( file_data ) except ( EOFError , SuspiciousOperation ) : self . create ( ) expiry_age = self . get_expiry_age ( modification = self . _last_modification ( ) , expiry = session_data . get ( '' ) ) if expiry_age < : session_data = { } self . delete ( ) self . create ( ) except IOError : self . create ( ) return session_data def create ( self ) : while True : self . _session_key = self . _get_new_session_key ( ) try : self . save ( must_create = True ) except CreateError : continue self . modified = True self . _session_cache = { } return def save ( self , must_create = False ) : session_data = self . _get_session ( no_load = must_create ) session_file_name = self . _key_to_file ( ) try : flags = os . O_WRONLY | os . O_CREAT | getattr ( os , '' , ) if must_create : flags |= os . O_EXCL fd = os . open ( session_file_name , flags ) os . close ( fd ) except OSError as e : if must_create and e . errno == errno . EEXIST : raise CreateError raise dir , prefix = os . path . split ( session_file_name ) try : output_file_fd , output_file_name = tempfile . mkstemp ( dir = dir , prefix = prefix + '' ) renamed = False try : try : os . write ( output_file_fd , self . encode ( session_data ) . encode ( ) ) finally : os . close ( output_file_fd ) os . rename ( output_file_name , session_file_name ) renamed = True finally : if not renamed : os . unlink ( output_file_name ) except ( OSError , IOError , EOFError ) : pass ", "answer": "def exists ( self , session_key ) :"}, {"prompt": " __all__ = [ '' , '' ] default_app_config = '' version_info = ( , , , '' , ) def get_version ( ) : \"\" version = '' % ( version_info [ : ] ) if version_info [ ] != '' : ", "answer": "import os"}, {"prompt": " \"\"\"\"\"\" import re import markdown from markdown . extensions . codehilite import CodeHilite , CodeHiliteExtension FENCED_BLOCK_RE = re . compile ( r'' , re . MULTILINE | re . DOTALL ) CODE_WRAP = '' ", "answer": "LANG_TAG = ''"}, {"prompt": " if : import numpy as N from statlib import pstat , stats from pstat import * from stats import * from numpy import linalg as LA import operator , math def aanova ( data , effects = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ] ) : \"\"\"\"\"\" global alluniqueslist , Nlevels , Nfactors , Nsubjects , Nblevels , Nallsources global Bscols , Bbetweens , SSlist , SSsources , DM , DN , Bwonly_sources , D global Bwithins , alleffects , alleffsources outputlist = [ ] SSbtw = [ ] SSbtwsources = [ ] SSwb = [ ] SSwbsources = [ ] alleffects = [ ] alleffsources = [ ] SSlist = [ ] SSsources = [ ] print variables = if type ( data ) != type ( [ ] ) : data = data . tolist ( ) alluniqueslist = [ ] * ( len ( data [ ] ) - variables ) Nlevels = [ ] * ( len ( data [ ] ) - variables ) for column in range ( len ( Nlevels ) ) : alluniqueslist [ column ] = pstat . unique ( pstat . colex ( data , column ) ) Nlevels [ column ] = len ( alluniqueslist [ column ] ) Ncells = N . multiply . reduce ( Nlevels [ : ] ) Nfactors = len ( Nlevels [ : ] ) Nallsources = ** ( Nfactors + ) Nsubjects = len ( alluniqueslist [ ] ) Bwithins = findwithin ( data ) Bbetweens = ~ Bwithins & ( Nallsources - ) - Wcolumns = makelist ( Bwithins , Nfactors + ) Wscols = [ ] + Wcolumns Bscols = makelist ( Bbetweens + , Nfactors + ) Nwifactors = len ( Wscols ) - Nwlevels = N . take ( N . array ( Nlevels ) , Wscols ) Nbtwfactors = len ( Bscols ) - Nblevels = N . take ( N . array ( Nlevels ) , Bscols ) Nwsources = ** Nwifactors - Nbsources = Nallsources - Nwsources M = pstat . collapse ( data , Bscols , - , None , None , mean ) Marray = N . zeros ( Nblevels [ : ] , '' ) Narray = N . zeros ( Nblevels [ : ] , '' ) for row in M : idx = [ ] for i in range ( len ( row [ : - ] ) ) : idx . append ( alluniqueslist [ Bscols [ i ] ] . index ( row [ i ] ) ) idx = idx [ : ] Marray [ idx ] = Marray [ idx ] + row [ - ] Narray [ idx ] = Narray [ idx ] + Marray = Marray / Narray coefflist = [ [ [ ] ] , [ [ - , ] ] , [ [ - , , ] , [ , - , ] ] , [ [ - , - , , ] , [ , - , - , ] , [ - , , - , ] ] , [ [ - , - , , , ] , [ , - , - , - , ] , [ - , , , - , ] , [ , - , , - , ] ] , [ [ - , - , - , , , ] , [ , - , - , - , - , ] , [ - , , , - , - , ] , [ , - , , , - , ] , [ - , , - , , - , ] ] , [ [ - , - , - , , , , ] , [ , , - , - , - , , ] , [ - , , , , - , - , ] , [ , - , , , , - , ] , [ - , , - , , , - , ] , [ , - , , - , , - , ] ] , [ [ - , - , - , - , , , , ] , [ , , - , - , - , - , , ] , [ - , , , , - , - , - , ] , [ , - , - , , , - , - , ] , [ - , , - , - , , , - , ] , [ , - , , - , - , , - , ] , [ - , , - , , - , , - , ] ] , [ [ - , - , - , - , , , , , ] , [ , , - , - , - , - , - , , ] , [ - , , , , , - , - , - , ] , [ , - , - , , , , - , - , ] , [ - , , - , - , , , , - , ] , [ , - , , , - , , , - , ] , [ - , , - , , , - , , - , ] , [ , - , , - , , - , , - , ] ] , [ [ - , - , - , - , - , , , , , ] , [ , , - , - , - , - , - , - , , ] , [ - , , , , , - , - , - , - , ] , [ , - , - , , , , , - , - , ] , [ - , , - , - , - , , , , - , ] , [ , - , , , - , - , , , - , ] , [ , - , , - , - , , , - , , - ] , [ , - , , - , , , - , , - , ] , [ - , , - , , - , , - , , - , ] ] ] dindex = NDs = [ ] * Nwsources for source in range ( Nwsources ) : if subset ( source , Bwithins ) : NDs [ dindex ] = numlevels ( source , Nlevels ) dindex = dindex + cdata = pstat . collapse ( data , range ( Nfactors + ) , - , None , None , mean ) dummyval = - datavals = pstat . colex ( data , - ) while dummyval in datavals : dummyval = dummyval - DA = N . ones ( Nlevels , '' ) * dummyval if len ( Bscols ) == : subjslots = N . ones ( ( Nsubjects , ) ) else : subjslots = N . zeros ( Nblevels ) for i in range ( len ( data ) ) : idx = [ ] for j in range ( Nfactors + ) : new = alluniqueslist [ j ] . index ( data [ i ] [ j ] ) idx . append ( new ) DA [ idx ] = data [ i ] [ - ] btwidx = N . take ( idx , N . array ( Bscols ) ) subjslots [ btwidx ] = dcount = - Bwsources = [ ] Bwonly_sources = [ ] D = N . zeros ( Nwsources , N . PyObject ) DM = [ ] * Nwsources DN = [ ] * Nwsources for source in range ( , Nallsources , ) : if ( ( source - ) & Bwithins ) != : Bwsources . append ( source - ) if subset ( ( source - ) , Bwithins ) : dcount = dcount + Bwonly_sources . append ( source - ) dwsc = * DA Bnonsource = ( Nallsources - ) & ~ source Bwscols = makebin ( Wscols ) Bwithinnonsource = Bnonsource & Bwscols Lwithinnonsource = makelist ( Bwithinnonsource , Nfactors + ) for i in range ( len ( Lwithinnonsource ) - , - , - ) : dwsc = amean ( dwsc , Lwithinnonsource [ i ] ) mns = dwsc Bwithinsource = source & Bwscols Lwithinsourcecol = makelist ( Bwithinsource , Nfactors + ) Lsourceandbtws = makelist ( source | Bbetweens , Nfactors + ) if Lwithinnonsource < > [ ] : Lwithinsourcecol = map ( Lsourceandbtws . index , Lwithinsourcecol ) dvarshape = N . array ( N . take ( mns . shape , Lwithinsourcecol [ : ] ) ) - idxarray = N . indices ( dvarshape ) newshape = N . array ( [ idxarray . shape [ ] , N . multiply . reduce ( idxarray . shape [ : ] ) ] ) indxlist = N . swapaxes ( N . reshape ( idxarray , newshape ) , , ) for i in range ( len ( indxlist ) ) : coeffmatrix = N . ones ( mns . shape , N . Float ) Wsourcecol = makelist ( Bwscols & source , Nfactors + ) for wfactor in range ( len ( Lwithinsourcecol [ : ] ) ) : coeffmatrix = N . swapaxes ( coeffmatrix , , Lwithinsourcecol [ wfactor + ] ) nlevels = coeffmatrix . shape [ ] try : nextcoeff = coefflist [ nlevels - ] [ indxlist [ i , wfactor ] ] except IndexError : raise IndexError , \"\" for j in range ( nlevels ) : coeffmatrix [ j ] = coeffmatrix [ j ] * nextcoeff [ j ] coeffmatrix = N . swapaxes ( coeffmatrix , , Lwithinsourcecol [ wfactor + ] ) scratch = coeffmatrix * mns for j in range ( len ( coeffmatrix . shape [ : ] ) ) : scratch = N . add . reduce ( scratch , ) if len ( scratch . shape ) == : scratch . shape = list ( scratch . shape ) + [ ] try : tmp = D [ dcount ] . shape D [ dcount ] = pstat . aabut ( D [ dcount ] , scratch ) except AttributeError : D [ dcount ] = scratch variables = D [ dcount ] . shape [ ] tidx = range ( , len ( subjslots . shape ) ) + [ ] tsubjslots = N . transpose ( subjslots , tidx ) DMarray = N . zeros ( list ( tsubjslots . shape [ : - ] ) + [ variables ] , '' ) DNarray = N . zeros ( list ( tsubjslots . shape [ : - ] ) + [ variables ] , '' ) idx = [ ] * len ( tsubjslots . shape [ : - ] ) idx [ ] = - loopcap = N . array ( tsubjslots . shape [ : - ] ) - while incr ( idx , loopcap ) < > - : DNarray [ idx ] = float ( asum ( tsubjslots [ idx ] ) ) thismean = ( N . add . reduce ( tsubjslots [ idx ] * N . transpose ( D [ dcount ] ) , ) / DNarray [ idx ] ) thismean = N . array ( thismean , N . PyObject ) DMarray [ idx ] = thismean DM [ dcount ] = DMarray DN [ dcount ] = DNarray if Bscols [ : ] < > [ ] : BNs = pstat . colex ( [ Nlevels ] , Bscols [ : ] ) else : BNs = [ ] if ( ( source - ) & Bwithins ) == : sourcecols = makelist ( source - , Nfactors + ) Lsource = makelist ( ( Nallsources - ) & Bbetweens , Nfactors + ) btwcols = map ( Bscols . index , Lsource ) hn = aharmonicmean ( Narray , - ) SSw = idxlist = pstat . unique ( pstat . colex ( M , btwcols ) ) for row in M : idx = [ ] for i in range ( len ( row [ : - ] ) ) : idx . append ( alluniqueslist [ Bscols [ i ] ] . index ( row [ i ] ) ) idx = idx [ : ] newval = row [ - ] - Marray [ idx ] SSw = SSw + ( newval ) ** Lsource = makelist ( source - , Nfactors + ) btwsourcecols = ( N . array ( map ( Bscols . index , Lsource ) ) - ) . tolist ( ) Bbtwnonsourcedims = ~ source & Bbetweens Lbtwnonsourcedims = makelist ( Bbtwnonsourcedims , Nfactors + ) btwnonsourcedims = ( N . array ( map ( Bscols . index , Lbtwnonsourcedims ) ) - ) . tolist ( ) sourceMarray = amean ( Marray , btwnonsourcedims , ) sourceNarray = aharmonicmean ( Narray , btwnonsourcedims , ) ga = asum ( ( sourceMarray * sourceNarray ) / asum ( sourceNarray ) ) ga = N . reshape ( ga , N . ones ( len ( Marray . shape ) ) ) if source == Nallsources - : sourceNarray = aharmonicmean ( Narray ) sub_effects = * ga for subsource in range ( , source , ) : if subset ( subsource - , source - ) : sub_effects = ( sub_effects + alleffects [ alleffsources . index ( subsource ) ] ) effect = sourceMarray - sub_effects alleffects . append ( effect ) alleffsources . append ( source ) SS = asum ( ( effect ** * sourceNarray ) * N . multiply . reduce ( N . take ( Marray . shape , btwnonsourcedims ) ) ) SSlist . append ( SS ) SSsources . append ( source ) collapsed = pstat . collapse ( M , btwcols , - , None , len , mean ) contrastmns = pstat . collapse ( collapsed , btwsourcecols , - , sterr , len , mean ) contrastns = pstat . collapse ( collapsed , btwsourcecols , - , None , None , N . sum ) contrasthns = pstat . collapse ( collapsed , btwsourcecols , - , None , None , harmonicmean ) sourceNs = pstat . colex ( [ Nlevels ] , makelist ( source - , Nfactors + ) ) dfnum = N . multiply . reduce ( N . ravel ( N . array ( sourceNs ) - ) ) dfden = Nsubjects - N . multiply . reduce ( N . ravel ( BNs ) ) MS = SS / dfnum MSw = SSw / dfden if MSw < > : f = MS / MSw else : f = if f >= : prob = fprob ( dfnum , dfden , f ) else : prob = else : sourcewithins = ( source - ) & Bwithins workD = D [ Bwonly_sources . index ( sourcewithins ) ] if len ( workD . shape ) == : workD = workD [ : , N . NewAxis ] if len ( subjslots . shape ) == : subjslots = subjslots [ : , N . NewAxis ] ef = Dfull_model ( workD , subjslots ) if subset ( ( source - ) , Bwithins ) : er = Drestrict_mean ( workD , subjslots ) else : er = Drestrict_source ( workD , subjslots , source ) + ef SSw = LA . determinant ( ef ) SS = LA . determinant ( er ) - SSw sourceNs = pstat . colex ( [ Nlevels ] , makelist ( source , Nfactors + ) ) dfnum = N . multiply . reduce ( N . ravel ( N . array ( sourceNs ) - ) [ : ] ) if subset ( source - , Bwithins ) : dfden = Nsubjects - N . multiply . reduce ( N . ravel ( BNs ) ) - dfnum + MS = SS / dfnum MSw = SSw / dfden if MSw < > : f = MS / MSw else : f = if f >= : prob = fprob ( dfnum , dfden , f ) else : prob = else : try : p = workD . shape [ ] except IndexError : p = k = N . multiply . reduce ( N . ravel ( BNs ) ) m = Nsubjects - - ( p + k ) / d_en = float ( p ** + ( k - ) ** - ) if d_en == : s = else : s = math . sqrt ( ( ( p * ( k - ) ) ** - ) / d_en ) dfden = m * s - dfnum / + if LA . determinant ( er ) < > : lmbda = LA . determinant ( ef ) / LA . determinant ( er ) W = math . pow ( lmbda , ( / s ) ) f = ( ( - W ) / W ) * ( dfden / dfnum ) else : f = if f >= : prob = fprob ( dfnum , dfden , f ) else : prob = suffix = '' if prob < : suffix = '' elif prob < : suffix = '' elif prob < : suffix = '' adjsourcecols = N . array ( makelist ( source - , Nfactors + ) ) - thiseffect = '' for col in adjsourcecols : if len ( adjsourcecols ) > : thiseffect = thiseffect + effects [ col ] [ ] else : thiseffect = thiseffect + ( effects [ col ] ) outputlist = ( outputlist + [ [ thiseffect , round4 ( SS ) , dfnum , round4 ( SS / float ( dfnum ) ) , round4 ( f ) , round4 ( prob ) , suffix ] ] + [ [ thiseffect + '' , round4 ( SSw ) , dfden , round4 ( SSw / float ( dfden ) ) , '' , '' , '' ] ] + [ [ '' ] ] ) Lsource = makelist ( source - , Nfactors + ) collapsed = pstat . collapse ( cdata , Lsource , - , sterr , len , mean ) prefixcols = range ( len ( collapsed [ ] [ : - ] ) ) outlist = pstat . colex ( collapsed , prefixcols ) eff = [ ] for col in Lsource : eff . append ( effects [ col - ] ) for item in [ '' , '' , '' ] : eff . append ( item ) outlist = pstat . abut ( outlist , map ( round4 , pstat . colex ( collapsed , - ) ) , map ( round4 , pstat . colex ( collapsed , - ) ) , map ( round4 , pstat . colex ( collapsed , - ) ) ) outlist = [ eff ] + outlist pstat . printcc ( outlist ) print print title = [ [ '' , '' ] + effects [ : Nfactors ] ] title = title + [ [ '' ] + Nlevels ] facttypes = [ '' ] * Nfactors for i in range ( len ( Wscols [ : ] ) ) : facttypes [ Wscols [ i + ] - ] = '' title = title + [ [ '' , '' ] + facttypes ] pstat . printcc ( title ) print title = [ [ '' , '' , '' , '' , '' , '' , '' ] ] + [ '' ] outputlist = title + outputlist pstat . printcc ( outputlist ) return def Dfull_model ( workd , subjslots ) : \"\"\"\"\"\" workd = subtr_cellmeans ( workd , subjslots ) sserr = multivar_SScalc ( workd ) return sserr def Drestrict_mean ( workd , subjslots ) : \"\"\"\"\"\" errors = subtr_cellmeans ( workd , subjslots ) grandDmeans = amean ( workd , , ) errors = errors + N . transpose ( grandDmeans ) sserr = multivar_SScalc ( errors ) return sserr def Drestrict_source ( workd , subjslots , source ) : \"\"\"\"\"\" if source > : sourcewithins = ( source - ) & Bwithins sourcebetweens = ( source - ) & Bbetweens dindex = Bwonly_sources . index ( sourcewithins ) all_cellmeans = N . transpose ( DM [ dindex ] , [ - ] + range ( , len ( DM [ dindex ] . shape ) - ) ) all_cellns = N . transpose ( DN [ dindex ] , [ - ] + range ( , len ( DN [ dindex ] . shape ) - ) ) hn = aharmonicmean ( all_cellns ) levels = D [ dindex ] . shape [ ] SSm = N . zeros ( ( levels , levels ) , '' ) tworkd = N . transpose ( D [ dindex ] ) RSw = N . zeros ( ( levels , levels ) , '' ) RSinter = N . zeros ( ( levels , levels ) , N . PyObject ) for i in range ( levels ) : for j in range ( i , levels ) : RSw [ i , j ] = RSw [ j , i ] = N . sum ( tworkd [ i ] * tworkd [ j ] ) cross = all_cellmeans [ i ] * all_cellmeans [ j ] multfirst = asum ( cross * all_cellns [ i ] ) RSinter [ i , j ] = RSinter [ j , i ] = N . asarray ( multfirst ) SSm [ i , j ] = SSm [ j , i ] = ( amean ( all_cellmeans [ i ] ) * amean ( all_cellmeans [ j ] ) * len ( all_cellmeans [ i ] ) * hn ) SSw = RSw - RSinter Lsource = makelist ( sourcebetweens , Nfactors + ) btwsourcecols = ( N . array ( map ( Bscols . index , Lsource ) ) - ) . tolist ( ) Bbtwnonsourcedims = ~ source & Bbetweens Lbtwnonsourcedims = makelist ( Bbtwnonsourcedims , Nfactors + ) btwnonsourcedims = ( N . array ( map ( Bscols . index , Lbtwnonsourcedims ) ) - ) . tolist ( ) sourceDMarray = DM [ dindex ] * for dim in btwnonsourcedims : if dim == len ( DM [ dindex ] . shape ) - : raise ValueError , \"\" sourceDMarray = amean ( sourceDMarray , dim , ) sourceDNarray = aharmonicmean ( DN [ dindex ] , btwnonsourcedims , ) variableNs = asum ( sourceDNarray , range ( len ( sourceDMarray . shape ) - ) ) ga = asum ( ( sourceDMarray * sourceDNarray ) / variableNs , range ( len ( sourceDMarray . shape ) - ) , ) if source == Nallsources - : sourceDNarray = aharmonicmean ( DN [ dindex ] , range ( len ( sourceDMarray . shape ) - ) ) sub_effects = ga * for subsource in range ( , source - , ) : subsourcebtw = ( subsource - ) & Bbetweens if ( propersubset ( subsource - , source - ) and ( subsource - ) & Bwithins == ( source - ) & Bwithins and ( subsource - ) < > ( source - ) & Bwithins ) : sub_effects = ( sub_effects + alleffects [ alleffsources . index ( subsource ) ] ) effect = sourceDMarray - sub_effects alleffects . append ( effect ) alleffsources . append ( source ) SS = N . zeros ( ( levels , levels ) , '' ) SS = asum ( ( effect ** * sourceDNarray ) * N . multiply . reduce ( N . take ( DM [ dindex ] . shape , btwnonsourcedims ) ) , range ( len ( sourceDMarray . shape ) - ) ) SSlist . append ( SS ) SSsources . append ( source ) return SS def multivar_SScalc ( workd ) : if len ( workd . shape ) == : levels = else : levels = workd . shape [ ] sserr = N . zeros ( ( levels , levels ) , '' ) for i in range ( levels ) : for j in range ( i , levels ) : ssval = N . add . reduce ( workd [ i ] * workd [ j ] ) sserr [ i , j ] = ssval sserr [ j , i ] = ssval return sserr def subtr_cellmeans ( workd , subjslots ) : \"\"\"\"\"\" sourcedims = makelist ( Bbetweens , Nfactors + ) transidx = range ( len ( subjslots . shape ) ) [ : ] + [ ] tsubjslots = N . transpose ( subjslots , transidx ) tworkd = N . transpose ( workd ) errors = * tworkd if len ( sourcedims ) == : idx = [ - ] ", "answer": "loopcap = [ ]"}, {"prompt": " import os from setuptools import setup README = open ( os . path . join ( os . path . dirname ( __file__ ) , '' ) ) . read ( ) os . chdir ( os . path . normpath ( os . path . join ( os . path . abspath ( __file__ ) , os . pardir ) ) ) setup ( name = '' , ", "answer": "version = '' ,"}, {"prompt": " from mixbox import entities from mixbox import fields import cybox . bindings . http_session_object as http_session_binding from cybox . objects . uri_object import URI from cybox . objects . address_object import EmailAddress from cybox . objects . port_object import Port from cybox . common import ObjectProperties , String , DateTime , PositiveInteger , Integer class HTTPRequestLine ( entities . Entity ) : _binding = http_session_binding _binding_class = http_session_binding . HTTPRequestLineType _namespace = \"\" http_method = fields . TypedField ( \"\" , String ) value = fields . TypedField ( \"\" , String ) version = fields . TypedField ( \"\" , String ) class HostField ( entities . Entity ) : _binding = http_session_binding _binding_class = http_session_binding . HostFieldType _namespace = \"\" domain_name = fields . TypedField ( \"\" , URI ) port = fields . TypedField ( \"\" , Port ) class HTTPRequestHeaderFields ( entities . Entity ) : _binding = http_session_binding _binding_class = http_session_binding . HTTPRequestHeaderFieldsType _namespace = \"\" accept = fields . TypedField ( \"\" , String ) accept_charset = fields . TypedField ( \"\" , String ) accept_language = fields . TypedField ( \"\" , String ) accept_datetime = fields . TypedField ( \"\" , String ) accept_encoding = fields . TypedField ( \"\" , String ) authorization = fields . TypedField ( \"\" , String ) cache_control = fields . TypedField ( \"\" , String ) connection = fields . TypedField ( \"\" , String ) cookie = fields . TypedField ( \"\" , String ) content_length = fields . TypedField ( \"\" , Integer ) content_md5 = fields . TypedField ( \"\" , String ) content_type = fields . TypedField ( \"\" , String ) date = fields . TypedField ( \"\" , DateTime ) expect = fields . TypedField ( \"\" , String ) from_ = fields . TypedField ( \"\" , EmailAddress ) host = fields . TypedField ( \"\" , HostField ) if_match = fields . TypedField ( \"\" , String ) if_modified_since = fields . TypedField ( \"\" , DateTime ) if_none_match = fields . TypedField ( \"\" , String ) if_range = fields . TypedField ( \"\" , String ) if_unmodified_since = fields . TypedField ( \"\" , DateTime ) max_forwards = fields . TypedField ( \"\" , Integer ) pragma = fields . TypedField ( \"\" , String ) proxy_authorization = fields . TypedField ( \"\" , String ) range_ = fields . TypedField ( \"\" , String ) referer = fields . TypedField ( \"\" , URI ) te = fields . TypedField ( \"\" , String ) user_agent = fields . TypedField ( \"\" , String ) via = fields . TypedField ( \"\" , String ) warning = fields . TypedField ( \"\" , String ) dnt = fields . TypedField ( \"\" , String ) x_requested_with = fields . TypedField ( \"\" , String ) x_forwarded_for = fields . TypedField ( \"\" , String ) x_forwarded_proto = fields . TypedField ( \"\" , String ) x_att_deviceid = fields . TypedField ( \"\" , String ) x_wap_profile = fields . TypedField ( \"\" , URI ) class HTTPRequestHeader ( entities . Entity ) : _binding = http_session_binding _binding_class = http_session_binding . HTTPRequestHeaderType _namespace = \"\" raw_header = fields . TypedField ( \"\" , String ) ", "answer": "parsed_header = fields . TypedField ( \"\" , HTTPRequestHeaderFields )"}, {"prompt": " class report_results_and_logging : def __init__ ( self , dictionaryLongitude , epochsToPrint , M , Mv , epochIndex , spikeIntervalUnformatted , dictionary , epochMsDuration ) : self . epochsToPrint = epochsToPrint self . dictionaryLongitude = dictionaryLongitude self . M = M self . Mv = Mv self . epochIndex = epochIndex self . spikeIntervalUnformatted = spikeIntervalUnformatted self . dictionary = dictionary self . epochMsDuration = epochMsDuration print '' , self . epochIndex SpikeNumberInEpoch = [ ] * self . dictionaryLongitude for NeuronNumber in range ( self . dictionaryLongitude ) : for spikeOccurenceTime in self . M [ NeuronNumber ] : if ( spikeOccurenceTime >= ( self . epochIndex * self . spikeIntervalUnformatted ) and spikeOccurenceTime < ( ( self . epochIndex * self . spikeIntervalUnformatted ) + ( self . spikeIntervalUnformatted - ) ) ) : SpikeNumberInEpoch [ NeuronNumber ] = SpikeNumberInEpoch [ NeuronNumber ] + self . SpikeNumberInEpoch = SpikeNumberInEpoch def presenter ( self ) : print ( '' ) print ( sum ( self . SpikeNumberInEpoch ) / self . dictionaryLongitude ) print ( '' ) for NeuronNumber in range ( self . dictionaryLongitude ) : print self . dictionary . dictionary [ NeuronNumber ] [ ] , '' , self . SpikeNumberInEpoch [ NeuronNumber ] , '' , ", "answer": "print ( '' )"}, {"prompt": " from __future__ import unicode_literals from django . db import models , migrations from django . conf import settings class Migration ( migrations . Migration ) : dependencies = [ migrations . swappable_dependency ( settings . AUTH_USER_MODEL ) , ] operations = [ migrations . CreateModel ( name = '' , fields = [ ( '' , models . AutoField ( verbose_name = '' , serialize = False , auto_created = True , primary_key = True ) ) , ( '' , models . BooleanField ( default = True , help_text = b'' ) ) , ( '' , models . DateTimeField ( help_text = b'' , auto_now_add = True ) ) , ", "answer": "( '' , models . DateTimeField ( help_text = b'' , auto_now = True ) ) ,"}, {"prompt": " import numpy as np from . base import Homogeneous , HomogFamilyAlignment from functools import reduce class Affine ( Homogeneous ) : r\"\"\"\"\"\" def __init__ ( self , h_matrix , copy = True , skip_checks = False ) : Homogeneous . __init__ ( self , h_matrix , copy = copy , skip_checks = skip_checks ) @ classmethod def init_identity ( cls , n_dims ) : r\"\"\"\"\"\" return cls ( np . eye ( n_dims + ) , copy = False , skip_checks = True ) @ property def h_matrix ( self ) : r\"\"\"\"\"\" return self . _h_matrix def _set_h_matrix ( self , value , copy = True , skip_checks = False ) : r\"\"\"\"\"\" if not skip_checks : shape = value . shape if len ( shape ) != or shape [ ] != shape [ ] : raise ValueError ( \"\" \"\" ) if self . h_matrix is not None : ", "answer": "if self . n_dims != shape [ ] - :"}, {"prompt": " \"\" __version__ = \"\" import unittest import matplotlib as mpl ", "answer": "import matplotlib . axes"}, {"prompt": " from muntjac . api import VerticalLayout , Panel , Label , Button from muntjac . ui . button import IClickListener class PanelBasicExample ( VerticalLayout , IClickListener ) : def __init__ ( self ) : super ( PanelBasicExample , self ) . __init__ ( ) self . setSpacing ( True ) self . _panel = Panel ( '' ) self . _panel . setHeight ( '' ) layout = self . _panel . getContent ( ) layout . setMargin ( True ) layout . setSpacing ( True ) self . addComponent ( self . _panel ) for _ in range ( ) : l = Label ( '' ) self . _panel . addComponent ( l ) ", "answer": "b = Button ( '' )"}, {"prompt": " \"\"\"\"\"\" from google . appengine . api import datastore_types from google . appengine . api import validation from google . appengine . api import yaml_errors from google . appengine . api import yaml_object from google . appengine . datastore import datastore_pb from google . appengine . datastore import entity_pb class Property ( validation . Validated ) : \"\"\"\"\"\" ATTRIBUTES = { '' : validation . TYPE_STR , '' : validation . Options ( ( '' , ( '' , ) ) , ( '' , ( '' , ) ) , default = '' ) , } class Index ( validation . Validated ) : \"\"\"\"\"\" ATTRIBUTES = { '' : validation . TYPE_STR , '' : validation . Type ( bool , default = False ) , '' : validation . Optional ( validation . Repeated ( Property ) ) , } class IndexDefinitions ( validation . Validated ) : \"\"\"\"\"\" ATTRIBUTES = { '' : validation . Optional ( validation . Repeated ( Index ) ) , } def ParseIndexDefinitions ( document ) : \"\"\"\"\"\" try : return yaml_object . BuildSingleObject ( IndexDefinitions , document ) except yaml_errors . EmptyConfigurationFile : return None def ParseMultipleIndexDefinitions ( document ) : \"\"\"\"\"\" return yaml_object . BuildObjects ( IndexDefinitions , document ) def IndexDefinitionsToKeys ( indexes ) : \"\"\"\"\"\" keyset = set ( ) if indexes is not None : if indexes . indexes : for index in indexes . indexes : keyset . add ( IndexToKey ( index ) ) return keyset def IndexToKey ( index ) : \"\"\"\"\"\" ", "answer": "props = [ ]"}, {"prompt": " from ctypes import * import unittest import _ctypes_test testdll = CDLL ( _ctypes_test . __file__ ) def positive_address ( a ) : if a >= : return a import struct num_bits = struct . calcsize ( \"\" ) * a += L << num_bits assert a >= return a def c_wbuffer ( init ) : n = len ( init ) + return ( c_wchar * n ) ( * init ) class CharPointersTestCase ( unittest . TestCase ) : def setUp ( self ) : func = testdll . _testfunc_p_p func . restype = c_long func . argtypes = None def test_int_pointer_arg ( self ) : func = testdll . _testfunc_p_p func . restype = c_long self . failUnlessEqual ( , func ( ) ) ci = c_int ( ) func . argtypes = POINTER ( c_int ) , self . failUnlessEqual ( positive_address ( addressof ( ci ) ) , positive_address ( func ( byref ( ci ) ) ) ) func . argtypes = c_char_p , self . assertRaises ( ArgumentError , func , byref ( ci ) ) func . argtypes = POINTER ( c_short ) , self . assertRaises ( ArgumentError , func , byref ( ci ) ) func . argtypes = POINTER ( c_double ) , self . assertRaises ( ArgumentError , func , byref ( ci ) ) def test_POINTER_c_char_arg ( self ) : func = testdll . _testfunc_p_p func . restype = c_char_p func . argtypes = POINTER ( c_char ) , ", "answer": "self . failUnlessEqual ( None , func ( None ) )"}, {"prompt": " import os . path import re from . charwidth import get_char_width from . misc import seq2str2 from . unic import unic _MAX_ASSIGN_LENGTH = ", "answer": "_MAX_ERROR_LINES = "}, {"prompt": " import argparse import lintreview . github as github import sys from flask import url_for from lintreview . web import app def main ( ) : parser = create_parser ( ) args = parser . parse_args ( ) args . func ( args ) def register_hook ( args ) : try : process_hook ( github . register_hook , args ) sys . stdout . write ( '' ) except Exception as e : sys . stderr . write ( '' ) ", "answer": "sys . stderr . write ( e . message + '' )"}, {"prompt": " \"\"\"\"\"\" import os PROJECT_PATH = os . path . abspath ( os . path . dirname ( __file__ ) ) ", "answer": "execfile ( os . path . join ( PROJECT_PATH , '' ) )"}, {"prompt": " import atexit from pyVim import connect from tools import cli def setup_args ( ) : \"\"\"\"\"\" parser = cli . build_arg_parser ( ) parser . add_argument ( '' , '' , required = True , help = '' ) my_args = parser . parse_args ( ) return cli . prompt_for_password ( my_args ) args = setup_args ( ) si = None try : ", "answer": "si = connect . SmartConnect ( host = args . host ,"}, {"prompt": " \"\"\"\"\"\" import logging import unittest import google . cloud . dataflow as df from google . cloud . dataflow . examples . cookbook import bigquery_side_input class BigQuerySideInputTest ( unittest . TestCase ) : def test_create_groups ( self ) : p = df . Pipeline ( '' ) group_ids_pcoll = p | df . Create ( '' , [ '' , '' , '' ] ) corpus_pcoll = p | df . Create ( '' , [ { '' : '' } , { '' : '' } , { '' : '' } ] ) words_pcoll = p | df . Create ( '' , [ { '' : '' } , { '' : '' } , { '' : '' } ] ) ignore_corpus_pcoll = p | df . Create ( '' , [ '' ] ) ignore_word_pcoll = p | df . Create ( '' , [ '' ] ) groups = bigquery_side_input . create_groups ( group_ids_pcoll , corpus_pcoll , words_pcoll , ignore_corpus_pcoll , ignore_word_pcoll ) def group_matcher ( actual ) : self . assertEqual ( len ( actual ) , ) for group in actual : self . assertEqual ( len ( group ) , ) self . assertTrue ( group [ ] . startswith ( '' ) ) self . assertNotEqual ( group [ ] , '' ) self . assertTrue ( group [ ] . startswith ( '' ) ) self . assertNotEqual ( group [ ] , '' ) df . assert_that ( groups , group_matcher ) p . run ( ) if __name__ == '' : ", "answer": "logging . getLogger ( ) . setLevel ( logging . INFO )"}, {"prompt": " \"\"\"\"\"\" import numpy from collada . common import DaeObject , E , tag from collada . common import DaeIncompleteError , DaeBrokenRefError , DaeMalformedError , DaeUnsupportedError from collada . util import _correctValInNode from collada . xmlutil import etree as ElementTree class Light ( DaeObject ) : \"\"\"\"\"\" @ staticmethod def load ( collada , localscope , node ) : tecnode = node . find ( tag ( '' ) ) if tecnode is None or len ( tecnode ) == : raise DaeIncompleteError ( '' ) lightnode = tecnode [ ] if lightnode . tag == tag ( '' ) : return DirectionalLight . load ( collada , localscope , node ) elif lightnode . tag == tag ( '' ) : return PointLight . load ( collada , localscope , node ) elif lightnode . tag == tag ( '' ) : return AmbientLight . load ( collada , localscope , node ) elif lightnode . tag == tag ( '' ) : return SpotLight . load ( collada , localscope , node ) else : raise DaeUnsupportedError ( '' % lightnode . tag ) class DirectionalLight ( Light ) : \"\"\"\"\"\" def __init__ ( self , id , color , xmlnode = None ) : \"\"\"\"\"\" self . id = id \"\"\"\"\"\" self . direction = numpy . array ( [ , , - ] , dtype = numpy . float32 ) self . color = color \"\"\"\"\"\" if xmlnode != None : self . xmlnode = xmlnode \"\"\"\"\"\" else : self . xmlnode = E . light ( E . technique_common ( E . directional ( E . color ( '' . join ( map ( str , self . color ) ) ) ) ) , id = self . id , name = self . id ) def save ( self ) : \"\"\"\"\"\" self . xmlnode . set ( '' , self . id ) self . xmlnode . set ( '' , self . id ) colornode = self . xmlnode . find ( '' % ( tag ( '' ) , tag ( '' ) , tag ( '' ) ) ) colornode . text = '' . join ( map ( str , self . color ) ) @ staticmethod def load ( collada , localscope , node ) : colornode = node . find ( '' % ( tag ( '' ) , tag ( '' ) , tag ( '' ) ) ) if colornode is None : raise DaeIncompleteError ( '' ) try : color = tuple ( [ float ( v ) for v in colornode . text . split ( ) ] ) except ValueError as ex : raise DaeMalformedError ( '' ) return DirectionalLight ( node . get ( '' ) , color , xmlnode = node ) def bind ( self , matrix ) : \"\"\"\"\"\" return BoundDirectionalLight ( self , matrix ) def __str__ ( self ) : return '' % ( self . id , ) def __repr__ ( self ) : return str ( self ) class AmbientLight ( Light ) : \"\"\"\"\"\" def __init__ ( self , id , color , xmlnode = None ) : \"\"\"\"\"\" self . id = id \"\"\"\"\"\" self . color = color \"\"\"\"\"\" if xmlnode != None : self . xmlnode = xmlnode \"\"\"\"\"\" else : self . xmlnode = E . light ( E . technique_common ( E . ambient ( E . color ( '' . join ( map ( str , self . color ) ) ) ) ) , id = self . id , name = self . id ) def save ( self ) : \"\"\"\"\"\" self . xmlnode . set ( '' , self . id ) self . xmlnode . set ( '' , self . id ) colornode = self . xmlnode . find ( '' % ( tag ( '' ) , tag ( '' ) , tag ( '' ) ) ) colornode . text = '' . join ( map ( str , self . color ) ) @ staticmethod def load ( collada , localscope , node ) : colornode = node . find ( '' % ( tag ( '' ) , tag ( '' ) , tag ( '' ) ) ) if colornode is None : raise DaeIncompleteError ( '' ) try : color = tuple ( [ float ( v ) for v in colornode . text . split ( ) ] ) except ValueError as ex : raise DaeMalformedError ( '' ) return AmbientLight ( node . get ( '' ) , color , xmlnode = node ) def bind ( self , matrix ) : \"\"\"\"\"\" return BoundAmbientLight ( self , matrix ) def __str__ ( self ) : return '' % ( self . id , ) def __repr__ ( self ) : return str ( self ) class PointLight ( Light ) : \"\"\"\"\"\" def __init__ ( self , id , color , constant_att = None , linear_att = None , quad_att = None , zfar = None , xmlnode = None ) : \"\"\"\"\"\" self . id = id \"\"\"\"\"\" self . position = numpy . array ( [ , , ] , dtype = numpy . float32 ) self . color = color \"\"\"\"\"\" self . constant_att = constant_att \"\"\"\"\"\" self . linear_att = linear_att \"\"\"\"\"\" self . quad_att = quad_att \"\"\"\"\"\" self . zfar = zfar \"\"\"\"\"\" if xmlnode != None : self . xmlnode = xmlnode \"\"\"\"\"\" else : pnode = E . point ( E . color ( '' . join ( map ( str , self . color ) ) ) ) if self . constant_att is not None : pnode . append ( E . constant_attenuation ( str ( self . constant_att ) ) ) if self . linear_att is not None : pnode . append ( E . linear_attenuation ( str ( self . linear_att ) ) ) if self . quad_att is not None : pnode . append ( E . quadratic_attenuation ( str ( self . quad_att ) ) ) if self . zfar is not None : pnode . append ( E . zfar ( str ( self . zvar ) ) ) self . xmlnode = E . light ( E . technique_common ( pnode ) , id = self . id , name = self . id ) def save ( self ) : \"\"\"\"\"\" self . xmlnode . set ( '' , self . id ) self . xmlnode . set ( '' , self . id ) pnode = self . xmlnode . find ( '' % ( tag ( '' ) , tag ( '' ) ) ) colornode = pnode . find ( tag ( '' ) ) colornode . text = '' . join ( map ( str , self . color ) ) _correctValInNode ( pnode , '' , self . constant_att ) _correctValInNode ( pnode , '' , self . linear_att ) _correctValInNode ( pnode , '' , self . quad_att ) _correctValInNode ( pnode , '' , self . zfar ) @ staticmethod def load ( collada , localscope , node ) : pnode = node . find ( '' % ( tag ( '' ) , tag ( '' ) ) ) colornode = pnode . find ( tag ( '' ) ) if colornode is None : raise DaeIncompleteError ( '' ) try : color = tuple ( [ float ( v ) for v in colornode . text . split ( ) ] ) except ValueError as ex : raise DaeMalformedError ( '' ) constant_att = linear_att = quad_att = zfar = None qattnode = pnode . find ( tag ( '' ) ) cattnode = pnode . find ( tag ( '' ) ) lattnode = pnode . find ( tag ( '' ) ) zfarnode = pnode . find ( tag ( '' ) ) try : if cattnode is not None : constant_att = float ( cattnode . text ) if lattnode is not None : linear_att = float ( lattnode . text ) if qattnode is not None : quad_att = float ( qattnode . text ) if zfarnode is not None : zfar = float ( zfarnode . text ) except ValueError as ex : raise DaeMalformedError ( '' ) return PointLight ( node . get ( '' ) , color , constant_att , linear_att , quad_att , zfar , xmlnode = node ) def bind ( self , matrix ) : \"\"\"\"\"\" return BoundPointLight ( self , matrix ) def __str__ ( self ) : return '' % ( self . id , ) def __repr__ ( self ) : return str ( self ) class SpotLight ( Light ) : \"\"\"\"\"\" def __init__ ( self , id , color , constant_att = None , linear_att = None , quad_att = None , falloff_ang = None , falloff_exp = None , xmlnode = None ) : \"\"\"\"\"\" self . id = id \"\"\"\"\"\" self . color = color \"\"\"\"\"\" self . constant_att = constant_att \"\"\"\"\"\" self . linear_att = linear_att \"\"\"\"\"\" self . quad_att = quad_att \"\"\"\"\"\" self . falloff_ang = falloff_ang \"\"\"\"\"\" self . falloff_exp = falloff_exp \"\"\"\"\"\" if xmlnode != None : self . xmlnode = xmlnode \"\"\"\"\"\" else : pnode = E . spot ( E . color ( '' . join ( map ( str , self . color ) ) ) , ) if self . constant_att is not None : pnode . append ( E . constant_attenuation ( str ( self . constant_att ) ) ) if self . linear_att is not None : pnode . append ( E . linear_attenuation ( str ( self . linear_att ) ) ) if self . quad_att is not None : pnode . append ( E . quadratic_attenuation ( str ( self . quad_att ) ) ) if self . falloff_ang is not None : pnode . append ( E . falloff_angle ( str ( self . falloff_ang ) ) ) if self . falloff_exp is not None : pnode . append ( E . falloff_exponent ( str ( self . falloff_exp ) ) ) self . xmlnode = E . light ( E . technique_common ( pnode ) , id = self . id , name = self . id ) def save ( self ) : \"\"\"\"\"\" self . xmlnode . set ( '' , self . id ) self . xmlnode . set ( '' , self . id ) pnode = self . xmlnode . find ( '' % ( tag ( '' ) , tag ( '' ) ) ) colornode = pnode . find ( tag ( '' ) ) colornode . text = '' . join ( map ( str , self . color ) ) _correctValInNode ( pnode , '' , self . constant_att ) _correctValInNode ( pnode , '' , self . linear_att ) _correctValInNode ( pnode , '' , self . quad_att ) _correctValInNode ( pnode , '' , self . falloff_ang ) _correctValInNode ( pnode , '' , self . falloff_exp ) @ staticmethod def load ( collada , localscope , node ) : pnode = node . find ( '' % ( tag ( '' ) , tag ( '' ) ) ) colornode = pnode . find ( tag ( '' ) ) if colornode is None : raise DaeIncompleteError ( '' ) try : color = tuple ( [ float ( v ) for v in colornode . text . split ( ) ] ) except ValueError as ex : raise DaeMalformedError ( '' ) constant_att = linear_att = quad_att = falloff_ang = falloff_exp = None cattnode = pnode . find ( tag ( '' ) ) lattnode = pnode . find ( tag ( '' ) ) qattnode = pnode . find ( tag ( '' ) ) fangnode = pnode . find ( tag ( '' ) ) fexpnode = pnode . find ( tag ( '' ) ) try : if cattnode is not None : constant_att = float ( cattnode . text ) if lattnode is not None : linear_att = float ( lattnode . text ) if qattnode is not None : quad_att = float ( qattnode . text ) if fangnode is not None : falloff_ang = float ( fangnode . text ) if fexpnode is not None : falloff_exp = float ( fexpnode . text ) except ValueError as ex : raise DaeMalformedError ( '' ) return SpotLight ( node . get ( '' ) , color , constant_att , linear_att , quad_att , falloff_ang , falloff_exp , xmlnode = node ) def bind ( self , matrix ) : \"\"\"\"\"\" return BoundSpotLight ( self , matrix ) def __str__ ( self ) : return '' % ( self . id , ) def __repr__ ( self ) : return str ( self ) class BoundLight ( object ) : \"\"\"\"\"\" pass class BoundPointLight ( BoundLight ) : \"\"\"\"\"\" def __init__ ( self , plight , matrix ) : self . position = numpy . dot ( matrix [ : , : ] , plight . position ) + matrix [ : , ] \"\"\"\"\"\" self . color = plight . color \"\"\"\"\"\" self . constant_att = plight . constant_att if self . constant_att is None : self . constant_att = \"\"\"\"\"\" self . linear_att = plight . linear_att if self . linear_att is None : self . linear_att = \"\"\"\"\"\" self . quad_att = plight . quad_att if self . quad_att is None : self . quad_att = \"\"\"\"\"\" self . zfar = plight . zfar \"\"\"\"\"\" self . original = plight \"\"\"\"\"\" def __str__ ( self ) : return '' % str ( self . original . id ) def __repr__ ( self ) : return str ( self ) class BoundSpotLight ( BoundLight ) : \"\"\"\"\"\" def __init__ ( self , slight , matrix ) : self . position = matrix [ : , ] \"\"\"\"\"\" self . direction = - matrix [ : , ] \"\"\"\"\"\" self . up = matrix [ : , ] \"\"\"\"\"\" self . matrix = matrix \"\"\"\"\"\" self . color = slight . color \"\"\"\"\"\" self . constant_att = slight . constant_att if self . constant_att is None : self . constant_att = \"\"\"\"\"\" self . linear_att = slight . linear_att if self . linear_att is None : self . linear_att = \"\"\"\"\"\" self . quad_att = slight . quad_att if self . quad_att is None : self . quad_att = \"\"\"\"\"\" self . falloff_ang = slight . falloff_ang if self . falloff_ang is None : self . falloff_ang = \"\"\"\"\"\" self . falloff_exp = slight . falloff_exp if self . falloff_exp is None : self . falloff_exp = \"\"\"\"\"\" self . original = slight \"\"\"\"\"\" def __str__ ( self ) : return '' % str ( self . original . id ) def __repr__ ( self ) : return str ( self ) class BoundDirectionalLight ( BoundLight ) : \"\"\"\"\"\" def __init__ ( self , dlight , matrix ) : self . direction = numpy . dot ( matrix [ : , : ] , dlight . direction ) \"\"\"\"\"\" self . color = dlight . color \"\"\"\"\"\" self . original = dlight \"\"\"\"\"\" def __str__ ( self ) : return '' % str ( self . original . id ) def __repr__ ( self ) : return str ( self ) class BoundAmbientLight ( BoundLight ) : \"\"\"\"\"\" def __init__ ( self , alight , matrix ) : self . color = alight . color \"\"\"\"\"\" ", "answer": "self . original = alight"}, {"prompt": " \"\"\"\"\"\" __docformat__ = '' from docutils import nodes , languages from docutils . transforms import parts from docutils . parsers . rst import Directive ", "answer": "from docutils . parsers . rst import directives"}, {"prompt": " from shakespeare . tests import * import shakespeare . model as model import shakespeare . lib . feed as feed class TestFeed : nose_external = True @ classmethod def setup_class ( self ) : TestData . make_fixture ( ) @ classmethod def teardown_class ( self ) : TestData . remove_fixtures ( ) def test_01_load_entry ( self ) : import feedparser entry = feedparser . FeedParserDict ( ) title = u'' name = title . strip ( ) content = [ { '' : u'' , '' : '' } ] entry . title = title entry . content = content loader = feed . WorkIntroductionLoader ( ) work = loader . load_entry ( entry ) assert work . name == '' , work model . Session . commit ( ) model . Session . remove ( ) work = model . Work . by_name ( TestData . name ) ", "answer": "assert work . notes == content [ ] [ '' ] , work . notes"}, {"prompt": " import math import json import pycurl import sys from . import tests from . tests import Test from . import parsing from . parsing import * if sys . version_info [ ] > : from past . builtins import basestring from . import six from . six import binary_type from . six import text_type \"\"\"\"\"\" METRICS = { '' : pycurl . NAMELOOKUP_TIME , '' : pycurl . CONNECT_TIME , '' : pycurl . APPCONNECT_TIME , '' : pycurl . PRETRANSFER_TIME , '' : pycurl . STARTTRANSFER_TIME , '' : pycurl . REDIRECT_TIME , '' : pycurl . TOTAL_TIME , '' : pycurl . SIZE_DOWNLOAD , '' : pycurl . SIZE_UPLOAD , '' : pycurl . REQUEST_SIZE , '' : pycurl . SPEED_DOWNLOAD , '' : pycurl . SPEED_UPLOAD , '' : pycurl . REDIRECT_COUNT , '' : pycurl . NUM_CONNECTS } AGGREGATES = { '' : lambda x : float ( sum ( x ) ) / float ( len ( x ) ) , '' : lambda x : float ( sum ( x ) ) / float ( len ( x ) ) , '' : lambda x : / ( sum ( [ / float ( y ) for y in x ] ) / float ( len ( x ) ) ) , '' : lambda x : median ( x ) , '' : lambda x : std_deviation ( x ) , '' : lambda x : sum ( x ) , '' : lambda x : sum ( x ) } OUTPUT_FORMATS = [ u'' , u'' ] def median ( array ) : \"\"\"\"\"\" mysorted = [ x for x in array ] mysorted . sort ( ) middle = int ( len ( mysorted ) / ) if len ( mysorted ) % == : return float ( ( mysorted [ middle ] + mysorted [ middle - ] ) ) / else : return mysorted [ middle ] def std_deviation ( array ) : \"\"\"\"\"\" ", "answer": "if not array or len ( array ) == :"}, {"prompt": " import unittest import time from nose . tools import assert_raises , assert_equal , assert_true from pycassa import index , ColumnFamily , ConnectionPool , NotFoundException from pycassa . contrib . stubs import ColumnFamilyStub , ConnectionPoolStub from pycassa . util import convert_time_to_uuid pool = cf = indexed_cf = None pool_stub = cf_stub = indexed_cf_stub = None def setup_module ( ) : global pool , cf , indexed_cf , pool_stub , indexed_cf_stub , cf_stub credentials = { '' : '' , '' : '' } pool = ConnectionPool ( keyspace = '' , credentials = credentials , timeout = ) cf = ColumnFamily ( pool , '' , dict_class = TestDict ) indexed_cf = ColumnFamily ( pool , '' ) pool_stub = ConnectionPoolStub ( keyspace = '' , credentials = credentials , timeout = ) cf_stub = ColumnFamilyStub ( pool_stub , '' , dict_class = TestDict ) indexed_cf_stub = ColumnFamilyStub ( pool_stub , '' ) def teardown_module ( ) : cf . truncate ( ) cf_stub . truncate ( ) indexed_cf . truncate ( ) indexed_cf_stub . truncate ( ) pool . dispose ( ) class TestDict ( dict ) : pass class TestColumnFamilyStub ( unittest . TestCase ) : def setUp ( self ) : pass def tearDown ( self ) : for test_cf in ( cf , cf_stub ) : for key , columns in test_cf . get_range ( ) : test_cf . remove ( key ) def test_empty ( self ) : key = '' for test_cf in ( cf , cf_stub ) : assert_raises ( NotFoundException , test_cf . get , key ) assert_equal ( len ( test_cf . multiget ( [ key ] ) ) , ) for key , columns in test_cf . get_range ( ) : assert_equal ( len ( columns ) , ) def test_insert_get ( self ) : key = '' columns = { '' : '' , '' : '' } for test_cf in ( cf , cf_stub ) : assert_raises ( NotFoundException , test_cf . get , key ) ts = test_cf . insert ( key , columns ) assert_true ( isinstance ( ts , ( int , long ) ) ) assert_equal ( test_cf . get ( key ) , columns ) def test_insert_get_column_start_and_finish_reversed ( self ) : key = '' columns = { '' : '' , '' : '' } for test_cf in ( cf , cf_stub ) : assert_raises ( NotFoundException , test_cf . get , key ) ts = test_cf . insert ( key , columns ) assert_true ( isinstance ( ts , ( int , long ) ) ) test_cf . get ( key , column_reversed = True ) def test_insert_get_column_start_and_finish ( self ) : key = '' columns = { '' : '' , '' : '' , '' : '' , '' : '' } for test_cf in ( cf , cf_stub ) : assert_raises ( NotFoundException , test_cf . get , key ) ts = test_cf . insert ( key , columns ) assert_true ( isinstance ( ts , ( int , long ) ) ) assert_equal ( test_cf . get ( key , column_start = '' , column_finish = '' ) , { '' : '' , '' : '' } ) def test_insert_get_column_start_and_reversed ( self ) : key = '' columns = { '' : '' , '' : '' , '' : '' , '' : '' } for test_cf in ( cf , cf_stub ) : assert_raises ( NotFoundException , test_cf . get , key ) ts = test_cf . insert ( key , columns ) assert_true ( isinstance ( ts , ( int , long ) ) ) assert_equal ( test_cf . get ( key , column_start = '' , column_reversed = True ) , { '' : '' , '' : '' } ) def test_insert_get_column_count ( self ) : key = '' columns = { '' : '' , '' : '' , '' : '' , '' : '' } for test_cf in ( cf , cf_stub ) : assert_raises ( NotFoundException , test_cf . get , key ) ts = test_cf . insert ( key , columns ) assert_true ( isinstance ( ts , ( int , long ) ) ) assert_equal ( test_cf . get ( key , column_count = ) , { '' : '' , '' : '' , '' : '' } ) def test_insert_get_default_column_count ( self ) : keys = [ str ( i ) for i in range ( ) ] keys . sort ( ) keys_and_values = [ ( key , key ) for key in keys ] key = '' for test_cf in ( cf , cf_stub ) : assert_raises ( NotFoundException , test_cf . get , key ) test_cf . insert ( key , dict ( key_value for key_value in keys_and_values ) ) assert_equal ( test_cf . get ( key ) , dict ( [ key_value for key_value in keys_and_values ] [ : ] ) ) def test_insert_multiget ( self ) : key1 = '' columns1 = { '' : '' , '' : '' } key2 = '' ", "answer": "columns2 = { '' : '' , '' : '' }"}, {"prompt": " import time import os , sys , inspect from pylab import * import numpy import scipy . interpolate from droneapi . lib import APIException , Vehicle , Attitude , Location , GPSInfo , VehicleMode , Mission , Parameters , Command , CommandSequence from pymavlink import mavutil cmd_subfolder = os . path . realpath ( os . path . abspath ( os . path . join ( os . path . split ( inspect . getfile ( inspect . currentframe ( ) ) ) [ ] , \"\" ) ) ) if cmd_subfolder not in sys . path : sys . path . insert ( , cmd_subfolder ) import trajectoryAPI import coord_system TAKEOFF_HEIGHT = DISTANCE_LIMIT_LOOK_AT_METERS = DISTANCE_LIMIT_LOOK_FROM_METERS = def init_splinefollow ( drone ) : drone . states = { '' : _state_waiting , '' : _state_flyToStart , '' : _state_flySpline , } drone . lastLookFromPoint = None drone . lastLookAtPoint = None drone . altitudeOffset = drone . current_location = None drone . vehicle . add_attribute_observer ( '' , drone . location_callback ) def setSpline ( drone , data ) : lookAtN = data [ '' ] lookAtE = data [ '' ] lookAtD = data [ '' ] lookFromN = data [ '' ] lookFromE = data [ '' ] lookFromD = data [ '' ] drone . P_lookFromNED_spline = c_ [ lookFromN , lookFromE , lookFromD ] drone . T_lookFromNED_spline = c_ [ data [ '' ] , data [ '' ] , data [ '' ] ] drone . P_lookFromNED_ease = c_ [ array ( data [ '' ] ) ] drone . T_lookFromNED_ease = c_ [ array ( data [ '' ] ) ] drone . P_lookAtNED_spline = c_ [ lookAtN , lookAtE , lookAtD ] drone . T_lookAtNED_spline = c_ [ data [ '' ] , data [ '' ] , data [ '' ] ] drone . P_lookAtNED_ease = c_ [ array ( data [ '' ] ) ] drone . T_lookAtNED_ease = c_ [ array ( data [ '' ] ) ] drone . startAltitude = data [ '' ] drone . lastTime = data [ '' ] ; drone . refLLH = array ( [ data [ '' ] [ '' ] , data [ '' ] [ '' ] , data [ '' ] [ '' ] ] ) def newTrajectory ( drone , data ) : setSpline ( drone , data ) drone . lastLookFromPoint = None drone . lastLookAtPoint = None drone . altitudeOffset = drone . vehicle . add_attribute_observer ( '' , drone . location_callback ) configureSpline ( drone ) def changeCurrentTrajectory ( drone , data ) : setSpline ( drone , data ) configureSpline ( drone ) def _stateTransition ( drone , newState ) : print \"\" % ( drone . STATE , newState ) drone . currentStateTime = time . time ( ) drone . STATE = newState def start ( drone ) : if not drone . vehicle . armed : print \"\" drone . vehicle . armed = True drone . vehicle . flush ( ) time . sleep ( ) print \"\" drone . vehicle . mode = VehicleMode ( \"\" ) drone . vehicle . flush ( ) time . sleep ( ) TAKEOFF_HEIGHT = drone . refLLH [ ] - drone . altitudeOffset print \"\" % TAKEOFF_HEIGHT drone . vehicle . commands . takeoff ( TAKEOFF_HEIGHT ) drone . vehicle . flush ( ) while drone . vehicle . location . alt < TAKEOFF_HEIGHT - : time . sleep ( ) print \"\" drone . vehicle . mode = VehicleMode ( \"\" ) drone . vehicle . flush ( ) time . sleep ( ) _stateTransition ( drone , '' ) def _state_waiting ( drone , elapsed , dt ) : drone . flightFinished ( ) return def _state_flyToStart ( drone , elapsed , dt ) : l = drone . vehicle . location if l is None : return lookFromStartLLH = coord_system . ned2llh ( drone . P_lookFromNED_spline [ ] , drone . refLLH ) lookAtStartLLH = coord_system . ned2llh ( drone . P_lookAtNED_spline [ ] , drone . refLLH ) lookFromStartLLH [ ] = lookFromStartLLH [ ] - drone . altitudeOffset lookAtStartLLH [ ] = lookFromStartLLH [ ] - drone . altitudeOffset distanceToStart = coord_system . get_distance_llh ( lookFromStartLLH , numpy . array ( [ l . lat , l . lon , l . alt ] ) ) print \"\" % distanceToStart if distanceToStart > or np . linalg . norm ( drone . vehicle . velocity ) > : sendLookFrom ( drone , lookFromStartLLH ) sendLookAt ( drone , lookAtStartLLH ) else : return _stateTransition ( drone , '' ) def _state_flySpline ( drone , elapsed , dt ) : if elapsed > drone . lastTime : return _stateTransition ( drone , '' ) t_lookAt = drone . time_to_lookAt ( elapsed ) t_lookFrom = drone . time_to_lookFrom ( elapsed ) lookFromPointNED , TF , dTF = trajectoryAPI . _evaluate_spatial_spline ( drone . C_lookFrom_spline , drone . T_lookFrom_spline , drone . sd_lookFrom_spline , T_eval = np . array ( [ [ t_lookFrom , t_lookFrom , t_lookFrom ] ] ) ) lookAtPointNED , TA , dTA = trajectoryAPI . _evaluate_spatial_spline ( drone . C_lookAt_spline , drone . T_lookAt_spline , drone . sd_lookAt_spline , T_eval = np . array ( [ [ t_lookAt , t_lookAt , t_lookAt ] ] ) ) lookFromPoint = coord_system . ned2llh ( lookFromPointNED [ ] , drone . refLLH ) lookAtPoint = coord_system . ned2llh ( lookAtPointNED [ ] , drone . refLLH ) lookFromPoint [ ] = lookFromPoint [ ] - drone . altitudeOffset lookAtPoint [ ] = lookAtPoint [ ] - drone . altitudeOffset sendLookFrom ( drone , lookFromPoint ) if drone . lastLookAtPoint == None or coord_system . get_distance_llh ( drone . lastLookAtPoint , lookAtPoint ) > DISTANCE_LIMIT_LOOK_AT_METERS : drone . lastLookAtPoint = lookAtPoint sendLookAt ( drone , lookAtPoint ) def armed_callback ( drone , armed ) : print \"\" % armed def configureSpline ( drone ) : C_lookFromNED_spline , T_lookFrom2_spline , sd_lF = trajectoryAPI . _get_spatial_spline_coefficients ( drone . P_lookFromNED_spline , drone . T_lookFromNED_spline ) C_lookAtNED_spline , T_lookAt2_spline , sd_lA = trajectoryAPI . _get_spatial_spline_coefficients ( drone . P_lookAtNED_spline , drone . T_lookAtNED_spline ) T_linspace_norm_lookAt , T_user_progress_lookAt , P_user_progress_lookAt , ref_llh1 = trajectoryAPI . reparameterize_spline ( drone . P_lookAtNED_spline , drone . T_lookAtNED_spline , drone . P_lookAtNED_ease , drone . T_lookAtNED_ease ) T_linspace_norm_cameraPose , T_user_progress_lookFrom , P_user_progress_lookFrom , ref_llh2 = trajectoryAPI . reparameterize_spline ( drone . P_lookFromNED_spline , drone . T_lookFromNED_spline , drone . P_lookFromNED_ease , drone . T_lookFromNED_ease ) timeMaxT = drone . lastTime lookAtMaxT = drone . T_lookAtNED_spline [ - ] [ ] lookFromMaxT = drone . T_lookFromNED_spline [ - ] [ ] drone . altitudeOffset = drone . startAltitude drone . C_lookFrom_spline = C_lookFromNED_spline drone . T_lookFrom_spline = drone . T_lookFromNED_spline drone . sd_lookFrom_spline = sd_lF ", "answer": "drone . C_lookAt_spline = C_lookAtNED_spline"}, {"prompt": " class LibvorbisPackage ( XiphPackage ) : def __init__ ( self ) : ", "answer": "XiphPackage . __init__ ( self ,"}, {"prompt": " \"\"\"\"\"\" from flask_restplus . inputs import * ", "answer": "from . my_inputs import boolean "}, {"prompt": " \"\"\"\"\"\" ", "answer": "from ovs . dal . datalist import DataList"}, {"prompt": " \"\"\"\"\"\" from pypy . tool . pairtype import extendabletype from pypy . rpython . ootypesystem import ootype from pypy . rpython . lltypesystem import lltype from pypy . rpython . error import TyperError class TypeSystem ( object ) : __metaclass__ = extendabletype offers_exceptiondata = True def __getattr__ ( self , name ) : \"\"\"\"\"\" def load ( modname ) : try : return __import__ ( \"\" % ( self . name , modname ) , None , None , [ '' ] ) except ImportError : return None if name in ( '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ) : mod = load ( name ) if mod is not None : setattr ( self , name , mod ) return mod raise AttributeError ( name ) def derefType ( self , T ) : raise NotImplementedError ( ) def deref ( self , obj ) : \"\"\"\"\"\" raise NotImplementedError ( ) def check_null ( self , repr , hop ) : \"\"\"\"\"\" raise NotImplementedError ( ) def null_callable ( self , T ) : \"\"\"\"\"\" raise NotImplementedError ( ) def getcallabletype ( self , ARGS , RESTYPE ) : cls = self . callable_trait [ ] return cls ( ARGS , RESTYPE ) def getcallable ( self , graph , getconcretetype = None ) : \"\"\"\"\"\" if getconcretetype is None : getconcretetype = self . getconcretetype llinputs = [ getconcretetype ( v ) for v in graph . getargs ( ) ] lloutput = getconcretetype ( graph . getreturnvar ( ) ) typ , constr = self . callable_trait FT = typ ( llinputs , lloutput ) name = graph . name if hasattr ( graph , '' ) and callable ( graph . func ) : if hasattr ( graph . func , '' ) : fnobjattrs = graph . func . _llfnobjattrs_ . copy ( ) name = fnobjattrs . pop ( '' , name ) else : fnobjattrs = { } _callable = fnobjattrs . pop ( '' , graph . func ) return constr ( FT , name , graph = graph , _callable = _callable , ** fnobjattrs ) else : return constr ( FT , name , graph = graph ) def getexternalcallable ( self , ll_args , ll_result , name , ** kwds ) : typ , constr = self . callable_trait FT = typ ( ll_args , ll_result ) return constr ( FT , name , ** kwds ) def getconcretetype ( self , v ) : \"\"\"\"\"\" raise NotImplementedError ( ) def perform_normalizations ( self , rtyper ) : \"\"\"\"\"\" from pypy . rpython . normalizecalls import perform_normalizations perform_normalizations ( rtyper ) class LowLevelTypeSystem ( TypeSystem ) : name = \"\" callable_trait = ( lltype . FuncType , lltype . functionptr ) def derefType ( self , T ) : assert isinstance ( T , lltype . Ptr ) return T . TO def deref ( self , obj ) : assert isinstance ( lltype . typeOf ( obj ) , lltype . Ptr ) return obj . _obj def check_null ( self , repr , hop ) : vlist = hop . inputargs ( repr ) return hop . genop ( '' , vlist , resulttype = lltype . Bool ) def getconcretetype ( self , v ) : return getattr ( v , '' , lltype . Ptr ( lltype . PyObject ) ) def null_callable ( self , T ) : return lltype . nullptr ( T . TO ) def generic_is ( self , robj1 , robj2 , hop ) : roriginal1 = robj1 roriginal2 = robj2 if robj1 . lowleveltype is lltype . Void : robj1 = robj2 elif robj2 . lowleveltype is lltype . Void : robj2 = robj1 if ( not isinstance ( robj1 . lowleveltype , lltype . Ptr ) or not isinstance ( robj2 . lowleveltype , lltype . Ptr ) ) : raise TyperError ( '' % ( roriginal1 , roriginal2 ) ) if robj1 . lowleveltype != robj2 . lowleveltype : raise TyperError ( '' % ( roriginal1 , roriginal2 ) ) v_list = hop . inputargs ( robj1 , robj2 ) return hop . genop ( '' , v_list , resulttype = lltype . Bool ) class ObjectOrientedTypeSystem ( TypeSystem ) : name = \"\" callable_trait = ( ootype . StaticMethod , ootype . static_meth ) def derefType ( self , T ) : assert isinstance ( T , ootype . OOType ) return T def deref ( self , obj ) : assert isinstance ( ootype . typeOf ( obj ) , ootype . OOType ) return obj def check_null ( self , repr , hop ) : vlist = hop . inputargs ( repr ) return hop . genop ( '' , vlist , resulttype = ootype . Bool ) def getconcretetype ( self , v ) : return v . concretetype def null_callable ( self , T ) : return ootype . null ( T ) def generic_is ( self , robj1 , robj2 , hop ) : roriginal1 = robj1 roriginal2 = robj2 if robj1 . lowleveltype is lltype . Void : robj1 = robj2 elif robj2 . lowleveltype is lltype . Void : robj2 = robj1 if ( not isinstance ( robj1 . lowleveltype , ( ootype . Instance , ootype . BuiltinADTType ) ) or not isinstance ( robj2 . lowleveltype , ( ootype . Instance , ootype . BuiltinADTType ) ) ) and ( robj1 . lowleveltype is not ootype . Class or robj2 . lowleveltype is not ootype . Class ) : raise TyperError ( '' % ( roriginal1 , roriginal2 ) ) v_list = hop . inputargs ( robj1 , robj2 ) return hop . genop ( '' , v_list , resulttype = lltype . Bool ) LowLevelTypeSystem . instance = LowLevelTypeSystem ( ) ObjectOrientedTypeSystem . instance = ObjectOrientedTypeSystem ( ) getfunctionptr = LowLevelTypeSystem . instance . getcallable from pypy . tool . pairtype import pairtype from pypy . annotation . model import SomeObject class __extend__ ( pairtype ( TypeSystem , SomeObject ) ) : def rtyper_makerepr ( ( ts , s_obj ) , rtyper ) : return s_obj . rtyper_makerepr ( rtyper ) ", "answer": "def rtyper_makekey ( ( ts , s_obj ) , rtyper ) :"}, {"prompt": " import datetime ", "answer": "from south . db import db"}, {"prompt": " \"\"\"\"\"\" import functools import re import tokenize re_assert_true_instance = re . compile ( r\"\" r\"\" ) re_assert_equal_type = re . compile ( r\"\" r\"\" ) re_assert_equal_end_with_none = re . compile ( r\"\" ) re_assert_equal_start_with_none = re . compile ( r\"\" ) re_assert_true_false_with_in_or_not_in = re . compile ( r\"\" r\"\" ) re_assert_true_false_with_in_or_not_in_spaces = re . compile ( r\"\" r\"\" ) re_assert_equal_in_end_with_true_or_false = re . compile ( r\"\" ) re_assert_equal_in_start_with_true_or_false = re . compile ( r\"\" ) re_no_construct_dict = re . compile ( r\"\" ) re_no_construct_list = re . compile ( r\"\" ) re_str_format = re . compile ( r\"\"\"\"\"\" , re . X ) re_raises = re . compile ( r\"\" ) re_db_import = re . compile ( r\"\" ) re_objects_import = re . compile ( r\"\" ) re_old_type_class = re . compile ( r\"\" ) re_datetime_alias = re . compile ( r\"\" ) def skip_ignored_lines ( func ) : @ functools . wraps ( func ) def wrapper ( logical_line , physical_line , filename ) : ", "answer": "line = physical_line . strip ( )"}, {"prompt": " import logging import importlib from django . apps import apps from django . core . exceptions import MiddlewareNotUsed from django . utils . lru_cache import lru_cache from django . utils . module_loading import module_has_submodule from . import app_settings def configure_logging ( level , format , filename ) : \"\"\"\"\"\" logging . root . handlers = [ ] handler = logging . StreamHandler ( ) if filename : handler = logging . handlers . WatchedFileHandler ( filename ) handler . setFormatter ( logging . Formatter ( format ) ) logging . root . addHandler ( handler ) if level is not None : logging . root . setLevel ( level ) return handler . stream . fileno ( ) @ lru_cache ( ) def get_path ( path ) : module_name , attr = path . rsplit ( '' , ) ", "answer": "module = importlib . import_module ( module_name )"}, {"prompt": " \"\"\"\"\"\" import sys sys . path [ : ] = [ \"\" ] from pymongo . ismaster import IsMaster from pymongo . server import Server from pymongo . server_description import ServerDescription ", "answer": "from test import unittest"}, {"prompt": " from __future__ import absolute_import , print_function , unicode_literals , division from sc2reader . factories . sc2factory import SC2Factory from sc2reader . factories . sc2factory import FileCachedSC2Factory ", "answer": "from sc2reader . factories . sc2factory import DictCachedSC2Factory"}, {"prompt": " from setuptools import setup setup ( name = \"\" , version = '' , ", "answer": "description = '' ,"}, {"prompt": " \"\"\"\"\"\" import os import re from types import BuiltinFunctionType , FunctionType DEBUG = True class ApiDocWriter ( object ) : '''''' rst_section_levels = [ '' , '' , '' , '' , '' ] def __init__ ( self , package_name , rst_extension = '' , package_skip_patterns = None , module_skip_patterns = None , ) : '''''' if package_skip_patterns is None : package_skip_patterns = [ '' ] if module_skip_patterns is None : module_skip_patterns = [ '' , '' ] self . package_name = package_name self . rst_extension = rst_extension self . package_skip_patterns = package_skip_patterns self . module_skip_patterns = module_skip_patterns def get_package_name ( self ) : return self . _package_name def set_package_name ( self , package_name ) : '''''' self . _package_name = package_name root_module = self . _import ( package_name ) self . root_path = root_module . __path__ [ - ] self . written_modules = None package_name = property ( get_package_name , set_package_name , None , '' ) def _import ( self , name ) : '''''' mod = __import__ ( name ) components = name . split ( '' ) for comp in components [ : ] : mod = getattr ( mod , comp ) return mod def _get_object_name ( self , line ) : '''''' name = line . split ( ) [ ] . split ( '' ) [ ] . strip ( ) return name . rstrip ( '' ) def _uri2path ( self , uri ) : '''''' if uri == self . package_name : return os . path . join ( self . root_path , '' ) path = uri . replace ( self . package_name + '' , '' ) path = path . replace ( '' , os . path . sep ) path = os . path . join ( self . root_path , path ) if os . path . exists ( path + '' ) : path += '' elif os . path . exists ( os . path . join ( path , '' ) ) : path = os . path . join ( path , '' ) else : return None return path def _path2uri ( self , dirpath ) : '''''' package_dir = self . package_name . replace ( '' , os . path . sep ) relpath = dirpath . replace ( self . root_path , package_dir ) if relpath . startswith ( os . path . sep ) : relpath = relpath [ : ] return relpath . replace ( os . path . sep , '' ) def _parse_module ( self , uri ) : '''''' filename = self . _uri2path ( uri ) if filename is None : print ( filename , '' ) return ( [ ] , [ ] ) f = open ( filename , '' ) functions , classes = self . _parse_lines ( f ) f . close ( ) return functions , classes def _parse_module_with_import ( self , uri ) : \"\"\"\"\"\" mod = __import__ ( uri , fromlist = [ uri . split ( '' ) [ - ] ] ) obj_strs = [ obj for obj in dir ( mod ) if not obj . startswith ( '' ) ] functions = [ ] classes = [ ] for obj_str in obj_strs : if obj_str not in mod . __dict__ : continue obj = mod . __dict__ [ obj_str ] if isinstance ( obj , ( FunctionType , BuiltinFunctionType ) ) : functions . append ( obj_str ) else : try : issubclass ( obj , object ) classes . append ( obj_str ) except TypeError : pass return functions , classes def _parse_lines ( self , linesource ) : '''''' functions = [ ] classes = [ ] for line in linesource : if line . startswith ( '' ) and line . count ( '' ) : name = self . _get_object_name ( line ) if not name . startswith ( '' ) : functions . append ( name ) elif line . startswith ( '' ) : name = self . _get_object_name ( line ) if not name . startswith ( '' ) : classes . append ( name ) else : pass functions . sort ( ) classes . sort ( ) return functions , classes def generate_api_doc ( self , uri ) : '''''' functions , classes = self . _parse_module_with_import ( uri ) if not len ( functions ) and not len ( classes ) and DEBUG : print ( '' , uri ) ", "answer": "return ''"}, {"prompt": " '''''' from __future__ import absolute_import , print_function import errno import logging import os import tempfile import shutil import salt . utils from salt . exceptions import SaltInvocationError from salt . ext . six . moves . urllib . parse import urlparse as _urlparse log = logging . getLogger ( __name__ ) __virtualname__ = '' def __virtual__ ( ) : '''''' if __grains__ . get ( '' , False ) in ( '' , '' ) : return __virtualname__ return ( False , '' ) def _get_build_env ( env ) : '''''' env_override = '' if env is None : return env_override if not isinstance ( env , dict ) : raise SaltInvocationError ( '' ) for key , value in env . items ( ) : env_override += '' . format ( key , value ) env_override += '' . format ( key ) ", "answer": "return env_override"}, {"prompt": " from django . utils . translation import ugettext_lazy as _ from horizon import tabs from horizon import workflows from openstack_dashboard . dashboards . admin . defaults import tabs as project_tabs from openstack_dashboard . dashboards . admin . defaults import workflows as project_workflows from openstack_dashboard . usage import quotas ", "answer": "class IndexView ( tabs . TabbedTableView ) :"}, {"prompt": " '''''' import csv import sys ", "answer": "import random"}, {"prompt": " import os from twisted . trial import unittest , util from nevow import context from nevow import flat from nevow . flat . flatstan import _PrecompiledSlot from nevow import loaders from nevow import tags as t class TestDocFactories ( unittest . TestCase ) : def _preprocessorTest ( self , docFactory ) : def preprocessor ( uncompiled ) : self . assertEquals ( len ( uncompiled ) , ) uncompiled = uncompiled [ ] self . assertEquals ( uncompiled . tagName , '' ) self . assertEquals ( len ( uncompiled . children ) , ) self . assertEquals ( uncompiled . children [ ] . tagName , '' ) self . assertEquals ( uncompiled . children [ ] . children , [ '' ] ) self . assertEquals ( uncompiled . children [ ] . tagName , '' ) self . assertEquals ( uncompiled . children [ ] . children , [ '' ] ) return t . div [ '' ] doc = docFactory . load ( preprocessors = [ preprocessor ] ) self . assertEquals ( doc , [ '' ] ) def test_stanPreprocessors ( self ) : \"\"\"\"\"\" factory = loaders . stan ( t . div [ t . span [ '' ] , t . span [ '' ] ] ) return self . _preprocessorTest ( factory ) def test_stan ( self ) : doc = t . ul ( id = '' ) [ t . li [ '' ] , t . li [ '' ] , t . li [ '' ] ] df = loaders . stan ( doc ) self . assertEquals ( df . load ( ) [ ] , '' ) def test_stanPrecompiled ( self ) : \"\"\"\"\"\" doc = flat . precompile ( t . ul ( id = '' ) [ t . li [ '' ] , t . li [ '' ] , t . slot ( '' ) ] ) df = loaders . stan ( doc ) loaded = df . load ( ) self . assertEqual ( loaded [ ] , '' ) self . failUnless ( isinstance ( loaded [ ] , _PrecompiledSlot ) ) self . assertEqual ( loaded [ ] . name , '' ) self . assertEqual ( loaded [ ] , '' ) def test_htmlstr ( self ) : doc = '' df = loaders . htmlstr ( doc ) self . assertEquals ( df . load ( ) [ ] , doc ) test_htmlstr . suppress = [ util . suppress ( message = r\"\" \"\" ) ] def test_htmlfile ( self ) : doc = '' temp = self . mktemp ( ) f = file ( temp , '' ) f . write ( doc ) f . close ( ) df = loaders . htmlfile ( temp ) self . assertEquals ( df . load ( ) [ ] , doc ) test_htmlfile . suppress = [ util . suppress ( message = r\"\" \"\" ) ] def test_htmlfile_slots ( self ) : doc = '' temp = self . mktemp ( ) f = file ( temp , '' ) f . write ( doc ) f . close ( ) df = loaders . htmlfile ( temp ) self . assertEquals ( df . load ( ) [ ] . children , [ '' ] ) test_htmlfile_slots . suppress = [ util . suppress ( message = r\"\" \"\" ) ] def test_xmlstr ( self ) : doc = '' df = loaders . xmlstr ( doc ) self . assertEquals ( df . load ( ) [ ] , doc ) def test_xmlstrPreprocessors ( self ) : \"\"\"\"\"\" factory = loaders . xmlstr ( '' ) return self . _preprocessorTest ( factory ) def test_xmlfile ( self ) : doc = '' temp = self . mktemp ( ) f = file ( temp , '' ) f . write ( doc ) f . close ( ) df = loaders . xmlfile ( temp ) self . assertEquals ( df . load ( ) [ ] , doc ) def test_xmlfilePreprocessors ( self ) : \"\"\"\"\"\" xmlFile = self . mktemp ( ) f = file ( xmlFile , '' ) f . write ( '' ) f . close ( ) factory = loaders . xmlfile ( xmlFile ) return self . _preprocessorTest ( factory ) def test_patterned ( self ) : \"\"\"\"\"\" doc = t . div [ t . p [ t . span ( pattern = '' ) [ '' ] ] ] df = loaders . stan ( doc , pattern = '' ) self . assertEquals ( df . load ( ) [ ] . tagName , '' ) self . assertEquals ( df . load ( ) [ ] . children [ ] , '' ) def test_ignoreDocType ( self ) : doc = '''''' df = loaders . xmlstr ( doc , ignoreDocType = True ) self . assertEquals ( flat . flatten ( df ) , '' ) def test_ignoreComment ( self ) : doc = '' df = loaders . xmlstr ( doc , ignoreComment = True ) self . assertEquals ( flat . flatten ( df ) , '' ) class TestDocFactoriesCache ( unittest . TestCase ) : doc = '''''' nsdoc = '''''' stan = t . div [ t . p ( pattern = '' ) [ '' ] , t . p ( pattern = '' ) [ '' ] ] def test_stan ( self ) : loader = loaders . stan ( self . stan ) self . assertEquals ( id ( loader . load ( ) ) , id ( loader . load ( ) ) ) loader = loaders . stan ( self . stan , pattern = '' ) self . assertEquals ( id ( loader . load ( ) ) , id ( loader . load ( ) ) ) l1 = loaders . stan ( self . stan , pattern = '' ) l2 = loaders . stan ( self . stan , pattern = '' ) self . assertNotEqual ( id ( l1 . load ( ) ) , id ( l2 . load ( ) ) ) l1 = loaders . stan ( self . stan , pattern = '' ) l2 = loaders . stan ( self . stan , pattern = '' ) self . assertNotEqual ( id ( l1 . load ( ) ) , id ( l2 . load ( ) ) ) def test_htmlstr ( self ) : loader = loaders . htmlstr ( self . doc ) self . assertEquals ( id ( loader . load ( ) ) , id ( loader . load ( ) ) ) loader = loaders . htmlstr ( self . doc , pattern = '' ) self . assertEquals ( id ( loader . load ( ) ) , id ( loader . load ( ) ) ) l1 = loaders . htmlstr ( self . doc , pattern = '' ) l2 = loaders . htmlstr ( self . doc , pattern = '' ) self . assertNotEqual ( id ( l1 . load ( ) ) , id ( l2 . load ( ) ) ) l1 = loaders . htmlstr ( self . doc , pattern = '' ) l2 = loaders . htmlstr ( self . doc , pattern = '' ) self . assertNotEqual ( id ( l1 . load ( ) ) , id ( l2 . load ( ) ) ) test_htmlstr . suppress = [ util . suppress ( message = r\"\" \"\" ) ] def test_htmlfile ( self ) : temp = self . mktemp ( ) f = file ( temp , '' ) f . write ( self . doc ) f . close ( ) loader = loaders . htmlfile ( temp ) self . assertEquals ( id ( loader . load ( ) ) , id ( loader . load ( ) ) ) l1 = loaders . htmlfile ( temp , pattern = '' ) l2 = loaders . htmlfile ( temp , pattern = '' ) self . assertNotEqual ( id ( l1 . load ( ) ) , id ( l2 . load ( ) ) ) l1 = loaders . htmlfile ( temp , pattern = '' ) l2 = loaders . htmlfile ( temp , pattern = '' ) self . assertNotEqual ( id ( l1 . load ( ) ) , id ( l2 . load ( ) ) ) test_htmlfile . suppress = [ util . suppress ( message = r\"\" \"\" ) ] def test_htmlfileReload ( self ) : temp = self . mktemp ( ) f = file ( temp , '' ) f . write ( self . doc ) f . close ( ) loader = loaders . htmlfile ( temp ) r = loader . load ( ) self . assertEquals ( id ( r ) , id ( loader . load ( ) ) ) os . utime ( temp , ( os . path . getatime ( temp ) , os . path . getmtime ( temp ) + ) ) self . assertNotEqual ( id ( r ) , id ( loader . load ( ) ) ) test_htmlfileReload . suppress = [ util . suppress ( message = r\"\" \"\" ) ] def test_xmlstr ( self ) : loader = loaders . xmlstr ( self . nsdoc ) self . assertEquals ( id ( loader . load ( ) ) , id ( loader . load ( ) ) ) loader = loaders . xmlstr ( self . nsdoc , pattern = '' ) self . assertEquals ( id ( loader . load ( ) ) , id ( loader . load ( ) ) ) l1 = loaders . xmlstr ( self . nsdoc , pattern = '' ) l2 = loaders . xmlstr ( self . nsdoc , pattern = '' ) self . assertNotEqual ( id ( l1 . load ( ) ) , id ( l2 . load ( ) ) ) l1 = loaders . xmlstr ( self . nsdoc , pattern = '' ) l2 = loaders . xmlstr ( self . nsdoc , pattern = '' ) self . assertNotEqual ( id ( l1 . load ( ) ) , id ( l2 . load ( ) ) ) def test_xmlSlotDefault ( self ) : \"\"\"\"\"\" slotsdoc = '''''' loader = loaders . xmlstr ( slotsdoc ) loaded = loader . load ( ) self . assertEquals ( loaded [ ] . default , None ) self . assertEquals ( loaded [ ] . default , \"\" ) def test_xmlfile ( self ) : temp = self . mktemp ( ) f = file ( temp , '' ) f . write ( self . nsdoc ) f . close ( ) loader = loaders . xmlfile ( temp ) self . assertEquals ( id ( loader . load ( ) ) , id ( loader . load ( ) ) ) loader = loaders . xmlfile ( temp , pattern = '' ) self . assertEquals ( id ( loader . load ( ) ) , id ( loader . load ( ) ) ) l1 = loaders . xmlfile ( temp , pattern = '' ) l2 = loaders . xmlfile ( temp , pattern = '' ) self . assertNotEqual ( id ( l1 . load ( ) ) , id ( l2 . load ( ) ) ) l1 = loaders . xmlfile ( temp , pattern = '' ) l2 = loaders . xmlfile ( temp , pattern = '' ) self . assertNotEqual ( id ( l1 . load ( ) ) , id ( l2 . load ( ) ) ) def test_xmlfileReload ( self ) : temp = self . mktemp ( ) f = file ( temp , '' ) f . write ( self . nsdoc ) f . close ( ) loader = loaders . xmlfile ( temp ) r = loader . load ( ) self . assertEquals ( id ( r ) , id ( loader . load ( ) ) ) os . utime ( temp , ( os . path . getatime ( temp ) , os . path . getmtime ( temp ) + ) ) self . assertNotEqual ( id ( r ) , id ( loader . load ( ) ) ) def test_reloadAfterPrecompile ( self ) : \"\"\"\"\"\" temp = self . mktemp ( ) f = file ( temp , '' ) f . write ( '' ) f . close ( ) ctx = context . WovenContext ( ) doc = loaders . htmlfile ( temp ) pc = flat . precompile ( flat . flatten ( doc ) , ctx ) ", "answer": "before = '' . join ( flat . serialize ( pc , ctx ) )"}, {"prompt": " import os import sys import subprocess import sublime import sublime_plugin class MouCommand ( sublime_plugin . WindowCommand ) : def run ( self ) : filename = self . window . active_view ( ) . file_name ( ) if filename is None : return proc_env = os . environ . copy ( ) ", "answer": "encoding = sys . getfilesystemencoding ( )"}, {"prompt": " import json from planet . api import utils from _common import read_fixture def test_geometry_from_json ( ) : assert None is utils . geometry_from_json ( { } ) collection = { '' : '' , '' : [ ] } assert None is utils . geometry_from_json ( collection ) geom = { '' : '' } assert geom == utils . geometry_from_json ( geom ) feature = { '' : '' , '' : geom } assert geom == utils . geometry_from_json ( feature ) collection = { '' : '' , '' : [ feature ] } assert geom == utils . geometry_from_json ( collection ) def test_build_conditions ( ) : workspace = json . loads ( read_fixture ( '' ) ) c = utils . build_conditions ( workspace ) assert c [ '' ] == '' assert c [ '' ] == assert c [ '' ] == assert c [ '' ] == assert c [ '' ] == ", "answer": "assert c [ '' ] == "}, {"prompt": " \"\" __pychecker__ = \"\" import sys import os import shutil import gflags from flags_modules_for_testing import module_foo from flags_modules_for_testing import module_bar from flags_modules_for_testing import module_baz FLAGS = gflags . FLAGS import gflags_googletest as googletest class FlagsUnitTest ( googletest . TestCase ) : \"\" def setUp ( self ) : FLAGS . UseGnuGetOpt ( False ) def test_flags ( self ) : number_test_framework_flags = len ( FLAGS . RegisteredFlags ( ) ) repeatHelp = \"\" gflags . DEFINE_integer ( \"\" , , repeatHelp , lower_bound = , short_name = '' ) gflags . DEFINE_string ( \"\" , \"\" , \"\" ) gflags . DEFINE_boolean ( \"\" , , \"\" ) gflags . DEFINE_boolean ( \"\" , , \"\" ) gflags . DEFINE_boolean ( \"\" , , \"\" ) gflags . DEFINE_boolean ( \"\" , , \"\" ) gflags . DEFINE_integer ( \"\" , , \"\" ) gflags . DEFINE_integer ( \"\" , L , \"\" ) gflags . DEFINE_list ( '' , '' , \"\" ) gflags . DEFINE_list ( '' , [ , , ] , \"\" ) gflags . DEFINE_enum ( \"\" , None , [ '' , '' , '' , '' , '' ] , \"\" ) number_defined_flags = + self . assertEqual ( len ( FLAGS . RegisteredFlags ( ) ) , number_defined_flags + number_test_framework_flags ) assert FLAGS . repeat == , \"\" + FLAGS . repeat assert FLAGS . name == '' , \"\" + FLAGS . name assert FLAGS . debug == , \"\" + FLAGS . debug assert FLAGS . q == , \"\" + FLAGS . q assert FLAGS . x == , \"\" + FLAGS . x assert FLAGS . l == L , ( \"\" + FLAGS . l ) assert FLAGS . letters == [ '' , '' , '' ] , ( \"\" + FLAGS . letters ) assert FLAGS . numbers == [ , , ] , ( \"\" + FLAGS . numbers ) assert FLAGS . kwery is None , ( \"\" + FLAGS . kwery ) flag_values = FLAGS . FlagValuesDict ( ) assert flag_values [ '' ] == assert flag_values [ '' ] == '' assert flag_values [ '' ] == assert flag_values [ '' ] == assert flag_values [ '' ] == assert flag_values [ '' ] == assert flag_values [ '' ] == assert flag_values [ '' ] == L assert flag_values [ '' ] == [ '' , '' , '' ] assert flag_values [ '' ] == [ , , ] assert flag_values [ '' ] is None assert FLAGS [ '' ] . default_as_str == \"\" assert FLAGS [ '' ] . default_as_str == \"\" assert FLAGS [ '' ] . default_as_str == \"\" assert FLAGS [ '' ] . default_as_str == \"\" assert FLAGS [ '' ] . default_as_str == \"\" assert FLAGS [ '' ] . default_as_str == \"\" assert FLAGS [ '' ] . default_as_str == \"\" assert FLAGS [ '' ] . default_as_str == \"\" assert FLAGS [ '' ] . default_as_str == \"\" assert FLAGS [ '' ] . default_as_str == \"\" keys = list ( FLAGS ) keys . sort ( ) reg_flags = FLAGS . RegisteredFlags ( ) reg_flags . sort ( ) self . assertEqual ( keys , reg_flags ) argv = ( '' , ) argv = FLAGS ( argv ) assert len ( argv ) == , \"\" assert argv [ ] == '' , \"\" argv = ( '' , '' , '' , '' , '' ) argv = FLAGS ( argv ) assert len ( argv ) == , \"\" assert argv [ ] == '' , \"\" assert FLAGS [ '' ] . present == FLAGS [ '' ] . present = assert FLAGS [ '' ] . present == FLAGS [ '' ] . present = assert FLAGS [ '' ] . present == FLAGS [ '' ] . present = assert FLAGS [ '' ] . present == FLAGS [ '' ] . present = self . assertEqual ( len ( FLAGS . RegisteredFlags ( ) ) , number_defined_flags + number_test_framework_flags ) assert '' in FLAGS . RegisteredFlags ( ) assert '' in FLAGS . RegisteredFlags ( ) assert '' in FLAGS . RegisteredFlags ( ) assert '' in FLAGS . RegisteredFlags ( ) assert '' in FLAGS . RegisteredFlags ( ) assert '' in FLAGS . RegisteredFlags ( ) assert '' in FLAGS . RegisteredFlags ( ) assert '' in FLAGS . RegisteredFlags ( ) assert '' in FLAGS . RegisteredFlags ( ) assert '' in FLAGS . RegisteredFlags ( ) assert FLAGS . has_key ( '' ) assert not FLAGS . has_key ( '' ) assert '' in FLAGS assert '' not in FLAGS del FLAGS . r self . assertEqual ( len ( FLAGS . RegisteredFlags ( ) ) , number_defined_flags - + number_test_framework_flags ) assert not '' in FLAGS . RegisteredFlags ( ) argv = ( '' , '' , '' , '' ) argv = FLAGS ( argv ) assert len ( argv ) == , \"\" assert argv [ ] == '' , \"\" assert argv [ ] == '' , \"\" assert FLAGS [ '' ] . present == FLAGS [ '' ] . present = assert FLAGS [ '' ] . present == FLAGS [ '' ] . present = argv = ( '' , '' ) argv = FLAGS ( argv ) assert len ( argv ) == , \"\" assert argv [ ] == '' , \"\" assert FLAGS [ '' ] . present == assert FLAGS [ '' ] . value FLAGS . Reset ( ) assert FLAGS [ '' ] . present == assert not FLAGS [ '' ] . value argv = ( '' , '' ) argv = FLAGS ( argv ) assert len ( argv ) == , \"\" assert argv [ ] == '' , \"\" assert FLAGS [ '' ] . present == assert FLAGS [ '' ] . value == '' FLAGS . Reset ( ) assert FLAGS [ '' ] . present == assert FLAGS [ '' ] . value == None argv = ( '' , '' , '' ) argv = FLAGS ( argv ) self . assertEquals ( FLAGS . x , ) self . assertEquals ( type ( FLAGS . x ) , int ) argv = ( '' , '' , '' ) argv = FLAGS ( argv ) self . assertEquals ( FLAGS . x , ) self . assertEquals ( type ( FLAGS . x ) , long ) argv = ( '' , '' , '' ) argv = FLAGS ( argv ) self . assertEquals ( FLAGS . x , ) self . assertEquals ( type ( FLAGS . x ) , int ) argv = ( '' , '' , '' ) argv = FLAGS ( argv ) self . assertEquals ( FLAGS . x , ) self . assertEquals ( type ( FLAGS . x ) , int ) argv = ( '' , '' , '' ) try : argv = FLAGS ( argv ) raise AssertionError ( \"\" ) except gflags . IllegalFlagValue : pass gflags . DEFINE_boolean ( \"\" , None , \"\" ) argv = ( '' , '' ) argv = FLAGS ( argv ) assert FLAGS . test0 == gflags . DEFINE_boolean ( \"\" , None , \"\" ) argv = ( '' , '' ) argv = FLAGS ( argv ) assert FLAGS . test1 == FLAGS . test0 = None argv = ( '' , '' ) argv = FLAGS ( argv ) assert FLAGS . test0 == FLAGS . test1 = None argv = ( '' , '' ) argv = FLAGS ( argv ) assert FLAGS . test1 == FLAGS . test0 = None argv = ( '' , '' ) argv = FLAGS ( argv ) assert FLAGS . test0 == FLAGS . test1 = None argv = ( '' , '' ) argv = FLAGS ( argv ) assert FLAGS . test1 == FLAGS . noexec = None argv = ( '' , '' , '' , '' ) argv = FLAGS ( argv ) assert FLAGS . noexec == FLAGS . noexec = None argv = ( '' , '' , '' , '' ) argv = FLAGS ( argv ) assert FLAGS . noexec == gflags . DEFINE_boolean ( \"\" , None , \"\" ) argv = ( '' , ) argv = FLAGS ( argv ) assert FLAGS . testnone == None gflags . DEFINE_boolean ( \"\" , None , \"\" ) gflags . DEFINE_boolean ( \"\" , None , \"\" ) gflags . DEFINE_boolean ( \"\" , None , \"\" ) gflags . DEFINE_integer ( \"\" , None , \"\" ) argv = ( '' , '' , '' ) argv = FLAGS ( argv ) assert FLAGS . get ( '' , '' ) == assert FLAGS . get ( '' , '' ) == assert FLAGS . get ( '' , '' ) == '' assert FLAGS . get ( '' , '' ) == '' lists = [ [ '' , '' , '' , '' ] , [ ] , ] gflags . DEFINE_list ( '' , '' , '' ) gflags . DEFINE_spaceseplist ( '' , '' , '' ) for name , sep in ( ( '' , '' ) , ( '' , '' ) , ( '' , '' ) ) : for lst in lists : argv = ( '' , '' % ( name , sep . join ( lst ) ) ) argv = FLAGS ( argv ) self . assertEquals ( getattr ( FLAGS , name ) , lst ) flagsHelp = str ( FLAGS ) assert flagsHelp . find ( \"\" ) != - , \"\" assert flagsHelp . find ( repeatHelp ) != - , \"\" argv = ( '' , '' , '' , '' , '' ) argv = FLAGS ( argv ) self . assertEqual ( FLAGS . get ( '' , None ) , ) self . assertEqual ( FLAGS . get ( '' , None ) , ) gflags . DEFINE_multistring ( '' , '' , '' , short_name = '' ) self . assertEqual ( FLAGS . get ( '' , None ) , [ '' , ] ) multi_string_defs = [ '' , '' , ] gflags . DEFINE_multistring ( '' , multi_string_defs , '' , short_name = '' ) self . assertEqual ( FLAGS . get ( '' , None ) , multi_string_defs ) argv = ( '' , '' , '' , '' ) argv = FLAGS ( argv ) self . assertEqual ( FLAGS . get ( '' , None ) , [ '' , '' , ] ) argv = ( '' , '' , '' ) argv = FLAGS ( argv ) self . assertEqual ( FLAGS . get ( '' , None ) , ) self . assertEqual ( FLAGS . get ( '' , None ) , ) argv = ( '' , '' , '' , '' , '' ) argv = FLAGS ( argv ) self . assertEqual ( FLAGS . get ( '' , None ) , ) self . assertEqual ( FLAGS . get ( '' , None ) , ) self . assertEqual ( FLAGS . get ( '' , None ) , ) argv = ( '' , '' , '' , '' ) argv = FLAGS ( argv ) self . assertEqual ( FLAGS . get ( '' , None ) , ) self . assertEqual ( FLAGS . get ( '' , None ) , ) self . assertEqual ( FLAGS . get ( '' , None ) , ) oldtestlist = FLAGS . testlist oldtestspacelist = FLAGS . testspacelist argv = ( '' , FLAGS [ '' ] . Serialize ( ) , FLAGS [ '' ] . Serialize ( ) , FLAGS [ '' ] . Serialize ( ) , FLAGS [ '' ] . Serialize ( ) ) argv = FLAGS ( argv ) self . assertEqual ( FLAGS [ '' ] . Serialize ( ) , '' ) self . assertEqual ( FLAGS [ '' ] . Serialize ( ) , '' ) self . assertEqual ( FLAGS [ '' ] . Serialize ( ) , '' ) self . assertEqual ( FLAGS [ '' ] . Serialize ( ) , '' ) testlist1 = [ '' , '' ] testspacelist1 = [ '' , '' , '' ] FLAGS . testlist = list ( testlist1 ) FLAGS . testspacelist = list ( testspacelist1 ) argv = ( '' , FLAGS [ '' ] . Serialize ( ) , FLAGS [ '' ] . Serialize ( ) ) argv = FLAGS ( argv ) self . assertEqual ( FLAGS . testlist , testlist1 ) self . assertEqual ( FLAGS . testspacelist , testspacelist1 ) testlist1 = [ '' , '' ] testspacelist1 = [ '' , '' , '' ] FLAGS . testlist = list ( testlist1 ) FLAGS . testspacelist = list ( testspacelist1 ) argv = ( '' , FLAGS [ '' ] . Serialize ( ) , FLAGS [ '' ] . Serialize ( ) ) argv = FLAGS ( argv ) self . assertEqual ( FLAGS . testlist , testlist1 ) self . assertEqual ( FLAGS . testspacelist , testspacelist1 ) FLAGS . testlist = oldtestlist FLAGS . testspacelist = oldtestspacelist def ArgsString ( ) : flagnames = FLAGS . RegisteredFlags ( ) flagnames . sort ( ) nonbool_flags = [ '' % ( name , FLAGS . get ( name , None ) ) for name in flagnames if not isinstance ( FLAGS [ name ] , gflags . BooleanFlag ) ] truebool_flags = [ '' % ( name ) for name in flagnames if isinstance ( FLAGS [ name ] , gflags . BooleanFlag ) and FLAGS . get ( name , None ) ] falsebool_flags = [ '' % ( name ) for name in flagnames if isinstance ( FLAGS [ name ] , gflags . BooleanFlag ) and not FLAGS . get ( name , None ) ] return '' . join ( nonbool_flags + truebool_flags + falsebool_flags ) argv = ( '' , '' , '' , '' ) FLAGS ( argv ) self . assertEqual ( FLAGS . get ( '' , None ) , ) self . assertEqual ( FLAGS . get ( '' , None ) , '' ) self . assertEqual ( FLAGS . get ( '' , None ) , ) self . assertEqual ( ArgsString ( ) , \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" ) argv = ( '' , '' , '' , '' , '' ) FLAGS ( argv ) self . assertEqual ( FLAGS . get ( '' , None ) , ) self . assertEqual ( FLAGS . get ( '' , None ) , '' ) self . assertEqual ( FLAGS . get ( '' , None ) , ) self . assertEqual ( ArgsString ( ) , \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" \"\" ) try : gflags . DEFINE_boolean ( \"\" , , \"\" , short_name = '' ) raise AssertionError ( \"\" ) except gflags . DuplicateFlag , e : pass try : gflags . DEFINE_boolean ( \"\" , , \"\" , short_name = '' ) gflags . DEFINE_boolean ( \"\" , , \"\" , short_name = '' ) raise AssertionError ( \"\" ) except gflags . DuplicateFlag , e : self . assertTrue ( \"\" in e . args [ ] ) self . assertTrue ( \"\" in e . args [ ] ) self . assertTrue ( \"\" in e . args [ ] ) try : gflags . DEFINE_boolean ( \"\" , , \"\" , short_name = '' ) gflags . DEFINE_boolean ( \"\" , , \"\" ) raise AssertionError ( \"\" ) except gflags . DuplicateFlag , e : self . assertTrue ( \"\" in e . args [ ] ) self . assertTrue ( \"\" in e . args [ ] ) self . assertTrue ( \"\" in e . args [ ] ) flagnames = [ \"\" ] original_flags = gflags . FlagValues ( ) gflags . DEFINE_boolean ( flagnames [ ] , False , \"\" , flag_values = original_flags ) duplicate_flags = module_foo . DuplicateFlags ( flagnames ) try : original_flags . AppendFlagValues ( duplicate_flags ) except gflags . DuplicateFlagError , e : self . assertTrue ( \"\" in str ( e ) ) self . assertTrue ( \"\" in str ( e ) ) try : gflags . DEFINE_boolean ( \"\" , , \"\" , short_name = '' , allow_override = ) flag = FLAGS . FlagDict ( ) [ '' ] self . assertEqual ( flag . default , ) gflags . DEFINE_boolean ( \"\" , , \"\" , short_name = '' , allow_override = ) flag = FLAGS . FlagDict ( ) [ '' ] self . assertEqual ( flag . default , ) except gflags . DuplicateFlag , e : raise AssertionError ( \"\" ) try : gflags . DEFINE_boolean ( \"\" , , \"\" , short_name = '' , allow_override = ) flag = FLAGS . FlagDict ( ) [ '' ] self . assertEqual ( flag . default , ) gflags . DEFINE_boolean ( \"\" , , \"\" , short_name = '' , allow_override = ) flag = FLAGS . FlagDict ( ) [ '' ] self . assertEqual ( flag . default , ) except gflags . DuplicateFlag , e : raise AssertionError ( \"\" ) try : gflags . DEFINE_boolean ( \"\" , , \"\" , short_name = '' , ", "answer": "allow_override = )"}, {"prompt": " from django import forms from . models import Order , Item class OrderForm ( forms . ModelForm ) : class Meta : model = Order fields = [ '' ] def save ( self , commit = True ) : instance = super ( OrderForm , self ) . save ( commit = commit ) if commit : instance . action_on_save = True instance . save ( ) return instance class ItemForm ( forms . ModelForm ) : flag = forms . BooleanField ( initial = True ) class Meta : model = Item fields = [ '' , '' , '' , '' , '' ] class AddressForm ( forms . Form ) : name = forms . CharField ( max_length = , required = True ) line1 = forms . CharField ( max_length = , required = False ) line2 = forms . CharField ( max_length = , required = False ) city = forms . CharField ( max_length = , required = False ) postcode = forms . CharField ( max_length = , required = True ) def __init__ ( self , * args , ** kwargs ) : self . user = kwargs . pop ( '' ) ", "answer": "super ( AddressForm , self ) . __init__ ( * args , ** kwargs ) "}, {"prompt": " \"\"\"\"\"\" import posixpath from tornado import options from tornado . web import UIModule from viewfinder . backend . base import environ from viewfinder . backend . resources . resources_mgr import ResourcesManager from viewfinder . backend . www . basic_auth import BasicAuthHandler __author__ = '' class Header ( UIModule ) : \"\"\"\"\"\" def render ( self , ** settings ) : if isinstance ( self . handler , BasicAuthHandler ) : user = self . handler . get_current_user ( ) if user is not None : name = user else : name = None else : name = self . handler . _GetCurrentUserName ( ) return self . render_string ( '' , name = name , ** settings ) def javascript_files ( self ) : jsfiles = ResourcesManager . Instance ( ) . GetAssetPaths ( '' ) if environ . ServerEnvironment . IsDevBox ( ) : jsfiles . append ( '' ) return jsfiles def css_files ( self ) : ", "answer": "return ResourcesManager . Instance ( ) . GetAssetPaths ( '' )"}, {"prompt": " \"\"\"\"\"\" __author__ = '' import datetime import difflib import logging import pytz from django import test from django . core import exceptions as django_ex from services . common import misc , helpers as db_tools from services . configuration . models import tle as tle_models from services . leop import utils as launch_utils from services . leop . jrpc . serializers import launch as launch_serial from services . leop . jrpc . serializers import messages as messages_serial from services . leop . jrpc . views import launch as launch_jrpc from services . leop . jrpc . views import messages as messages_jrpc from services . leop . models import launch as launch_models from services . simulation . models import groundtracks as simulation_models from website import settings as satnet_settings class TestLaunchViews ( test . TestCase ) : \"\"\"\"\"\" def setUp ( self ) : \"\"\"\"\"\" self . __verbose_testing = False satnet_settings . JRPC_PERMISSIONS = True self . __user = db_tools . create_user_profile ( ) self . __request_1 = db_tools . create_request ( user_profile = self . __user ) self . __gs_1_id = '' self . __gs_1 = db_tools . create_gs ( user_profile = self . __user , identifier = self . __gs_1_id ) self . __gs_2_id = '' self . __gs_2 = db_tools . create_gs ( user_profile = self . __user , identifier = self . __gs_2_id ) self . __admin = db_tools . create_user_profile ( username = '' , email = '' , is_staff = True ) self . __request_2 = db_tools . create_request ( user_profile = self . __admin ) self . __leop_tle_l1 = db_tools . ISS_TLE [ ] self . __leop_tle_l2 = db_tools . ISS_TLE [ ] self . __leop_id = '' self . __leop_date = pytz . utc . localize ( datetime . datetime . today ( ) ) self . __leop = db_tools . create_launch ( admin = self . __admin , identifier = self . __leop_id , date = self . __leop_date , tle_l1 = self . __leop_tle_l1 , tle_l2 = self . __leop_tle_l2 ) self . __leop_serial_date = str ( self . __leop . date . isoformat ( ) ) self . __leop_cs = launch_utils . generate_cluster_callsign ( self . __leop_id ) self . __leop_sc_id = launch_utils . generate_cluster_sc_identifier ( self . __leop_id , self . __leop_cs ) self . __ufo_id = self . __ufo_sc_id = launch_utils . generate_object_sc_identifier ( self . __leop_id , self . __ufo_id ) self . __ufo_callsign = '' self . __ufo_tle_l1 = self . __leop_tle_l1 self . __ufo_tle_l2 = self . __leop_tle_l2 self . __leop_2_tle_l1 = db_tools . TIANGONG_TLE [ ] self . __leop_2_tle_l2 = db_tools . TIANGONG_TLE [ ] if not self . __verbose_testing : logging . getLogger ( '' ) . setLevel ( level = logging . CRITICAL ) logging . getLogger ( '' ) . setLevel ( level = logging . CRITICAL ) def test_list_groundstations ( self ) : \"\"\"\"\"\" try : launch_jrpc . list_groundstations ( '' , ** { '' : None } ) self . fail ( '' ) except django_ex . PermissionDenied : pass try : launch_jrpc . list_groundstations ( self . __leop_id , ** { '' : self . __request_1 } ) self . fail ( '' ) except django_ex . PermissionDenied : pass e_gs = { launch_serial . JRPC_K_AVAILABLE_GS : [ self . __gs_1_id , self . __gs_2_id ] , launch_serial . JRPC_K_IN_USE_GS : [ ] } try : a_gs = launch_jrpc . list_groundstations ( self . __leop_id , ** { '' : self . __request_2 } ) self . assertEqual ( a_gs , e_gs ) except django_ex . PermissionDenied : self . fail ( '' ) launch_jrpc . add_groundstations ( self . __leop_id , groundstations = [ self . __gs_1_id ] , ** { '' : self . __request_2 } ) e_gs = { launch_serial . JRPC_K_AVAILABLE_GS : [ self . __gs_2_id ] , launch_serial . JRPC_K_IN_USE_GS : [ self . __gs_1_id ] } a_gs = launch_jrpc . list_groundstations ( self . __leop_id , ** { '' : self . __request_2 } ) self . assertEqual ( a_gs , e_gs ) def test_add_groundstations ( self ) : \"\"\"\"\"\" try : launch_jrpc . add_groundstations ( '' , None , ** { '' : None } ) self . fail ( '' ) except django_ex . PermissionDenied : pass try : launch_jrpc . add_groundstations ( '' , None , ** { '' : self . __request_1 } ) self . fail ( '' ) except django_ex . PermissionDenied : pass try : launch_jrpc . add_groundstations ( '' , [ '' ] , ** { '' : self . __request_2 } ) self . fail ( '' ) except launch_models . Launch . DoesNotExist : pass self . assertRaises ( Exception , launch_jrpc . add_groundstations , None , ** { '' : self . __request_2 } ) gss = [ self . __gs_1_id , self . __gs_2_id ] actual = launch_jrpc . add_groundstations ( self . __leop_id , gss , ** { '' : self . __request_2 } ) expected = { launch_serial . JRPC_K_LEOP_ID : self . __leop_id } self . assertEqual ( actual , expected ) cluster = launch_models . Launch . objects . get ( identifier = self . __leop_id ) self . assertEqual ( len ( cluster . groundstations . all ( ) ) , , '' ) def test_remove_groundstations ( self ) : \"\"\"\"\"\" self . assertRaises ( django_ex . PermissionDenied , launch_jrpc . remove_groundstations , '' , None , ** { '' : None } ) self . assertRaises ( django_ex . PermissionDenied , launch_jrpc . remove_groundstations , '' , None , ** { '' : self . __request_1 } ) self . assertRaises ( launch_models . Launch . DoesNotExist , launch_jrpc . remove_groundstations , '' , [ '' ] , ** { '' : self . __request_2 } ) actual = launch_jrpc . remove_groundstations ( self . __leop_id , None , ** { '' : self . __request_2 } ) expected = { launch_serial . JRPC_K_LEOP_ID : self . __leop_id } self . assertEqual ( actual , expected ) actual = launch_jrpc . remove_groundstations ( self . __leop_id , [ ] , ** { '' : self . __request_2 } ) expected = { launch_serial . JRPC_K_LEOP_ID : self . __leop_id } self . assertEqual ( actual , expected ) gss = [ self . __gs_1_id , self . __gs_2_id ] launch_jrpc . add_groundstations ( self . __leop_id , gss , ** { '' : self . __request_2 } ) cluster = launch_models . Launch . objects . get ( identifier = self . __leop_id ) self . assertEqual ( len ( cluster . groundstations . all ( ) ) , , '' ) self . assertTrue ( launch_jrpc . remove_groundstations ( self . __leop_id , gss , ** { '' : self . __request_2 } ) , '' ) self . assertEqual ( len ( cluster . groundstations . all ( ) ) , , '' ) def test_add_unknown ( self ) : \"\"\"\"\"\" self . assertRaises ( Exception , launch_jrpc . add_unknown , self . __leop_id , None ) self . assertRaises ( ", "answer": "Exception , launch_jrpc . add_unknown , self . __leop_id , - "}, {"prompt": " def alphabet_to_number ( word ) : alphabet = '' number = '' array_alphabet = list ( alphabet ) array_number = number . split ( '' ) converted_word = [ ] for letter in word : for n in range ( , len ( array_number ) , ) : if letter == array_alphabet [ n ] : converted_word . append ( array_number [ n ] ) converted_word . append ( '' ) del converted_word [ - ] return '' . join ( converted_word ) def number_to_alphabet ( numbers ) : alphabet = '' number = '' array_number = number . split ( '' ) array_alphabet = list ( alphabet ) numbers = numbers . split ( '' ) converted_numbers = [ ] for num in numbers : for n in range ( , len ( array_alphabet ) , ) : if int ( num ) > : ", "answer": "num = str ( int ( num ) - )"}, {"prompt": " from django . contrib import admin from cms_redirects . models import CMSRedirect class CMSRedirectAdmin ( admin . ModelAdmin ) : list_display = ( '' , '' , '' , '' , '' , '' , ) list_filter = ( '' , ) search_fields = ( '' , '' , '' ) radio_fields = { '' : admin . VERTICAL } fieldsets = [ ( '' , { \"\" : ( '' , '' , ) } ) , ( '' , { \"\" : ( '' , '' , '' , ) } ) , ] ", "answer": "admin . site . register ( CMSRedirect , CMSRedirectAdmin ) "}, {"prompt": " from django . views . generic import ListView from . models import Sponsor class SponsorList ( ListView ) : model = Sponsor ", "answer": "template_name = ''"}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import from . base import ( alias , Enumeration , EnumMember , ReturnValueOnlyEnumMember , XmlEnumeration , XmlMappedEnumMember ) class XL_CHART_TYPE ( Enumeration ) : \"\"\"\"\"\" __ms_name__ = '' __url__ = ( '' ) __members__ = ( EnumMember ( '' , - , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , - , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , - , '' ) , EnumMember ( '' , - , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , - , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , - , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , - , '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' '' ) , EnumMember ( '' , , '' ) , EnumMember ( '' , , '' '' ) , ) @ alias ( '' ) class XL_DATA_LABEL_POSITION ( XmlEnumeration ) : \"\"\"\"\"\" __ms_name__ = '' __url__ = ( '' ) __members__ = ( XmlMappedEnumMember ( '' , , '' , '' ", "answer": "''"}, {"prompt": " import sys from twisted . python import modules modules . theSystemPath = modules . PythonPath ( [ ] , moduleDict = { } ) from twisted . internet import gireactor for name in gireactor . _PYGTK_MODULES : ", "answer": "if sys . modules [ name ] is not None :"}, {"prompt": " \"\"\"\"\"\" from __future__ import print_function , division from sympy import Mul from sympy . core . compatibility import u , range from sympy . external import import_module from sympy . physics . quantum . gate import Gate , OneQubitGate , CGate , CGateS from sympy . core . core import BasicMeta from sympy . core . assumptions import ManagedProperties __all__ = [ '' , '' , '' , '' , '' , '' , '' , ] np = import_module ( '' ) matplotlib = import_module ( '' , __import__kwargs = { '' : [ '' ] } , catch = ( RuntimeError , ) ) if not np or not matplotlib : class CircuitPlot ( object ) : def __init__ ( * args , ** kwargs ) : raise ImportError ( '' ) def circuit_plot ( * args , ** kwargs ) : raise ImportError ( '' ) else : pyplot = matplotlib . pyplot Line2D = matplotlib . lines . Line2D Circle = matplotlib . patches . Circle class CircuitPlot ( object ) : \"\"\"\"\"\" scale = fontsize = linewidth = control_radius = not_radius = swap_delta = labels = [ ] inits = { } label_buffer = def __init__ ( self , c , nqubits , ** kwargs ) : self . circuit = c self . ngates = len ( self . circuit . args ) self . nqubits = nqubits self . update ( kwargs ) self . _create_grid ( ) self . _create_figure ( ) self . _plot_wires ( ) self . _plot_gates ( ) self . _finish ( ) def update ( self , kwargs ) : \"\"\"\"\"\" self . __dict__ . update ( kwargs ) def _create_grid ( self ) : \"\"\"\"\"\" scale = self . scale wire_grid = np . arange ( , self . nqubits * scale , scale , dtype = float ) gate_grid = np . arange ( , self . ngates * scale , scale , dtype = float ) self . _wire_grid = wire_grid self . _gate_grid = gate_grid def _create_figure ( self ) : \"\"\"\"\"\" self . _figure = pyplot . figure ( figsize = ( self . ngates * self . scale , self . nqubits * self . scale ) , facecolor = '' , edgecolor = '' ) ax = self . _figure . add_subplot ( , , , frameon = True ) ax . set_axis_off ( ) offset = * self . scale ax . set_xlim ( self . _gate_grid [ ] - offset , self . _gate_grid [ - ] + offset ) ax . set_ylim ( self . _wire_grid [ ] - offset , self . _wire_grid [ - ] + offset ) ax . set_aspect ( '' ) self . _axes = ax def _plot_wires ( self ) : \"\"\"\"\"\" xstart = self . _gate_grid [ ] xstop = self . _gate_grid [ - ] xdata = ( xstart - self . scale , xstop + self . scale ) for i in range ( self . nqubits ) : ydata = ( self . _wire_grid [ i ] , self . _wire_grid [ i ] ) line = Line2D ( xdata , ydata , color = '' , lw = self . linewidth ) self . _axes . add_line ( line ) if self . labels : init_label_buffer = if self . inits . get ( self . labels [ i ] ) : init_label_buffer = self . _axes . text ( xdata [ ] - self . label_buffer - init_label_buffer , ydata [ ] , render_label ( self . labels [ i ] , self . inits ) , size = self . fontsize , color = '' , ha = '' , va = '' ) self . _plot_measured_wires ( ) def _plot_measured_wires ( self ) : ismeasured = self . _measurements ( ) xstop = self . _gate_grid [ - ] dy = for im in ismeasured : xdata = ( self . _gate_grid [ ismeasured [ im ] ] , xstop + self . scale ) ydata = ( self . _wire_grid [ im ] + dy , self . _wire_grid [ im ] + dy ) line = Line2D ( xdata , ydata , color = '' , lw = self . linewidth ) ", "answer": "self . _axes . add_line ( line )"}, {"prompt": " \"\"\"\"\"\" from protorpc import messages from protorpc import remote from . import model from . import utils __all__ = [ '' , '' ] _protocols_registry = remote . Protocols . new_default ( ) _default_protocol = '' ", "answer": "class EnumProperty ( model . IntegerProperty ) :"}, {"prompt": " from twisted . trial import unittest from twisted . internet import tcp , protocol from nacl . signing import SigningKey from nacl . exceptions import CryptoError from . . import util , errors class Utils ( unittest . TestCase ) : def test_split_into ( self ) : self . failUnlessEqual ( util . split_into ( \"\" , [ , , ] ) , [ \"\" , \"\" , \"\" ] ) self . failUnlessEqual ( util . split_into ( \"\" , [ , ] , True ) , [ \"\" , \"\" , \"\" ] ) self . failUnlessRaises ( ValueError , util . split_into , \"\" , [ , ] , False ) self . failUnlessRaises ( ValueError , util . split_into , \"\" , [ , ] ) def test_ascii ( self ) : b2a = util . to_ascii a2b = util . from_ascii for prefix in ( \"\" , \"\" ) : for length in range ( , ) : b1 = \"\" * length for base in ( \"\" , \"\" , \"\" , \"\" ) : a = b2a ( b1 , prefix , base ) b2 = a2b ( a , prefix , base ) self . failUnlessEqual ( b1 , b2 ) self . failUnlessRaises ( NotImplementedError , b2a , \"\" , encoding = \"\" ) self . failUnlessRaises ( NotImplementedError , a2b , \"\" , encoding = \"\" ) def test_nonce ( self ) : n1 = util . make_nonce ( ) self . failUnlessEqual ( len ( n1 ) , ) n2 = util . make_nonce ( ) self . failIfEqual ( n1 , n2 ) def test_equal ( self ) : self . failUnless ( util . equal ( \"\" , \"\" ) ) self . failIf ( util . equal ( \"\" , \"\" ) ) def test_x_or_none ( self ) : self . failUnlessEqual ( util . hex_or_none ( None ) , None ) self . failUnlessEqual ( util . hex_or_none ( \"\" ) , \"\" ) self . failUnlessEqual ( util . unhex_or_none ( None ) , None ) self . failUnlessEqual ( util . unhex_or_none ( \"\" ) , \"\" ) def test_remove_prefix ( self ) : self . failUnlessEqual ( util . remove_prefix ( \"\" , \"\" ) , \"\" ) x = self . failUnlessRaises ( util . BadPrefixError , util . remove_prefix , \"\" , \"\" ) self . failUnlessEqual ( str ( x ) , \"\" ) x = self . failUnlessRaises ( ValueError , util . remove_prefix , \"\" , \"\" , ValueError ) self . failUnlessEqual ( str ( x ) , \"\" ) class Signatures ( unittest . TestCase ) : def test_verify_with_prefix ( self ) : sk = SigningKey . generate ( ) vk = sk . verify_key m = \"\" prefix = \"\" ", "answer": "sk2 = SigningKey . generate ( )"}, {"prompt": " from jinja2 import Environment , FileSystemLoader import requests import json import os import next . broker . broker from next . api . resource_manager import ResourceManager from next . api . targetmapper import TargetMapper TEMPLATES_DIRECTORY = os . path . dirname ( __file__ ) loader = FileSystemLoader ( TEMPLATES_DIRECTORY ) env = Environment ( loader = loader ) resource_manager = ResourceManager ( ) broker = next . broker . broker . JobBroker ( ) targetmapper = TargetMapper ( ) class WidgetGenerator ( ) : def getQuery ( self , args ) : \"\"\"\"\"\" exp_uid = args [ \"\" ] app_id = args [ \"\" ] if '' in args [ '' ] . keys ( ) : args [ '' ] [ '' ] = exp_uid + \"\" + args [ '' ] [ '' ] args_json = json . dumps ( args [ \"\" ] ) response_json , didSucceed , message = broker . applyAsync ( app_id , exp_uid , \"\" , args_json ) response_dict = json . loads ( response_json ) for target_index in response_dict [ \"\" ] : target_index [ '' ] = targetmapper . get_target_data ( exp_uid , target_index [ \"\" ] ) ", "answer": "query = { }"}, {"prompt": " import os import sys here = sys . path [ ] sys . path . insert ( , os . path . join ( here , '' ) ) import logging import logging . handlers import threading import time import pytest import testUtils as utils import snoopyDispatcher as snoopyDis from coap import coap , coapDefines as d , coapResource log = logging . getLogger ( '' ) log . addHandler ( utils . NullHandler ( ) ) LOG_MODULES = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , ] IPADDRESS1 = '' IPADDRESS2 = '' RESOURCE = '' DUMMYVAL = [ , , ] def getTestModuleName ( request ) : return request . module . __name__ . split ( '' ) [ - ] def getTestFunctionName ( request ) : return request . function . __name__ . split ( '' ) [ - ] def loggingSetup ( request ) : moduleName = getTestModuleName ( request ) logHandler = logging . handlers . RotatingFileHandler ( filename = '' . format ( moduleName ) , mode = '' , backupCount = , ) logHandler . setFormatter ( logging . Formatter ( '' ) ) for loggerName in [ moduleName ] + LOG_MODULES : temp = logging . getLogger ( loggerName ) temp . setLevel ( logging . DEBUG ) temp . addHandler ( logHandler ) log . debug ( \"\" ) def loggingTeardown ( request ) : moduleName = getTestModuleName ( request ) output = [ ] output += [ '' ] for t in threading . enumerate ( ) : output += [ '' . format ( t . name ) ] output = '' . join ( output ) log . debug ( output ) log . debug ( \"\" ) for loggerName in [ moduleName ] + LOG_MODULES : temp = logging . getLogger ( loggerName ) temp . handler = [ ] @ pytest . fixture ( scope = '' ) def logFixtureModule ( request ) : loggingSetup ( request ) f = lambda : loggingTeardown ( request ) request . addfinalizer ( f ) @ pytest . fixture ( scope = '' ) def logFixture ( logFixtureModule , request ) : log . debug ( '' . format ( getTestFunctionName ( request ) ) ) return logFixtureModule def snoppyTeardown ( snoppy ) : snoppy . close ( ) @ pytest . fixture ( scope = '' ) def snoopyDispatcher ( request ) : moduleName = getTestModuleName ( request ) snoopy = snoopyDis . snoopyDispatcher ( '' . format ( moduleName ) ) f = lambda : snoppyTeardown ( snoopy ) request . addfinalizer ( f ) class dummyResource ( coapResource . coapResource ) : def __init__ ( self ) : ", "answer": "coapResource . coapResource . __init__ ("}, {"prompt": " from os . path import dirname , join from setuptools import setup , find_packages with open ( join ( dirname ( __file__ ) , '' ) , '' ) as f : version = f . read ( ) . decode ( '' ) . strip ( ) setup ( name = '' , version = version , url = '' , description = '' , long_description = open ( '' ) . read ( ) , author = '' , maintainer = '' , maintainer_email = '' , license = '' , packages = find_packages ( exclude = ( '' , '' ) ) , include_package_data = True , zip_safe = False , entry_points = { '' : [ '' ] } , classifiers = [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , ", "answer": "'' ,"}, {"prompt": " \"\"\"\"\"\" from __future__ import absolute_import from . . import util , exc from . base import _registrars from . registry import _EventKey CANCEL = util . symbol ( '' ) NO_RETVAL = util . symbol ( '' ) ", "answer": "def _event_key ( target , identifier , fn ) :"}, {"prompt": " from datetime import datetime from django . core . files import storage class DummyStorage ( storage . Storage ) : \"\"\"\"\"\" def _save ( self , name , content ) : ", "answer": "return ''"}, {"prompt": " from ztag . annotation import * import re class Helix ( Annotation ) : protocol = protocols . HTTP subprotocol = protocols . HTTP . GET port = None version_re = re . compile ( \"\" , re . IGNORECASE ", "answer": ")"}, {"prompt": " import codecs from scrapy . exceptions import NotConfigured from frontera . contrib . scrapy . middlewares . seeds import SeedLoader class FileSeedLoader ( SeedLoader ) : def configure ( self , settings ) : self . seeds_source = settings . get ( '' ) if not self . seeds_source : raise NotConfigured ", "answer": "def load_seeds ( self ) :"}, {"prompt": " \"\"\"\"\"\" import Tkinter , tkFileDialog , tkMessageBox from twisted . conch import error from twisted . conch . ui import tkvt100 from twisted . conch . ssh import transport , userauth , connection , common , keys from twisted . conch . ssh import session , forwarding , channel from twisted . conch . client . default import isInKnownHosts from twisted . internet import reactor , defer , protocol , tksupport from twisted . python import usage , log import os , sys , getpass , struct , base64 , signal class TkConchMenu ( Tkinter . Frame ) : def __init__ ( self , * args , ** params ) : apply ( Tkinter . Frame . __init__ , ( self , ) + args , params ) self . master . title ( '' ) self . localRemoteVar = Tkinter . StringVar ( ) self . localRemoteVar . set ( '' ) Tkinter . Label ( self , anchor = '' , justify = '' , text = '' ) . grid ( column = , row = , sticky = '' ) self . host = Tkinter . Entry ( self ) self . host . grid ( column = , columnspan = , row = , sticky = '' ) Tkinter . Label ( self , anchor = '' , justify = '' , text = '' ) . grid ( column = , row = , sticky = '' ) self . port = Tkinter . Entry ( self ) self . port . grid ( column = , columnspan = , row = , sticky = '' ) Tkinter . Label ( self , anchor = '' , justify = '' , text = '' ) . grid ( column = , row = , sticky = '' ) self . user = Tkinter . Entry ( self ) self . user . grid ( column = , columnspan = , row = , sticky = '' ) Tkinter . Label ( self , anchor = '' , justify = '' , text = '' ) . grid ( column = , row = , sticky = '' ) self . command = Tkinter . Entry ( self ) self . command . grid ( column = , columnspan = , row = , sticky = '' ) Tkinter . Label ( self , anchor = '' , justify = '' , text = '' ) . grid ( column = , row = , sticky = '' ) self . identity = Tkinter . Entry ( self ) self . identity . grid ( column = , row = , sticky = '' ) Tkinter . Button ( self , command = self . getIdentityFile , text = '' ) . grid ( column = , row = , sticky = '' ) Tkinter . Label ( self , text = '' ) . grid ( column = , row = , sticky = '' ) self . forwards = Tkinter . Listbox ( self , height = , width = ) self . forwards . grid ( column = , columnspan = , row = , sticky = '' ) Tkinter . Button ( self , text = '' , command = self . addForward ) . grid ( column = , row = ) Tkinter . Button ( self , text = '' , command = self . removeForward ) . grid ( column = , row = ) self . forwardPort = Tkinter . Entry ( self ) self . forwardPort . grid ( column = , row = , sticky = '' ) Tkinter . Label ( self , text = '' ) . grid ( column = , row = , sticky = '' ) self . forwardHost = Tkinter . Entry ( self ) self . forwardHost . grid ( column = , row = , sticky = '' ) Tkinter . Label ( self , text = '' ) . grid ( column = , row = , sticky = '' ) self . localForward = Tkinter . Radiobutton ( self , text = '' , variable = self . localRemoteVar , value = '' ) self . localForward . grid ( column = , row = ) self . remoteForward = Tkinter . Radiobutton ( self , text = '' , variable = self . localRemoteVar , value = '' ) self . remoteForward . grid ( column = , row = ) Tkinter . Label ( self , text = '' ) . grid ( column = , columnspan = , row = , sticky = '' ) Tkinter . Label ( self , anchor = '' , justify = '' , text = '' ) . grid ( column = , row = , sticky = '' ) self . cipher = Tkinter . Entry ( self , name = '' ) self . cipher . grid ( column = , columnspan = , row = , sticky = '' ) Tkinter . Label ( self , anchor = '' , justify = '' , text = '' ) . grid ( column = , row = , sticky = '' ) self . mac = Tkinter . Entry ( self , name = '' ) self . mac . grid ( column = , columnspan = , row = , sticky = '' ) Tkinter . Label ( self , anchor = '' , justify = '' , text = '' ) . grid ( column = , row = , sticky = '' ) self . escape = Tkinter . Entry ( self , name = '' ) self . escape . grid ( column = , columnspan = , row = , sticky = '' ) Tkinter . Button ( self , text = '' , command = self . doConnect ) . grid ( column = , columnspan = , row = , sticky = '' ) self . grid_rowconfigure ( , weight = , minsize = ) self . grid_columnconfigure ( , weight = , minsize = ) self . master . protocol ( \"\" , sys . exit ) def getIdentityFile ( self ) : r = tkFileDialog . askopenfilename ( ) if r : self . identity . delete ( , Tkinter . END ) self . identity . insert ( Tkinter . END , r ) def addForward ( self ) : port = self . forwardPort . get ( ) self . forwardPort . delete ( , Tkinter . END ) host = self . forwardHost . get ( ) self . forwardHost . delete ( , Tkinter . END ) if self . localRemoteVar . get ( ) == '' : self . forwards . insert ( Tkinter . END , '' % ( port , host ) ) else : self . forwards . insert ( Tkinter . END , '' % ( port , host ) ) def removeForward ( self ) : cur = self . forwards . curselection ( ) if cur : self . forwards . remove ( cur [ ] ) def doConnect ( self ) : finished = options [ '' ] = self . host . get ( ) options [ '' ] = self . port . get ( ) options [ '' ] = self . user . get ( ) options [ '' ] = self . command . get ( ) cipher = self . cipher . get ( ) mac = self . mac . get ( ) escape = self . escape . get ( ) if cipher : if cipher in SSHClientTransport . supportedCiphers : SSHClientTransport . supportedCiphers = [ cipher ] else : tkMessageBox . showerror ( '' , '' ) finished = if mac : if mac in SSHClientTransport . supportedMACs : SSHClientTransport . supportedMACs = [ mac ] elif finished : tkMessageBox . showerror ( '' , '' ) finished = if escape : if escape == '' : options [ '' ] = None elif escape [ ] == '' and len ( escape ) == : options [ '' ] = chr ( ord ( escape [ ] ) - ) elif len ( escape ) == : options [ '' ] = escape elif finished : tkMessageBox . showerror ( '' , \"\" % escape ) finished = if self . identity . get ( ) : options . identitys . append ( self . identity . get ( ) ) for line in self . forwards . get ( , Tkinter . END ) : if line [ ] == '' : options . opt_localforward ( line [ : ] ) else : options . opt_remoteforward ( line [ : ] ) if '' in options [ '' ] : options [ '' ] , options [ '' ] = options [ '' ] . split ( '' , ) if ( not options [ '' ] or not options [ '' ] ) and finished : tkMessageBox . showerror ( '' , '' ) finished = if finished : self . master . quit ( ) self . master . destroy ( ) if options [ '' ] : realout = sys . stdout log . startLogging ( sys . stderr ) sys . stdout = realout else : log . discardLogs ( ) log . deferr = handleError if not options . identitys : options . identitys = [ '' , '' ] host = options [ '' ] port = int ( options [ '' ] or ) log . msg ( ( host , port ) ) reactor . connectTCP ( host , port , SSHClientFactory ( ) ) frame . master . deiconify ( ) frame . master . title ( '' % ( options [ '' ] , options [ '' ] ) ) else : self . focus ( ) class GeneralOptions ( usage . Options ) : synopsis = \"\"\"\"\"\" optParameters = [ [ '' , '' , None , '' ] , [ '' , '' , '' , '' ] , [ '' , '' , '' , \"\" ] , [ '' , '' , None , '' ] , [ '' , '' , None , '' ] , [ '' , '' , None , '' ] , [ '' , '' , None , '' ] , [ '' , '' , None , '' ] , ] optFlags = [ [ '' , '' , '' ] , [ '' , '' , '' ] , [ '' , '' , '' ] , [ '' , '' , '' ] , [ '' , '' , '' ] , [ '' , '' , '' ] , [ '' , '' , '' ] , [ '' , '' , '' ] ] _ciphers = transport . SSHClientTransport . supportedCiphers _macs = transport . SSHClientTransport . supportedMACs compData = usage . Completions ( mutuallyExclusive = [ ( \"\" , \"\" ) ] , optActions = { \"\" : usage . CompleteList ( _ciphers ) , \"\" : usage . CompleteList ( _macs ) , \"\" : usage . Completer ( descr = \"\" ) , \"\" : usage . Completer ( descr = \"\" ) } , extraActions = [ usage . CompleteUserAtHost ( ) , usage . Completer ( descr = \"\" ) , usage . Completer ( descr = \"\" , repeat = True ) ] ) identitys = [ ] localForwards = [ ] remoteForwards = [ ] def opt_identity ( self , i ) : self . identitys . append ( i ) def opt_localforward ( self , f ) : localPort , remoteHost , remotePort = f . split ( '' ) localPort = int ( localPort ) remotePort = int ( remotePort ) self . localForwards . append ( ( localPort , ( remoteHost , remotePort ) ) ) def opt_remoteforward ( self , f ) : remotePort , connHost , connPort = f . split ( '' ) remotePort = int ( remotePort ) connPort = int ( connPort ) self . remoteForwards . append ( ( remotePort , ( connHost , connPort ) ) ) def opt_compress ( self ) : SSHClientTransport . supportedCompressions [ : ] = [ '' ] def parseArgs ( self , * args ) : if args : self [ '' ] = args [ ] self [ '' ] = '' . join ( args [ : ] ) else : self [ '' ] = '' self [ '' ] = '' options = None menu = None exitStatus = frame = None def deferredAskFrame ( question , echo ) : if frame . callback : raise ValueError ( \"\" ) d = defer . Deferred ( ) resp = [ ] def gotChar ( ch , resp = resp ) : if not ch : return if ch == '' : reactor . stop ( ) if ch == '' : frame . write ( '' ) stresp = '' . join ( resp ) del resp frame . callback = None d . callback ( stresp ) return elif <= ord ( ch ) < : resp . append ( ch ) if echo : frame . write ( ch ) elif ord ( ch ) == and resp : if echo : frame . write ( '' ) resp . pop ( ) frame . callback = gotChar frame . write ( question ) frame . canvas . focus_force ( ) return d def run ( ) : global menu , options , frame args = sys . argv [ : ] if '' in args : i = args . index ( '' ) args = args [ i : i + ] + args del args [ i + : i + ] for arg in args [ : ] : try : i = args . index ( arg ) if arg [ : ] == '' and args [ i + ] [ ] != '' : args [ i : i + ] = [ ] except ValueError : pass root = Tkinter . Tk ( ) root . withdraw ( ) top = Tkinter . Toplevel ( ) menu = TkConchMenu ( top ) menu . pack ( side = Tkinter . TOP , fill = Tkinter . BOTH , expand = ) options = GeneralOptions ( ) try : options . parseOptions ( args ) except usage . UsageError , u : print '' % u options . opt_help ( ) sys . exit ( ) for k , v in options . items ( ) : if v and hasattr ( menu , k ) : getattr ( menu , k ) . insert ( Tkinter . END , v ) for ( p , ( rh , rp ) ) in options . localForwards : menu . forwards . insert ( Tkinter . END , '' % ( p , rh , rp ) ) options . localForwards = [ ] for ( p , ( rh , rp ) ) in options . remoteForwards : menu . forwards . insert ( Tkinter . END , '' % ( p , rh , rp ) ) options . remoteForwards = [ ] frame = tkvt100 . VT100Frame ( root , callback = None ) root . geometry ( '' % ( tkvt100 . fontWidth * frame . width + , tkvt100 . fontHeight * frame . height + ) ) frame . pack ( side = Tkinter . TOP ) tksupport . install ( root ) root . withdraw ( ) if ( options [ '' ] and options [ '' ] ) or '' in options [ '' ] : menu . doConnect ( ) else : top . mainloop ( ) reactor . run ( ) sys . exit ( exitStatus ) def handleError ( ) : from twisted . python import failure global exitStatus exitStatus = log . err ( failure . Failure ( ) ) reactor . stop ( ) raise class SSHClientFactory ( protocol . ClientFactory ) : noisy = def stopFactory ( self ) : reactor . stop ( ) def buildProtocol ( self , addr ) : return SSHClientTransport ( ) def clientConnectionFailed ( self , connector , reason ) : tkMessageBox . showwarning ( '' , '' % ( reason . type , reason . value ) ) class SSHClientTransport ( transport . SSHClientTransport ) : def receiveError ( self , code , desc ) : global exitStatus exitStatus = '' % ( code , desc ) ", "answer": "def sendDisconnect ( self , code , reason ) :"}, {"prompt": " from django . contrib import admin from services . cord . models import * from django import forms from django . utils . safestring import mark_safe from django . contrib . auth . admin import UserAdmin from django . contrib . admin . widgets import FilteredSelectMultiple from django . contrib . auth . forms import ReadOnlyPasswordHashField from django . contrib . auth . signals import user_logged_in from django . utils import timezone from django . contrib . contenttypes import generic from suit . widgets import LinkedSelect from core . admin import ServiceAppAdmin , SliceInline , ServiceAttrAsTabInline , ReadOnlyAwareAdmin , XOSTabularInline , ServicePrivilegeInline , TenantRootTenantInline , TenantRootPrivilegeInline from core . middleware import get_request from services . vtn . models import * from services . cord . models import CordSubscriberRoot from functools import update_wrapper from django . contrib . admin . views . main import ChangeList from django . core . urlresolvers import reverse from django . contrib . admin . utils import quote class VTNServiceForm ( forms . ModelForm ) : privateGatewayMac = forms . CharField ( required = False ) localManagementIp = forms . CharField ( required = False ) ovsdbPort = forms . CharField ( required = False ) ", "answer": "sshPort = forms . CharField ( required = False )"}, {"prompt": " try : from pkg_resources import resource_string except ImportError : resource_string = None from django . template import TemplateDoesNotExist from django . conf import settings def load_template_source ( template_name , template_dirs = None ) : \"\"\"\"\"\" if resource_string is not None : pkg_name = '' + template_name ", "answer": "for app in settings . INSTALLED_APPS :"}, {"prompt": " from SimpleCV import * import time \"\"\"\"\"\" def identifyGender ( ) : f = FaceRecognizer ( ) cam = Camera ( ) img = cam . getImage ( ) cascade = LAUNCH_PATH + \"\" + \"\" feat = img . findHaarFeatures ( cascade ) if feat : crop_image = feat . sortArea ( ) [ - ] . crop ( ) feat . sortArea ( ) [ - ] . draw ( ) f . load ( LAUNCH_PATH + \"\" + \"\" ) w , h = f . imageSize crop_image = crop_image . resize ( w , h ) label , confidence = f . predict ( crop_image ) ", "answer": "print label"}, {"prompt": " \"\"\"\"\"\" import sys if sys . platform . startswith ( '' ) : import ctypes from ctypes import windll from ctypes . wintypes import ( BOOL , DOUBLE , DWORD , HBITMAP , HDC , HGDIOBJ , HWND , INT , LPARAM , LONG , UINT , WORD ) SRCCOPY = DIB_RGB_COLORS = BI_RGB = class RECT ( ctypes . Structure ) : _fields_ = [ ( '' , ctypes . c_long ) , ( '' , ctypes . c_long ) , ( '' , ctypes . c_long ) , ( '' , ctypes . c_long ) ] class BITMAPINFOHEADER ( ctypes . Structure ) : _fields_ = [ ( '' , DWORD ) , ( '' , LONG ) , ( '' , LONG ) , ( '' , WORD ) , ( '' , WORD ) , ( '' , DWORD ) , ( '' , DWORD ) , ( '' , LONG ) , ( '' , LONG ) , ( '' , DWORD ) , ( '' , DWORD ) ] class BITMAPINFO ( ctypes . Structure ) : ", "answer": "_fields_ = [ ( '' , BITMAPINFOHEADER ) , ( '' , DWORD * ) ]"}, {"prompt": " \"\"\"\"\"\" import re import string import hmac from math import log from random import randrange , choice from hashlib import sha1 , md5 from itertools import chain from datetime import datetime from sqlalchemy import select from sqlalchemy . orm import relation , backref , synonym , Query , dynamic_loader , synonym , eagerload from sqlalchemy . orm . interfaces import AttributeExtension from sqlalchemy . ext . associationproxy import association_proxy from werkzeug import escape , ImmutableList , ImmutableDict , cached_property from babel import Locale from solace import settings from solace . database import atomic_add , mapper from solace . utils . formatting import format_creole from solace . utils . remoting import RemoteObject from solace . database import session from solace . schema import users , topics , posts , votes , comments , post_revisions , tags , topic_tags , user_activities , user_badges , user_messages , openid_user_mapping _paragraph_re = re . compile ( r'' ) _key_chars = unicode ( string . letters + string . digits ) def random_key ( length ) : \"\"\"\"\"\" return u'' . join ( choice ( _key_chars ) for x in xrange ( length ) ) def random_password ( length = ) : \"\"\"\"\"\" consonants = '' vowels = '' return u'' . join ( [ choice ( consonants ) + choice ( vowels ) + choice ( consonants + vowels ) for _ in xrange ( length // + ) ] ) [ : length ] def simple_repr ( f ) : \"\"\"\"\"\" def __repr__ ( self ) : try : val = f ( self ) if isinstance ( val , unicode ) : val = val . encode ( '' ) except Exception : val = '' return '' % ( type ( self ) . __name__ , val ) return __repr__ class TextRendererMixin ( object ) : \"\"\"\"\"\" render_text_inline = False def _get_text ( self ) : return self . _text def _set_text ( self , value ) : self . _text = value self . rendered_text = format_creole ( value , inline = self . render_text_inline ) text = property ( _get_text , _set_text ) del _get_text , _set_text ", "answer": "class UserQuery ( Query ) :"}, {"prompt": " from django . conf . urls import * urlpatterns = patterns ( \"\" , ( r'' , include ( '' ) ) , url ( r'' , '' , name = \"\" ) , ", "answer": ") "}, {"prompt": " from oslo_log import log as logging from sqlalchemy import MetaData , Table , Index from nova . i18n import _LI LOG = logging . getLogger ( __name__ ) def upgrade ( migrate_engine ) : \"\"\"\"\"\" meta = MetaData ( bind = migrate_engine ) instances = Table ( '' , meta , autoload = True ) for index in instances . indexes : if [ c . name for c in index . columns ] == [ '' , '' ] : LOG . info ( _LI ( '' '' ) ) break else : index = Index ( '' , instances . c . project_id , instances . c . deleted ) ", "answer": "index . create ( )"}, {"prompt": " from setuptools import find_packages from reviewboard . extensions . packaging import setup from reviewbotext import get_package_version PACKAGE = \"\" setup ( name = \"\" , version = get_package_version ( ) , license = \"\" , description = \"\" , author = \"\" , maintainer = \"\" , include_package_data = True , packages = find_packages ( ) , entry_points = { ", "answer": "'' :"}, {"prompt": " import os import shlex import struct import platform import subprocess def get_terminal_size ( ) : \"\"\"\"\"\" current_os = platform . system ( ) tuple_xy = None if current_os == '' : tuple_xy = _get_terminal_size_windows ( ) if tuple_xy is None : tuple_xy = _get_terminal_size_tput ( ) if current_os in [ '' , '' ] or current_os . startswith ( '' ) : tuple_xy = _get_terminal_size_linux ( ) if tuple_xy is None : tuple_xy = ( , ) return tuple_xy def _get_terminal_size_windows ( ) : try : from ctypes import windll , create_string_buffer h = windll . kernel32 . GetStdHandle ( - ) csbi = create_string_buffer ( ) res = windll . kernel32 . GetConsoleScreenBufferInfo ( h , csbi ) if res : ( bufx , bufy , curx , cury , wattr , left , top , right , bottom , maxx , maxy ) = struct . unpack ( \"\" , csbi . raw ) sizex = right - left + sizey = bottom - top + return sizex , sizey except : pass def _get_terminal_size_tput ( ) : try : cols = int ( subprocess . check_call ( shlex . split ( '' ) ) ) rows = int ( subprocess . check_call ( shlex . split ( '' ) ) ) return ( cols , rows ) except : pass def _get_terminal_size_linux ( ) : def ioctl_GWINSZ ( fd ) : try : import fcntl import termios cr = struct . unpack ( '' , fcntl . ioctl ( fd , termios . TIOCGWINSZ , '' ) ) return cr except : pass cr = ioctl_GWINSZ ( ) or ioctl_GWINSZ ( ) or ioctl_GWINSZ ( ) if not cr : try : fd = os . open ( os . ctermid ( ) , os . O_RDONLY ) cr = ioctl_GWINSZ ( fd ) os . close ( fd ) except : pass if not cr : ", "answer": "try :"}, {"prompt": " from llvmlite import binding as llvm from llvmlite import ir as lc llvm . initialize ( ) llvm . initialize_native_target ( ) llvm . initialize_native_asmprinter ( ) mod = lc . Module ( ) mod . triple = llvm . get_default_triple ( ) func = lc . Function ( mod , lc . FunctionType ( lc . VoidType ( ) , [ lc . IntType ( ) ] ) , name = '' ) builder = lc . IRBuilder ( func . append_basic_block ( ) ) builder . ret_void ( ) print ( mod ) mod = llvm . parse_assembly ( str ( mod ) ) mod . verify ( ) print ( repr ( mod ) ) print ( mod ) with llvm . create_module_pass_manager ( ) as pm : with llvm . create_pass_manager_builder ( ) as pmb : pmb . populate ( pm ) pm . run ( mod ) print ( mod ) tm = llvm . Target . from_default_triple ( ) . create_target_machine ( ) ee = llvm . create_mcjit_compiler ( mod , tm ) func = mod . get_function ( \"\" ) ", "answer": "print ( func , ee . get_function_address ( \"\" ) )"}, {"prompt": " from collections import defaultdict import itertools import unittest import mock import time import os import random from tempfile import mkdtemp from shutil import rmtree from eventlet import Timeout from swift . account import auditor from swift . common . storage_policy import POLICIES from swift . common . utils import Timestamp from test . unit import debug_logger , patch_policies , with_tempdir from test . unit . account . test_backend import ( AccountBrokerPreTrackContainerCountSetup ) class FakeAccountBroker ( object ) : def __init__ ( self , path ) : self . path = path self . db_file = path self . file = os . path . basename ( path ) def is_deleted ( self ) : return False def get_info ( self ) : if self . file . startswith ( '' ) : raise ValueError ( ) if self . file . startswith ( '' ) : return defaultdict ( int ) def get_policy_stats ( self , ** kwargs ) : if self . file . startswith ( '' ) : raise ValueError ( ) if self . file . startswith ( '' ) : return defaultdict ( int ) class TestAuditor ( unittest . TestCase ) : def setUp ( self ) : self . testdir = os . path . join ( mkdtemp ( ) , '' ) self . logger = debug_logger ( ) rmtree ( self . testdir , ignore_errors = ) os . mkdir ( self . testdir ) fnames = [ '' , '' , '' , '' , '' ] for fn in fnames : with open ( os . path . join ( self . testdir , fn ) , '' ) as f : f . write ( '' ) def tearDown ( self ) : rmtree ( os . path . dirname ( self . testdir ) , ignore_errors = ) @ mock . patch ( '' , FakeAccountBroker ) def test_run_forever ( self ) : sleep_times = random . randint ( , ) call_times = sleep_times - class FakeTime ( object ) : def __init__ ( self ) : self . times = def sleep ( self , sec ) : self . times += if self . times >= sleep_times : raise ValueError ( ) def time ( self ) : return time . time ( ) conf = { } test_auditor = auditor . AccountAuditor ( conf , logger = self . logger ) with mock . patch ( '' , FakeTime ( ) ) : def fake_audit_location_generator ( * args , ** kwargs ) : files = os . listdir ( self . testdir ) return [ ( os . path . join ( self . testdir , f ) , '' , '' ) for f in files ] with mock . patch ( '' , fake_audit_location_generator ) : self . assertRaises ( ValueError , test_auditor . run_forever ) self . assertEqual ( test_auditor . account_failures , * call_times ) self . assertEqual ( test_auditor . account_passes , * call_times ) def fake_one_audit_pass ( reported ) : raise Timeout ( ) with mock . patch ( '' , fake_one_audit_pass ) : with mock . patch ( '' , FakeTime ( ) ) : self . assertRaises ( ValueError , test_auditor . run_forever ) self . assertEqual ( test_auditor . account_failures , * call_times ) self . assertEqual ( test_auditor . account_passes , * call_times ) @ mock . patch ( '' , FakeAccountBroker ) def test_run_once ( self ) : conf = { } test_auditor = auditor . AccountAuditor ( conf , logger = self . logger ) def fake_audit_location_generator ( * args , ** kwargs ) : files = os . listdir ( self . testdir ) return [ ( os . path . join ( self . testdir , f ) , '' , '' ) for f in files ] with mock . patch ( '' , fake_audit_location_generator ) : test_auditor . run_once ( ) self . assertEqual ( test_auditor . account_failures , ) self . assertEqual ( test_auditor . account_passes , ) @ mock . patch ( '' , FakeAccountBroker ) def test_one_audit_pass ( self ) : conf = { } test_auditor = auditor . AccountAuditor ( conf , logger = self . logger ) def fake_audit_location_generator ( * args , ** kwargs ) : files = os . listdir ( self . testdir ) return [ ( os . path . join ( self . testdir , f ) , '' , '' ) for f in files ] test_auditor . logging_interval = with mock . patch ( '' , fake_audit_location_generator ) : test_auditor . _one_audit_pass ( test_auditor . logging_interval ) self . assertEqual ( test_auditor . account_failures , ) self . assertEqual ( test_auditor . account_passes , ) @ mock . patch ( '' , FakeAccountBroker ) def test_account_auditor ( self ) : conf = { } test_auditor = auditor . AccountAuditor ( conf , logger = self . logger ) files = os . listdir ( self . testdir ) for f in files : path = os . path . join ( self . testdir , f ) test_auditor . account_audit ( path ) self . assertEqual ( test_auditor . account_failures , ) self . assertEqual ( test_auditor . account_passes , ) @ patch_policies class TestAuditorRealBrokerMigration ( AccountBrokerPreTrackContainerCountSetup , unittest . TestCase ) : def test_db_migration ( self ) : policies = itertools . cycle ( POLICIES ) num_containers = len ( POLICIES ) * per_policy_container_counts = defaultdict ( int ) for i in range ( num_containers ) : name = '' % i policy = next ( policies ) self . broker . put_container ( name , next ( self . ts ) , , , , int ( policy ) ) per_policy_container_counts [ int ( policy ) ] += self . broker . _commit_puts ( ) self . assertEqual ( num_containers , self . broker . get_info ( ) [ '' ] ) self . assertUnmigrated ( self . broker ) conf = { '' : self . tempdir , '' : False , '' : self . tempdir } test_auditor = auditor . AccountAuditor ( conf , logger = debug_logger ( ) ) test_auditor . run_once ( ) self . restore_account_broker ( ) broker = auditor . AccountBroker ( self . db_path ) with broker . get ( ) as conn : rows = conn . execute ( '''''' ) . fetchall ( ) for policy_index , container_count in rows : self . assertEqual ( container_count , per_policy_container_counts [ policy_index ] ) class TestAuditorRealBroker ( unittest . TestCase ) : def setUp ( self ) : self . logger = debug_logger ( ) @ with_tempdir def test_db_validate_fails ( self , tempdir ) : ts = ( Timestamp ( t ) . internal for t in itertools . count ( int ( time . time ( ) ) ) ) db_path = os . path . join ( tempdir , '' , '' , '' , '' , '' , '' ) broker = auditor . AccountBroker ( db_path , account = '' ) broker . initialize ( next ( ts ) ) policies = itertools . cycle ( POLICIES ) num_containers = len ( POLICIES ) * per_policy_container_counts = defaultdict ( int ) for i in range ( num_containers ) : name = '' % i policy = next ( policies ) broker . put_container ( name , next ( ts ) , , , , int ( policy ) ) per_policy_container_counts [ int ( policy ) ] += broker . _commit_puts ( ) self . assertEqual ( broker . get_info ( ) [ '' ] , num_containers ) messed_up_policy = random . choice ( list ( POLICIES ) ) with broker . get ( ) as conn : conn . executescript ( '''''' % int ( messed_up_policy ) ) policy_stats = broker . get_policy_stats ( ) self . assertEqual ( policy_stats [ int ( messed_up_policy ) ] [ '' ] , per_policy_container_counts [ int ( messed_up_policy ) ] - ) conf = { '' : tempdir , '' : False , '' : tempdir } test_auditor = auditor . AccountAuditor ( conf , logger = self . logger ) test_auditor . run_once ( ) self . assertEqual ( test_auditor . account_failures , ) error_lines = test_auditor . logger . get_lines_for_level ( '' ) self . assertEqual ( len ( error_lines ) , ) error_message = error_lines [ ] self . assertTrue ( broker . db_file in error_message ) self . assertTrue ( '' in error_message ) self . assertTrue ( '' in error_message ) self . assertEqual ( test_auditor . logger . get_increment_counts ( ) , { '' : } ) ", "answer": "if __name__ == '' :"}, {"prompt": " import sublime , sublime_plugin class PareditPushBracketCommand ( sublime_plugin . TextCommand ) : def run ( self , edit ) : print '' + '' for region in self . view . sel ( ) : pos = self . view . sel ( ) [ ] . begin ( ) first_closing = None first = True def search ( openings , pos , first_closing , first ) : print \"\" + str ( pos ) + \"\" quit = while quit < : next_opening = self . view . find ( '' , pos ) print \"\" + str ( next_opening ) next_closing = self . view . find ( '' , pos ) print \"\" + str ( next_closing ) if ( next_opening == None ) and ( next_closing == None ) : print '' break if ( next_opening != None ) and ( next_opening . begin ( ) < next_closing . begin ( ) ) : openings += pos = next_opening . begin ( ) + print '' + str ( openings ) else : if ( first_closing == None and openings == ) or ( first_closing == None and first == True ) : print '' first_closing = next_closing dont_break = True else : dont_break = False if openings - >= : openings -= print '' + str ( openings ) else : dont_break = True print '' + str ( openings ) pos = next_closing . begin ( ) + quit += if openings == and dont_break == False : print '' break first = False ", "answer": "if first_closing == None :"}, {"prompt": " from sympy import ( pi , sin , cos , Symbol , Integral , Sum , sqrt , log , oo , LambertW , I , meijerg , exp_polar , Max , Piecewise ) from sympy . plotting import ( plot , plot_parametric , plot3d_parametric_line , plot3d , plot3d_parametric_surface ) from sympy . plotting . plot import unset_show from sympy . utilities . pytest import skip , raises ", "answer": "from sympy . plotting . experimental_lambdify import lambdify"}, {"prompt": " from rest_framework . decorators import api_view from rest_framework . response import Response from rest_framework . reverse import reverse from rest_framework import serializers from rest_framework import generics from rest_framework import status from core . models import * from django . forms import widgets from services . cord . models import VOLTTenant , VOLTService , CordSubscriberRoot from xos . apibase import XOSListCreateAPIView , XOSRetrieveUpdateDestroyAPIView , XOSPermissionDenied from api . xosapi_helpers import PlusModelSerializer , XOSViewSet , ReadOnlyField def get_default_volt_service ( ) : volt_services = VOLTService . get_service_objects ( ) . all ( ) if volt_services : return volt_services [ ] . id return None class VOLTTenantForAPI ( VOLTTenant ) : class Meta : proxy = True app_label = \"\" @ property def subscriber ( self ) : return self . subscriber_root . id @ subscriber . setter def subscriber ( self , value ) : self . subscriber_root = value @ property def related ( self ) : related = { } if self . vcpe : related [ \"\" ] = self . vcpe . id if self . vcpe . instance : related [ \"\" ] = self . vcpe . instance . id related [ \"\" ] = self . vcpe . instance . name related [ \"\" ] = self . vcpe . wan_container_ip if self . vcpe . instance . node : related [ \"\" ] = self . vcpe . instance . node . name return related class VOLTTenantSerializer ( PlusModelSerializer ) : id = ReadOnlyField ( ) service_specific_id = serializers . CharField ( required = False ) s_tag = serializers . CharField ( ) c_tag = serializers . CharField ( ) subscriber = serializers . PrimaryKeyRelatedField ( queryset = CordSubscriberRoot . get_tenant_objects ( ) . all ( ) , required = False ) related = serializers . DictField ( required = False ) property_fields = [ \"\" ] humanReadableName = serializers . SerializerMethodField ( \"\" ) class Meta : model = VOLTTenantForAPI fields = ( '' , '' , '' , '' , '' , '' , '' ) def getHumanReadableName ( self , obj ) : return obj . __unicode__ ( ) class VOLTTenantViewSet ( XOSViewSet ) : base_name = \"\" method_name = \"\" method_kind = \"\" queryset = VOLTTenantForAPI . get_tenant_objects ( ) . all ( ) serializer_class = VOLTTenantSerializer @ classmethod def get_urlpatterns ( self , api_path = \"\" ) : patterns = super ( VOLTTenantViewSet , self ) . get_urlpatterns ( api_path = api_path ) return patterns def list ( self , request ) : ", "answer": "queryset = self . filter_queryset ( self . get_queryset ( ) )"}, {"prompt": " from setuptools import setup install_requires = [ '' , '' ] setup ( name = '' , packages = [ '' ] , version = '' , author = '' , author_email = '' , url = '' , description = '' , install_requires = install_requires , test_suite = '' , tests_require = [ '' ] , classifiers = [ ", "answer": "'' ,"}, {"prompt": " from zipline . utils . memoize import lazyval class ZiplineError ( Exception ) : msg = None def __init__ ( self , ** kwargs ) : self . kwargs = kwargs @ lazyval def message ( self ) : return str ( self ) def __str__ ( self ) : msg = self . msg . format ( ** self . kwargs ) return msg __unicode__ = __str__ __repr__ = __str__ class NoTradeDataAvailable ( ZiplineError ) : pass class NoTradeDataAvailableTooEarly ( NoTradeDataAvailable ) : msg = \"\" class NoTradeDataAvailableTooLate ( NoTradeDataAvailable ) : msg = \"\" class BenchmarkAssetNotAvailableTooEarly ( NoTradeDataAvailableTooEarly ) : pass class BenchmarkAssetNotAvailableTooLate ( NoTradeDataAvailableTooLate ) : pass class InvalidBenchmarkAsset ( ZiplineError ) : msg = \"\"\"\"\"\" . strip ( ) class WrongDataForTransform ( ZiplineError ) : \"\"\"\"\"\" msg = \"\" class UnsupportedSlippageModel ( ZiplineError ) : \"\"\"\"\"\" msg = \"\"\"\"\"\" . strip ( ) class SetSlippagePostInit ( ZiplineError ) : msg = \"\"\"\"\"\" . strip ( ) class SetCancelPolicyPostInit ( ZiplineError ) : msg = \"\"\"\"\"\" . strip ( ) class RegisterTradingControlPostInit ( ZiplineError ) : msg = \"\"\"\"\"\" . strip ( ) class RegisterAccountControlPostInit ( ZiplineError ) : msg = \"\"\"\"\"\" . strip ( ) class UnsupportedCommissionModel ( ZiplineError ) : \"\"\"\"\"\" msg = \"\"\"\"\"\" . strip ( ) class UnsupportedCancelPolicy ( ZiplineError ) : \"\"\"\"\"\" msg = \"\"\"\"\"\" . strip ( ) class SetCommissionPostInit ( ZiplineError ) : \"\"\"\"\"\" msg = \"\"\"\"\"\" . strip ( ) class TransactionWithNoVolume ( ZiplineError ) : \"\"\"\"\"\" msg = \"\"\"\"\"\" . strip ( ) class TransactionWithWrongDirection ( ZiplineError ) : \"\"\"\"\"\" msg = \"\"\"\"\"\" . strip ( ) class TransactionWithNoAmount ( ZiplineError ) : \"\"\"\"\"\" msg = \"\"\"\"\"\" . strip ( ) class TransactionVolumeExceedsOrder ( ZiplineError ) : \"\"\"\"\"\" msg = \"\"\"\"\"\" . strip ( ) class UnsupportedOrderParameters ( ZiplineError ) : \"\"\"\"\"\" msg = \"\" class CannotOrderDelistedAsset ( ZiplineError ) : \"\"\"\"\"\" msg = \"\" class BadOrderParameters ( ZiplineError ) : \"\"\"\"\"\" msg = \"\" class OrderDuringInitialize ( ZiplineError ) : \"\"\"\"\"\" msg = \"\" class SetBenchmarkOutsideInitialize ( ZiplineError ) : \"\"\"\"\"\" msg = \"\" ", "answer": "class AccountControlViolation ( ZiplineError ) :"}, {"prompt": " import os import unittest import shutil import wcloud . tasks . wcloud_tasks as wcloud_tasks from weblab . admin . script import Creation cwd = os . getcwd ( ) if cwd . endswith ( os . path . join ( \"\" , \"\" ) ) : cwd = cwd [ : len ( cwd ) - len ( os . path . join ( \"\" , \"\" ) ) ] os . chdir ( os . path . join ( cwd , \"\" ) ) class TestWcloudTasks ( unittest . TestCase ) : wcloud_settings = { \"\" : \"\" , \"\" : \"\" , \"\" : \"\" , \"\" : \"\" } def test_nothing ( self ) : pass def test_prepare_system ( self ) : settings = wcloud_tasks . prepare_system . delay ( \"\" , \"\" , \"\" , \"\" , \"\" , self . wcloud_settings ) . get ( ) self . _settings = settings def test_create_weblab_environment ( self ) : settings = wcloud_tasks . prepare_system . delay ( \"\" , \"\" , \"\" , \"\" , \"\" , self . wcloud_settings ) . get ( ) self . _settings = settings base_url = os . path . join ( wcloud_tasks . flask_app . config [ \"\" ] , settings [ Creation . BASE_URL ] ) wcloud_tasks . create_weblab_environment . delay ( base_url , settings ) . get ( ) def test_configure_web_server ( self ) : settings = wcloud_tasks . prepare_system . delay ( \"\" , \"\" , \"\" , \"\" , \"\" , self . wcloud_settings ) . get ( ) self . _settings = settings base_url = os . path . join ( wcloud_tasks . flask_app . config [ \"\" ] , settings [ Creation . BASE_URL ] ) creation_results = wcloud_tasks . create_weblab_environment . delay ( base_url , settings ) . get ( ) wcloud_tasks . configure_web_server . delay ( creation_results ) . get ( ) def test_register_and_start_instance ( self ) : settings = wcloud_tasks . prepare_system . delay ( \"\" , \"\" , \"\" , \"\" , \"\" , self . wcloud_settings ) . get ( ) self . _settings = settings base_url = os . path . join ( wcloud_tasks . flask_app . config [ \"\" ] , settings [ Creation . BASE_URL ] ) creation_results = wcloud_tasks . create_weblab_environment . delay ( base_url , settings ) . get ( ) wcloud_tasks . configure_web_server . delay ( creation_results ) . get ( ) wcloud_tasks . register_and_start_instance . delay ( \"\" , { } ) . get ( ) start_port , end_port = creation_results [ \"\" ] , creation_results [ \"\" ] def test_finish_deployment ( self ) : settings = wcloud_tasks . prepare_system . delay ( \"\" , \"\" , \"\" , \"\" , \"\" , self . wcloud_settings ) . get ( ) self . _settings = settings base_url = os . path . join ( wcloud_tasks . flask_app . config [ \"\" ] , settings [ Creation . BASE_URL ] ) creation_results = wcloud_tasks . create_weblab_environment . delay ( base_url , settings ) . get ( ) wcloud_tasks . configure_web_server . delay ( creation_results ) . get ( ) wcloud_tasks . register_and_start_instance . delay ( \"\" , self . wcloud_settings ) . get ( ) start_port , end_port = creation_results [ \"\" ] , creation_results [ \"\" ] wcloud_tasks . finish_deployment . delay ( \"\" , settings , start_port , end_port , self . wcloud_settings ) . get ( ) def setUp ( self ) : import wcloud . test . prepare as prepare prepare . prepare_test_database ( \"\" , \"\" ) def tearDown ( self ) : try : pass except : pass try : ", "answer": "instances_file = os . path . join ( wcloud_tasks . flask_app . config [ \"\" ] , \"\" )"}, {"prompt": " from twisted . internet import reactor from twisted . spread import pb from twisted . cred . credentials import UsernamePassword from pbecho import DefinedError def success ( message ) : print \"\" , message def failure ( error ) : ", "answer": "t = error . trap ( DefinedError )"}, {"prompt": " from ncclient . operations . lock import * import unittest from mock import patch from ncclient import manager import ncclient . manager import ncclient . transport from ncclient . xml_ import * from ncclient . operations import RaiseMode from xml . etree import ElementTree class TestLock ( unittest . TestCase ) : def setUp ( self ) : self . device_handler = manager . make_device_handler ( { '' : '' } ) @ patch ( '' ) @ patch ( '' ) def test_lock_default_param ( self , mock_request , mock_session ) : session = ncclient . transport . SSHSession ( self . device_handler ) obj = Lock ( session , self . device_handler , raise_mode = RaiseMode . ALL ) obj . request ( ) node = new_ele ( \"\" ) sub_ele ( sub_ele ( node , \"\" ) , \"\" ) xml = ElementTree . tostring ( node , method = '' ) call = mock_request . call_args_list [ ] [ ] [ ] call = ElementTree . tostring ( call , method = '' ) self . assertEqual ( call , xml ) @ patch ( '' ) @ patch ( '' ) def test_lock ( self , mock_request , mock_session ) : session = ncclient . transport . SSHSession ( self . device_handler ) obj = Lock ( session , self . device_handler , raise_mode = RaiseMode . ALL ) obj . request ( target = \"\" ) node = new_ele ( \"\" ) sub_ele ( sub_ele ( node , \"\" ) , \"\" ) xml = ElementTree . tostring ( node , method = '' ) call = mock_request . call_args_list [ ] [ ] [ ] call = ElementTree . tostring ( call , method = '' ) self . assertEqual ( call , xml ) @ patch ( '' ) @ patch ( '' ) def test_unlock_default_param ( self , mock_request , mock_session ) : session = ncclient . transport . SSHSession ( self . device_handler ) obj = Unlock ( session , self . device_handler , raise_mode = RaiseMode . ALL ) obj . request ( ) node = new_ele ( \"\" ) sub_ele ( sub_ele ( node , \"\" ) , \"\" ) xml = ElementTree . tostring ( node , method = '' ) call = mock_request . call_args_list [ ] [ ] [ ] call = ElementTree . tostring ( call , method = '' ) self . assertEqual ( call , xml ) @ patch ( '' ) @ patch ( '' ) def test_unlock ( self , mock_request , mock_session ) : session = ncclient . transport . SSHSession ( self . device_handler ) obj = Unlock ( session , self . device_handler , raise_mode = RaiseMode . ALL ) obj . request ( target = \"\" ) ", "answer": "node = new_ele ( \"\" )"}, {"prompt": " from SipAddress import SipAddress from SipRoute import SipRoute from UaStateGeneric import UaStateGeneric from CCEvents import CCEventRing , CCEventConnect , CCEventFail , CCEventRedirect , CCEventDisconnect , CCEventPreConnect class UacStateRinging ( UaStateGeneric ) : sname = '' triedauth = False def recvResponse ( self , resp , tr ) : body = resp . getBody ( ) code , reason = resp . getSCode ( ) scode = ( code , reason , body ) if code < : if self . ua . p1xx_ts == None : self . ua . p1xx_ts = resp . rtime self . ua . last_scode = code event = CCEventRing ( scode , rtime = resp . rtime , origin = self . ua . origin ) for ring_cb in self . ua . ring_cbs : ring_cb ( self . ua , resp . rtime , self . ua . origin , code ) if body != None : ", "answer": "if self . ua . on_remote_sdp_change != None :"}, {"prompt": " from django . core . exceptions import ValidationError from os import path as fs_path from time import strftime from django . utils . text import slugify from django . utils import six from django . utils . translation import ugettext as _ from django . core . cache import cache from django . conf import settings from django . db import models from collections import OrderedDict try : from django . utils . deconstruct import deconstructible except ImportError : def deconstructible ( old_class ) : return old_class UPLOAD_TO_OPTIONS = { \"\" : [ \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" ] , \"\" : , \"\" : \"\" } @ deconstructible class UploadTo ( object ) : \"\"\"\"\"\" def __init__ ( self , ** kwargs ) : \"\"\"\"\"\" self . options = UPLOAD_TO_OPTIONS . copy ( ) if hasattr ( settings , \"\" ) : self . options . update ( settings . UPLOAD_TO_OPTIONS ) self . options . update ( kwargs ) @ staticmethod def get_file_info ( full_filename ) : filename = fs_path . basename ( full_filename ) . lower ( ) filename , file_ext = filename . rsplit ( \"\" , ) return { \"\" : filename , \"\" : file_ext , \"\" : full_filename } def validate_file_info ( self , file_info ) : file_ext = file_info [ \"\" ] if file_ext in self . options [ \"\" ] : raise ValueError ( \"\" % file_ext ) def generate_file_name ( self , instance , file_info ) : model_name = instance . __class__ . __name__ filename = file_info [ \"\" ] max_len = self . options [ \"\" ] file_info [ \"\" ] = slugify ( filename ) [ : max_len ] return strftime ( self . options [ \"\" ] ) . format ( model_name = model_name , instance = instance , ** file_info ) def __call__ ( self , instance , full_filename ) : \"\"\"\"\"\" full_filename = six . text_type ( full_filename ) file_info = self . get_file_info ( full_filename ) self . validate_file_info ( file_info ) return self . generate_file_name ( instance , file_info ) def upload_to ( instance , full_filename ) : upload_to_obj = UploadTo ( ) return upload_to_obj ( instance , full_filename ) def cached_model_property ( model_method = None , readonly = True , cache_timeout = None ) : \"\"\"\"\"\" def func ( f ) : def _get_cache_key ( obj ) : \"\"\"\"\"\" model_name = getattr ( obj , \"\" ) . db_table method_name = f . __name__ return \"\" % ( model_name , obj . pk , method_name ) def get_x ( obj ) : cache_key = _get_cache_key ( obj ) result = cache . get ( cache_key ) if result is None : result = f ( obj ) set_x ( obj , result ) return result def del_x ( obj ) : \"\"\"\"\"\" cache_key = _get_cache_key ( obj ) cache . delete ( cache_key ) def set_x ( obj , value ) : \"\"\"\"\"\" cache_key = _get_cache_key ( obj ) if cache_timeout is None : cache . set ( cache_key , value ) else : cache . set ( cache_key , value , cache_timeout ) if readonly : return property ( fget = get_x , fdel = del_x ) else : return property ( fget = get_x , fset = set_x , fdel = del_x ) if model_method : return func ( model_method ) return func class Choices ( OrderedDict ) : \"\"\"\"\"\" _read_only = True _choices_id = None def __init__ ( self , choices , order_by = \"\" ) : \"\"\"\"\"\" self . _read_only = False super ( Choices , self ) . __init__ ( choices ) self . _choices = _choices = [ ] self . _order_by = order_by if not choices : return choice_ids = set ( ) for choice_code , choice_options in self . items ( ) : if not issubclass ( choice_options . __class__ , dict ) : choice_options = { \"\" : choice_options } self [ choice_code ] = choice_options choice_id = choice_options [ \"\" ] choice_ids . add ( choice_id ) if \"\" not in choice_options : choice_options [ \"\" ] = choice_code . replace ( \"\" , \"\" ) . capitalize ( ) display = choice_options [ \"\" ] _choices . append ( ( choice_id , _ ( display ) ) ) if order_by == \"\" : _choices . sort ( key = lambda x : x [ ] ) elif order_by == \"\" : _choices . sort ( key = lambda x : x [ ] ) self . _read_only = True def get_display_name ( self , choice_id ) : \"\"\"\"\"\" return self . get_value ( choice_id , \"\" ) def get_value ( self , choice_id , choice_key , raise_exception = True ) : \"\"\"\"\"\" if self . _choices_id is None : self . _choices_id = { item [ \"\" ] : ( key , item ) for key , item in six . iteritems ( self ) } choice_name , choice = self . _choices_id [ choice_id ] if choice_key is None : return choice_name elif raise_exception : return choice [ choice_key ] else : return choice . get ( choice_key ) def get_code_name ( self , choice_id ) : \"\"\"\"\"\" return self . get_value ( choice_id , choice_key = None ) def __getattr__ ( self , attr_name ) : if attr_name in self : return self [ attr_name ] [ \"\" ] raise AttributeError ( \"\" % ( attr_name , self . __class__ . __name__ ) ) def __call__ ( self ) : \"\"\"\"\"\" return self . _choices def __setattr__ ( self , attr , * args ) : if self . _read_only and attr in self : raise TypeError ( \"\" ) super ( Choices , self ) . __setattr__ ( attr , * args ) def __setitem__ ( self , * args ) : if self . _read_only : raise TypeError ( \"\" ) super ( Choices , self ) . __setitem__ ( * args ) def __dir__ ( self ) : return list ( self . keys ( ) ) + dir ( self . __class__ ) def copy ( self ) : new_self = Choices ( { } , order_by = self . _order_by ) new_self . update ( self ) return new_self def update ( self , new_data = None , ** kwargs ) : \"\"\"\"\"\" if self . _read_only : raise TypeError ( \"\" ) if not new_data : new_data = kwargs if not isinstance ( new_data , Choices ) : new_data = Choices ( new_data ) assert isinstance ( new_data , Choices ) common_keys = set ( new_data . keys ( ) ) & set ( self . keys ( ) ) if common_keys : raise ValueError ( \"\" % \"\" . join ( common_keys ) ) self . _choices += ( new_data ( ) ) self . _choices_id = None super ( Choices , self ) . update ( new_data ) def __enter__ ( self ) : return self def __exit__ ( self , * args , ** kwargs ) : self . _read_only = True def __add__ ( self , other ) : self . _read_only = False with self . copy ( ) as result : result . update ( other ) self . _read_only = True return result class KeyValueContainer ( dict ) : def __init__ ( self , seq = None , separator = \"\" , ** kwargs ) : super ( KeyValueContainer , self ) . __init__ ( ) self . sep = separator if isinstance ( seq , six . string_types ) : seq = self . _parse_string ( seq ) if seq is not None : seq = dict ( seq ) kwargs . update ( seq ) for key , value in six . iteritems ( kwargs ) : self . __setitem__ ( key , value ) def __str__ ( self ) : result = [ ] for key , val in six . iteritems ( self ) : result . append ( u\"\" % ( key , self . sep , val ) ) return u\"\" . join ( result ) + \"\" def __setitem__ ( self , key , item ) : if item is None : item = \"\" else : item = six . text_type ( item ) super ( KeyValueContainer , self ) . __setitem__ ( key , item ) def __unicode__ ( self ) : ", "answer": "return self . __str__ ( )"}, {"prompt": " from mixbox import fields import cybox . bindings . win_critical_section_object as win_critical_section_binding from cybox . common import ObjectProperties , HexBinary , NonNegativeInteger ", "answer": "class WinCriticalSection ( ObjectProperties ) :"}, {"prompt": " import abc import collections from neutron_lib import exceptions from oslo_concurrency import lockutils from oslo_log import log as logging import six from neutron . _i18n import _LW , _LI from neutron . agent . l2 import agent_extension from neutron . api . rpc . callbacks . consumer import registry from neutron . api . rpc . callbacks import events from neutron . api . rpc . callbacks import resources from neutron . api . rpc . handlers import resources_rpc from neutron import manager LOG = logging . getLogger ( __name__ ) @ six . add_metaclass ( abc . ABCMeta ) class QosAgentDriver ( object ) : \"\"\"\"\"\" SUPPORTED_RULES = set ( ) @ abc . abstractmethod def initialize ( self ) : \"\"\"\"\"\" def create ( self , port , qos_policy ) : \"\"\"\"\"\" self . _handle_update_create_rules ( '' , port , qos_policy ) def consume_api ( self , agent_api ) : \"\"\"\"\"\" def update ( self , port , qos_policy ) : \"\"\"\"\"\" self . _handle_update_create_rules ( '' , port , qos_policy ) def delete ( self , port , qos_policy = None ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " from __future__ import unicode_literals from django . core . paginator import Paginator from celery . task import task from sequere . utils import get_setting @ task ( name = '' ) def dispatch_action ( action_uid , dispatch = True ) : from sequere . models import get_followers from sequere . contrib . timeline import app from . import Timeline logger = dispatch_action . get_logger ( ) action = app . backend . get_action ( action_uid ) paginator = Paginator ( get_followers ( action . actor ) , get_setting ( '' ) ) logger . info ( '' % ( action , paginator . count ) ) for num_page in paginator . page_range : page = paginator . page ( num_page ) for obj , timestamp in page . object_list : if action . actor == obj : continue timeline = Timeline ( obj ) timeline . save ( action , dispatch = dispatch ) def populate_actions ( from_uid , to_uid , method , logger = None ) : from sequere import app from . import Timeline from_instance = app . backend . get_from_uid ( from_uid ) to_instance = app . backend . get_from_uid ( to_uid ) paginator = Paginator ( Timeline ( from_instance ) . get_public ( ) , get_setting ( '' ) ) timeline = Timeline ( to_instance ) if logger : logger . info ( '' % ( method , to_instance , paginator . count , from_instance ) ) for num_page in paginator . page_range : page = paginator . page ( num_page ) for action in page . object_list : getattr ( timeline , method ) ( action , dispatch = False ) @ task ( name = '' ) def import_actions ( from_uid , to_uid ) : populate_actions ( from_uid , to_uid , '' , logger = import_actions . get_logger ( ) ) @ task ( name = '' ) def remove_actions ( from_uid , to_uid ) : populate_actions ( from_uid , to_uid , '' , ", "answer": "logger = remove_actions . get_logger ( ) ) "}, {"prompt": " import unittest import mock import json import runabove class TestToken ( unittest . TestCase ) : answer_token = '''''' @ mock . patch ( '' ) def setUp ( self , mock_wrapper ) : self . mock_wrapper = mock_wrapper self . token = runabove . token . TokenManager ( mock_wrapper , None ) def test_base_path ( self ) : self . assertEquals ( self . token . basepath , '' ) ", "answer": "def test_token_existance ( self ) :"}, {"prompt": " \"\"\"\"\"\" from . import Widget from . import Layout , VBox , HBox , GroupWidget , PlotWidget class PlotLayout ( Layout ) : \"\"\"\"\"\" def init ( self ) : self . _box = HBox ( parent = self ) with self . _box : self . _left = VBox ( flex = ) with VBox ( flex = ) : self . _plot = PlotWidget ( flex = , ", "answer": "style = '' )"}, {"prompt": " from mox3 import mox from neutronclient . common import exceptions from neutronclient . tests . unit import test_cli20 as neutron_test_cli20 import requests from gbpclient . gbp import v2_0 as gbpV2_0 from gbpclient import gbpshell from gbpclient . v2_0 import client as gbpclient API_VERSION = neutron_test_cli20 . API_VERSION FORMAT = neutron_test_cli20 . FORMAT TOKEN = neutron_test_cli20 . TOKEN ENDURL = neutron_test_cli20 . ENDURL capture_std_streams = neutron_test_cli20 . capture_std_streams end_url = neutron_test_cli20 . end_url class FakeStdout ( neutron_test_cli20 . FakeStdout ) : pass class MyResp ( neutron_test_cli20 . MyResp ) : pass class MyApp ( neutron_test_cli20 . MyApp ) : pass class MyUrlComparator ( neutron_test_cli20 . MyUrlComparator ) : ", "answer": "pass"}, {"prompt": " \"\"\"\"\"\" class Error ( Exception ) : pass class DecodeError ( Error ) : pass class EncodeError ( Error ) : pass class Message ( object ) : \"\"\"\"\"\" __slots__ = [ ] DESCRIPTOR = None def __deepcopy__ ( self , memo = None ) : clone = type ( self ) ( ) clone . MergeFrom ( self ) return clone def __eq__ ( self , other_msg ) : \"\"\"\"\"\" raise NotImplementedError def __ne__ ( self , other_msg ) : return not self == other_msg def __hash__ ( self ) : raise TypeError ( '' ) def __str__ ( self ) : \"\"\"\"\"\" raise NotImplementedError def __unicode__ ( self ) : \"\"\"\"\"\" raise NotImplementedError def MergeFrom ( self , other_msg ) : \"\"\"\"\"\" raise NotImplementedError def CopyFrom ( self , other_msg ) : \"\"\"\"\"\" if self is other_msg : return self . Clear ( ) self . MergeFrom ( other_msg ) def Clear ( self ) : \"\"\"\"\"\" raise NotImplementedError def SetInParent ( self ) : \"\"\"\"\"\" raise NotImplementedError def IsInitialized ( self ) : \"\"\"\"\"\" ", "answer": "raise NotImplementedError"}, {"prompt": " import copy import os . path from robot . output import LOGGER from robot . errors import FrameworkError from robot . utils import normpath , seq2str2 , is_string from . builder import ResourceFileBuilder from . handlerstore import HandlerStore from . testlibraries import TestLibrary class Importer ( object ) : def __init__ ( self ) : self . _library_cache = ImportCache ( ) self . _resource_cache = ImportCache ( ) def reset ( self ) : self . __init__ ( ) def close_global_library_listeners ( self ) : for lib in self . _library_cache . values ( ) : lib . close_global_listeners ( ) def import_library ( self , name , args , alias , variables ) : lib = TestLibrary ( name , args , variables , create_handlers = False ) positional , named = lib . positional_args , lib . named_args lib = self . _import_library ( name , positional , named , lib ) if alias : alias = variables . replace_scalar ( alias ) lib = self . _copy_library ( lib , alias ) LOGGER . info ( \"\" % ( name , alias ) ) return lib def import_resource ( self , path ) : if path in self . _resource_cache : LOGGER . info ( \"\" % path ) else : resource = ResourceFileBuilder ( ) . build ( path ) self . _resource_cache [ path ] = resource return self . _resource_cache [ path ] def _import_library ( self , name , positional , named , lib ) : ", "answer": "args = positional + [ '' % arg for arg in named ]"}, {"prompt": " import unittest import time import logging import numpy import ufora . native . Cumulus as CumulusNative import ufora . cumulus . test . InMemoryCumulusSimulation as InMemoryCumulusSimulation import ufora . distributed . S3 . InMemoryS3Interface as InMemoryS3Interface import ufora . native . TCMalloc as TCMallocNative import ufora . native . CallbackScheduler as CallbackScheduler import ufora . test . PerformanceTestReporter as PerformanceTestReporter import cPickle as pickle callbackScheduler = CallbackScheduler . singletonForTesting ( ) class CumulusWorkerDatasetLoadServiceIntegrationTest ( unittest . TestCase ) : def assertBecomesTrueEventually ( self , f , timeout , msgFun ) : t0 = time . time ( ) while not f ( ) : time . sleep ( ) if time . time ( ) - t0 > timeout : self . assertTrue ( False , msgFun ( ) ) def computeUsingSeveralWorkers ( self , * args , ** kwds ) : return InMemoryCumulusSimulation . computeUsingSeveralWorkers ( * args , ** kwds ) def test_PythonIoTaskService ( self ) : s3 = InMemoryS3Interface . InMemoryS3InterfaceFactory ( ) for ix1 in range ( ) : for ix2 in range ( ) : s3 ( ) . setKeyValue ( \"\" , \"\" % ( ix1 , ix2 ) , \"\" . join ( ( \"\" % ( ix1 , ix2 , ix3 ) for ix3 in range ( ) ) ) ) text = \"\"\"\"\"\" self . assertIsNotNone ( self . computeUsingSeveralWorkers ( text , s3 , ) ) def test_PythonIoTaskService2 ( self ) : s3 = InMemoryS3Interface . InMemoryS3InterfaceFactory ( ) for ix1 in range ( ) : for ix2 in range ( ) : s3 ( ) . setKeyValue ( \"\" , \"\" % ( ix1 , ix2 ) , \"\" . join ( ( \"\" % ( ix1 , ix2 , ix3 ) for ix3 in range ( ) ) ) ) text = \"\"\"\"\"\" self . assertIsNotNone ( self . computeUsingSeveralWorkers ( text , s3 , ) ) def test_PythonIoTaskService3 ( self ) : s3 = InMemoryS3Interface . InMemoryS3InterfaceFactory ( ) s3 . setThroughputPerMachine ( * * ) for ix in range ( ) : s3 ( ) . setKeyValue ( \"\" , \"\" % ix , \"\" * * * ) text = \"\"\"\"\"\" self . assertIsNotNone ( self . computeUsingSeveralWorkers ( text , s3 , , timeout = , blockUntilConnected = True ) ) totalBytecount = for machine , bytecount in s3 . getPerMachineBytecounts ( ) . iteritems ( ) : totalBytecount += bytecount self . assertTrue ( totalBytecount / / <= , totalBytecount / / ) def test_PythonIoTaskServiceInLoop ( self ) : bytesUsed = [ ] for ix in range ( ) : bytesUsed . append ( TCMallocNative . getMemoryStat ( \"\" ) / / ) s3 = InMemoryS3Interface . InMemoryS3InterfaceFactory ( ) s3 . setThroughputPerMachine ( * * ) for ix in range ( ) : s3 ( ) . setKeyValue ( \"\" , \"\" % ix , \"\" * * * ) text = \"\"\"\"\"\" self . computeUsingSeveralWorkers ( text , s3 , , timeout = , blockUntilConnected = True ) self . assertTrue ( bytesUsed [ ] < bytesUsed [ - ] - , bytesUsed ) def test_CalculationRicochet ( self ) : s3 = InMemoryS3Interface . InMemoryS3InterfaceFactory ( ) text = \"\"\"\"\"\" vResult , sim = InMemoryCumulusSimulation . computeUsingSeveralWorkers ( \"\" , s3 , , timeout = , memoryLimitMb = , threadCount = , useInMemoryCache = True , returnSimulation = True ) try : v = vResult . asResult . result t0 = time . time ( ) sim . compute ( text . replace ( \"\" , \"\" ) . replace ( \"\" , \"\" ) , timeout = , v = v ) PerformanceTestReporter . recordTest ( \"\" , time . time ( ) - t0 , None ) t0 = time . time ( ) sim . compute ( text . replace ( \"\" , \"\" ) . replace ( \"\" , \"\" ) , timeout = , v = v ) PerformanceTestReporter . recordTest ( \"\" , time . time ( ) - t0 , None ) finally : sim . teardown ( ) def dataCreationTest ( self , totalMB , workers = , threadsPerWorker = ) : s3 = InMemoryS3Interface . InMemoryS3InterfaceFactory ( ) text = \"\"\"\"\"\" % ( totalMB * * / ) self . assertIsNotNone ( self . computeUsingSeveralWorkers ( text , s3 , workers , timeout = , memoryLimitMb = totalMB / workers * , threadCount = threadsPerWorker , useInMemoryCache = False ) ) @ PerformanceTestReporter . PerfTest ( \"\" ) def test_createData_500_1 ( self ) : self . dataCreationTest ( ) @ PerformanceTestReporter . PerfTest ( \"\" ) def test_createData_1000_1 ( self ) : self . dataCreationTest ( ) @ PerformanceTestReporter . PerfTest ( \"\" ) def test_createData_2000_1 ( self ) : self . dataCreationTest ( ) @ PerformanceTestReporter . PerfTest ( \"\" ) def test_createData_500_2 ( self ) : self . dataCreationTest ( , , ) @ PerformanceTestReporter . PerfTest ( \"\" ) def test_createData_1000_2 ( self ) : self . dataCreationTest ( , , ) @ PerformanceTestReporter . PerfTest ( \"\" ) def test_createData_2000_2 ( self ) : self . dataCreationTest ( , , ) @ PerformanceTestReporter . PerfTest ( \"\" ) def test_DataFanout ( self ) : s3 = InMemoryS3Interface . InMemoryS3InterfaceFactory ( ) text = \"\"\"\"\"\" self . assertIsNotNone ( self . computeUsingSeveralWorkers ( text , s3 , , timeout = ) ) @ PerformanceTestReporter . PerfTest ( \"\" ) def test_LargeCSVParse ( self ) : s3 = InMemoryS3Interface . InMemoryS3InterfaceFactory ( ) for ix1 in range ( ) : s3 ( ) . setKeyValue ( \"\" , \"\" % ix1 , \"\" . join ( ( \"\" % ( ix1 , ix2 , ix1 * ix2 ) for ix2 in range ( ) ) ) ) text = \"\"\"\"\"\" res = self . computeUsingSeveralWorkers ( text , s3 , , memoryLimitMb = , timeout = ) self . assertTrue ( res . isResult ( ) , res ) self . assertEqual ( res . asResult . result . pyval , * ) @ PerformanceTestReporter . PerfTest ( \"\" ) def test_CreateManySmallVectors ( self ) : s3 = InMemoryS3Interface . InMemoryS3InterfaceFactory ( ) text = \"\"\"\"\"\" res = self . computeUsingSeveralWorkers ( text , s3 , ) self . assertTrue ( res . isResult ( ) ) self . assertEqual ( res . asResult . result . pyval , ) def test_CalculateWithCachecallsFirst ( self ) : s3 = InMemoryS3Interface . InMemoryS3InterfaceFactory ( ) text = \"\"\"\"\"\" res = self . computeUsingSeveralWorkers ( text , s3 , , timeout = ) self . assertIsNotNone ( res ) self . assertTrue ( res . isResult ( ) ) self . assertEqual ( res . asResult . result . pyval , \"\" ) @ PerformanceTestReporter . PerfTest ( \"\" ) def test_CachecallsAndVectors ( self ) : s3 = InMemoryS3Interface . InMemoryS3InterfaceFactory ( ) text = \"\"\"\"\"\" res = self . computeUsingSeveralWorkers ( text , s3 , , timeout = ) self . assertTrue ( res . isResult ( ) ) self . assertEqual ( res . asResult . result . pyval , \"\" ) @ PerformanceTestReporter . PerfTest ( \"\" ) def test_VectorsAndSums ( self ) : s3 = InMemoryS3Interface . InMemoryS3InterfaceFactory ( ) text = \"\"\"\"\"\" res = self . computeUsingSeveralWorkers ( text , s3 , , timeout = ) self . assertTrue ( res . isResult ( ) , res ) @ PerformanceTestReporter . PerfTest ( \"\" ) def test_ParseRowsAsFloatVectors ( self ) : s3 = InMemoryS3Interface . InMemoryS3InterfaceFactory ( ) rows = bucketData = \"\" . join ( [ \"\" . join ( [ str ( ( ( x * row ) ** ) % ) for x in range ( ) ] ) for row in range ( rows ) ] ) s3 ( ) . setKeyValue ( \"\" , \"\" , bucketData ) text = \"\"\"\"\"\" res = self . computeUsingSeveralWorkers ( text , s3 , , timeout = ) self . assertTrue ( res . isResult ( ) , res ) self . assertEqual ( res . asResult . result . pyval , rows ) @ PerformanceTestReporter . PerfTest ( \"\" ) def test_ParseRowsAsFloatTuples ( self ) : s3 = InMemoryS3Interface . InMemoryS3InterfaceFactory ( ) rows = bucketData = \"\" . join ( [ \"\" . join ( [ str ( ( ( x * row ) ** ) % ) for x in range ( ) ] ) for row in range ( rows ) ] ) s3 ( ) . setKeyValue ( \"\" , \"\" , bucketData ) text = \"\"\"\"\"\" t0 = time . time ( ) parsedInPython2 = [ [ float ( x ) for x in row . split ( \"\" ) ] for row in bucketData . split ( \"\" ) ] pythonTime = time . time ( ) - t0 t0 = time . time ( ) res = self . computeUsingSeveralWorkers ( text , s3 , , memoryLimitMb = , timeout = ) foraTime = time . time ( ) - t0 t0 = time . time ( ) res = self . computeUsingSeveralWorkers ( text , s3 , , memoryLimitMb = , timeout = ) foraTime2 = time . time ( ) - t0 self . assertTrue ( res . isResult ( ) , res ) self . assertEqual ( res . asResult . result . pyval , rows ) print \"\" % ( foraTime , foraTime2 , pythonTime , foraTime / pythonTime ) @ PerformanceTestReporter . PerfTest ( \"\" ) def test_largeVectorRange ( self ) : s3 = InMemoryS3Interface . InMemoryS3InterfaceFactory ( ) res = self . computeUsingSeveralWorkers ( \"\"\"\"\"\" , s3 , , timeout = ) if res . isResult ( ) : self . assertEqual ( res . asResult . result . pyvalOrNone , * , res ) else : self . assertTrue ( False , res ) @ PerformanceTestReporter . PerfTest ( \"\" ) def test_sortLargeVectorRange ( self ) : s3 = InMemoryS3Interface . InMemoryS3InterfaceFactory ( ) for ix in range ( ) : t0 = time . time ( ) self . computeUsingSeveralWorkers ( \"\"\"\"\"\" , s3 , , timeout = ) foraTime = time . time ( ) - t0 t0 = time . time ( ) v = [ ( ix ** % , ix ) for ix in range ( * * ) ] v = sorted ( v ) pyTime = time . time ( ) - t0 print \"\" % ( pyTime , foraTime , pyTime / foraTime ) def test_sortVec2 ( self ) : s3 = InMemoryS3Interface . InMemoryS3InterfaceFactory ( ) result = self . computeUsingSeveralWorkers ( \"\"\"\"\"\" , s3 , ) self . assertEqual ( result . asResult . result . pyval , True ) def test_performManySums ( self ) : s3 = InMemoryS3Interface . InMemoryS3InterfaceFactory ( ) for ix in range ( ) : t0 = time . time ( ) self . computeUsingSeveralWorkers ( \"\"\"\"\"\" , s3 , ) foraTime = time . time ( ) - t0 t0 = time . time ( ) v = numpy . ones ( ) . cumsum ( ) - for ix in range ( ) : ( v + ix ) . sum ( ) pyTime = time . time ( ) - t0 print \"\" % ( pyTime , foraTime , pyTime / foraTime ) def test_computeManyGetitems ( self ) : s3 = InMemoryS3Interface . InMemoryS3InterfaceFactory ( ) interpreterTimes = [ ] for ix in range ( ) : interpTime = self . computeUsingSeveralWorkers ( \"\"\"\"\"\" % ix , s3 , , wantsStats = True , timeout = ) [ ] . timeSpentInInterpreter interpreterTimes . append ( interpTime ) for interpTime in interpreterTimes [ : ] : self . assertLess ( interpTime , ( sum ( interpreterTimes ) - interpTime ) / ( len ( interpreterTimes ) - ) * ) @ PerformanceTestReporter . PerfTest ( \"\" ) def test_gcOfPagedVectors ( self ) : s3 = InMemoryS3Interface . InMemoryS3InterfaceFactory ( ) self . computeUsingSeveralWorkers ( \"\"\"\"\"\" , s3 , , timeout = ) @ PerformanceTestReporter . PerfTest ( \"\" ) def test_produceLotsOfData ( self ) : s3 = InMemoryS3Interface . InMemoryS3InterfaceFactory ( ) result , simulation = self . computeUsingSeveralWorkers ( \"\"\"\"\"\" , s3 , , timeout = , returnSimulation = True ) try : def test ( ) : for worker , vdm , eventHandler in simulation . workersVdmsAndEventHandlers : self . assertTrue ( vdm . curTotalUsedBytes ( ) < * * , \"\" % ( vdm . curTotalUsedBytes ( ) / / ) ) test ( ) finally : simulation . teardown ( ) def test_schedulerEventsAreSerializable ( self ) : s3 = InMemoryS3Interface . InMemoryS3InterfaceFactory ( ) result , simulation = self . computeUsingSeveralWorkers ( \"\"\"\"\"\" , s3 , , timeout = , returnSimulation = True ) try : someHadEvents = False for worker , vdm , eventHandler in simulation . workersVdmsAndEventHandlers : events = eventHandler . extractEvents ( ) events2 = pickle . loads ( pickle . dumps ( events ) ) print len ( events ) , \"\" print len ( pickle . dumps ( events ) ) , \"\" print len ( pickle . dumps ( events ) ) / len ( events ) , \"\" self . assertTrue ( len ( events2 ) == len ( events ) ) if len ( events ) : someHadEvents = True CumulusNative . replayCumulusWorkerEventStream ( events , True ) self . assertTrue ( someHadEvents ) worker = None vdm = None eventHandler = None finally : simulation . teardown ( ) @ PerformanceTestReporter . PerfTest ( \"\" ) def test_fanout ( self ) : s3 = InMemoryS3Interface . InMemoryS3InterfaceFactory ( ) self . computeUsingSeveralWorkers ( \"\"\"\"\"\" , s3 , , timeout = ) @ PerformanceTestReporter . PerfTest ( \"\" ) def test_vector_string_apply ( self ) : s3 = InMemoryS3Interface . InMemoryS3InterfaceFactory ( ) InMemoryCumulusSimulation . computeUsingSeveralWorkers ( \"\"\"\"\"\" , s3 , , timeout = ) def test_page_glomming_basic ( self ) : s3 = InMemoryS3Interface . InMemoryS3InterfaceFactory ( ) result , simulation = self . computeUsingSeveralWorkers ( \"\"\"\"\"\" , s3 , , timeout = , returnSimulation = True ) try : sprt = simulation . getWorker ( ) . getSystemwidePageRefcountTracker ( ) def activePageCount ( ) : return len ( [ x for x in sprt . getAllPages ( ) if sprt . machinesWithPageInRam ( x ) ] ) self . assertBecomesTrueEventually ( lambda : activePageCount ( ) == , , lambda : \"\" % ( len ( sprt . getAllPages ( ) ) , sprt . getViewOfSystem ( ) ) ) sprt = None finally : simulation . teardown ( ) def test_page_glomming_multiple ( self ) : s3 = InMemoryS3Interface . InMemoryS3InterfaceFactory ( ) result , simulation = self . computeUsingSeveralWorkers ( \"\"\"\"\"\" , s3 , , timeout = , returnSimulation = True ) try : sprt = simulation . getWorker ( ) . getSystemwidePageRefcountTracker ( ) def activePageCount ( ) : return len ( [ x for x in sprt . getAllPages ( ) if sprt . machinesWithPageInRam ( x ) ] ) self . assertBecomesTrueEventually ( lambda : activePageCount ( ) <= , , lambda : \"\" % ( activePageCount ( ) , sprt . getViewOfSystem ( ) ) ) sprt = None finally : simulation . teardown ( ) def test_page_glomming_common_pages ( self ) : s3 = InMemoryS3Interface . InMemoryS3InterfaceFactory ( ) result , simulation = self . computeUsingSeveralWorkers ( \"\"\"\"\"\" , s3 , , timeout = , returnSimulation = True ) try : sprt = simulation . getWorker ( ) . getSystemwidePageRefcountTracker ( ) def noOrphanedPages ( ) : return len ( sprt . getPagesThatAppearOrphaned ( ) ) == self . assertBecomesTrueEventually ( noOrphanedPages , , lambda : \"\" % ( sprt . getViewOfSystem ( ) ) ) sprt = None finally : simulation . teardown ( ) def test_invalidURL ( self ) : ", "answer": "s3 = InMemoryS3Interface . InMemoryS3InterfaceFactory ( )"}, {"prompt": " from __future__ import print_function from pickle import load , dump from scipy import array , sqrt from pylab import errorbar , show class ExTools ( ) : agent = None loadName = \"\" saveName = \"\" resuName = \"\" rl = [ ] rll = [ ] def __init__ ( self , batch = , prnts = , kind = \"\" ) : self . batch = batch self . prnts = prnts self . kind = kind def loadWeights ( self , filename ) : filepointer = open ( filename ) self . agent . learner . current = load ( filepointer ) filepointer . close ( ) self . agent . learner . gd . init ( self . agent . learner . current ) self . agent . learner . epsilon = self . agent . learner . initSigmas ( ) def saveWeights ( self , filename , w ) : filepointer = open ( filename , '' ) dump ( w , filepointer ) filepointer . close ( ) def saveResults ( self , filename , results ) : filepointer = open ( filename , '' ) dump ( results , filepointer ) filepointer . close ( ) def printResults ( self , resList , runs , updates ) : if self . kind == \"\" : rLen = len ( resList ) avReward = array ( resList ) . sum ( ) / rLen print ( ( \"\" , self . agent . learner . _bestFound ( ) ) ) print ( ( \"\" , runs , ", "answer": "\"\" , ( updates + ) * self . batch * self . prnts ,"}, {"prompt": " import morepath from webtest import TestApp as Client from morepath . error import LinkError , ConflictError import pytest def setup_module ( module ) : morepath . disable_implicit ( ) def test_defer_links ( ) : class Root ( morepath . App ) : pass class Sub ( morepath . App ) : pass @ Root . path ( path = '' ) class RootModel ( object ) : pass @ Root . view ( model = RootModel ) def root_model_default ( self , request ) : return request . link ( SubModel ( ) ) @ Root . view ( model = RootModel , name = '' ) def root_model_class_link ( self , request ) : return request . class_link ( SubModel ) @ Sub . path ( path = '' ) class SubModel ( object ) : pass @ Root . mount ( app = Sub , path = '' ) def mount_sub ( ) : return Sub ( ) @ Root . defer_links ( model = SubModel ) def defer_links_sub_model ( app , obj ) : return app . child ( Sub ( ) ) c = Client ( Root ( ) ) response = c . get ( '' ) assert response . body == b'' with pytest . raises ( LinkError ) : c . get ( '' ) def test_defer_view ( ) : class Root ( morepath . App ) : pass class Sub ( morepath . App ) : pass @ Root . path ( path = '' ) class RootModel ( object ) : pass @ Root . json ( model = RootModel ) def root_model_default ( self , request ) : return request . view ( SubModel ( ) ) @ Sub . path ( path = '' ) class SubModel ( object ) : pass @ Sub . json ( model = SubModel ) def submodel_default ( self , request ) : return { '' : '' } @ Root . mount ( app = Sub , path = '' ) def mount_sub ( ) : return Sub ( ) @ Root . defer_links ( model = SubModel ) def defer_links_sub_model ( app , obj ) : return app . child ( Sub ( ) ) c = Client ( Root ( ) ) response = c . get ( '' ) assert response . json == { '' : '' } def test_defer_view_predicates ( ) : class Root ( morepath . App ) : pass class Sub ( morepath . App ) : pass @ Root . path ( path = '' ) class RootModel ( object ) : pass @ Root . json ( model = RootModel ) def root_model_default ( self , request ) : return request . view ( SubModel ( ) , name = '' ) @ Sub . path ( path = '' ) class SubModel ( object ) : pass @ Sub . json ( model = SubModel , name = '' ) def submodel_edit ( self , request ) : return { '' : '' } @ Root . mount ( app = Sub , path = '' ) def mount_sub ( ) : return Sub ( ) @ Root . defer_links ( model = SubModel ) def defer_links_sub_model ( app , obj ) : return app . child ( Sub ( ) ) c = Client ( Root ( ) ) response = c . get ( '' ) assert response . json == { '' : '' } def test_defer_view_missing_view ( ) : class Root ( morepath . App ) : pass class Sub ( morepath . App ) : pass @ Root . path ( path = '' ) class RootModel ( object ) : pass @ Root . json ( model = RootModel ) def root_model_default ( self , request ) : return { '' : request . view ( SubModel ( ) , name = '' ) } @ Sub . path ( path = '' ) class SubModel ( object ) : pass @ Sub . json ( model = SubModel , name = '' ) def submodel_edit ( self , request ) : return { '' : '' } @ Root . mount ( app = Sub , path = '' ) def mount_sub ( ) : return Sub ( ) @ Root . defer_links ( model = SubModel ) def defer_links_sub_model ( app , obj ) : return app . child ( Sub ( ) ) c = Client ( Root ( ) ) response = c . get ( '' ) assert response . json == { '' : None } def test_defer_links_mount_parameters ( ) : class root ( morepath . App ) : pass class sub ( morepath . App ) : pass def __init__ ( self , name ) : self . name = name @ root . path ( path = '' ) class RootModel ( object ) : pass @ root . view ( model = RootModel ) def root_model_default ( self , request ) : return request . link ( SubModel ( '' ) ) class SubModel ( object ) : def __init__ ( self , name ) : self . name = name @ sub . path ( path = '' , model = SubModel ) def get_sub_model ( request ) : return SubModel ( request . app . name ) @ root . mount ( app = sub , path = '' , variables = lambda a : { '' : a . name } ) def mount_sub ( mount_name ) : return sub ( name = mount_name ) @ root . defer_links ( model = SubModel ) def defer_links_sub_model ( app , obj ) : return app . child ( sub ( name = obj . name ) ) c = Client ( root ( ) ) response = c . get ( '' ) assert response . body == b'' def test_defer_link_acquisition ( ) : class root ( morepath . App ) : pass class sub ( morepath . App ) : pass @ root . path ( path = '' ) class Model ( object ) : def __init__ ( self , id ) : self . id = id @ root . view ( model = Model ) def model_default ( self , request ) : return \"\" @ sub . path ( path = '' ) class SubModel ( object ) : pass @ sub . view ( model = SubModel ) def sub_model_default ( self , request ) : return request . link ( Model ( '' ) ) @ root . mount ( app = sub , path = '' ) def mount_sub ( obj , app ) : return app . child ( sub ( ) ) @ sub . defer_links ( model = Model ) def get_parent ( app , obj ) : return app . parent c = Client ( root ( ) ) response = c . get ( '' ) assert response . body == b'' def test_defer_view_acquisition ( ) : class root ( morepath . App ) : pass class sub ( morepath . App ) : pass @ root . path ( path = '' ) class Model ( object ) : def __init__ ( self , id ) : self . id = id @ root . json ( model = Model ) def model_default ( self , request ) : return { \"\" : \"\" } @ sub . path ( path = '' ) class SubModel ( object ) : pass @ sub . json ( model = SubModel ) def sub_model_default ( self , request ) : return request . view ( Model ( '' ) ) @ root . mount ( app = sub , path = '' ) def mount_sub ( obj , app ) : return app . child ( sub ( ) ) @ sub . defer_links ( model = Model ) def get_parent ( app , obj ) : return app . parent c = Client ( root ( ) ) response = c . get ( '' ) assert response . json == { \"\" : \"\" } def test_defer_link_acquisition_blocking ( ) : class root ( morepath . App ) : pass class sub ( morepath . App ) : pass @ root . path ( path = '' ) class Model ( object ) : def __init__ ( self , id ) : self . id = id @ root . view ( model = Model ) def model_default ( self , request ) : return \"\" @ sub . path ( path = '' ) class SubModel ( object ) : pass @ sub . view ( model = SubModel ) def sub_model_default ( self , request ) : try : return request . link ( Model ( '' ) ) except LinkError : return \"\" @ root . mount ( app = sub , path = '' ) def mount_sub ( ) : return sub ( ) c = Client ( root ( ) ) response = c . get ( '' ) assert response . body == b'' def test_defer_view_acquisition_blocking ( ) : class root ( morepath . App ) : pass class sub ( morepath . App ) : pass @ root . path ( path = '' ) class Model ( object ) : def __init__ ( self , id ) : self . id = id @ root . json ( model = Model ) def model_default ( self , request ) : return { \"\" : \"\" } @ sub . path ( path = '' ) class SubModel ( object ) : pass @ sub . json ( model = SubModel ) def sub_model_default ( self , request ) : return request . view ( Model ( '' ) ) is None @ root . mount ( app = sub , path = '' ) def mount_sub ( ) : return sub ( ) c = Client ( root ( ) ) response = c . get ( '' ) assert response . json is True def test_defer_link_should_not_cause_web_views_to_exist ( ) : class root ( morepath . App ) : pass class sub ( morepath . App ) : pass @ root . path ( path = '' ) class Model ( object ) : pass @ root . view ( model = Model ) def model_default ( self , request ) : return \"\" @ root . view ( model = Model , name = '' ) def model_extra ( self , request ) : return \"\" @ sub . path ( path = '' ) class SubModel ( Model ) : pass @ sub . view ( model = SubModel ) def sub_model_default ( self , request ) : return request . link ( Model ( ) ) @ root . mount ( app = sub , path = '' ) def mount_sub ( ) : return sub ( ) @ sub . defer_links ( model = Model ) def get_parent ( app , obj ) : return app . parent c = Client ( root ( ) ) response = c . get ( '' ) assert response . body == b'' c . get ( '' , status = ) def test_defer_link_to_parent_from_root ( ) : class root ( morepath . App ) : pass class sub ( morepath . App ) : ", "answer": "pass"}, {"prompt": " from oslo_log import log as logging from nova . i18n import _LW from nova . scheduler import filters from nova import servicegroup LOG = logging . getLogger ( __name__ ) class ComputeFilter ( filters . BaseHostFilter ) : \"\"\"\"\"\" def __init__ ( self ) : self . servicegroup_api = servicegroup . API ( ) run_filter_once_per_request = True def host_passes ( self , host_state , spec_obj ) : \"\"\"\"\"\" service = host_state . service if service [ '' ] : LOG . debug ( \"\" , { '' : host_state , '' : service . get ( '' ) } ) return False else : if not self . servicegroup_api . service_is_up ( service ) : LOG . warning ( _LW ( \"\" \"\" ) , { '' : host_state } ) ", "answer": "return False"}, {"prompt": " import mock from oslo_utils import uuidutils from neutron . agent . l3 import ha_router from neutron . tests import base _uuid = uuidutils . generate_uuid class TestBasicRouterOperations ( base . BaseTestCase ) : def setUp ( self ) : super ( TestBasicRouterOperations , self ) . setUp ( ) def _create_router ( self , router = None , ** kwargs ) : if not router : router = mock . MagicMock ( ) self . agent_conf = mock . Mock ( ) self . router_id = _uuid ( ) ", "answer": "return ha_router . HaRouter ( mock . sentinel . enqueue_state ,"}, {"prompt": " from subprocess import Popen from test_common import * import socket , ssl , time , os , signal if __name__ == \"\" : ghostunnel = None try : root = RootCert ( '' ) root . create_signed_cert ( '' ) root . create_signed_cert ( '' ) root . create_signed_cert ( '' ) ghostunnel = run_ghostunnel ( [ '' , '' . format ( LOCALHOST ) , '' . format ( LOCALHOST ) , '' , '' , '' , '' . format ( LOCALHOST , STATUS_PORT ) ] ) pair1 = SocketPair ( TlsClient ( '' , '' , ) , TcpServer ( ) ) ", "answer": "pair1 . validate_can_send_from_client ( \"\" , \"\" )"}, {"prompt": " import stubout from nova import exception from nova import flags from nova import vsa from nova import volume from nova import db from nova import context from nova import test from nova import log as logging import nova . image . fake FLAGS = flags . FLAGS LOG = logging . getLogger ( '' ) class VsaVolumesTestCase ( test . TestCase ) : def setUp ( self ) : super ( VsaVolumesTestCase , self ) . setUp ( ) self . stubs = stubout . StubOutForTesting ( ) self . vsa_api = vsa . API ( ) self . volume_api = volume . API ( ) self . context = context . get_admin_context ( ) self . default_vol_type = self . vsa_api . get_vsa_volume_type ( self . context ) def fake_show_by_name ( meh , context , name ) : return { '' : , '' : { '' : , '' : } } self . stubs . Set ( nova . image . fake . _FakeImageService , '' , fake_show_by_name ) param = { '' : '' } vsa_ref = self . vsa_api . create ( self . context , ** param ) self . vsa_id = vsa_ref [ '' ] def tearDown ( self ) : if self . vsa_id : self . vsa_api . delete ( self . context , self . vsa_id ) self . stubs . UnsetAll ( ) super ( VsaVolumesTestCase , self ) . tearDown ( ) def _default_volume_param ( self ) : return { '' : , '' : None , '' : '' , '' : '' , '' : self . default_vol_type , '' : { '' : self . vsa_id } } def _get_all_volumes_by_vsa ( self ) : return self . volume_api . get_all ( self . context , search_opts = { '' : { \"\" : str ( self . vsa_id ) } } ) def test_vsa_volume_create_delete ( self ) : \"\"\"\"\"\" volume_param = self . _default_volume_param ( ) volume_ref = self . volume_api . create ( self . context , ** volume_param ) self . assertEqual ( volume_ref [ '' ] , volume_param [ '' ] ) self . assertEqual ( volume_ref [ '' ] , volume_param [ '' ] ) self . assertEqual ( volume_ref [ '' ] , volume_param [ '' ] ) self . assertEqual ( volume_ref [ '' ] , '' ) vols2 = self . _get_all_volumes_by_vsa ( ) self . assertEqual ( , len ( vols2 ) ) volume_ref = vols2 [ ] self . assertEqual ( volume_ref [ '' ] , ", "answer": "volume_param [ '' ] )"}, {"prompt": " import os import os . path import sys ", "answer": "xdg = os . getenv ( '' ) or os . path . join ( os . getenv ( '' ) , '' )"}, {"prompt": " __author__ = '' import os import fnmatch import hashlib import sys import optparse import gzip from collections import defaultdict try : from cStringIO import StringIO except ImportError : from StringIO import StringIO import envoy import yaml import slimit import cssmin OUTPUT_DIR = '' CONFIG_FILE = '' ASSETS_INFO_FILE = '' def _log ( msg ) : sys . stderr . write ( '' % msg ) def load_config ( path ) : return yaml . load ( open ( path ) ) if sys . version < ( , ) : class GzipFile ( gzip . GzipFile ) : def __enter__ ( self ) : if self . fileobj is None : raise ValueError ( '' ) return self def __exit__ ( self , * args ) : self . close ( ) else : GzipFile = gzip . GzipFile class AssetManager ( object ) : \"\"\"\"\"\" def __init__ ( self , config , basedir = None ) : self . config = config self . basedir = basedir or os . getcwd ( ) def _get_bundles_by_type ( self , type ) : \"\"\"\"\"\" bundles = { } bundle_definitions = self . config . get ( type ) if bundle_definitions is None : return bundles for bundle_name , paths in bundle_definitions . items ( ) : bundle_files = [ ] for path in paths : pattern = abspath = os . path . join ( self . basedir , path ) assetdir = os . path . dirname ( abspath ) fnames = [ os . path . join ( assetdir , fname ) for fname in os . listdir ( assetdir ) ] expanded_fnames = fnmatch . filter ( fnames , pattern ) ", "answer": "bundle_files . extend ( sorted ( expanded_fnames ) )"}, {"prompt": " \"\"\"\"\"\" ", "answer": "__version__ = '' "}, {"prompt": " from __future__ import print_function import argparse import fileinput import os import sys from pre_commit_hooks . util import cmd_output def _fix_file ( filename , markdown = False ) : for line in fileinput . input ( [ filename ] , inplace = True ) : if markdown and ( not line . isspace ( ) ) and ( line . endswith ( \"\" ) ) : line = line . rstrip ( '' ) if not line [ - ] . isspace ( ) : print ( line + \"\" ) continue print ( line . rstrip ( ) ) def fix_trailing_whitespace ( argv = None ) : ", "answer": "parser = argparse . ArgumentParser ( )"}, {"prompt": " import copy import pecan from pecan import core from solum . api . controllers . camp . v1_1 . datamodel import types as camp_types from solum . api . controllers . camp . v1_1 import uris from solum . api . controllers import common_types from solum . api . controllers . v1 . datamodel import types as api_types from solum . api . handlers . camp import attribute_definition_handler class AttributeLink ( common_types . Link ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " \"\"\"\"\"\" def split_path ( path , minsegs = , maxsegs = None , rest_with_last = False ) : \"\"\"\"\"\" if not maxsegs : ", "answer": "maxsegs = minsegs"}, {"prompt": " \"\"\"\"\"\" __author__ = '' import logging import util class Range ( object ) : \"\"\"\"\"\" java_class = '' def __init__ ( self , start = , end = ) : \"\"\"\"\"\" self . start = start self . end = end if self . end - self . start < : raise ValueError ( '' ) def __str__ ( self ) : ", "answer": "return '' + str ( self . start ) + '' + str ( self . end ) + ''"}, {"prompt": " from __future__ import print_function import copy import os import sys import time import unittest from nose . plugins . skip import SkipTest from nose . tools import assert_raises import numpy from six . moves import xrange import theano from theano import tensor , config from theano . sandbox import rng_mrg from theano . sandbox . rng_mrg import MRG_RandomStreams from theano . sandbox . cuda import cuda_available from theano . tests import unittest_tools as utt from theano . tests . unittest_tools import attr if cuda_available : from theano . sandbox . cuda import float32_shared_constructor mode = config . mode mode_with_gpu = theano . compile . mode . get_default_mode ( ) . including ( '' ) utt . seed_rng ( ) java_samples = numpy . loadtxt ( os . path . join ( os . path . split ( theano . __file__ ) [ ] , '' , '' ) ) def test_deterministic ( ) : seed = utt . fetch_seed ( ) sample_size = ( , ) test_use_cuda = [ False ] if cuda_available : test_use_cuda . append ( True ) for use_cuda in test_use_cuda : R = MRG_RandomStreams ( seed = seed , use_cuda = use_cuda ) u = R . uniform ( size = sample_size ) f = theano . function ( [ ] , u ) fsample1 = f ( ) fsample2 = f ( ) assert not numpy . allclose ( fsample1 , fsample2 ) R2 = MRG_RandomStreams ( seed = seed , use_cuda = use_cuda ) u2 = R2 . uniform ( size = sample_size ) g = theano . function ( [ ] , u2 ) gsample1 = g ( ) gsample2 = g ( ) assert numpy . allclose ( fsample1 , gsample1 ) assert numpy . allclose ( fsample2 , gsample2 ) def test_consistency_randomstreams ( ) : \"\"\"\"\"\" seed = n_samples = n_streams = n_substreams = test_use_cuda = [ False ] if cuda_available : test_use_cuda . append ( True ) for use_cuda in test_use_cuda : samples = [ ] rng = MRG_RandomStreams ( seed = seed , use_cuda = use_cuda ) for i in range ( n_streams ) : stream_samples = [ ] u = rng . uniform ( size = ( n_substreams , ) , nstreams = n_substreams ) f = theano . function ( [ ] , u ) for j in range ( n_samples ) : s = f ( ) stream_samples . append ( s ) stream_samples = numpy . array ( stream_samples ) stream_samples = stream_samples . T . flatten ( ) samples . append ( stream_samples ) samples = numpy . array ( samples ) . flatten ( ) assert ( numpy . allclose ( samples , java_samples ) ) def test_consistency_cpu_serial ( ) : \"\"\"\"\"\" seed = n_samples = n_streams = n_substreams = samples = [ ] curr_rstate = numpy . array ( [ seed ] * , dtype = '' ) for i in range ( n_streams ) : stream_rstate = curr_rstate . copy ( ) for j in range ( n_substreams ) : rstate = theano . shared ( numpy . array ( [ stream_rstate . copy ( ) ] , dtype = '' ) ) new_rstate , sample = rng_mrg . mrg_uniform . new ( rstate , ndim = None , ", "answer": "dtype = config . floatX ,"}, {"prompt": " \"\"\"\"\"\" from . base import TethysGizmoOptions __all__ = [ '' , '' ] class ButtonGroup ( TethysGizmoOptions ) : \"\"\"\"\"\" def __init__ ( self , buttons , vertical = False , attributes = '' , classes = '' ) : \"\"\"\"\"\" super ( ButtonGroup , self ) . __init__ ( attributes = attributes , classes = classes ) self . buttons = buttons self . vertical = vertical class Button ( TethysGizmoOptions ) : \"\"\"\"\"\" ", "answer": "def __init__ ( self , display_text = '' , name = '' , style = '' , icon = '' , href = '' ,"}, {"prompt": " \"\"\"\"\"\" from django . core . management . base import NoArgsCommand from moztrap . model . core . auth import Role , Permission ROLES = { } ROLES [ \"\" ] = [ \"\" , ] ROLES [ \"\" ] = [ \"\" , \"\" , ] + ROLES [ \"\" ] ROLES [ \"\" ] = [ \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , \"\" , ] + ROLES [ \"\" ] ROLES [ \"\" ] = [ \"\" , ] + ROLES [ \"\" ] class Command ( NoArgsCommand ) : help = ( \"\" ) def handle_noargs ( self , ** options ) : verbosity = int ( options . get ( '' , ) ) for role_name , perms in ROLES . iteritems ( ) : role , created = Role . objects . get_or_create ( name = role_name ) if not created : if verbosity : print ( \"\" % role_name ) continue if verbosity : print ( \"\" % role_name ) for perm_label in perms : ", "answer": "app_label , codename = perm_label . split ( \"\" )"}, {"prompt": " from __future__ import absolute_import , division , with_statement from revolver import command , package from revolver . core import run def install ( ) : package . ensure ( \"\" ) ", "answer": "if not command . exists ( \"\" ) :"}, {"prompt": " from __future__ import unicode_literals import tests . backport_assert_raises from nose . tools import assert_raises import boto3 import boto from boto . exception import EC2ResponseError import sure from moto import mock_ec2 SAMPLE_DOMAIN_NAME = u'' SAMPLE_NAME_SERVERS = [ u'' , u'' ] @ mock_ec2 def test_dhcp_options_associate ( ) : \"\"\"\"\"\" conn = boto . connect_vpc ( '' , '' ) dhcp_options = conn . create_dhcp_options ( SAMPLE_DOMAIN_NAME , SAMPLE_NAME_SERVERS ) vpc = conn . create_vpc ( \"\" ) rval = conn . associate_dhcp_options ( dhcp_options . id , vpc . id ) rval . should . be . equal ( True ) @ mock_ec2 def test_dhcp_options_associate_invalid_dhcp_id ( ) : \"\"\"\"\"\" conn = boto . connect_vpc ( '' , '' ) vpc = conn . create_vpc ( \"\" ) with assert_raises ( EC2ResponseError ) as cm : conn . associate_dhcp_options ( \"\" , vpc . id ) cm . exception . code . should . equal ( '' ) cm . exception . status . should . equal ( ) cm . exception . request_id . should_not . be . none @ mock_ec2 def test_dhcp_options_associate_invalid_vpc_id ( ) : \"\"\"\"\"\" conn = boto . connect_vpc ( '' , '' ) dhcp_options = conn . create_dhcp_options ( SAMPLE_DOMAIN_NAME , SAMPLE_NAME_SERVERS ) with assert_raises ( EC2ResponseError ) as cm : conn . associate_dhcp_options ( dhcp_options . id , \"\" ) cm . exception . code . should . equal ( '' ) cm . exception . status . should . equal ( ) cm . exception . request_id . should_not . be . none @ mock_ec2 def test_dhcp_options_delete_with_vpc ( ) : \"\"\"\"\"\" conn = boto . connect_vpc ( '' , '' ) dhcp_options = conn . create_dhcp_options ( SAMPLE_DOMAIN_NAME , SAMPLE_NAME_SERVERS ) dhcp_options_id = dhcp_options . id vpc = conn . create_vpc ( \"\" ) rval = conn . associate_dhcp_options ( dhcp_options_id , vpc . id ) rval . should . be . equal ( True ) with assert_raises ( EC2ResponseError ) as cm : conn . delete_dhcp_options ( dhcp_options_id ) cm . exception . code . should . equal ( '' ) cm . exception . status . should . equal ( ) cm . exception . request_id . should_not . be . none vpc . delete ( ) with assert_raises ( EC2ResponseError ) as cm : conn . get_all_dhcp_options ( [ dhcp_options_id ] ) cm . exception . code . should . equal ( '' ) cm . exception . status . should . equal ( ) cm . exception . request_id . should_not . be . none @ mock_ec2 def test_create_dhcp_options ( ) : \"\"\"\"\"\" conn = boto . connect_vpc ( '' , '' ) dhcp_option = conn . create_dhcp_options ( SAMPLE_DOMAIN_NAME , SAMPLE_NAME_SERVERS ) dhcp_option . options [ u'' ] [ ] . should . be . equal ( SAMPLE_DOMAIN_NAME ) dhcp_option . options [ u'' ] [ ] . should . be . equal ( SAMPLE_NAME_SERVERS [ ] ) dhcp_option . options [ u'' ] [ ] . should . be . equal ( SAMPLE_NAME_SERVERS [ ] ) @ mock_ec2 def test_create_dhcp_options_invalid_options ( ) : \"\"\"\"\"\" conn = boto . connect_vpc ( '' , '' ) servers = [ \"\" , \"\" , \"\" , \"\" , \"\" ] with assert_raises ( EC2ResponseError ) as cm : conn . create_dhcp_options ( ntp_servers = servers ) cm . exception . code . should . equal ( '' ) cm . exception . status . should . equal ( ) cm . exception . request_id . should_not . be . none with assert_raises ( EC2ResponseError ) as cm : conn . create_dhcp_options ( netbios_node_type = \"\" ) cm . exception . code . should . equal ( '' ) cm . exception . status . should . equal ( ) cm . exception . request_id . should_not . be . none @ mock_ec2 def test_describe_dhcp_options ( ) : \"\"\"\"\"\" conn = boto . connect_vpc ( '' , '' ) dhcp_option = conn . create_dhcp_options ( ) dhcp_options = conn . get_all_dhcp_options ( [ dhcp_option . id ] ) dhcp_options . should . be . length_of ( ) dhcp_options = conn . get_all_dhcp_options ( ) dhcp_options . should . be . length_of ( ) @ mock_ec2 def test_describe_dhcp_options_invalid_id ( ) : \"\"\"\"\"\" conn = boto . connect_vpc ( '' , '' ) with assert_raises ( EC2ResponseError ) as cm : conn . get_all_dhcp_options ( [ \"\" ] ) cm . exception . code . should . equal ( '' ) cm . exception . status . should . equal ( ) cm . exception . request_id . should_not . be . none @ mock_ec2 def test_delete_dhcp_options ( ) : \"\"\"\"\"\" conn = boto . connect_vpc ( '' , '' ) dhcp_option = conn . create_dhcp_options ( ) dhcp_options = conn . get_all_dhcp_options ( [ dhcp_option . id ] ) dhcp_options . should . be . length_of ( ) conn . delete_dhcp_options ( dhcp_option . id ) with assert_raises ( EC2ResponseError ) as cm : conn . get_all_dhcp_options ( [ dhcp_option . id ] ) cm . exception . code . should . equal ( '' ) cm . exception . status . should . equal ( ) cm . exception . request_id . should_not . be . none @ mock_ec2 def test_delete_dhcp_options_invalid_id ( ) : conn = boto . connect_vpc ( '' , '' ) conn . create_dhcp_options ( ) with assert_raises ( EC2ResponseError ) as cm : conn . delete_dhcp_options ( \"\" ) cm . exception . code . should . equal ( '' ) cm . exception . status . should . equal ( ) cm . exception . request_id . should_not . be . none @ mock_ec2 def test_delete_dhcp_options_malformed_id ( ) : conn = boto . connect_vpc ( '' , '' ) conn . create_dhcp_options ( ) with assert_raises ( EC2ResponseError ) as cm : conn . delete_dhcp_options ( \"\" ) cm . exception . code . should . equal ( '' ) cm . exception . status . should . equal ( ) cm . exception . request_id . should_not . be . none @ mock_ec2 def test_dhcp_tagging ( ) : conn = boto . connect_vpc ( '' , '' ) dhcp_option = conn . create_dhcp_options ( ) dhcp_option . add_tag ( \"\" , \"\" ) tag = conn . get_all_tags ( ) [ ] tag . name . should . equal ( \"\" ) tag . value . should . equal ( \"\" ) dhcp_option = conn . get_all_dhcp_options ( ) [ ] dhcp_option . tags . should . have . length_of ( ) dhcp_option . tags [ \"\" ] . should . equal ( \"\" ) @ mock_ec2 def test_dhcp_options_get_by_tag ( ) : conn = boto . connect_vpc ( '' , '' ) dhcp1 = conn . create_dhcp_options ( '' , [ '' ] ) dhcp1 . add_tag ( '' , '' ) dhcp1 . add_tag ( '' , '' ) dhcp2 = conn . create_dhcp_options ( '' , [ '' ] ) dhcp2 . add_tag ( '' , '' ) dhcp2 . add_tag ( '' , '' ) filters = { '' : '' , '' : '' } dhcp_options_sets = conn . get_all_dhcp_options ( filters = filters ) dhcp_options_sets . should . have . length_of ( ) dhcp_options_sets [ ] . options [ '' ] [ ] . should . be . equal ( '' ) dhcp_options_sets [ ] . options [ '' ] [ ] . should . be . equal ( '' ) dhcp_options_sets [ ] . tags [ '' ] . should . equal ( '' ) dhcp_options_sets [ ] . tags [ '' ] . should . equal ( '' ) filters = { '' : '' , '' : '' } dhcp_options_sets = conn . get_all_dhcp_options ( filters = filters ) dhcp_options_sets . should . have . length_of ( ) dhcp_options_sets [ ] . options [ '' ] [ ] . should . be . equal ( '' ) dhcp_options_sets [ ] . options [ '' ] [ ] . should . be . equal ( '' ) dhcp_options_sets [ ] . tags [ '' ] . should . equal ( '' ) dhcp_options_sets [ ] . tags [ '' ] . should . equal ( '' ) filters = { '' : '' } dhcp_options_sets = conn . get_all_dhcp_options ( filters = filters ) dhcp_options_sets . should . have . length_of ( ) @ mock_ec2 def test_dhcp_options_get_by_id ( ) : conn = boto . connect_vpc ( '' , '' ) dhcp1 = conn . create_dhcp_options ( '' , [ '' ] ) dhcp1 . add_tag ( '' , '' ) dhcp1 . add_tag ( '' , '' ) dhcp1_id = dhcp1 . id dhcp2 = conn . create_dhcp_options ( '' , [ '' ] ) dhcp2 . add_tag ( '' , '' ) dhcp2 . add_tag ( '' , '' ) dhcp2_id = dhcp2 . id dhcp_options_sets = conn . get_all_dhcp_options ( ) dhcp_options_sets . should . have . length_of ( ) dhcp_options_sets = conn . get_all_dhcp_options ( filters = { '' : dhcp1_id } ) dhcp_options_sets . should . have . length_of ( ) dhcp_options_sets [ ] . options [ '' ] [ ] . should . be . equal ( '' ) dhcp_options_sets [ ] . options [ '' ] [ ] . should . be . equal ( '' ) dhcp_options_sets = conn . get_all_dhcp_options ( filters = { '' : dhcp2_id } ) dhcp_options_sets . should . have . length_of ( ) dhcp_options_sets [ ] . options [ '' ] [ ] . should . be . equal ( '' ) dhcp_options_sets [ ] . options [ '' ] [ ] . should . be . equal ( '' ) @ mock_ec2 def test_dhcp_options_get_by_value_filter ( ) : ec2 = boto3 . resource ( '' , region_name = '' ) ec2 . create_dhcp_options ( DhcpConfigurations = [ { '' : '' , '' : [ '' ] } , { '' : '' , '' : [ '' ] } ] ) ec2 . create_dhcp_options ( DhcpConfigurations = [ { '' : '' , '' : [ '' ] } , ", "answer": "{ '' : '' , '' : [ '' ] }"}, {"prompt": " \"\"\"\"\"\" from httpretty import HTTPretty from cloudcafe . compute . hosts_api . client import HostsClient from metatests . cloudcafe . compute . fixtures import ClientTestFixture from metatests . cloudcafe . compute . hosts . client . responses import HostsMockResponse HOST_NAME = \"\" class HostsClientTest ( ClientTestFixture ) : ", "answer": "@ classmethod"}, {"prompt": " \"\"\"\"\"\" from __future__ import unicode_literals from future . builtins import range from django . conf import settings from django . utils . translation import ugettext_lazy as _ from mezzanine . conf import register_setting generic_comments = getattr ( settings , \"\" , \"\" ) == \"\" if generic_comments : register_setting ( name = \"\" , label = _ ( \"\" ) , description = _ ( \"\" ) , editable = True , default = False , ) register_setting ( name = \"\" , label = _ ( \"\" ) , description = _ ( \"\" ", "answer": "\"\" ) ,"}, {"prompt": " from __future__ import unicode_literals ", "answer": "from django . db import migrations , models"}, {"prompt": " import json import hashlib import os from markwiki . exceptions import UserStorageError from markwiki . models . user import User from markwiki . storage . user import UserStorage class FileUserStorage ( UserStorage ) : '''''' def __init__ ( self , config ) : self . _path = os . path . join ( config [ '' ] , '' ) self . _id_index_file = os . path . join ( self . _path , '' ) self . _id_index = { } self . _email_index_file = os . path . join ( self . _path , '' ) self . _email_index = { } def initialize ( self ) : if not os . path . exists ( self . _path ) : os . mkdir ( self . _path ) self . _write_json ( self . _id_index , self . _id_index_file ) self . _write_json ( self . _email_index , self . _email_index_file ) else : self . _read_indices ( ) def create ( self , user ) : '''''' user_file = self . _get_user_file ( user . name ) if os . path . exists ( user_file ) : raise UserStorageError ( '' ) if self . find_by_email ( user . email ) is not None : raise UserStorageError ( '' ) user . user_id = self . _generate_user_id ( ) self . _write_json ( user . __dict__ , user_file ) self . _update_indices ( user , user_file ) def find_by_email ( self , email ) : '''''' user_file = self . _email_index . get ( email ) if user_file is None : return None return self . _load_user ( user_file ) ", "answer": "def find_by_id ( self , user_id ) :"}, {"prompt": " import math def tolerant_equals ( a , b , atol = , rtol = ) : return math . fabs ( a - b ) <= ( atol + rtol * math . fabs ( b ) ) try : import bottleneck as bn nanmean = bn . nanmean nanstd = bn . nanstd nansum = bn . nansum nanmax = bn . nanmax nanmin = bn . nanmin nanargmax = bn . nanargmax nanargmin = bn . nanargmin except ImportError : import numpy as np nanmean = np . nanmean nanstd = np . nanstd nansum = np . nansum nanmax = np . nanmax nanmin = np . nanmin nanargmax = np . nanargmax nanargmin = np . nanargmin def round_if_near_integer ( a , epsilon = ) : \"\"\"\"\"\" ", "answer": "if abs ( a - round ( a ) ) <= epsilon :"}, {"prompt": " \"\"\"\"\"\" import os , shutil , sys , tempfile from optparse import OptionParser tmpeggs = tempfile . mkdtemp ( ) usage = '''''' parser = OptionParser ( usage = usage ) parser . add_option ( \"\" , \"\" , help = \"\" ) parser . add_option ( \"\" , \"\" , dest = '' , action = \"\" , default = False , help = ( \"\" \"\" \"\" \"\" \"\" ", "answer": "\"\" ) )"}, {"prompt": " \"\"\"\"\"\" __version__ = \"\" import tokenize import os , shutil import sys verbose = recurse = dryrun = makebackup = True def usage ( msg = None ) : if msg is not None : print >> sys . stderr , msg print >> sys . stderr , __doc__ def errprint ( * args ) : sep = \"\" for arg in args : sys . stderr . write ( sep + str ( arg ) ) sep = \"\" sys . stderr . write ( \"\" ) def main ( ) : import getopt global verbose , recurse , dryrun , makebackup try : opts , args = getopt . getopt ( sys . argv [ : ] , \"\" , [ \"\" , \"\" , \"\" , \"\" , \"\" ] ) except getopt . error , msg : usage ( msg ) return for o , a in opts : if o in ( '' , '' ) : dryrun += elif o in ( '' , '' ) : recurse += elif o in ( '' , '' ) : makebackup = False elif o in ( '' , '' ) : verbose += elif o in ( '' , '' ) : usage ( ) return if not args : r = Reindenter ( sys . stdin ) r . run ( ) r . write ( sys . stdout ) return for arg in args : check ( arg ) def check ( file ) : if os . path . isdir ( file ) and not os . path . islink ( file ) : if verbose : print \"\" , file names = os . listdir ( file ) for name in names : fullname = os . path . join ( file , name ) if ( ( recurse and os . path . isdir ( fullname ) and not os . path . islink ( fullname ) and not os . path . split ( fullname ) [ ] . startswith ( \"\" ) ) or name . lower ( ) . endswith ( \"\" ) ) : check ( fullname ) return if verbose : print \"\" , file , \"\" , try : f = open ( file ) except IOError , msg : errprint ( \"\" % ( file , str ( msg ) ) ) return r = Reindenter ( f ) f . close ( ) if r . run ( ) : if verbose : print \"\" if dryrun : print \"\" if not dryrun : bak = file + \"\" if makebackup : shutil . copyfile ( file , bak ) if verbose : print \"\" , file , \"\" , bak f = open ( file , \"\" ) r . write ( f ) f . close ( ) if verbose : print \"\" , file return True else : if verbose : print \"\" return False def _rstrip ( line , JUNK = '' ) : \"\"\"\"\"\" i = len ( line ) while i > and line [ i - ] in JUNK : i -= return line [ : i ] class Reindenter : def __init__ ( self , f ) : self . find_stmt = self . level = self . raw = f . readlines ( ) self . lines = [ _rstrip ( line ) . expandtabs ( ) + \"\" for line in self . raw ] self . lines . insert ( , None ) self . index = self . stats = [ ] def run ( self ) : tokenize . tokenize ( self . getline , self . tokeneater ) lines = self . lines while lines and lines [ - ] == \"\" : lines . pop ( ) stats = self . stats stats . append ( ( len ( lines ) , ) ) have2want = { } after = self . after = [ ] i = stats [ ] [ ] after . extend ( lines [ : i ] ) for i in range ( len ( stats ) - ) : thisstmt , thislevel = stats [ i ] nextstmt = stats [ i + ] [ ] have = getlspace ( lines [ thisstmt ] ) want = thislevel * if want < : if have : want = have2want . get ( have , - ) if want < : for j in xrange ( i + , len ( stats ) - ) : jline , jlevel = stats [ j ] if jlevel >= : if have == getlspace ( lines [ jline ] ) : want = jlevel * break if want < : for j in xrange ( i - , - , - ) : jline , jlevel = stats [ j ] if jlevel >= : want = have + getlspace ( after [ jline - ] ) - getlspace ( lines [ jline ] ) break if want < : want = have else : want = assert want >= have2want [ have ] = want diff = want - have if diff == or have == : after . extend ( lines [ thisstmt : nextstmt ] ) else : for line in lines [ thisstmt : nextstmt ] : if diff > : if line == \"\" : after . append ( line ) else : after . append ( \"\" * diff + line ) else : remove = min ( getlspace ( line ) , - diff ) after . append ( line [ remove : ] ) return self . raw != self . after def write ( self , f ) : f . writelines ( self . after ) def getline ( self ) : if self . index >= len ( self . lines ) : line = \"\" else : line = self . lines [ self . index ] self . index += return line def tokeneater ( self , type , token , ( sline , scol ) , end , line , INDENT = tokenize . INDENT , DEDENT = tokenize . DEDENT , NEWLINE = tokenize . NEWLINE , COMMENT = tokenize . COMMENT , NL = tokenize . NL ) : if type == NEWLINE : self . find_stmt = elif type == INDENT : self . find_stmt = self . level += elif type == DEDENT : self . find_stmt = self . level -= elif type == COMMENT : if self . find_stmt : self . stats . append ( ( sline , - ) ) elif type == NL : pass ", "answer": "elif self . find_stmt :"}, {"prompt": " from django . core . urlresolvers import reverse from unittest . mock import patch from orchestra . tests . helpers import OrchestraAuthenticatedTestCase from orchestra . models import CommunicationPreference from orchestra . tests . helpers . fixtures import WorkerFactory from orchestra . tests . helpers . fixtures import setup_models class AccountSettingsTest ( OrchestraAuthenticatedTestCase ) : def setUp ( self ) : super ( ) . setUp ( ) self . request_client , self . user = self . authenticate_user ( ) self . url = reverse ( '' ) self . worker = WorkerFactory ( user = self . user ) def _get_account_settings_mock_data ( self ) : return { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , } def test_get_form ( self ) : response = self . request_client . get ( self . url ) self . assertEqual ( response . status_code , ) self . assertTemplateUsed ( response , '' ) @ patch ( '' ) def test_change_all_fields ( self , mock_get_slack_user_id ) : mock_get_slack_user_id . return_value = '' data = self . _get_account_settings_mock_data ( ) response = self . request_client . post ( self . url , data ) self . assertTrue ( response . context [ '' ] ) self . user . refresh_from_db ( ) self . assertEqual ( self . user . first_name , data [ '' ] ) self . assertEqual ( self . user . last_name , data [ '' ] ) self . worker . refresh_from_db ( ) self . assertEqual ( self . worker . slack_username , data [ '' ] ) self . assertEqual ( self . worker . phone , data [ '' ] + data [ '' ] ) self . assertEqual ( self . worker . slack_user_id , '' ) @ patch ( '' ) def test_missing_fields ( self , mock_get_slack_user_id ) : ", "answer": "mock_get_slack_user_id . return_value = ''"}, {"prompt": " \"\"\"\"\"\" from django . core . exceptions import ImproperlyConfigured ", "answer": "raise ImproperlyConfigured ( '' )"}, {"prompt": " import mimeparse def determine_format ( request , serializer , default_format = '' ) : \"\"\"\"\"\" if request . GET . get ( '' ) : if request . GET [ '' ] in serializer . formats : ", "answer": "return serializer . get_mime_for_format ( request . GET [ '' ] )"}, {"prompt": " import tornado . web import waterbutler class StatusHandler ( tornado . web . RequestHandler ) : def get ( self ) : \"\"\"\"\"\" ", "answer": "self . write ( {"}, {"prompt": " from __future__ import absolute_import import os import collections import ConfigParser NoDefault = object ( ) SECTIONS = collections . OrderedDict ( ) class attrdict ( dict ) : \"\" def __init__ ( self , * args , ** kwargs ) : dict . __init__ ( self , * args , ** kwargs ) self . __dict__ = self class ConfigurationError ( Exception ) : \"\" def __init__ ( self , section , name , message ) : self . section = section self . name = name self . message = message def __str__ ( self ) : return '' % ( self . section , self . name , self . message ) def boolean ( input ) : \"\"\"\"\"\" if input . lower ( ) in ( \"\" , \"\" ) : return True elif input . lower ( ) in ( \"\" , \"\" ) : return False else : raise ValueError ( '' % input ) class Option ( object ) : \"\" def __init__ ( self , convert , default = NoDefault , validator = None ) : self . convert = convert self . default = default self . validator = validator def _make_extractor ( cls , prefix = \"\" , required = True ) : section_name = cls . __name__ [ : - len ( \"\" ) ] . lower ( ) if prefix : section_name = prefix + \"\" + section_name def config_extractor ( parser ) : section = attrdict ( ) for name , option_def in vars ( cls ) . iteritems ( ) : if not isinstance ( option_def , Option ) : continue try : value = parser . get ( section_name , name ) except ( ConfigParser . NoSectionError , ConfigParser . NoOptionError ) : if option_def . default is NoDefault : raise ConfigurationError ( section_name , name , \"\" ) value = option_def . default else : try : value = option_def . convert ( value ) except Exception , e : raise ConfigurationError ( section_name , name , e ) section [ name ] = value return section config_extractor . required = required config_extractor . prefix = prefix SECTIONS [ section_name ] = config_extractor def config_section ( * args , ** kwargs ) : if len ( args ) == and not kwargs : return _make_extractor ( args [ ] ) def config_decorator ( cls ) : return _make_extractor ( cls , ** kwargs ) return config_decorator @ config_section class SshConfig ( object ) : user = Option ( str ) key_filename = Option ( str , default = None ) strict_host_key_checking = Option ( boolean , default = True ) timeout = Option ( int , default = ) @ config_section class DeployConfig ( object ) : build_host = Option ( str ) deploy_binary = Option ( str ) build_binary = Option ( str ) ", "answer": "@ config_section"}, {"prompt": " '''''' def multiply ( a , b ) : \"\"\"\"\"\" ", "answer": "return a * b "}, {"prompt": " import functools import random import netaddr from neutron . tests . common . exclusive_resources import resource_allocator def get_random_ip ( low , high ) : parent_range = netaddr . IPRange ( low , high ) return str ( random . choice ( parent_range ) ) class ExclusiveIPAddress ( resource_allocator . ExclusiveResource ) : \"\"\"\"\"\" def __init__ ( self , low , high ) : super ( ExclusiveIPAddress , self ) . __init__ ( ", "answer": "'' , functools . partial ( get_random_ip , low , high ) )"}, {"prompt": " zoo_animals = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' } del zoo_animals [ '' ] ", "answer": "del zoo_animals [ '' ]"}, {"prompt": " \"\"\"\"\"\" from setuptools import setup setup ( name = '' , version = '' , url = '' , license = '' , author = '' , author_email = '' , description = '' , long_description = __doc__ , packages = [ '' , ] , zip_safe = False , platforms = '' , install_requires = [ ", "answer": "''"}, {"prompt": " import os import spur import spur . ssh def create_ssh_shell ( missing_host_key = None , shell_type = None ) : port_var = os . environ . get ( \"\" ) port = int ( port_var ) if port_var is not None else None return spur . SshShell ( hostname = os . environ . get ( \"\" , \"\" ) , username = os . environ [ \"\" ] , ", "answer": "password = os . environ [ \"\" ] ,"}, {"prompt": " from django import forms ", "answer": "class DateForm ( forms . Form ) :"}, {"prompt": " '''''' from __future__ import absolute_import from salttesting import skipIf , TestCase from salttesting . helpers import ensure_in_syspath from salttesting . mock import ( NO_MOCK , NO_MOCK_REASON , MagicMock , patch ) ensure_in_syspath ( '' ) from salt . states import alias alias . __opts__ = { } alias . __salt__ = { } @ skipIf ( NO_MOCK , NO_MOCK_REASON ) class AliasTest ( TestCase ) : '''''' def test_present_has_target ( self ) : '''''' name = '' target = '' ret = { '' : '' . format ( name ) , '' : { } , '' : name , '' : True } has_target = MagicMock ( return_value = True ) with patch . dict ( alias . __salt__ , { '' : has_target } ) : self . assertEqual ( alias . present ( name , target ) , ret ) def test_present_has_not_target_test ( self ) : '''''' name = '' target = '' ret = { '' : '' . format ( name , target ) , '' : { } , '' : name , '' : None } has_target = MagicMock ( return_value = False ) with patch . dict ( alias . __salt__ , { '' : has_target } ) : with patch . dict ( alias . __opts__ , { '' : True } ) : self . assertEqual ( alias . present ( name , target ) , ret ) def test_present_set_target ( self ) : '''''' name = '' target = '' ret = { '' : '' . format ( name , target ) , '' : { '' : name } , '' : name , '' : True } has_target = MagicMock ( return_value = False ) set_target = MagicMock ( return_value = True ) with patch . dict ( alias . __salt__ , { '' : has_target } ) : with patch . dict ( alias . __opts__ , { '' : False } ) : ", "answer": "with patch . dict ( alias . __salt__ , { '' : set_target } ) :"}, {"prompt": " import os import base64 from django . db . models import F , Q ", "answer": "from xos . config import Config"}, {"prompt": " \"\"\"\"\"\" def grade ( autogen , key ) : if '' in key : return ( True , '' ) else : ", "answer": "return ( False , '' ) "}, {"prompt": " from __future__ import ( absolute_import , division , generators , nested_scopes , print_function , ", "answer": "unicode_literals , with_statement )"}, {"prompt": " import sys from pyswip . core import * class PrologError ( Exception ) : pass class NestedQueryError ( PrologError ) : \"\"\"\"\"\" pass def _initialize ( ) : args = [ ] args . append ( \"\" ) args . append ( \"\" ) args . append ( \"\" ) if SWI_HOME_DIR is not None : args . append ( \"\" % SWI_HOME_DIR ) result = PL_initialise ( len ( args ) , args ) if not result : raise PrologError ( \"\" \"\" % result ) swipl_fid = PL_open_foreign_frame ( ) swipl_load = PL_new_term_ref ( ) PL_chars_to_term ( \"\" \"\" \"\" \"\" , swipl_load ) PL_call ( swipl_load , None ) PL_discard_foreign_frame ( swipl_fid ) _initialize ( ) from pyswip . easy import getTerm class Prolog : \"\"\"\"\"\" _queryIsOpen = False class _QueryWrapper ( object ) : def __init__ ( self ) : if Prolog . _queryIsOpen : raise NestedQueryError ( \"\" ) def __call__ ( self , query , maxresult , catcherrors , normalize ) : swipl_fid = PL_open_foreign_frame ( ) swipl_head = PL_new_term_ref ( ) swipl_args = PL_new_term_refs ( ) swipl_goalCharList = swipl_args swipl_bindingList = swipl_args + PL_put_list_chars ( swipl_goalCharList , query ) swipl_predicate = PL_predicate ( \"\" , , None ) plq = catcherrors and ( PL_Q_NODEBUG | PL_Q_CATCH_EXCEPTION ) or PL_Q_NORMAL swipl_qid = PL_open_query ( None , plq , swipl_predicate , swipl_args ) Prolog . _queryIsOpen = True try : while maxresult and PL_next_solution ( swipl_qid ) : maxresult -= bindings = [ ] swipl_list = PL_copy_term_ref ( swipl_bindingList ) t = getTerm ( swipl_list ) if normalize : try : v = t . value except AttributeError : v = { } for r in [ x . value for x in t ] : v . update ( r ) yield v else : yield t if PL_exception ( swipl_qid ) : term = getTerm ( PL_exception ( swipl_qid ) ) raise PrologError ( \"\" . join ( [ \"\" , query , \"\" , \"\" , str ( term ) , \"\" ] ) ) finally : PL_cut_query ( swipl_qid ) PL_discard_foreign_frame ( swipl_fid ) Prolog . _queryIsOpen = False def asserta ( cls , assertion , catcherrors = False ) : next ( cls . query ( assertion . join ( [ \"\" , \"\" ] ) , catcherrors = catcherrors ) ) asserta = classmethod ( asserta ) def assertz ( cls , assertion , catcherrors = False ) : ", "answer": "next ( cls . query ( assertion . join ( [ \"\" , \"\" ] ) , catcherrors = catcherrors ) )"}, {"prompt": " from . import command from . import hook from . import utils from . import xcbq from six import MAXSIZE import warnings class Key ( object ) : \"\"\"\"\"\" def __init__ ( self , modifiers , key , * commands , ** kwds ) : self . modifiers = modifiers self . key = key self . commands = commands self . desc = kwds . get ( \"\" , \"\" ) if key not in xcbq . keysyms : raise utils . QtileError ( \"\" % key ) self . keysym = xcbq . keysyms [ key ] try : self . modmask = utils . translate_masks ( self . modifiers ) except KeyError as v : raise utils . QtileError ( v ) def __repr__ ( self ) : return \"\" % ( self . modifiers , self . key ) class Drag ( object ) : \"\"\"\"\"\" def __init__ ( self , modifiers , button , * commands , ** kwargs ) : self . start = kwargs . get ( \"\" ) self . focus = kwargs . get ( \"\" , \"\" ) self . modifiers = modifiers self . button = button self . commands = commands try : self . button_code = int ( self . button . replace ( '' , '' ) ) self . modmask = utils . translate_masks ( self . modifiers ) except KeyError as v : raise utils . QtileError ( v ) def __repr__ ( self ) : return \"\" % ( self . modifiers , self . button ) class Click ( object ) : \"\"\"\"\"\" def __init__ ( self , modifiers , button , * commands , ** kwargs ) : self . focus = kwargs . get ( \"\" , \"\" ) self . modifiers = modifiers self . button = button self . commands = commands try : self . button_code = int ( self . button . replace ( '' , '' ) ) self . modmask = utils . translate_masks ( self . modifiers ) except KeyError as v : raise utils . QtileError ( v ) def __repr__ ( self ) : return \"\" % ( self . modifiers , self . button ) class EzConfig ( object ) : \"\"\"\"\"\" modifier_keys = { '' : '' , '' : '' , '' : '' , '' : '' , } def parse ( self , spec ) : \"\"\"\"\"\" mods = [ ] keys = [ ] for key in spec . split ( '' ) : if not key : break if key in self . modifier_keys : if keys : msg = '' raise utils . QtileError ( msg % spec ) mods . append ( self . modifier_keys [ key ] ) continue if len ( key ) == : keys . append ( key ) continue if len ( key ) > and key [ ] == '' and key [ - ] == '>' : keys . append ( key [ : - ] ) continue if not keys : msg = '' raise utils . QtileError ( msg % spec ) if len ( keys ) > : msg = '' % spec raise utils . QtileError ( msg ) return mods , keys [ ] class EzKey ( EzConfig , Key ) : def __init__ ( self , keydef , * commands ) : modkeys , key = self . parse ( keydef ) super ( EzKey , self ) . __init__ ( modkeys , key , * commands ) class EzClick ( EzConfig , Click ) : def __init__ ( self , btndef , * commands , ** kwargs ) : modkeys , button = self . parse ( btndef ) button = '' % button super ( EzClick , self ) . __init__ ( modkeys , button , * commands , ** kwargs ) class EzDrag ( EzConfig , Drag ) : def __init__ ( self , btndef , * commands , ** kwargs ) : modkeys , button = self . parse ( btndef ) button = '' % button super ( EzDrag , self ) . __init__ ( modkeys , button , * commands , ** kwargs ) class ScreenRect ( object ) : def __init__ ( self , x , y , width , height ) : self . x = x self . y = y self . width = width self . height = height def __repr__ ( self ) : return '' % ( self . __class__ . __name__ , self . x , self . y , self . width , self . height ) def hsplit ( self , columnwidth ) : assert columnwidth > assert columnwidth < self . width return ( self . __class__ ( self . x , self . y , columnwidth , self . height ) , self . __class__ ( self . x + columnwidth , self . y , self . width - columnwidth , self . height ) ) def vsplit ( self , rowheight ) : assert rowheight > assert rowheight < self . height return ( self . __class__ ( self . x , self . y , self . width , rowheight ) , self . __class__ ( self . x , self . y + rowheight , self . width , self . height - rowheight ) ) class Screen ( command . CommandObject ) : \"\"\"\"\"\" def __init__ ( self , top = None , bottom = None , left = None , right = None , x = None , y = None , width = None , height = None ) : self . group = None self . previous_group = None self . top = top self . bottom = bottom self . left = left self . right = right self . qtile = None self . index = None self . x = x self . y = y self . width = width self . height = height def _configure ( self , qtile , index , x , y , width , height , group ) : self . qtile = qtile self . index = index self . x = x self . y = y self . width = width self . height = height self . setGroup ( group ) for i in self . gaps : i . _configure ( qtile , self ) @ property def gaps ( self ) : return ( i for i in [ self . top , self . bottom , self . left , self . right ] if i ) @ property def dx ( self ) : return self . x + self . left . size if self . left else self . x @ property def dy ( self ) : return self . y + self . top . size if self . top else self . y @ property def dwidth ( self ) : val = self . width if self . left : val -= self . left . size if self . right : val -= self . right . size return val @ property def dheight ( self ) : val = self . height if self . top : val -= self . top . size if self . bottom : val -= self . bottom . size return val def get_rect ( self ) : return ScreenRect ( self . dx , self . dy , self . dwidth , self . dheight ) def setGroup ( self , new_group , save_prev = True ) : \"\"\"\"\"\" if new_group . screen == self : return if save_prev : self . previous_group = self . group if new_group is None : return if new_group . screen : g1 = self . group s1 = self g2 = new_group s2 = new_group . screen s2 . group = g1 g1 . _setScreen ( s2 ) s1 . group = g2 g2 . _setScreen ( s1 ) else : old_group = self . group self . group = new_group new_group . _setScreen ( self ) if old_group is not None : old_group . _setScreen ( None ) hook . fire ( \"\" ) hook . fire ( \"\" ) hook . fire ( \"\" , self . group . layouts [ self . group . currentLayout ] , self . group ) def _items ( self , name ) : if name == \"\" : return ( True , list ( range ( len ( self . group . layouts ) ) ) ) elif name == \"\" : return ( True , [ i . window . wid for i in self . group . windows ] ) elif name == \"\" : return ( False , [ x . position for x in self . gaps ] ) def _select ( self , name , sel ) : if name == \"\" : if sel is None : return self . group . layout else : return utils . lget ( self . group . layouts , sel ) elif name == \"\" : if sel is None : return self . group . currentWindow else : for i in self . group . windows : if i . window . wid == sel : return i elif name == \"\" : return getattr ( self , sel ) def resize ( self , x = None , y = None , w = None , h = None ) : x = x or self . x y = y or self . y w = w or self . width h = h or self . height self . _configure ( self . qtile , self . index , x , y , w , h , self . group ) for bar in [ self . top , self . bottom , self . left , self . right ] : if bar : bar . draw ( ) self . qtile . call_soon ( self . group . layoutAll ( ) ) def cmd_info ( self ) : \"\"\"\"\"\" return dict ( index = self . index , width = self . width , height = self . height , x = self . x , y = self . y ) def cmd_resize ( self , x = None , y = None , w = None , h = None ) : \"\"\"\"\"\" self . resize ( x , y , w , h ) def cmd_next_group ( self , skip_empty = False , skip_managed = False ) : \"\"\"\"\"\" n = self . group . nextGroup ( skip_empty , skip_managed ) self . setGroup ( n ) return n . name ", "answer": "def cmd_prev_group ( self , skip_empty = False , skip_managed = False ) :"}, {"prompt": " \"\"\"\"\"\" import copy import copy_reg import numbers import pint class _UnitRegistry ( pint . UnitRegistry ) : \"\"\"\"\"\" def __init__ ( self ) : super ( _UnitRegistry , self ) . __init__ ( ) self . define ( '' ) self . define ( '' ) def parse_expression ( self , input_string , * args , ** kwargs ) : result = super ( _UnitRegistry , self ) . parse_expression ( input_string , * args , ** kwargs ) if ( isinstance ( result , numbers . Number ) and input_string . strip ( ) . endswith ( '' ) ) : return self . Quantity ( result , self . Unit ( '' ) ) return result _UNIT_REGISTRY = _UnitRegistry ( ) ", "answer": "def _PickleQuantity ( q ) :"}, {"prompt": " \"\"\"\"\"\" import os from PyQt4 import QtGui , uic from util import Util FORM_CLASS , _ = uic . loadUiType ( os . path . join ( ", "answer": "os . path . dirname ( __file__ ) , '' ) )"}, {"prompt": " import pprint import sys import spotipy import spotipy . util as util import simplejson as json if len ( sys . argv ) > : username = sys . argv [ ] else : print ( \"\" % ( sys . argv [ ] , ) ) sys . exit ( ) scope = '' token = util . prompt_for_user_token ( username , scope ) ", "answer": "if token :"}, {"prompt": " import py import sys , os , re from pypy . rlib . rarithmetic import r_longlong from pypy . rlib . debug import ll_assert , debug_print from pypy . translator . translator import TranslationContext from pypy . translator . backendopt import all from pypy . translator . c . genc import CStandaloneBuilder , ExternalCompilationInfo from pypy . annotation . listdef import s_list_of_strings from pypy . tool . udir import udir from pypy . tool . autopath import pypydir class TestStandalone ( object ) : config = None def test_hello_world ( self ) : def entry_point ( argv ) : os . write ( , \"\" ) argv = argv [ : ] os . write ( , \"\" + str ( len ( argv ) ) + \"\" ) for s in argv : os . write ( , \"\" + str ( s ) + \"\" ) return t = TranslationContext ( self . config ) t . buildannotator ( ) . build_types ( entry_point , [ s_list_of_strings ] ) t . buildrtyper ( ) . specialize ( ) cbuilder = CStandaloneBuilder ( t , entry_point , t . config ) cbuilder . generate_source ( ) cbuilder . compile ( ) data = cbuilder . cmdexec ( '' ) assert data . startswith ( '''''' ) def test_print ( self ) : def entry_point ( argv ) : print \"\" argv = argv [ : ] print \"\" , len ( argv ) print \"\" , argv print \"\" , print [ len ( s ) for s in argv ] return t = TranslationContext ( self . config ) t . buildannotator ( ) . build_types ( entry_point , [ s_list_of_strings ] ) t . buildrtyper ( ) . specialize ( ) cbuilder = CStandaloneBuilder ( t , entry_point , t . config ) cbuilder . generate_source ( ) cbuilder . compile ( ) data = cbuilder . cmdexec ( '' ) assert data . startswith ( '''''' '''''' '''''' '''''' ) def test_counters ( self ) : from pypy . rpython . lltypesystem import lltype from pypy . rpython . lltypesystem . lloperation import llop def entry_point ( argv ) : llop . instrument_count ( lltype . Void , '' , ) llop . instrument_count ( lltype . Void , '' , ) llop . instrument_count ( lltype . Void , '' , ) llop . instrument_count ( lltype . Void , '' , ) llop . instrument_count ( lltype . Void , '' , ) return t = TranslationContext ( self . config ) t . config . translation . instrument = True t . buildannotator ( ) . build_types ( entry_point , [ s_list_of_strings ] ) t . buildrtyper ( ) . specialize ( ) cbuilder = CStandaloneBuilder ( t , entry_point , config = t . config ) cbuilder . generate_source ( ) cbuilder . compile ( ) counters_fname = udir . join ( \"\" ) os . environ [ '' ] = str ( counters_fname ) try : data = cbuilder . cmdexec ( ) finally : del os . environ [ '' ] f = counters_fname . open ( '' ) counters_data = f . read ( ) f . close ( ) import struct counters = struct . unpack ( \"\" , counters_data ) assert counters == ( , , ) def test_prof_inline ( self ) : if sys . platform == '' : py . test . skip ( \"\" ) def add ( a , b ) : return a + b - b + b - b + b - b + b - b + b - b + b - b + b def entry_point ( argv ) : tot = x = int ( argv [ ] ) while x > : tot = add ( tot , x ) x -= os . write ( , str ( tot ) ) return from pypy . translator . interactive import Translation t = Translation ( entry_point , backend = '' , standalone = True ) t . backendopt ( inline_threshold = , profile_based_inline = \"\" ) exe = t . compile ( ) out = py . process . cmdexec ( \"\" % exe ) assert int ( out ) == * / t = Translation ( entry_point , backend = '' , standalone = True ) t . backendopt ( inline_threshold = all . INLINE_THRESHOLD_FOR_TEST * , profile_based_inline = \"\" ) exe = t . compile ( ) out = py . process . cmdexec ( \"\" % exe ) assert int ( out ) == * / def test_frexp ( self ) : import math def entry_point ( argv ) : m , e = math . frexp ( ) x , y = math . frexp ( ) print m , x return t = TranslationContext ( self . config ) t . buildannotator ( ) . build_types ( entry_point , [ s_list_of_strings ] ) t . buildrtyper ( ) . specialize ( ) cbuilder = CStandaloneBuilder ( t , entry_point , t . config ) cbuilder . generate_source ( ) cbuilder . compile ( ) data = cbuilder . cmdexec ( '' ) assert map ( float , data . split ( ) ) == [ , ] def test_profopt ( self ) : def add ( a , b ) : return a + b - b + b - b + b - b + b - b + b - b + b - b + b def entry_point ( argv ) : tot = x = int ( argv [ ] ) while x > : tot = add ( tot , x ) x -= os . write ( , str ( tot ) ) return from pypy . translator . interactive import Translation t = Translation ( entry_point , backend = '' , standalone = True , profopt = \"\" ) t . backendopt ( ) exe = t . compile ( ) out = py . process . cmdexec ( \"\" % exe ) assert int ( out ) == * / t = Translation ( entry_point , backend = '' , standalone = True , profopt = \"\" , noprofopt = True ) t . backendopt ( ) exe = t . compile ( ) out = py . process . cmdexec ( \"\" % exe ) assert int ( out ) == * / if hasattr ( os , '' ) : def test_os_setpgrp ( self ) : def entry_point ( argv ) : os . setpgrp ( ) return t = TranslationContext ( self . config ) t . buildannotator ( ) . build_types ( entry_point , [ s_list_of_strings ] ) t . buildrtyper ( ) . specialize ( ) cbuilder = CStandaloneBuilder ( t , entry_point , t . config ) cbuilder . generate_source ( ) cbuilder . compile ( ) def test_profopt_mac_osx_bug ( self ) : if sys . platform == '' : py . test . skip ( \"\" ) def entry_point ( argv ) : import os pid = os . fork ( ) if pid : os . waitpid ( pid , ) else : os . _exit ( ) return from pypy . translator . interactive import Translation t = Translation ( entry_point , backend = '' , standalone = True , profopt = \"\" ) t . backendopt ( ) exe = t . compile ( ) t = Translation ( entry_point , backend = '' , standalone = True , profopt = \"\" , noprofopt = True ) t . backendopt ( ) exe = t . compile ( ) def test_standalone_large_files ( self ) : from pypy . module . posix . test . test_posix2 import need_sparse_files need_sparse_files ( ) filename = str ( udir . join ( '' ) ) r4800000000 = r_longlong ( L ) def entry_point ( argv ) : fd = os . open ( filename , os . O_RDWR | os . O_CREAT , ) os . lseek ( fd , r4800000000 , ) os . write ( fd , \"\" ) newpos = os . lseek ( fd , , ) if newpos == r4800000000 + : print \"\" else : print \"\" os . close ( fd ) return t = TranslationContext ( self . config ) t . buildannotator ( ) . build_types ( entry_point , [ s_list_of_strings ] ) t . buildrtyper ( ) . specialize ( ) cbuilder = CStandaloneBuilder ( t , entry_point , t . config ) cbuilder . generate_source ( ) cbuilder . compile ( ) data = cbuilder . cmdexec ( '' ) assert data . strip ( ) == \"\" def test_separate_files ( self ) : fname = py . path . local ( pypydir ) . join ( '' , '' , '' , '' ) dirname = udir . join ( \"\" ) . ensure ( dir = ) fname2 = dirname . join ( \"\" ) ", "answer": "fname2 . write ( \"\"\"\"\"\" )"}, {"prompt": " from marshmallow import Schema , fields , validate class OptionSchema ( Schema ) : ", "answer": "id = fields . Integer ( dump_only = True )"}, {"prompt": " from django . forms import Form , CharField , IntegerField , ValidationError , DateField from django . forms . formsets import formset_factory , BaseFormSet from django . test import TestCase class Choice ( Form ) : choice = CharField ( ) votes = IntegerField ( ) ChoiceFormSet = formset_factory ( Choice ) class FavoriteDrinkForm ( Form ) : name = CharField ( ) class BaseFavoriteDrinksFormSet ( BaseFormSet ) : def clean ( self ) : seen_drinks = [ ] for drink in self . cleaned_data : if drink [ '' ] in seen_drinks : raise ValidationError ( '' ) seen_drinks . append ( drink [ '' ] ) class EmptyFsetWontValidate ( BaseFormSet ) : def clean ( self ) : raise ValidationError ( \"\" ) FavoriteDrinksFormSet = formset_factory ( FavoriteDrinkForm , formset = BaseFavoriteDrinksFormSet , extra = ) class FormsFormsetTestCase ( TestCase ) : def test_basic_formset ( self ) : formset = ChoiceFormSet ( auto_id = False , prefix = '' ) self . assertHTMLEqual ( str ( formset ) , \"\"\"\"\"\" ) data = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , } formset = ChoiceFormSet ( data , auto_id = False , prefix = '' ) self . assertTrue ( formset . is_valid ( ) ) self . assertEqual ( [ form . cleaned_data for form in formset . forms ] , [ { '' : , '' : u'' } ] ) formset = ChoiceFormSet ( ) self . assertFalse ( formset . is_valid ( ) ) self . assertFalse ( formset . has_changed ( ) ) def test_formset_validation ( self ) : data = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , } formset = ChoiceFormSet ( data , auto_id = False , prefix = '' ) self . assertFalse ( formset . is_valid ( ) ) self . assertEqual ( formset . errors , [ { '' : [ u'' ] } ] ) def test_formset_has_changed ( self ) : data = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , } blank_formset = ChoiceFormSet ( data , auto_id = False , prefix = '' ) self . assertFalse ( blank_formset . has_changed ( ) ) data [ '' ] = '' invalid_formset = ChoiceFormSet ( data , auto_id = False , prefix = '' ) self . assertFalse ( invalid_formset . is_valid ( ) ) self . assertTrue ( invalid_formset . has_changed ( ) ) data [ '' ] = '' valid_formset = ChoiceFormSet ( data , auto_id = False , prefix = '' ) self . assertTrue ( valid_formset . is_valid ( ) ) self . assertTrue ( valid_formset . has_changed ( ) ) def test_formset_initial_data ( self ) : initial = [ { '' : u'' , '' : } ] formset = ChoiceFormSet ( initial = initial , auto_id = False , prefix = '' ) form_output = [ ] for form in formset . forms : form_output . append ( form . as_ul ( ) ) self . assertHTMLEqual ( '' . join ( form_output ) , \"\"\"\"\"\" ) data = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , } formset = ChoiceFormSet ( data , auto_id = False , prefix = '' ) self . assertTrue ( formset . is_valid ( ) ) self . assertEqual ( [ form . cleaned_data for form in formset . forms ] , [ { '' : , '' : u'' } , { } ] ) def test_second_form_partially_filled ( self ) : data = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , } formset = ChoiceFormSet ( data , auto_id = False , prefix = '' ) self . assertFalse ( formset . is_valid ( ) ) self . assertEqual ( formset . errors , [ { } , { '' : [ u'' ] } ] ) def test_delete_prefilled_data ( self ) : data = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , } formset = ChoiceFormSet ( data , auto_id = False , prefix = '' ) self . assertFalse ( formset . is_valid ( ) ) self . assertEqual ( formset . errors , [ { '' : [ u'' ] , '' : [ u'' ] } , { } ] ) def test_displaying_more_than_one_blank_form ( self ) : ChoiceFormSet = formset_factory ( Choice , extra = ) formset = ChoiceFormSet ( auto_id = False , prefix = '' ) form_output = [ ] for form in formset . forms : form_output . append ( form . as_ul ( ) ) self . assertHTMLEqual ( '' . join ( form_output ) , \"\"\"\"\"\" ) data = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , } formset = ChoiceFormSet ( data , auto_id = False , prefix = '' ) self . assertTrue ( formset . is_valid ( ) ) self . assertEqual ( [ form . cleaned_data for form in formset . forms ] , [ { } , { } , { } ] ) def test_single_form_completed ( self ) : data = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , } ChoiceFormSet = formset_factory ( Choice , extra = ) formset = ChoiceFormSet ( data , auto_id = False , prefix = '' ) self . assertTrue ( formset . is_valid ( ) ) self . assertEqual ( [ form . cleaned_data for form in formset . forms ] , [ { '' : , '' : u'' } , { } , { } ] ) def test_second_form_partially_filled_2 ( self ) : data = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , } ChoiceFormSet = formset_factory ( Choice , extra = ) formset = ChoiceFormSet ( data , auto_id = False , prefix = '' ) self . assertFalse ( formset . is_valid ( ) ) self . assertEqual ( formset . errors , [ { } , { '' : [ u'' ] } , { } ] ) def test_more_initial_data ( self ) : data = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , } initial = [ { '' : u'' , '' : } ] ChoiceFormSet = formset_factory ( Choice , extra = ) formset = ChoiceFormSet ( initial = initial , auto_id = False , prefix = '' ) form_output = [ ] for form in formset . forms : form_output . append ( form . as_ul ( ) ) self . assertHTMLEqual ( '' . join ( form_output ) , \"\"\"\"\"\" ) self . assertTrue ( formset . empty_form . empty_permitted ) self . assertHTMLEqual ( formset . empty_form . as_ul ( ) , \"\"\"\"\"\" ) def test_formset_with_deletion ( self ) : ChoiceFormSet = formset_factory ( Choice , can_delete = True ) initial = [ { '' : u'' , '' : } , { '' : u'' , '' : } ] formset = ChoiceFormSet ( initial = initial , auto_id = False , prefix = '' ) form_output = [ ] for form in formset . forms : form_output . append ( form . as_ul ( ) ) self . assertHTMLEqual ( '' . join ( form_output ) , \"\"\"\"\"\" ) data = { '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , '' : '' , } formset = ChoiceFormSet ( data , auto_id = False , prefix = '' ) self . assertTrue ( formset . is_valid ( ) ) self . assertEqual ( [ form . cleaned_data for form in formset . forms ] , [ { '' : , '' : False , '' : u'' } , { '' : , '' : True , '' : u'' } , { } ] ) self . assertEqual ( [ form . cleaned_data for form in formset . deleted_forms ] , [ { '' : , '' : True , '' : u'' } ] ) class CheckForm ( Form ) : field = IntegerField ( min_value = ) ", "answer": "data = {"}, {"prompt": " \"\"\"\"\"\" __date__ = '' __license__ = '' import re from git_deploy . utils import ssh_command_target from git_deploy . config import log class DeployLogError ( Exception ) : \"\"\"\"\"\" def __init__ ( self , message = \"\" , exit_code = ) : Exception . __init__ ( self , message ) self . _exit_code = int ( exit_code ) @ property def exit_code ( self ) : return self . _exit_code class DeployLogDefault ( object ) : \"\"\"\"\"\" LOGNAME_ARCHIVE = '' LOGNAME_ACTIVE = '' __instance = None def __init__ ( self , target , path , user , local_key_path ) : \"\"\"\"\"\" self . __class__ . __instance = self self . target = target self . path = path + '' self . user = user self . key_path = local_key_path def __new__ ( cls , * args , ** kwargs ) : \"\"\"\"\"\" if not cls . __instance : ", "answer": "cls . __instance = super ( DeployLogDefault , cls ) . __new__ ( cls )"}, {"prompt": " __author__ = '' from . import sensors import threading from pybrain . utilities import threaded from pybrain . tools . networking . udpconnection import UDPServer from pybrain . rl . environments . environment import Environment from scipy import ones , zeros , array , clip , arange , sqrt from time import sleep class FlexCubeEnvironment ( Environment ) : def __init__ ( self , render = True , realtime = True , ip = \"\" , port = \"\" ) : self . render = render if self . render : self . updateDone = True self . updateLock = threading . Lock ( ) self . server = UDPServer ( ip , port ) self . actLen = self . mySensors = sensors . Sensors ( [ \"\" ] ) self . dists = array ( [ , sqrt ( ) * , sqrt ( ) * ] ) self . gravVect = array ( [ , - , ] ) self . centerOfGrav = zeros ( ( , ) , float ) self . pos = ones ( ( , ) , float ) self . vel = zeros ( ( , ) , float ) self . SpringM = ones ( ( , ) , float ) self . d = self . dt = self . startHight = self . dumping = self . fraktMin = self . fraktMax = self . minAkt = self . dists [ ] * self . fraktMin self . maxAkt = self . dists [ ] * self . fraktMax self . reset ( ) self . count = self . setEdges ( ) self . act ( array ( [ ] * ) ) self . euler ( ) self . realtime = realtime self . step = def closeSocket ( self ) : self . server . UDPInSock . close ( ) ", "answer": "sleep ( )"}, {"prompt": " '''''' import datetime as dt import random __title__ = '' __version__ = '' __license__ = '' __copyright__ = '' class Model ( object ) : '''''' seed = None schedule = None running = True def __init__ ( self , seed = None ) : '''''' if seed is None : self . seed = dt . datetime . now ( ) else : self . seed = seed random . seed ( seed ) self . running = True def run_model ( self ) : '''''' while self . running : self . step ( ) def step ( self ) : ", "answer": "''''''"}, {"prompt": " \"\"\"\"\"\" import sys if sys . version . startswith ( '' ) : from configparser import ConfigParser else : from ConfigParser import ConfigParser import os . path from glob import glob from . collection import imread_collection_wrapper __all__ = [ '' , '' , '' , '' , '' , '' , '' ] plugin_store = None plugin_provides = { } plugin_module_name = { } plugin_meta_data = { } preferred_plugins = { '' : [ '' , '' , '' , '' ] , '' : [ '' ] , '' : [ '' ] } def _clear_plugins ( ) : \"\"\"\"\"\" global plugin_store plugin_store = { '' : [ ] , '' : [ ] , '' : [ ] , '' : [ ] , '' : [ ] , '' : [ ] } _clear_plugins ( ) def _load_preferred_plugins ( ) : io_types = [ '' , '' , '' , '' , '' ] for p_type in io_types : _set_plugin ( p_type , preferred_plugins [ '' ] ) plugin_types = ( p for p in preferred_plugins . keys ( ) if p != '' ) for p_type in plugin_types : _set_plugin ( p_type , preferred_plugins [ p_type ] ) def _set_plugin ( plugin_type , plugin_list ) : for plugin in plugin_list : if plugin not in available_plugins : continue try : use_plugin ( plugin , kind = plugin_type ) break except ( ImportError , RuntimeError , OSError ) : pass def reset_plugins ( ) : _clear_plugins ( ) _load_preferred_plugins ( ) def _parse_config_file ( filename ) : \"\"\"\"\"\" parser = ConfigParser ( ) parser . read ( filename ) name = parser . sections ( ) [ ] meta_data = { } for opt in parser . options ( name ) : meta_data [ opt ] = parser . get ( name , opt ) return name , meta_data def _scan_plugins ( ) : \"\"\"\"\"\" pd = os . path . dirname ( __file__ ) config_files = glob ( os . path . join ( pd , '' , '' ) ) for filename in config_files : name , meta_data = _parse_config_file ( filename ) plugin_meta_data [ name ] = meta_data provides = [ s . strip ( ) for s in meta_data [ '' ] . split ( '' ) ] valid_provides = [ p for p in provides if p in plugin_store ] for p in provides : if not p in plugin_store : print ( \"\" \"\" % ( name , p ) ) need_to_add_collection = ( '' not in valid_provides and '' in valid_provides ) if need_to_add_collection : valid_provides . append ( '' ) plugin_provides [ name ] = valid_provides plugin_module_name [ name ] = os . path . basename ( filename ) [ : - ] _scan_plugins ( ) def find_available_plugins ( loaded = False ) : \"\"\"\"\"\" active_plugins = set ( ) for plugin_func in plugin_store . values ( ) : for plugin , func in plugin_func : active_plugins . add ( plugin ) d = { } for plugin in plugin_provides : if not loaded or plugin in active_plugins : d [ plugin ] = [ f for f in plugin_provides [ plugin ] if not f . startswith ( '' ) ] return d available_plugins = find_available_plugins ( ) ", "answer": "def call_plugin ( kind , * args , ** kwargs ) :"}, {"prompt": " from __future__ import ( absolute_import , division , generators , nested_scopes , print_function , unicode_literals , with_statement ) from textwrap import dedent from pants . backend . graph_info . tasks . list_owners import ListOwners from pants . backend . python . targets . python_library import PythonLibrary from pants . base . exceptions import TaskError from pants . build_graph . build_file_aliases import BuildFileAliases from pants_test . tasks . task_test_base import ConsoleTaskTestBase class ListOwnersTest ( ConsoleTaskTestBase ) : @ classmethod def task_type ( cls ) : return ListOwners @ property def alias_groups ( self ) : return BuildFileAliases ( targets = { '' : PythonLibrary } ) def setUp ( self ) : super ( ListOwnersTest , self ) . setUp ( ) def add_to_build_file ( path , name , * sources ) : all_sources = [ \"\" . format ( source ) for source in list ( sources ) ] self . add_to_build_file ( path , dedent ( \"\"\"\"\"\" . format ( name = name , all_sources = '' . join ( all_sources ) ) ) ) add_to_build_file ( '' , '' , '' ) add_to_build_file ( '' , '' , '' ) add_to_build_file ( '' , '' , '' ) add_to_build_file ( '' , '' , '' , '' , '' ) add_to_build_file ( '' , '' , '' ) add_to_build_file ( '' , '' , '' ) add_to_build_file ( '' , '' , '' ) def test_no_targets ( self ) : self . assert_console_output ( passthru_args = [ '' ] ) def test_no_targets_output_format_json ( self ) : self . assert_console_output ( dedent ( \"\"\"\"\"\" ) . lstrip ( '' ) , passthru_args = [ '' ] , options = { '' : '' } ) def test_one_target ( self ) : self . assert_console_output ( '' , passthru_args = [ '' ] ) def test_one_target_output_format_json ( self ) : self . assert_console_output ( dedent ( \"\"\"\"\"\" ) . lstrip ( '' ) , passthru_args = [ '' ] , options = { '' : '' } ) def test_multiple_targets ( self ) : self . assert_console_output ( '' , '' , passthru_args = [ '' ] ) ", "answer": "def test_multiple_targets_output_format_json ( self ) :"}, {"prompt": " from sahara . plugins import utils as plugin_utils ", "answer": "from sahara . service . edp . spark import engine as shell_engine"}, {"prompt": " from cleo . commands import Command class FoobarCommand ( Command ) : def configure ( self ) : ", "answer": "self . set_name ( '' ) . set_description ( '' )"}, {"prompt": " import bookshelf ", "answer": "import config"}, {"prompt": " \"\"\"\"\"\" import copy from django import VERSION from django import forms from django . core . urlresolvers import reverse from django . utils import six class WidgetMixin ( object ) : \"\"\"\"\"\" def __init__ ( self , url = None , forward = None , * args , ** kwargs ) : \"\"\"\"\"\" self . url = url self . forward = forward or [ ] super ( WidgetMixin , self ) . __init__ ( * args , ** kwargs ) def build_attrs ( self , * args , ** kwargs ) : \"\"\"\"\"\" attrs = super ( WidgetMixin , self ) . build_attrs ( * args , ** kwargs ) if self . url is not None : attrs [ '' ] = self . url autocomplete_function = getattr ( self , '' , None ) if autocomplete_function : attrs . setdefault ( '' , autocomplete_function ) if self . forward : ", "answer": "attrs . setdefault ( '' ,"}, {"prompt": " from __future__ import absolute_import import os import traceback from abc import abstractmethod from . archiver import Archiver from . common import chmod_plus_w , safe_copy , safe_mkdtemp , safe_rmtree from . compatibility import AbstractClass from . installer import WheelInstaller from . interpreter import PythonInterpreter from . package import EggPackage , Package , SourcePackage , WheelPackage from . platforms import Platform from . tracer import TRACER from . util import DistributionHelper class TranslatorBase ( AbstractClass ) : \"\"\"\"\"\" @ abstractmethod def translate ( self , link , into = None ) : pass class ChainedTranslator ( TranslatorBase ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " '''''' from __future__ import absolute_import import re import salt . utils __func_alias__ = { '' : '' , '' : '' , } def __virtual__ ( ) : if salt . utils . which ( '' ) is not None : return True return ( False , '' ) def start ( name ) : '''''' cmd = '' . format ( name ) return not __salt__ [ '' ] ( cmd , python_shell = False ) def stop ( name ) : '''''' cmd = '' . format ( name ) return not __salt__ [ '' ] ( cmd , python_shell = False ) def restart ( name ) : '''''' cmd = '' . format ( name ) return not __salt__ [ '' ] ( cmd , python_shell = False ) def unmonitor ( name ) : '''''' cmd = '' . format ( name ) return not __salt__ [ '' ] ( cmd , python_shell = False ) def monitor ( name ) : '''''' cmd = '' . format ( name ) return not __salt__ [ '' ] ( cmd , python_shell = False ) def summary ( svc_name = '' ) : '''''' ret = { } cmd = '' res = __salt__ [ '' ] ( cmd ) . splitlines ( ) for line in res : if '' in line : return dict ( monit = '' , result = False ) elif not line or svc_name not in line or '' in line : continue else : parts = line . split ( '' ) if len ( parts ) == : resource , name , status_ = ( parts [ ] . strip ( ) , parts [ ] , parts [ ] . strip ( ) ) if svc_name != '' and svc_name != name : continue if resource not in ret : ret [ resource ] = { } ret [ resource ] [ name ] = status_ return ret def status ( svc_name = '' ) : '''''' cmd = '' res = __salt__ [ '' ] ( cmd ) prostr = '' + '' * s = res . replace ( '' , prostr ) . replace ( \"\" , '' ) . split ( '' ) entries = { } for process in s [ : - ] : pro = process . splitlines ( ) tmp = { } for items in pro : key = items [ : ] . strip ( ) tmp [ key ] = items [ : ] . strip ( ) entries [ pro [ ] . split ( ) [ ] ] = tmp if svc_name == '' : ret = entries else : ret = entries . get ( svc_name , '' ) return ret def reload_ ( ) : '''''' cmd = '' return not __salt__ [ '' ] ( cmd , python_shell = False ) def configtest ( ) : '''''' ret = { } cmd = '' out = __salt__ [ '' ] ( cmd ) if out [ '' ] != : ret [ '' ] = '' ret [ '' ] = out [ '' ] ret [ '' ] = False return ret ret [ '' ] = '' ret [ '' ] = out [ '' ] ret [ '' ] = True return ret def version ( ) : '''''' cmd = '' out = __salt__ [ '' ] ( cmd ) . splitlines ( ) ret = out [ ] . split ( ) return ret [ - ] def id_ ( reset = False ) : '''''' if reset : id_pattern = re . compile ( r'' ) cmd = '' out = __salt__ [ '' ] ( cmd , python_shell = True ) ret = id_pattern . search ( out [ '' ] ) . group ( '' ) return ret if ret else False else : cmd = '' out = __salt__ [ '' ] ( cmd ) ", "answer": "ret = out . split ( '' ) [ - ] . strip ( )"}, {"prompt": " from robot . utils import py2to3 from . tags import TagPatterns @ py2to3 class Criticality ( object ) : def __init__ ( self , critical_tags = None , non_critical_tags = None ) : self . critical_tags = self . _get_tag_patterns ( critical_tags ) self . non_critical_tags = self . _get_tag_patterns ( non_critical_tags ) def _get_tag_patterns ( self , tags ) : return TagPatterns ( tags ) if not isinstance ( tags , TagPatterns ) else tags def tag_is_critical ( self , tag ) : return self . critical_tags . match ( tag ) def tag_is_non_critical ( self , tag ) : return self . non_critical_tags . match ( tag ) def test_is_critical ( self , test ) : if self . critical_tags and not self . critical_tags . match ( test . tags ) : return False return not self . non_critical_tags . match ( test . tags ) ", "answer": "def __nonzero__ ( self ) :"}, {"prompt": " import sublime , sublime_plugin import subprocess import re class GTKDarkThemeVariantSetter ( sublime_plugin . EventListener ) : def get_output_matches ( self , arguments , pattern ) : output = subprocess . Popen ( arguments , stdout = subprocess . PIPE ) . communicate ( ) [ ] return re . findall ( pattern , output . decode ( \"\" ) ) def get_sublime_pids ( self ) : return self . get_output_matches ( [ \"\" , \"\" , \"\" , \"\" , \"\" ] , \"\" ) def get_window_ids ( self ) : return self . get_output_matches ( [ \"\" , \"\" , \"\" ] , \"\" ) ", "answer": "def get_pid_from_window_id ( self , window_id ) :"}, {"prompt": " SCHEMA_APIS = '' SCHEMA_PATH = '' FILE_EXT_JSON = '' FILE_EXT_YAML = '' SWAGGER_FILE_NAMES = [ '' + '' + FILE_EXT_JSON , ", "answer": "'' + '' + FILE_EXT_JSON ,"}, {"prompt": " from os . path import abspath , dirname , join import os import sys sys . stdout = sys . stderr sys . path . insert ( , abspath ( join ( dirname ( __file__ ) , \"\" , \"\" ) ) ) sys . path . insert ( , abspath ( join ( dirname ( __file__ ) , \"\" ) ) ) sys . path . insert ( , abspath ( join ( dirname ( __file__ ) , \"\" , \"\" ) ) ) os . environ [ \"\" ] = \"\" ", "answer": "from django . core . handlers . wsgi import WSGIHandler"}, {"prompt": " \"\"\"\"\"\" from lmi . scripts . common import command from lmi . scripts . common import errors from lmi . scripts . common . formatter import command as fcmd from lmi . scripts . networking import * def cmd_list_devices ( ns , device_names = None ) : \"\"\"\"\"\" for d in list_devices ( ns , device_names ) : yield ( d . ElementName , ns . LMI_IPNetworkConnection . OperatingStatusValues . value_name ( d . OperatingStatus ) , get_mac ( ns , d ) ) def cmd_show_devices ( ns , device_names = None ) : \"\"\"\"\"\" for device in list_devices ( ns , device_names ) : yield fcmd . NewTableCommand ( title = \"\" % device . ElementName ) yield ( \"\" , ns . LMI_IPNetworkConnection . OperatingStatusValues . value_name ( device . OperatingStatus ) ) yield ( \"\" , get_mac ( ns , device ) ) for ip , prefix in get_ipv4_addresses ( ns , device ) : yield ( \"\" , \"\" % ( ip , prefix ) ) for ip , mask in get_ipv6_addresses ( ns , device ) : yield ( \"\" , \"\" % ( ip , mask ) ) for gw in get_default_gateways ( ns , device ) : yield ( \"\" , gw ) for dns in get_dns_servers ( ns , device ) : yield ( \"\" , dns ) for setting in get_active_settings ( ns , device ) : yield ( \"\" , setting . Caption ) for setting in get_available_settings ( ns , device ) : yield ( \"\" , setting . Caption ) class ListDevice ( command . LmiLister ) : CALLABLE = '' COLUMNS = ( '' , '' , '' ) def transform_options ( self , options ) : \"\"\"\"\"\" options [ '' ] = options . pop ( '' ) class ShowDevice ( command . LmiLister ) : CALLABLE = '' COLUMNS = [ ] def transform_options ( self , options ) : \"\"\"\"\"\" options [ '' ] = options . pop ( '' ) class Device ( command . LmiCommandMultiplexer ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " from twisted . cred import portal from twisted . cred . checkers import InMemoryUsernamePasswordDatabaseDontUse from twisted . conch import avatar from twisted . conch . checkers import SSHPublicKeyChecker , InMemorySSHKeyDB from twisted . conch . ssh import factory , userauth , connection , keys , session from twisted . conch . ssh . transport import SSHServerTransport from twisted . internet import reactor , protocol from twisted . python import log from twisted . python import components from zope . interface import implements import sys log . startLogging ( sys . stderr ) \"\"\"\"\"\" SERVER_RSA_PRIVATE = '' SERVER_RSA_PUBLIC = '' CLIENT_RSA_PUBLIC = '' PRIMES = { : [ ( L , L ) ] , : [ ( L , L ) ] , } class ExampleAvatar ( avatar . ConchUser ) : \"\"\"\"\"\" def __init__ ( self , username ) : avatar . ConchUser . __init__ ( self ) self . username = username self . channelLookup . update ( { '' : session . SSHSession } ) class ExampleRealm ( object ) : \"\"\"\"\"\" implements ( portal . IRealm ) def requestAvatar ( self , avatarId , mind , * interfaces ) : \"\"\"\"\"\" return interfaces [ ] , ExampleAvatar ( avatarId ) , lambda : None class EchoProtocol ( protocol . Protocol ) : \"\"\"\"\"\" def dataReceived ( self , data ) : \"\"\"\"\"\" if data == '' : data = '' elif data == '' : self . transport . loseConnection ( ) return self . transport . write ( data ) class ExampleSession ( object ) : \"\"\"\"\"\" def __init__ ( self , avatar ) : \"\"\"\"\"\" def getPty ( self , term , windowSize , attrs ) : \"\"\"\"\"\" def execCommand ( self , proto , cmd ) : \"\"\"\"\"\" raise Exception ( \"\" ) def openShell ( self , transport ) : \"\"\"\"\"\" protocol = EchoProtocol ( ) protocol . makeConnection ( transport ) transport . makeConnection ( session . wrapProtocol ( protocol ) ) def eofReceived ( self ) : pass def closed ( self ) : pass components . registerAdapter ( ExampleSession , ExampleAvatar , session . ISession ) class ExampleFactory ( factory . SSHFactory ) : \"\"\"\"\"\" protocol = SSHServerTransport publicKeys = { ", "answer": "'' : keys . Key . fromFile ( SERVER_RSA_PUBLIC )"}, {"prompt": " from __future__ import ( absolute_import , division , generators , nested_scopes , print_function , unicode_literals , with_statement ) import os import shlex import tempfile import unittest import warnings from contextlib import contextmanager from textwrap import dedent from pants . base . deprecated import CodeRemovedError from pants . option . arg_splitter import GLOBAL_SCOPE from pants . option . config import Config from pants . option . custom_types import file_option , target_option from pants . option . errors import ( BooleanOptionNameWithNo , FrozenRegistration , ImplicitValIsNone , InvalidKwarg , InvalidMemberType , MemberTypeNotAllowed , NoOptionNames , OptionAlreadyRegistered , OptionNameDash , OptionNameDoubleDash , ParseError , RecursiveSubsystemOption , Shadowing ) from pants . option . global_options import GlobalOptionsRegistrar from pants . option . option_tracker import OptionTracker from pants . option . options import Options from pants . option . options_bootstrapper import OptionsBootstrapper from pants . option . parser import Parser from pants . option . ranked_value import RankedValue from pants . option . scope import ScopeInfo from pants . util . contextutil import temporary_file , temporary_file_path from pants . util . dirutil import safe_mkdtemp def task ( scope ) : return ScopeInfo ( scope , ScopeInfo . TASK ) def intermediate ( scope ) : return ScopeInfo ( scope , ScopeInfo . INTERMEDIATE ) def subsystem ( scope ) : return ScopeInfo ( scope , ScopeInfo . SUBSYSTEM ) class OptionsTest ( unittest . TestCase ) : _known_scope_infos = [ intermediate ( '' ) , task ( '' ) , task ( '' ) , intermediate ( '' ) , intermediate ( '' ) , task ( '' ) , task ( '' ) , task ( '' ) , task ( '' ) , task ( '' ) , task ( '' ) ] def _register ( self , options ) : def register_global ( * args , ** kwargs ) : options . register ( GLOBAL_SCOPE , * args , ** kwargs ) register_global ( '' , '' , type = bool , help = '' , recursive = True ) register_global ( '' , '' , type = int , default = , recursive = True , fingerprint = True ) register_global ( '' , type = list , member_type = int ) register_global ( '' , type = list ) register_global ( '' ) register_global ( '' ) register_global ( '' , type = bool , fingerprint = True ) register_global ( '' , type = bool , implicit_value = False ) register_global ( '' , type = bool , default = True ) register_global ( '' , type = bool , default = False ) register_global ( '' , type = bool , implicit_value = False , default = False ) register_global ( '' , type = bool , implicit_value = False , default = True ) register_global ( '' , choices = [ '' , '' ] ) register_global ( '' , choices = [ , ] , type = list , member_type = int ) register_global ( '' , type = list , member_type = int , default = '' ) register_global ( '' , type = dict , default = '' ) register_global ( '' , type = list , member_type = dict , default = '' ) register_global ( '' , type = target_option , default = '' ) register_global ( '' , type = list , member_type = target_option , default = [ '' , '' ] ) register_global ( '' , type = file_option , default = None ) register_global ( '' , type = list , member_type = file_option ) register_global ( '' , default = '' , implicit_value = '' ) register_global ( '' , type = int , recursive = True ) register_global ( '' , type = int , recursive = True ) register_global ( '' , removal_version = '' , removal_hint = '' ) register_global ( '' , type = bool , removal_version = '' , removal_hint = '' ) register_global ( '' , removal_version = '' , removal_hint = '' ) options . register ( '' , '' , type = int , recursive = True ) options . register ( '' , '' ) options . register ( '' , '' , removal_version = '' , removal_hint = '' ) options . register ( '' , '' , type = bool , removal_version = '' , removal_hint = '' ) options . register ( '' , '' , fingerprint = True ) options . register ( '' , '' ) options . register ( '' , '' ) options . register ( '' , '' ) options . register ( '' , '' ) options . register ( '' , '' ) options . register ( '' , '' , fromfile = True ) options . register ( '' , '' , type = int , fromfile = True ) options . register ( '' , '' , type = dict , fromfile = True ) options . register ( '' , '' , type = list , fromfile = True ) options . register ( '' , '' , type = list , member_type = int , fromfile = True ) def _create_config ( self , config ) : with open ( os . path . join ( safe_mkdtemp ( ) , '' ) , '' ) as fp : for section , options in config . items ( ) : fp . write ( '' . format ( section ) ) for key , value in options . items ( ) : fp . write ( '' . format ( key , value ) ) return Config . load ( configpaths = [ fp . name ] ) def _parse ( self , args_str , env = None , config = None , bootstrap_option_values = None ) : args = shlex . split ( str ( args_str ) ) options = Options . create ( env = env or { } , config = self . _create_config ( config or { } ) , known_scope_infos = OptionsTest . _known_scope_infos , args = args , bootstrap_option_values = bootstrap_option_values , option_tracker = OptionTracker ( ) ) self . _register ( options ) return options def test_env_type_int ( self ) : options = Options . create ( env = { '' : \"\" } , config = self . _create_config ( { } ) , known_scope_infos = OptionsTest . _known_scope_infos , args = shlex . split ( '' ) , option_tracker = OptionTracker ( ) ) options . register ( GLOBAL_SCOPE , '' , type = list , member_type = int ) self . assertEqual ( [ , ] , options . for_global_scope ( ) . foo_bar ) options = Options . create ( env = { '' : '' } , config = self . _create_config ( { } ) , known_scope_infos = OptionsTest . _known_scope_infos , args = shlex . split ( '' ) , option_tracker = OptionTracker ( ) ) options . register ( GLOBAL_SCOPE , '' , type = int ) self . assertEqual ( , options . for_global_scope ( ) . foo_bar ) def test_arg_scoping ( self ) : options = self . _parse ( '' ) self . assertEqual ( True , options . for_global_scope ( ) . verbose ) options = self . _parse ( '' ) self . assertEqual ( [ '' ] , options . target_specs ) self . assertEqual ( True , options . for_global_scope ( ) . verbose ) with self . assertRaises ( ParseError ) : self . _parse ( '' ) . for_global_scope ( ) options = self . _parse ( '' ) self . assertEqual ( True , options . for_global_scope ( ) . verbose ) self . assertEqual ( True , options . for_scope ( '' ) . verbose ) self . assertEqual ( False , options . for_scope ( '' ) . verbose ) options = self . _parse ( '' '' ) self . assertEqual ( True , options . for_global_scope ( ) . verbose ) self . assertEqual ( False , options . for_scope ( '' ) . verbose ) self . assertEqual ( True , options . for_scope ( '' ) . verbose ) self . assertEqual ( True , options . for_scope ( '' ) . verbose ) self . assertEqual ( False , options . for_scope ( '' ) . verbose ) options = self . _parse ( '' , config = { '' : { '' : [ '' , '' ] } } ) self . assertEqual ( [ , - ] , options . for_global_scope ( ) . y ) options = self . _parse ( '' , config = { '' : { '' : [ '' , '' ] } } ) self . assertEqual ( [ , - , , - , ] , options . for_global_scope ( ) . y ) options = self . _parse ( '' ) self . assertEqual ( [ ] , options . for_global_scope ( ) . y ) options = self . _parse ( '' , env = { '' : \"\" } ) self . assertEqual ( [ '' , '' ] , options . for_global_scope ( ) . config_override ) options = self . _parse ( '' , env = { '' : \"\" } ) self . assertEqual ( [ '' ] , options . for_global_scope ( ) . config_override ) options = self . _parse ( '' , config = { '' : { '' : '' } } ) self . assertEqual ( [ , ] , options . for_global_scope ( ) . listy ) options = self . _parse ( '' ) self . assertEqual ( { '' : '' } , options . for_global_scope ( ) . dicty ) options = self . _parse ( '' ) self . assertEqual ( [ { '' : '' } , { '' : '' } ] , options . for_global_scope ( ) . dict_listy ) options = self . _parse ( '' ) self . assertEqual ( '' , options . for_global_scope ( ) . targety ) options = self . _parse ( '' ) self . assertEqual ( '' , options . for_global_scope ( ) . targety ) options = self . _parse ( '' ) self . assertEqual ( [ '' , '' ] , options . for_global_scope ( ) . target_listy ) with temporary_file_path ( ) as fp : options = self . _parse ( '' . format ( fp ) ) self . assertEqual ( fp , options . for_global_scope ( ) . filey ) with temporary_file_path ( ) as fp1 : with temporary_file_path ( ) as fp2 : options = self . _parse ( '' . format ( fp1 , fp2 ) ) self . assertEqual ( [ fp1 , fp2 ] , options . for_global_scope ( ) . file_listy ) def test_explicit_boolean_values ( self ) : options = self . _parse ( '' ) self . assertFalse ( options . for_global_scope ( ) . verbose ) options = self . _parse ( '' ) self . assertFalse ( options . for_global_scope ( ) . verbose ) options = self . _parse ( '' ) self . assertTrue ( options . for_global_scope ( ) . verbose ) options = self . _parse ( '' ) self . assertTrue ( options . for_global_scope ( ) . verbose ) def test_boolean_defaults ( self ) : options = self . _parse ( '' ) self . assertFalse ( options . for_global_scope ( ) . store_true_flag ) self . assertTrue ( options . for_global_scope ( ) . store_false_flag ) self . assertFalse ( options . for_global_scope ( ) . store_true_def_false_flag ) self . assertTrue ( options . for_global_scope ( ) . store_true_def_true_flag ) self . assertFalse ( options . for_global_scope ( ) . store_false_def_false_flag ) self . assertTrue ( options . for_global_scope ( ) . store_false_def_true_flag ) def test_boolean_set_option ( self ) : options = self . _parse ( '' '' '' ) self . assertTrue ( options . for_global_scope ( ) . store_true_flag ) self . assertFalse ( options . for_global_scope ( ) . store_false_flag ) self . assertTrue ( options . for_global_scope ( ) . store_true_def_false_flag ) self . assertTrue ( options . for_global_scope ( ) . store_true_def_true_flag ) self . assertFalse ( options . for_global_scope ( ) . store_false_def_false_flag ) self . assertFalse ( options . for_global_scope ( ) . store_false_def_true_flag ) def test_boolean_negate_option ( self ) : options = self . _parse ( '' '' '' ) self . assertFalse ( options . for_global_scope ( ) . store_true_flag ) self . assertTrue ( options . for_global_scope ( ) . store_false_flag ) self . assertFalse ( options . for_global_scope ( ) . store_true_def_false_flag ) self . assertFalse ( options . for_global_scope ( ) . store_true_def_true_flag ) self . assertTrue ( options . for_global_scope ( ) . store_false_def_false_flag ) self . assertTrue ( options . for_global_scope ( ) . store_false_def_true_flag ) def test_boolean_config_override_true ( self ) : options = self . _parse ( '' , config = { '' : { '' : True , '' : True , '' : True , '' : True , '' : True , '' : True , } } ) self . assertTrue ( options . for_global_scope ( ) . store_true_flag ) self . assertTrue ( options . for_global_scope ( ) . store_false_flag ) self . assertTrue ( options . for_global_scope ( ) . store_true_def_false_flag ) self . assertTrue ( options . for_global_scope ( ) . store_true_def_true_flag ) self . assertTrue ( options . for_global_scope ( ) . store_false_def_false_flag ) self . assertTrue ( options . for_global_scope ( ) . store_false_def_true_flag ) def test_boolean_config_override_false ( self ) : options = self . _parse ( '' , config = { '' : { '' : False , '' : False , '' : False , '' : False , '' : False , '' : False , } } ) self . assertFalse ( options . for_global_scope ( ) . store_true_flag ) self . assertFalse ( options . for_global_scope ( ) . store_false_flag ) self . assertFalse ( options . for_global_scope ( ) . store_true_def_false_flag ) self . assertFalse ( options . for_global_scope ( ) . store_true_def_true_flag ) self . assertFalse ( options . for_global_scope ( ) . store_false_def_false_flag ) self . assertFalse ( options . for_global_scope ( ) . store_false_def_true_flag ) def test_boolean_invalid_value ( self ) : with self . assertRaises ( Parser . BooleanConversionError ) : self . _parse ( '' , config = { '' : { '' : , } } ) . for_global_scope ( ) with self . assertRaises ( Parser . BooleanConversionError ) : self . _parse ( '' , config = { '' : { '' : '' , } } ) . for_global_scope ( ) def test_list_option ( self ) : def check ( expected , args_str , env = None , config = None ) : options = self . _parse ( args_str = args_str , env = env , config = config ) self . assertEqual ( expected , options . for_global_scope ( ) . listy ) check ( [ , , , ] , '' ) check ( [ , , , , ] , '' ) check ( [ , , , , ] , '' ) check ( [ , ] , '' ) check ( [ , , , , , , , , ] , '' , env = { '' : '' } , config = { '' : { '' : '' } } ) check ( [ , , , ] , '' , env = { '' : '' } , config = { '' : { '' : '' } } ) check ( [ , , , , , ] , '' , env = { '' : '' } , config = { '' : { '' : '' } } ) check ( [ , ] , '' , env = { '' : '' } , config = { '' : { '' : '' } } ) def test_dict_list_option ( self ) : def check ( expected , args_str , env = None , config = None ) : options = self . _parse ( args_str = args_str , env = env , config = config ) self . assertEqual ( expected , options . for_global_scope ( ) . dict_listy ) check ( [ { '' : , '' : } , { '' : } ] , '' ) check ( [ { '' : , '' : } , { '' : } , { '' : , '' : } ] , '' ) check ( [ { '' : , '' : } , { '' : } , { '' : , '' : } , { '' : } ] , '' ) check ( [ { '' : , '' : } , { '' : } , { '' : , '' : } , { '' : } ] , '' ) check ( [ { '' : , '' : } , { '' : } ] , '' ) check ( [ { '' : , '' : } , { '' : } , { '' : , '' : } ] , '' , env = { '' : '' } ) check ( [ { '' : , '' : } , { '' : } , { '' : , '' : } , { '' : } ] , '' , env = { '' : '' } ) check ( [ { '' : , '' : } , { '' : } ] , '' , env = { '' : '' } ) check ( [ { '' : , '' : } , { '' : } , { '' : , '' : } ] , '' , config = { '' : { '' : '' } } ) check ( [ { '' : , '' : } , { '' : } , { '' : , '' : } , { '' : } ] , '' , config = { '' : { '' : '' } } ) check ( [ { '' : , '' : } , { '' : } ] , '' , config = { '' : { '' : '' } } ) def test_target_list_option ( self ) : def check ( expected , args_str , env = None , config = None ) : options = self . _parse ( args_str = args_str , env = env , config = config ) self . assertEqual ( expected , options . for_global_scope ( ) . target_listy ) check ( [ '' , '' ] , '' ) check ( [ '' , '' , '' , '' ] , '' ) check ( [ '' , '' , '' , '' ] , '' ) check ( [ '' , '' ] , '' ) check ( [ '' , '' , '' ] , '' , env = { '' : '' } ) check ( [ '' , '' , '' , '' ] , '' , env = { '' : '' } ) check ( [ '' , '' ] , '' , env = { '' : '' } ) check ( [ '' , '' , '' ] , '' , config = { '' : { '' : '' } } ) check ( [ '' , '' , '' , '' ] , '' , config = { '' : { '' : '' } } ) check ( [ '' , '' ] , '' , config = { '' : { '' : '' } } ) def test_defaults ( self ) : options = self . _parse ( '' ) self . assertEqual ( , options . for_global_scope ( ) . num ) self . assertEqual ( , options . for_scope ( '' ) . num ) self . assertEqual ( , options . for_scope ( '' ) . num ) self . assertEqual ( , options . for_scope ( '' ) . num ) self . assertEqual ( , options . for_scope ( '' ) . num ) options = self . _parse ( '' ) self . assertEqual ( , options . for_global_scope ( ) . num ) self . assertEqual ( , options . for_scope ( '' ) . num ) self . assertEqual ( , options . for_scope ( '' ) . num ) config = { '' : { '' : '' } , '' : { '' : '' } , '' : { '' : '' } } options = self . _parse ( '' , config = config ) self . assertEqual ( , options . for_global_scope ( ) . num ) self . assertEqual ( , options . for_scope ( '' ) . num ) self . assertEqual ( , options . for_scope ( '' ) . num ) env = { '' : '' } options = self . _parse ( '' , env = env , config = config ) self . assertEqual ( , options . for_global_scope ( ) . num ) self . assertEqual ( , options . for_scope ( '' ) . num ) self . assertEqual ( , options . for_scope ( '' ) . num ) options = self . _parse ( '' , env = env , config = config ) self . assertEqual ( , options . for_global_scope ( ) . num ) self . assertEqual ( , options . for_scope ( '' ) . num ) self . assertEqual ( , options . for_scope ( '' ) . num ) def test_choices ( self ) : options = self . _parse ( '' ) self . assertEqual ( '' , options . for_global_scope ( ) . str_choices ) options = self . _parse ( '' , config = { '' : { '' : '' } } ) self . assertEqual ( '' , options . for_global_scope ( ) . str_choices ) with self . assertRaises ( ParseError ) : options = self . _parse ( '' ) options . for_global_scope ( ) with self . assertRaises ( ParseError ) : options = self . _parse ( '' , config = { '' : { '' : '' } } ) options . for_global_scope ( ) options = self . _parse ( '' ) self . assertEqual ( [ , ] , options . for_global_scope ( ) . int_choices ) def test_validation ( self ) : def assertError ( expected_error , * args , ** kwargs ) : with self . assertRaises ( expected_error ) : options = Options . create ( args = [ ] , env = { } , config = self . _create_config ( { } ) , known_scope_infos = [ ] , option_tracker = OptionTracker ( ) ) options . register ( GLOBAL_SCOPE , * args , ** kwargs ) options . for_global_scope ( ) assertError ( NoOptionNames ) assertError ( OptionNameDash , '' ) assertError ( OptionNameDoubleDash , '' ) assertError ( InvalidKwarg , '' , badkwarg = ) assertError ( ImplicitValIsNone , '' , implicit_value = None ) assertError ( BooleanOptionNameWithNo , '' , type = bool ) assertError ( MemberTypeNotAllowed , '' , member_type = int ) assertError ( MemberTypeNotAllowed , '' , type = dict , member_type = int ) assertError ( InvalidMemberType , '' , type = list , member_type = set ) assertError ( InvalidMemberType , '' , type = list , member_type = list ) assertError ( InvalidMemberType , '' , type = list , member_type = list ) def test_frozen_registration ( self ) : options = Options . create ( args = [ ] , env = { } , config = self . _create_config ( { } ) , known_scope_infos = [ task ( '' ) ] , option_tracker = OptionTracker ( ) ) options . register ( '' , '' ) with self . assertRaises ( FrozenRegistration ) : options . register ( GLOBAL_SCOPE , '' ) def test_implicit_value ( self ) : options = self . _parse ( '' ) self . assertEqual ( '' , options . for_global_scope ( ) . implicit_valuey ) options = self . _parse ( '' ) self . assertEqual ( '' , options . for_global_scope ( ) . implicit_valuey ) options = self . _parse ( '' ) self . assertEqual ( '' , options . for_global_scope ( ) . implicit_valuey ) def test_shadowing ( self ) : options = Options . create ( env = { } , config = self . _create_config ( { } ) , known_scope_infos = [ task ( '' ) , intermediate ( '' ) , task ( '' ) ] , args = '' , option_tracker = OptionTracker ( ) ) options . register ( '' , '' ) options . register ( '' , '' , '' ) with self . assertRaises ( Shadowing ) : options . register ( '' , '' ) with self . assertRaises ( Shadowing ) : options . register ( '' , '' ) with self . assertRaises ( Shadowing ) : options . register ( '' , '' ) with self . assertRaises ( Shadowing ) : options . register ( '' , '' , '' ) with self . assertRaises ( Shadowing ) : options . register ( '' , '' , '' ) def test_recursion ( self ) : options = self . _parse ( '' ) self . assertEqual ( , options . for_global_scope ( ) . num ) self . assertEqual ( , options . for_scope ( '' ) . num ) options = self . _parse ( '' ) self . assertEqual ( '' , options . for_global_scope ( ) . bar_baz ) options = self . _parse ( '' ) with self . assertRaises ( ParseError ) : options . for_scope ( '' ) def test_no_recursive_subsystem_options ( self ) : options = Options . create ( env = { } , config = self . _create_config ( { } ) , known_scope_infos = [ subsystem ( '' ) ] , args = '' , option_tracker = OptionTracker ( ) ) with self . assertRaises ( RecursiveSubsystemOption ) : options . register ( '' , '' , recursive = False ) options . for_scope ( '' ) with self . assertRaises ( RecursiveSubsystemOption ) : options . register ( '' , '' , recursive = True ) options . for_scope ( '' ) def test_is_known_scope ( self ) : options = self . _parse ( '' ) for scope_info in self . _known_scope_infos : self . assertTrue ( options . is_known_scope ( scope_info . scope ) ) self . assertFalse ( options . is_known_scope ( '' ) ) def test_designdoc_example ( self ) : config = { '' : { '' : '' } , '' : { '' : '' , '' : '' } , } env = { '' : '' } options = self . _parse ( '' , env = env , config = config ) self . assertEqual ( , options . for_global_scope ( ) . a ) self . assertEqual ( , options . for_global_scope ( ) . b ) with self . assertRaises ( AttributeError ) : options . for_global_scope ( ) . c self . assertEqual ( , options . for_scope ( '' ) . a ) self . assertEqual ( , options . for_scope ( '' ) . b ) self . assertEqual ( , options . for_scope ( '' ) . c ) self . assertEqual ( , options . for_scope ( '' ) . a ) self . assertEqual ( , options . for_scope ( '' ) . b ) self . assertEqual ( , options . for_scope ( '' ) . c ) def test_file_spec_args ( self ) : with tempfile . NamedTemporaryFile ( ) as tmp : tmp . write ( dedent ( \"\"\"\"\"\" ) ) tmp . flush ( ) cmdline = '' '' . format ( filename = tmp . name ) bootstrapper = OptionsBootstrapper ( args = shlex . split ( cmdline ) ) bootstrap_options = bootstrapper . get_bootstrap_options ( ) . for_global_scope ( ) options = self . _parse ( cmdline , bootstrap_option_values = bootstrap_options ) sorted_specs = sorted ( options . target_specs ) self . assertEqual ( [ '' , '' , '' , '' ] , sorted_specs ) def test_passthru_args ( self ) : options = self . _parse ( '' ) self . assertEqual ( [ '' , '' ] , options . passthru_args_for_scope ( '' ) ) self . assertEqual ( [ '' , '' ] , options . passthru_args_for_scope ( '' ) ) self . assertEqual ( [ '' , '' ] , options . passthru_args_for_scope ( '' ) ) self . assertEqual ( [ ] , options . passthru_args_for_scope ( '' ) ) self . assertEqual ( [ ] , options . passthru_args_for_scope ( '' ) ) self . assertEqual ( [ ] , options . passthru_args_for_scope ( None ) ) def test_global_scope_env_vars ( self ) : def check_pants_foo ( expected_val , env ) : val = self . _parse ( '' , env = env ) . for_global_scope ( ) . pants_foo self . assertEqual ( expected_val , val ) check_pants_foo ( '' , { '' : '' , '' : '' , '' : '' , } ) check_pants_foo ( '' , { '' : '' , '' : '' , } ) check_pants_foo ( '' , { '' : '' , } ) check_pants_foo ( None , { } ) check_pants_foo ( '' , { '' : '' , '' : '' , } ) def check_bar_baz ( expected_val , env ) : val = self . _parse ( '' , env = env ) . for_global_scope ( ) . bar_baz self . assertEqual ( expected_val , val ) check_bar_baz ( '' , { '' : '' , '' : '' , '' : '' , } ) check_bar_baz ( '' , { '' : '' , '' : '' , } ) check_bar_baz ( None , { '' : '' , } ) check_bar_baz ( None , { } ) def test_scoped_env_vars ( self ) : def check_scoped_spam ( scope , expected_val , env ) : val = self . _parse ( '' , env = env ) . for_scope ( scope ) . spam self . assertEqual ( expected_val , val ) check_scoped_spam ( '' , '' , { '' : '' } ) check_scoped_spam ( '' , '' , { '' : '' } ) check_scoped_spam ( '' , '' , { '' : '' } ) check_scoped_spam ( '' , '' , { '' : '' } ) def test_drop_flag_values ( self ) : options = self . _parse ( '' , env = { '' : '' } , config = { '' : { '' : } } ) defaulted_only_options = options . drop_flag_values ( ) self . assertEqual ( '' , options . for_global_scope ( ) . bar_baz ) self . assertIsNone ( defaulted_only_options . for_global_scope ( ) . bar_baz ) self . assertEqual ( , options . for_global_scope ( ) . num ) self . assertEqual ( , defaulted_only_options . for_global_scope ( ) . num ) self . assertEqual ( , options . for_scope ( '' ) . num ) self . assertEqual ( , defaulted_only_options . for_scope ( '' ) . num ) self . assertEqual ( '' , options . for_global_scope ( ) . pants_foo ) self . assertEqual ( '' , defaulted_only_options . for_global_scope ( ) . pants_foo ) def test_deprecated_option_past_removal ( self ) : \"\"\"\"\"\" with self . assertRaises ( CodeRemovedError ) : self . _parse ( '' ) . for_global_scope ( ) @ contextmanager def warnings_catcher ( self ) : with warnings . catch_warnings ( record = True ) as w : warnings . simplefilter ( '' ) yield w def test_deprecated_options ( self ) : def assertWarning ( w , option_string ) : self . assertEquals ( , len ( w ) ) self . assertTrue ( issubclass ( w [ - ] . category , DeprecationWarning ) ) warning_message = str ( w [ - ] . message ) self . assertIn ( \"\" , warning_message ) self . assertIn ( option_string , warning_message ) with self . warnings_catcher ( ) as w : options = self . _parse ( '' ) self . assertEquals ( '' , options . for_global_scope ( ) . global_crufty ) assertWarning ( w , '' ) with self . warnings_catcher ( ) as w : options = self . _parse ( '' ) self . assertTrue ( options . for_global_scope ( ) . global_crufty_boolean ) assertWarning ( w , '' ) with self . warnings_catcher ( ) as w : options = self . _parse ( '' ) self . assertFalse ( options . for_global_scope ( ) . global_crufty_boolean ) assertWarning ( w , '' ) with self . warnings_catcher ( ) as w : options = self . _parse ( '' ) self . assertEquals ( '' , options . for_scope ( '' ) . crufty ) assertWarning ( w , '' ) ", "answer": "with self . warnings_catcher ( ) as w :"}, {"prompt": " \"\"\"\"\"\" import os import warnings from twisted . mail import mail from twisted . mail import maildir from twisted . mail import relay from twisted . mail import relaymanager from twisted . mail import alias from twisted . internet import endpoints from twisted . python import usage ", "answer": "from twisted . cred import checkers"}, {"prompt": " import unittest from resync . mapper import Mapper , MapperError , Map class TestMapper ( unittest . TestCase ) : def test00_mapper_creation ( self ) : m1 = Mapper ( [ '' , '' ] ) self . assertEqual ( len ( m1 ) , ) m2 = Mapper ( mappings = [ '' , '' ] ) self . assertEqual ( len ( m2 ) , ) self . assertEqual ( str ( m1 ) , str ( m2 ) ) m3 = Mapper ( [ '' ] ) self . assertEqual ( len ( m3 ) , ) self . assertEqual ( str ( m1 ) , str ( m3 ) ) m4 = Mapper ( [ '' , '' ] ) m5 = Mapper ( [ '' , '' ] ) self . assertEqual ( len ( m4 ) , ) ", "answer": "self . assertEqual ( len ( m5 ) , )"}, {"prompt": " from muntjac . ui . window import Window from muntjac . demo . sampler . APIResource import APIResource from muntjac . demo . sampler . Feature import Feature , Version class SubwindowAutoSized ( Feature ) : def getSinceVersion ( self ) : return Version . OLD def getName ( self ) : return '' def getDescription ( self ) : return ( '' '' '' '' ) def getRelatedAPI ( self ) : return [ APIResource ( Window ) ] def getRelatedFeatures ( self ) : from muntjac . demo . sampler . FeatureSet import Windows from muntjac . demo . sampler . features . windows . SubwindowSized import SubwindowSized return [ SubwindowSized , Windows ] def getRelatedResources ( self ) : ", "answer": "return None "}, {"prompt": " import struct import string from binascii import crc32 from ImpactPacket import ProtocolPacket from Dot11Crypto import RC4 frequency = { : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , : , } class Dot11ManagementCapabilities ( ) : CAPABILITY_RESERVED_1 = int ( \"\" , ) CAPABILITY_RESERVED_2 = int ( \"\" , ) CAPABILITY_DSSS_OFDM = int ( \"\" , ) CAPABILITY_RESERVED_3 = int ( \"\" , ) CAPABILITY_RESERVED_4 = int ( \"\" , ) CAPABILITY_SHORT_SLOT_TIME = int ( \"\" , ) CAPABILITY_RESERVED_5 = int ( \"\" , ) CAPABILITY_RESERVED_6 = int ( \"\" , ) CAPABILITY_CH_AGILITY = int ( \"\" , ) CAPABILITY_PBCC = int ( \"\" , ) CAPABILITY_SHORT_PREAMBLE = int ( \"\" , ) CAPABILITY_PRIVACY = int ( \"\" , ) CAPABILITY_CF_POLL_REQ = int ( \"\" , ) CAPABILITY_CF_POLLABLE = int ( \"\" , ) CAPABILITY_IBSS = int ( \"\" , ) CAPABILITY_ESS = int ( \"\" , ) class Dot11Types ( ) : DOT11_TYPE_MANAGEMENT = int ( \"\" , ) DOT11_SUBTYPE_MANAGEMENT_ASSOCIATION_REQUEST = int ( \"\" , ) DOT11_SUBTYPE_MANAGEMENT_ASSOCIATION_RESPONSE = int ( \"\" , ) DOT11_SUBTYPE_MANAGEMENT_REASSOCIATION_REQUEST = int ( \"\" , ) DOT11_SUBTYPE_MANAGEMENT_REASSOCIATION_RESPONSE = int ( \"\" , ) DOT11_SUBTYPE_MANAGEMENT_PROBE_REQUEST = int ( \"\" , ) DOT11_SUBTYPE_MANAGEMENT_PROBE_RESPONSE = int ( \"\" , ) DOT11_SUBTYPE_MANAGEMENT_RESERVED1 = int ( \"\" , ) DOT11_SUBTYPE_MANAGEMENT_RESERVED2 = int ( \"\" , ) DOT11_SUBTYPE_MANAGEMENT_BEACON = int ( \"\" , ) DOT11_SUBTYPE_MANAGEMENT_ATIM = int ( \"\" , ) DOT11_SUBTYPE_MANAGEMENT_DISASSOCIATION = int ( \"\" , ) DOT11_SUBTYPE_MANAGEMENT_AUTHENTICATION = int ( \"\" , ) DOT11_SUBTYPE_MANAGEMENT_DEAUTHENTICATION = int ( \"\" , ) DOT11_SUBTYPE_MANAGEMENT_ACTION = int ( \"\" , ) DOT11_SUBTYPE_MANAGEMENT_RESERVED3 = int ( \"\" , ) DOT11_SUBTYPE_MANAGEMENT_RESERVED4 = int ( \"\" , ) DOT11_TYPE_MANAGEMENT_SUBTYPE_ASSOCIATION_REQUEST = DOT11_TYPE_MANAGEMENT | DOT11_SUBTYPE_MANAGEMENT_ASSOCIATION_REQUEST << DOT11_TYPE_MANAGEMENT_SUBTYPE_ASSOCIATION_RESPONSE = DOT11_TYPE_MANAGEMENT | DOT11_SUBTYPE_MANAGEMENT_ASSOCIATION_RESPONSE << DOT11_TYPE_MANAGEMENT_SUBTYPE_REASSOCIATION_REQUEST = DOT11_TYPE_MANAGEMENT | DOT11_SUBTYPE_MANAGEMENT_REASSOCIATION_REQUEST << DOT11_TYPE_MANAGEMENT_SUBTYPE_REASSOCIATION_RESPONSE = DOT11_TYPE_MANAGEMENT | DOT11_SUBTYPE_MANAGEMENT_REASSOCIATION_RESPONSE << DOT11_TYPE_MANAGEMENT_SUBTYPE_PROBE_REQUEST = DOT11_TYPE_MANAGEMENT | DOT11_SUBTYPE_MANAGEMENT_PROBE_REQUEST << DOT11_TYPE_MANAGEMENT_SUBTYPE_PROBE_RESPONSE = DOT11_TYPE_MANAGEMENT | DOT11_SUBTYPE_MANAGEMENT_PROBE_RESPONSE << DOT11_TYPE_MANAGEMENT_SUBTYPE_RESERVED1 = DOT11_TYPE_MANAGEMENT | DOT11_SUBTYPE_MANAGEMENT_RESERVED1 << DOT11_TYPE_MANAGEMENT_SUBTYPE_RESERVED2 = DOT11_TYPE_MANAGEMENT | DOT11_SUBTYPE_MANAGEMENT_RESERVED2 << DOT11_TYPE_MANAGEMENT_SUBTYPE_BEACON = DOT11_TYPE_MANAGEMENT | DOT11_SUBTYPE_MANAGEMENT_BEACON << DOT11_TYPE_MANAGEMENT_SUBTYPE_ATIM = DOT11_TYPE_MANAGEMENT | DOT11_SUBTYPE_MANAGEMENT_ATIM << DOT11_TYPE_MANAGEMENT_SUBTYPE_DISASSOCIATION = DOT11_TYPE_MANAGEMENT | DOT11_SUBTYPE_MANAGEMENT_DISASSOCIATION << DOT11_TYPE_MANAGEMENT_SUBTYPE_AUTHENTICATION = DOT11_TYPE_MANAGEMENT | DOT11_SUBTYPE_MANAGEMENT_AUTHENTICATION << DOT11_TYPE_MANAGEMENT_SUBTYPE_DEAUTHENTICATION = DOT11_TYPE_MANAGEMENT | DOT11_SUBTYPE_MANAGEMENT_DEAUTHENTICATION << DOT11_TYPE_MANAGEMENT_SUBTYPE_ACTION = DOT11_TYPE_MANAGEMENT | DOT11_SUBTYPE_MANAGEMENT_ACTION << DOT11_TYPE_MANAGEMENT_SUBTYPE_RESERVED3 = DOT11_TYPE_MANAGEMENT | DOT11_SUBTYPE_MANAGEMENT_RESERVED3 << DOT11_TYPE_MANAGEMENT_SUBTYPE_RESERVED4 = DOT11_TYPE_MANAGEMENT | DOT11_SUBTYPE_MANAGEMENT_RESERVED4 << DOT11_TYPE_CONTROL = int ( \"\" , ) DOT11_SUBTYPE_CONTROL_RESERVED1 = int ( \"\" , ) DOT11_SUBTYPE_CONTROL_RESERVED2 = int ( \"\" , ) DOT11_SUBTYPE_CONTROL_RESERVED3 = int ( \"\" , ) DOT11_SUBTYPE_CONTROL_RESERVED4 = int ( \"\" , ) DOT11_SUBTYPE_CONTROL_RESERVED5 = int ( \"\" , ) DOT11_SUBTYPE_CONTROL_RESERVED6 = int ( \"\" , ) DOT11_SUBTYPE_CONTROL_RESERVED7 = int ( \"\" , ) DOT11_SUBTYPE_CONTROL_RESERVED8 = int ( \"\" , ) DOT11_SUBTYPE_CONTROL_BLOCK_ACK_REQUEST = int ( \"\" , ) DOT11_SUBTYPE_CONTROL_BLOCK_ACK = int ( \"\" , ) DOT11_SUBTYPE_CONTROL_POWERSAVE_POLL = int ( \"\" , ) DOT11_SUBTYPE_CONTROL_REQUEST_TO_SEND = int ( \"\" , ) DOT11_SUBTYPE_CONTROL_CLEAR_TO_SEND = int ( \"\" , ) DOT11_SUBTYPE_CONTROL_ACKNOWLEDGMENT = int ( \"\" , ) DOT11_SUBTYPE_CONTROL_CF_END = int ( \"\" , ) DOT11_SUBTYPE_CONTROL_CF_END_CF_ACK = int ( \"\" , ) DOT11_TYPE_CONTROL_SUBTYPE_RESERVED1 = DOT11_TYPE_CONTROL | DOT11_SUBTYPE_CONTROL_RESERVED1 << DOT11_TYPE_CONTROL_SUBTYPE_RESERVED2 = DOT11_TYPE_CONTROL | DOT11_SUBTYPE_CONTROL_RESERVED2 << DOT11_TYPE_CONTROL_SUBTYPE_RESERVED3 = DOT11_TYPE_CONTROL | DOT11_SUBTYPE_CONTROL_RESERVED3 << DOT11_TYPE_CONTROL_SUBTYPE_RESERVED4 = DOT11_TYPE_CONTROL | DOT11_SUBTYPE_CONTROL_RESERVED4 << DOT11_TYPE_CONTROL_SUBTYPE_RESERVED5 = DOT11_TYPE_CONTROL | DOT11_SUBTYPE_CONTROL_RESERVED5 << DOT11_TYPE_CONTROL_SUBTYPE_RESERVED6 = DOT11_TYPE_CONTROL | DOT11_SUBTYPE_CONTROL_RESERVED6 << DOT11_TYPE_CONTROL_SUBTYPE_RESERVED7 = DOT11_TYPE_CONTROL | DOT11_SUBTYPE_CONTROL_RESERVED7 << DOT11_TYPE_CONTROL_SUBTYPE_BLOCK_ACK_REQUEST = DOT11_TYPE_CONTROL | DOT11_SUBTYPE_CONTROL_BLOCK_ACK_REQUEST << DOT11_TYPE_CONTROL_SUBTYPE_BLOCK_ACK = DOT11_TYPE_CONTROL | DOT11_SUBTYPE_CONTROL_BLOCK_ACK << DOT11_TYPE_CONTROL_SUBTYPE_POWERSAVE_POLL = DOT11_TYPE_CONTROL | DOT11_SUBTYPE_CONTROL_POWERSAVE_POLL << DOT11_TYPE_CONTROL_SUBTYPE_REQUEST_TO_SEND = DOT11_TYPE_CONTROL | DOT11_SUBTYPE_CONTROL_REQUEST_TO_SEND << DOT11_TYPE_CONTROL_SUBTYPE_CLEAR_TO_SEND = DOT11_TYPE_CONTROL | DOT11_SUBTYPE_CONTROL_CLEAR_TO_SEND << DOT11_TYPE_CONTROL_SUBTYPE_ACKNOWLEDGMENT = DOT11_TYPE_CONTROL | DOT11_SUBTYPE_CONTROL_ACKNOWLEDGMENT << DOT11_TYPE_CONTROL_SUBTYPE_CF_END = DOT11_TYPE_CONTROL | DOT11_SUBTYPE_CONTROL_CF_END << DOT11_TYPE_CONTROL_SUBTYPE_CF_END_CF_ACK = DOT11_TYPE_CONTROL | DOT11_SUBTYPE_CONTROL_CF_END_CF_ACK << DOT11_TYPE_DATA = int ( \"\" , ) DOT11_SUBTYPE_DATA = int ( \"\" , ) DOT11_SUBTYPE_DATA_CF_ACK = int ( \"\" , ) DOT11_SUBTYPE_DATA_CF_POLL = int ( \"\" , ) DOT11_SUBTYPE_DATA_CF_ACK_CF_POLL = int ( \"\" , ) DOT11_SUBTYPE_DATA_NULL_NO_DATA = int ( \"\" , ) DOT11_SUBTYPE_DATA_CF_ACK_NO_DATA = int ( \"\" , ) DOT11_SUBTYPE_DATA_CF_POLL_NO_DATA = int ( \"\" , ) DOT11_SUBTYPE_DATA_CF_ACK_CF_POLL_NO_DATA = int ( \"\" , ) DOT11_SUBTYPE_DATA_QOS_DATA = int ( \"\" , ) DOT11_SUBTYPE_DATA_QOS_DATA_CF_ACK = int ( \"\" , ) DOT11_SUBTYPE_DATA_QOS_DATA_CF_POLL = int ( \"\" , ) DOT11_SUBTYPE_DATA_QOS_DATA_CF_ACK_CF_POLL = int ( \"\" , ) DOT11_SUBTYPE_DATA_QOS_NULL_NO_DATA = int ( \"\" , ) DOT11_SUBTYPE_DATA_RESERVED1 = int ( \"\" , ) DOT11_SUBTYPE_DATA_QOS_CF_POLL_NO_DATA = int ( \"\" , ) DOT11_SUBTYPE_DATA_QOS_CF_ACK_CF_POLL_NO_DATA = int ( \"\" , ) DOT11_TYPE_DATA_SUBTYPE_DATA = DOT11_TYPE_DATA | DOT11_SUBTYPE_DATA << DOT11_TYPE_DATA_SUBTYPE_CF_ACK = DOT11_TYPE_DATA | DOT11_SUBTYPE_DATA_CF_ACK << DOT11_TYPE_DATA_SUBTYPE_CF_POLL = DOT11_TYPE_DATA | DOT11_SUBTYPE_DATA_CF_POLL << DOT11_TYPE_DATA_SUBTYPE_CF_ACK_CF_POLL = DOT11_TYPE_DATA | DOT11_SUBTYPE_DATA_CF_ACK_CF_POLL << DOT11_TYPE_DATA_SUBTYPE_NULL_NO_DATA = DOT11_TYPE_DATA | DOT11_SUBTYPE_DATA_NULL_NO_DATA << DOT11_TYPE_DATA_SUBTYPE_CF_ACK_NO_DATA = DOT11_TYPE_DATA | DOT11_SUBTYPE_DATA_CF_POLL_NO_DATA << DOT11_TYPE_DATA_SUBTYPE_CF_ACK_CF_POLL_NO_DATA = DOT11_TYPE_DATA | DOT11_SUBTYPE_DATA_CF_ACK_CF_POLL_NO_DATA << DOT11_TYPE_DATA_SUBTYPE_QOS_DATA = DOT11_TYPE_DATA | DOT11_SUBTYPE_DATA_QOS_DATA << DOT11_TYPE_DATA_SUBTYPE_QOS_DATA_CF_ACK = DOT11_TYPE_DATA | DOT11_SUBTYPE_DATA_QOS_DATA_CF_ACK << DOT11_TYPE_DATA_SUBTYPE_QOS_DATA_CF_POLL = DOT11_TYPE_DATA | DOT11_SUBTYPE_DATA_QOS_DATA_CF_POLL << DOT11_TYPE_DATA_SUBTYPE_QOS_DATA_CF_ACK_CF_POLL = DOT11_TYPE_DATA | DOT11_SUBTYPE_DATA_QOS_DATA_CF_ACK_CF_POLL << DOT11_TYPE_DATA_SUBTYPE_QOS_NULL_NO_DATA = DOT11_TYPE_DATA | DOT11_SUBTYPE_DATA_QOS_NULL_NO_DATA << DOT11_TYPE_DATA_SUBTYPE_RESERVED1 = DOT11_TYPE_DATA | DOT11_SUBTYPE_DATA_RESERVED1 << DOT11_TYPE_DATA_SUBTYPE_QOS_CF_POLL_NO_DATA = DOT11_TYPE_DATA | DOT11_SUBTYPE_DATA_QOS_CF_POLL_NO_DATA << DOT11_TYPE_DATA_SUBTYPE_QOS_CF_ACK_CF_POLL_NO_DATA = DOT11_TYPE_DATA | DOT11_SUBTYPE_DATA_QOS_CF_ACK_CF_POLL_NO_DATA << DOT11_TYPE_RESERVED = int ( \"\" , ) DOT11_SUBTYPE_RESERVED_RESERVED1 = int ( \"\" , ) DOT11_SUBTYPE_RESERVED_RESERVED2 = int ( \"\" , ) DOT11_SUBTYPE_RESERVED_RESERVED3 = int ( \"\" , ) DOT11_SUBTYPE_RESERVED_RESERVED4 = int ( \"\" , ) DOT11_SUBTYPE_RESERVED_RESERVED5 = int ( \"\" , ) DOT11_SUBTYPE_RESERVED_RESERVED6 = int ( \"\" , ) DOT11_SUBTYPE_RESERVED_RESERVED7 = int ( \"\" , ) DOT11_SUBTYPE_RESERVED_RESERVED8 = int ( \"\" , ) DOT11_SUBTYPE_RESERVED_RESERVED9 = int ( \"\" , ) DOT11_SUBTYPE_RESERVED_RESERVED10 = int ( \"\" , ) DOT11_SUBTYPE_RESERVED_RESERVED11 = int ( \"\" , ) DOT11_SUBTYPE_RESERVED_RESERVED12 = int ( \"\" , ) DOT11_SUBTYPE_RESERVED_RESERVED13 = int ( \"\" , ) DOT11_SUBTYPE_RESERVED_RESERVED14 = int ( \"\" , ) DOT11_SUBTYPE_RESERVED_RESERVED15 = int ( \"\" , ) DOT11_SUBTYPE_RESERVED_RESERVED16 = int ( \"\" , ) DOT11_TYPE_RESERVED_SUBTYPE_RESERVED1 = DOT11_TYPE_RESERVED | DOT11_SUBTYPE_RESERVED_RESERVED1 << DOT11_TYPE_RESERVED_SUBTYPE_RESERVED2 = DOT11_TYPE_RESERVED | DOT11_SUBTYPE_RESERVED_RESERVED2 << DOT11_TYPE_RESERVED_SUBTYPE_RESERVED3 = DOT11_TYPE_RESERVED | DOT11_SUBTYPE_RESERVED_RESERVED3 << DOT11_TYPE_RESERVED_SUBTYPE_RESERVED4 = DOT11_TYPE_RESERVED | DOT11_SUBTYPE_RESERVED_RESERVED4 << DOT11_TYPE_RESERVED_SUBTYPE_RESERVED5 = DOT11_TYPE_RESERVED | DOT11_SUBTYPE_RESERVED_RESERVED5 << DOT11_TYPE_RESERVED_SUBTYPE_RESERVED6 = DOT11_TYPE_RESERVED | DOT11_SUBTYPE_RESERVED_RESERVED6 << DOT11_TYPE_RESERVED_SUBTYPE_RESERVED7 = DOT11_TYPE_RESERVED | DOT11_SUBTYPE_RESERVED_RESERVED7 << DOT11_TYPE_RESERVED_SUBTYPE_RESERVED8 = DOT11_TYPE_RESERVED | DOT11_SUBTYPE_RESERVED_RESERVED8 << DOT11_TYPE_RESERVED_SUBTYPE_RESERVED9 = DOT11_TYPE_RESERVED | DOT11_SUBTYPE_RESERVED_RESERVED9 << DOT11_TYPE_RESERVED_SUBTYPE_RESERVED10 = DOT11_TYPE_RESERVED | DOT11_SUBTYPE_RESERVED_RESERVED10 << DOT11_TYPE_RESERVED_SUBTYPE_RESERVED11 = DOT11_TYPE_RESERVED | DOT11_SUBTYPE_RESERVED_RESERVED11 << DOT11_TYPE_RESERVED_SUBTYPE_RESERVED12 = DOT11_TYPE_RESERVED | DOT11_SUBTYPE_RESERVED_RESERVED12 << DOT11_TYPE_RESERVED_SUBTYPE_RESERVED13 = DOT11_TYPE_RESERVED | DOT11_SUBTYPE_RESERVED_RESERVED13 << DOT11_TYPE_RESERVED_SUBTYPE_RESERVED14 = DOT11_TYPE_RESERVED | DOT11_SUBTYPE_RESERVED_RESERVED14 << DOT11_TYPE_RESERVED_SUBTYPE_RESERVED15 = DOT11_TYPE_RESERVED | DOT11_SUBTYPE_RESERVED_RESERVED15 << DOT11_TYPE_RESERVED_SUBTYPE_RESERVED16 = DOT11_TYPE_RESERVED | DOT11_SUBTYPE_RESERVED_RESERVED16 << class Dot11 ( ProtocolPacket ) : def __init__ ( self , aBuffer = None , FCS_at_end = True ) : header_size = self . __FCS_at_end = not not FCS_at_end if self . __FCS_at_end : tail_size = else : tail_size = ProtocolPacket . __init__ ( self , header_size , tail_size ) if ( aBuffer ) : self . load_packet ( aBuffer ) def get_order ( self ) : \"\" b = self . header . get_byte ( ) return ( ( b >> ) & ) def set_order ( self , value ) : \"\" mask = ( ~ ) & masked = self . header . get_byte ( ) & mask nb = masked | ( ( value & ) << ) self . header . set_byte ( , nb ) def get_protectedFrame ( self ) : \"\" b = self . header . get_byte ( ) return ( ( b >> ) & ) def set_protectedFrame ( self , value ) : \"\" mask = ( ~ ) & masked = self . header . get_byte ( ) & mask nb = masked | ( ( value & ) << ) self . header . set_byte ( , nb ) def get_moreData ( self ) : \"\" b = self . header . get_byte ( ) return ( ( b >> ) & ) def set_moreData ( self , value ) : \"\" mask = ( ~ ) & masked = self . header . get_byte ( ) & mask nb = masked | ( ( value & ) << ) self . header . set_byte ( , nb ) def get_powerManagement ( self ) : \"\" b = self . header . get_byte ( ) return ( ( b >> ) & ) def set_powerManagement ( self , value ) : \"\" mask = ( ~ ) & masked = self . header . get_byte ( ) & mask nb = masked | ( ( value & ) << ) self . header . set_byte ( , nb ) def get_retry ( self ) : \"\" b = self . header . get_byte ( ) return ( ( b >> ) & ) def set_retry ( self , value ) : \"\" mask = ( ~ ) & masked = self . header . get_byte ( ) & mask nb = masked | ( ( value & ) << ) self . header . set_byte ( , nb ) def get_moreFrag ( self ) : \"\" b = self . header . get_byte ( ) return ( ( b >> ) & ) def set_moreFrag ( self , value ) : \"\" mask = ( ~ ) & masked = self . header . get_byte ( ) & mask nb = masked | ( ( value & ) << ) self . header . set_byte ( , nb ) def get_fromDS ( self ) : \"\" b = self . header . get_byte ( ) return ( ( b >> ) & ) def set_fromDS ( self , value ) : \"\" mask = ( ~ ) & masked = self . header . get_byte ( ) & mask nb = masked | ( ( value & ) << ) self . header . set_byte ( , nb ) def get_toDS ( self ) : \"\" b = self . header . get_byte ( ) return ( b & ) def set_toDS ( self , value ) : \"\" mask = ( ~ ) & masked = self . header . get_byte ( ) & mask nb = masked | ( value & ) self . header . set_byte ( , nb ) def get_subtype ( self ) : \"\" b = self . header . get_byte ( ) return ( ( b >> ) & ) def set_subtype ( self , value ) : \"\" mask = ( ~ ) & masked = self . header . get_byte ( ) & mask nb = masked | ( ( value << ) & ) self . header . set_byte ( , nb ) def get_type ( self ) : \"\" b = self . header . get_byte ( ) return ( ( b >> ) & ) def set_type ( self , value ) : \"\" mask = ( ~ ) & masked = self . header . get_byte ( ) & mask nb = masked | ( ( value << ) & ) self . header . set_byte ( , nb ) def get_type_n_subtype ( self ) : \"\" b = self . header . get_byte ( ) return ( ( b >> ) & ) def set_type_n_subtype ( self , value ) : \"\" mask = ( ~ ) & masked = self . header . get_byte ( ) & mask nb = masked | ( ( value << ) & ) self . header . set_byte ( , nb ) def get_version ( self ) : \"\" b = self . header . get_byte ( ) return ( b & ) def set_version ( self , value ) : \"\" mask = ( ~ ) & masked = self . header . get_byte ( ) & mask nb = masked | ( value & ) self . header . set_byte ( , nb ) def compute_checksum ( self , bytes ) : crcle = crc32 ( bytes ) & L crc = struct . pack ( '' , crcle ) ( crc_long , ) = struct . unpack ( '' , crc ) return crc_long def is_QoS_frame ( self ) : \"\" b = self . header . get_byte ( ) return ( b & ) and True def is_no_framebody_frame ( self ) : \"\" b = self . header . get_byte ( ) return ( b & ) and True def is_cf_poll_frame ( self ) : \"\" b = self . header . get_byte ( ) return ( b & ) and True def is_cf_ack_frame ( self ) : \"\" b = self . header . get_byte ( ) return ( b & ) and True def get_fcs ( self ) : \"\" if not self . __FCS_at_end : return None b = self . tail . get_long ( - , \">\" ) return b def set_fcs ( self , value = None ) : \"\" if not self . __FCS_at_end : return if value is None : payload = self . get_body_as_string ( ) crc32 = self . compute_checksum ( payload ) value = crc32 nb = value & self . tail . set_long ( - , nb ) class Dot11ControlFrameCTS ( ProtocolPacket ) : \"\" def __init__ ( self , aBuffer = None ) : header_size = tail_size = ProtocolPacket . __init__ ( self , header_size , tail_size ) if ( aBuffer ) : self . load_packet ( aBuffer ) def get_duration ( self ) : \"\" b = self . header . get_word ( , \"\" ) return b def set_duration ( self , value ) : \"\" nb = value & self . header . set_word ( , nb , \"\" ) def get_ra ( self ) : \"\" return self . header . get_bytes ( ) [ : ] def set_ra ( self , value ) : \"\" for i in range ( , ) : self . header . set_byte ( + i , value [ i ] ) class Dot11ControlFrameACK ( ProtocolPacket ) : \"\" def __init__ ( self , aBuffer = None ) : header_size = tail_size = ProtocolPacket . __init__ ( self , header_size , tail_size ) if ( aBuffer ) : self . load_packet ( aBuffer ) def get_duration ( self ) : \"\" b = self . header . get_word ( , \"\" ) return b def set_duration ( self , value ) : \"\" nb = value & self . header . set_word ( , nb , \"\" ) def get_ra ( self ) : \"\" return self . header . get_bytes ( ) [ : ] def set_ra ( self , value ) : \"\" for i in range ( , ) : self . header . set_byte ( + i , value [ i ] ) class Dot11ControlFrameRTS ( ProtocolPacket ) : \"\" def __init__ ( self , aBuffer = None ) : header_size = tail_size = ProtocolPacket . __init__ ( self , header_size , tail_size ) if ( aBuffer ) : self . load_packet ( aBuffer ) def get_duration ( self ) : \"\" b = self . header . get_word ( , \"\" ) return b def set_duration ( self , value ) : \"\" nb = value & self . header . set_word ( , nb , \"\" ) def get_ra ( self ) : \"\" return self . header . get_bytes ( ) [ : ] def set_ra ( self , value ) : \"\" for i in range ( , ) : self . header . set_byte ( + i , value [ i ] ) def get_ta ( self ) : \"\" return self . header . get_bytes ( ) [ : ] def set_ta ( self , value ) : \"\" for i in range ( , ) : self . header . set_byte ( + i , value [ i ] ) class Dot11ControlFramePSPoll ( ProtocolPacket ) : \"\" def __init__ ( self , aBuffer = None ) : header_size = tail_size = ProtocolPacket . __init__ ( self , header_size , tail_size ) if ( aBuffer ) : self . load_packet ( aBuffer ) def get_aid ( self ) : \"\" b = self . header . get_word ( , \"\" ) return b def set_aid ( self , value ) : \"\" nb = value & self . header . set_word ( , nb , \"\" ) def get_bssid ( self ) : \"\" return self . header . get_bytes ( ) [ : ] def set_bssid ( self , value ) : \"\" for i in range ( , ) : self . header . set_byte ( + i , value [ i ] ) def get_ta ( self ) : \"\" return self . header . get_bytes ( ) [ : ] def set_ta ( self , value ) : \"\" for i in range ( , ) : self . header . set_byte ( + i , value [ i ] ) class Dot11ControlFrameCFEnd ( ProtocolPacket ) : \"\" def __init__ ( self , aBuffer = None ) : header_size = tail_size = ProtocolPacket . __init__ ( self , header_size , tail_size ) if ( aBuffer ) : self . load_packet ( aBuffer ) def get_duration ( self ) : \"\" b = self . header . get_word ( , \"\" ) return b def set_duration ( self , value ) : \"\" nb = value & self . header . set_word ( , nb , \"\" ) def get_ra ( self ) : \"\" return self . header . get_bytes ( ) [ : ] def set_ra ( self , value ) : \"\" for i in range ( , ) : self . header . set_byte ( + i , value [ i ] ) def get_bssid ( self ) : \"\" return self . header . get_bytes ( ) [ : ] def set_bssid ( self , value ) : \"\" for i in range ( , ) : self . header . set_byte ( + i , value [ i ] ) class Dot11ControlFrameCFEndCFACK ( ProtocolPacket ) : '' def __init__ ( self , aBuffer = None ) : header_size = tail_size = ProtocolPacket . __init__ ( self , header_size , tail_size ) if ( aBuffer ) : self . load_packet ( aBuffer ) def get_duration ( self ) : '' b = self . header . get_word ( , \"\" ) return b def set_duration ( self , value ) : '' nb = value & self . header . set_word ( , nb , \"\" ) def get_ra ( self ) : '' return self . header . get_bytes ( ) [ : ] def set_ra ( self , value ) : '' for i in range ( , ) : self . header . set_byte ( + i , value [ i ] ) def get_bssid ( self ) : '' return self . header . get_bytes ( ) [ : ] def set_bssid ( self , value ) : '' for i in range ( , ) : self . header . set_byte ( + i , value [ i ] ) class Dot11DataFrame ( ProtocolPacket ) : '' def __init__ ( self , aBuffer = None ) : header_size = tail_size = ProtocolPacket . __init__ ( self , header_size , tail_size ) if ( aBuffer ) : self . load_packet ( aBuffer ) def get_duration ( self ) : '' b = self . header . get_word ( , \"\" ) return b def set_duration ( self , value ) : '' nb = value & self . header . set_word ( , nb , \"\" ) def get_address1 ( self ) : '' return self . header . get_bytes ( ) [ : ] def set_address1 ( self , value ) : '' for i in range ( , ) : self . header . set_byte ( + i , value [ i ] ) def get_address2 ( self ) : '' return self . header . get_bytes ( ) [ : ] def set_address2 ( self , value ) : '' for i in range ( , ) : self . header . set_byte ( + i , value [ i ] ) def get_address3 ( self ) : '' return self . header . get_bytes ( ) [ : ] def set_address3 ( self , value ) : '' for i in range ( , ) : self . header . set_byte ( + i , value [ i ] ) def get_sequence_control ( self ) : '' b = self . header . get_word ( , \"\" ) return b def set_sequence_control ( self , value ) : '' nb = value & self . header . set_word ( , nb , \"\" ) def get_fragment_number ( self ) : '' b = self . header . get_word ( , \"\" ) return ( b & ) def set_fragment_number ( self , value ) : '' mask = ( ~ ) & masked = self . header . get_word ( , \"\" ) & mask nb = masked | ( value & ) self . header . set_word ( , nb , \"\" ) def get_sequence_number ( self ) : '' b = self . header . get_word ( , \"\" ) return ( ( b >> ) & ) def set_sequence_number ( self , value ) : '' mask = ( ~ ) & masked = self . header . get_word ( , \"\" ) & mask nb = masked | ( ( value & ) << ) self . header . set_word ( , nb , \"\" ) def get_frame_body ( self ) : '' return self . get_body_as_string ( ) def set_frame_body ( self , data ) : '' self . load_body ( data ) class Dot11DataQoSFrame ( Dot11DataFrame ) : '' def __init__ ( self , aBuffer = None ) : header_size = tail_size = ProtocolPacket . __init__ ( self , header_size , tail_size ) if ( aBuffer ) : self . load_packet ( aBuffer ) def get_QoS ( self ) : '' b = self . header . get_word ( , \"\" ) return b def set_QoS ( self , value ) : '' nb = value & self . header . set_word ( , nb , \"\" ) class Dot11DataAddr4Frame ( Dot11DataFrame ) : '' def __init__ ( self , aBuffer = None ) : header_size = tail_size = ProtocolPacket . __init__ ( self , header_size , tail_size ) if ( aBuffer ) : self . load_packet ( aBuffer ) def get_address4 ( self ) : '' return self . header . get_bytes ( ) [ : ] def set_address4 ( self , value ) : '' for i in range ( , ) : self . header . set_byte ( + i , value [ i ] ) class Dot11DataAddr4QoSFrame ( Dot11DataAddr4Frame ) : '' def __init__ ( self , aBuffer = None ) : header_size = tail_size = ProtocolPacket . __init__ ( self , header_size , tail_size ) if ( aBuffer ) : self . load_packet ( aBuffer ) def get_QoS ( self ) : '' b = self . header . get_word ( , \"\" ) return b def set_QoS ( self , value ) : '' nb = value & self . header . set_word ( , nb , \"\" ) class SAPTypes ( ) : NULL = LLC_SLMGMT = SNA_PATHCTRL = IP = SNA1 = SNA2 = PROWAY_NM_INIT = NETWARE1 = OSINL1 = TI = OSINL2 = OSINL3 = SNA3 = BPDU = RS511 = OSINL4 = X25 = XNS = BACNET = NESTAR = PROWAY_ASLM = ARP = SNAP = HPJD = VINES1 = VINES2 = NETWARE2 = NETBIOS = IBMNM = HPEXT = UB = RPL = OSINL5 = GLOBAL = class LLC ( ProtocolPacket ) : '' DLC_UNNUMBERED_FRAMES = def __init__ ( self , aBuffer = None ) : header_size = tail_size = ProtocolPacket . __init__ ( self , header_size , tail_size ) if ( aBuffer ) : self . load_packet ( aBuffer ) def get_DSAP ( self ) : \"\" return self . header . get_byte ( ) def set_DSAP ( self , value ) : \"\" self . header . set_byte ( , value ) def get_SSAP ( self ) : \"\" return self . header . get_byte ( ) def set_SSAP ( self , value ) : \"\" self . header . set_byte ( , value ) def get_control ( self ) : \"\" return self . header . get_byte ( ) def set_control ( self , value ) : \"\" self . header . set_byte ( , value ) class SNAP ( ProtocolPacket ) : '' def __init__ ( self , aBuffer = None ) : header_size = tail_size = ProtocolPacket . __init__ ( self , header_size , tail_size ) if ( aBuffer ) : self . load_packet ( aBuffer ) def get_OUI ( self ) : \"\" b = self . header . get_bytes ( ) [ : ] . tostring ( ) ( oui , ) = struct . unpack ( '' , '' + b ) return oui def set_OUI ( self , value ) : \"\" mask = ( ( ~ ) & ) masked = self . header . get_long ( , \">\" ) & mask nb = masked | ( ( value & ) << ) self . header . set_long ( , nb ) def get_protoID ( self ) : \"\" return self . header . get_word ( , \">\" ) def set_protoID ( self , value ) : \"\" self . header . set_word ( , value , \">\" ) class Dot11WEP ( ProtocolPacket ) : '' def __init__ ( self , aBuffer = None ) : header_size = tail_size = ProtocolPacket . __init__ ( self , header_size , tail_size ) if ( aBuffer ) : self . load_packet ( aBuffer ) def is_WEP ( self ) : '' b = self . header . get_byte ( ) return not ( b & ) def get_iv ( self ) : '' b = self . header . get_bytes ( ) [ : ] . tostring ( ) ( iv , ) = struct . unpack ( '' , '' + b ) return iv def set_iv ( self , value ) : '' mask = ( ( ~ ) & ) masked = self . header . get_long ( , \">\" ) & mask nb = masked | ( ( value & ) << ) self . header . set_long ( , nb ) def get_keyid ( self ) : '' b = self . header . get_byte ( ) return ( ( b >> ) & ) def set_keyid ( self , value ) : '' mask = ( ~ ) & masked = self . header . get_byte ( ) & mask nb = masked | ( ( value & ) << ) self . header . set_byte ( , nb ) def get_decrypted_data ( self , key_string ) : '' if len ( self . body_string ) < : return self . body_string iv = struct . pack ( '' , self . get_iv ( ) ) [ - : ] key = iv + key_string rc4 = RC4 ( key ) decrypted_data = rc4 . decrypt ( self . body_string ) return decrypted_data def get_encrypted_data ( self , key_string ) : return self . get_decrypted_data ( key_string ) def encrypt_frame ( self , key_string ) : enc = self . get_encrypted_data ( key_string ) self . load_body ( enc ) class Dot11WEPData ( ProtocolPacket ) : '' def __init__ ( self , aBuffer = None ) : header_size = tail_size = ProtocolPacket . __init__ ( self , header_size , tail_size ) if ( aBuffer ) : self . load_packet ( aBuffer ) def get_icv ( self ) : \"\" b = self . tail . get_long ( - , \">\" ) return b def set_icv ( self , value = None ) : \"\" if value is None : value = self . get_computed_icv ( ) nb = value & self . tail . set_long ( - , nb ) def get_computed_icv ( self ) : crcle = crc32 ( self . body_string ) & L crc = struct . pack ( '' , crcle ) ( crc_long , ) = struct . unpack ( '' , crc ) return crc_long def check_icv ( self ) : computed_icv = self . get_computed_icv ( ) current_icv = self . get_icv ( ) if computed_icv == current_icv : return True else : return False class Dot11WPA ( ProtocolPacket ) : '' def __init__ ( self , aBuffer = None ) : header_size = tail_size = ProtocolPacket . __init__ ( self , header_size , tail_size ) if ( aBuffer ) : self . load_packet ( aBuffer ) def is_WPA ( self ) : '' b = self . get_WEPSeed ( ) == ( ( self . get_TSC1 ( ) | ) & ) return ( b and self . get_extIV ( ) ) def get_keyid ( self ) : '' b = self . header . get_byte ( ) return ( ( b >> ) & ) def set_keyid ( self , value ) : '' mask = ( ~ ) & masked = self . header . get_byte ( ) & mask nb = masked | ( ( value & ) << ) self . header . set_byte ( , nb ) def get_decrypted_data ( self ) : '' return self . body_string def get_TSC1 ( self ) : '' b = self . header . get_byte ( ) return ( b & ) def set_TSC1 ( self , value ) : '' nb = ( value & ) self . header . set_byte ( , nb ) def get_WEPSeed ( self ) : '' b = self . header . get_byte ( ) return ( b & ) def set_WEPSeed ( self , value ) : '' nb = ( value & ) self . header . set_byte ( , nb ) def get_TSC0 ( self ) : '' b = self . header . get_byte ( ) return ( b & ) def set_TSC0 ( self , value ) : '' nb = ( value & ) self . header . set_byte ( , nb ) def get_extIV ( self ) : '' b = self . header . get_byte ( ) return ( ( b >> ) & ) def set_extIV ( self , value ) : '' mask = ( ~ ) & masked = self . header . get_byte ( ) & mask nb = masked | ( ( value & ) << ) self . header . set_byte ( , nb ) def get_TSC2 ( self ) : '' b = self . header . get_byte ( ) return ( b & ) def set_TSC2 ( self , value ) : '' nb = ( value & ) self . header . set_byte ( , nb ) def get_TSC3 ( self ) : '' b = self . header . get_byte ( ) return ( b & ) def set_TSC3 ( self , value ) : '' nb = ( value & ) self . header . set_byte ( , nb ) def get_TSC4 ( self ) : '' b = self . header . get_byte ( ) return ( b & ) def set_TSC4 ( self , value ) : '' nb = ( value & ) self . header . set_byte ( , nb ) def get_TSC5 ( self ) : '' b = self . header . get_byte ( ) return ( b & ) def set_TSC5 ( self , value ) : '' nb = ( value & ) self . header . set_byte ( , nb ) class Dot11WPAData ( ProtocolPacket ) : '' def __init__ ( self , aBuffer = None ) : header_size = tail_size = ProtocolPacket . __init__ ( self , header_size , tail_size ) if ( aBuffer ) : self . load_packet ( aBuffer ) def get_icv ( self ) : \"\" b = self . tail . get_long ( - , \">\" ) return b def set_icv ( self , value = None ) : \"\" if value is None : value = self . compute_checksum ( self . body_string ) nb = value & self . tail . set_long ( - , nb ) def get_MIC ( self ) : '' return self . get_tail_as_string ( ) [ : ] def set_MIC ( self , value ) : '' value . ljust ( , '' ) value = value [ : ] icv = self . tail . get_buffer_as_string ( ) [ - : ] self . tail . set_bytes_from_string ( value + icv ) class Dot11WPA2 ( ProtocolPacket ) : '' def __init__ ( self , aBuffer = None ) : header_size = tail_size = ProtocolPacket . __init__ ( self , header_size , tail_size ) if ( aBuffer ) : self . load_packet ( aBuffer ) def is_WPA2 ( self ) : '' b = self . get_PN1 ( ) == ( ( self . get_PN0 ( ) | ) & ) return ( not b and self . get_extIV ( ) ) def get_extIV ( self ) : '' b = self . header . get_byte ( ) return ( ( b >> ) & ) def set_extIV ( self , value ) : '' mask = ( ~ ) & masked = self . header . get_byte ( ) & mask nb = masked | ( ( value & ) << ) self . header . set_byte ( , nb ) def get_keyid ( self ) : '' b = self . header . get_byte ( ) return ( ( b >> ) & ) def set_keyid ( self , value ) : '' mask = ( ~ ) & masked = self . header . get_byte ( ) & mask nb = masked | ( ( value & ) << ) self . header . set_byte ( , nb ) def get_decrypted_data ( self ) : '' return self . body_string def get_PN0 ( self ) : '' b = self . header . get_byte ( ) return ( b & ) def set_PN0 ( self , value ) : '' nb = ( value & ) self . header . set_byte ( , nb ) def get_PN1 ( self ) : '' b = self . header . get_byte ( ) return ( b & ) def set_PN1 ( self , value ) : '' nb = ( value & ) self . header . set_byte ( , nb ) def get_PN2 ( self ) : '' b = self . header . get_byte ( ) return ( b & ) def set_PN2 ( self , value ) : '' nb = ( value & ) self . header . set_byte ( , nb ) def get_PN3 ( self ) : '' b = self . header . get_byte ( ) return ( b & ) def set_PN3 ( self , value ) : '' nb = ( value & ) self . header . set_byte ( , nb ) def get_PN4 ( self ) : '' b = self . header . get_byte ( ) return ( b & ) def set_PN4 ( self , value ) : '' nb = ( value & ) self . header . set_byte ( , nb ) def get_PN5 ( self ) : '' b = self . header . get_byte ( ) return ( b & ) def set_PN5 ( self , value ) : '' nb = ( value & ) self . header . set_byte ( , nb ) class Dot11WPA2Data ( ProtocolPacket ) : '' def __init__ ( self , aBuffer = None ) : header_size = tail_size = ProtocolPacket . __init__ ( self , header_size , tail_size ) if ( aBuffer ) : self . load_packet ( aBuffer ) def get_MIC ( self ) : '' return self . get_tail_as_string ( ) def set_MIC ( self , value ) : '' value . ljust ( , '' ) value = value [ : ] self . tail . set_bytes_from_string ( value ) class RadioTap ( ProtocolPacket ) : __HEADER_BASE_SIZE = _PRESENT_FLAGS_SIZE = _BASE_PRESENT_FLAGS_OFFSET = class __RadioTapField ( object ) : ALIGNMENT = def __str__ ( self ) : return str ( self . __class__ . __name__ ) class RTF_TSFT ( __RadioTapField ) : BIT_NUMBER = STRUCTURE = \"\" ALIGNMENT = class RTF_FLAGS ( __RadioTapField ) : BIT_NUMBER = STRUCTURE = \"\" PROPERTY_CFP = PROPERTY_SHORTPREAMBLE = PROPERTY_WEP = PROPERTY_FRAGMENTATION = PROPERTY_FCS_AT_END = PROPERTY_PAYLOAD_PADDING = PROPERTY_BAD_FCS = PROPERTY_SHORT_GI = class RTF_RATE ( __RadioTapField ) : BIT_NUMBER = STRUCTURE = \"\" class RTF_CHANNEL ( __RadioTapField ) : BIT_NUMBER = STRUCTURE = \"\" ALIGNMENT = class RTF_FHSS ( __RadioTapField ) : BIT_NUMBER = STRUCTURE = \"\" class RTF_DBM_ANTSIGNAL ( __RadioTapField ) : BIT_NUMBER = STRUCTURE = \"\" class RTF_DBM_ANTNOISE ( __RadioTapField ) : BIT_NUMBER = STRUCTURE = \"\" class RTF_LOCK_QUALITY ( __RadioTapField ) : BIT_NUMBER = STRUCTURE = \"\" ALIGNMENT = class RTF_TX_ATTENUATION ( __RadioTapField ) : BIT_NUMBER = STRUCTURE = \"\" ALIGNMENT = class RTF_DB_TX_ATTENUATION ( __RadioTapField ) : BIT_NUMBER = STRUCTURE = \"\" ALIGNMENT = class RTF_DBM_TX_POWER ( __RadioTapField ) : BIT_NUMBER = STRUCTURE = \"\" ALIGNMENT = class RTF_ANTENNA ( __RadioTapField ) : BIT_NUMBER = STRUCTURE = \"\" class RTF_DB_ANTSIGNAL ( __RadioTapField ) : BIT_NUMBER = STRUCTURE = \"\" class RTF_DB_ANTNOISE ( __RadioTapField ) : BIT_NUMBER = STRUCTURE = \"\" class RTF_FCS_IN_HEADER ( __RadioTapField ) : BIT_NUMBER = STRUCTURE = \"\" ALIGNMENT = class RTF_TX_FLAGS ( __RadioTapField ) : BIT_NUMBER = STRUCTURE = \"\" ALIGNMENT = class RTF_RTS_RETRIES ( __RadioTapField ) : BIT_NUMBER = STRUCTURE = \"\" class RTF_DATA_RETRIES ( __RadioTapField ) : BIT_NUMBER = STRUCTURE = \"\" class RTF_XCHANNEL ( __RadioTapField ) : BIT_NUMBER = STRUCTURE = \"\" ALIGNMENT = class RTF_EXT ( __RadioTapField ) : BIT_NUMBER = STRUCTURE = [ ] radiotap_fields = __RadioTapField . __subclasses__ ( ) radiotap_fields . sort ( lambda x , y : cmp ( x . BIT_NUMBER , y . BIT_NUMBER ) ) def __init__ ( self , aBuffer = None ) : header_size = self . __HEADER_BASE_SIZE tail_size = if aBuffer : length = struct . unpack ( '' , aBuffer [ : ] ) [ ] header_size = length ProtocolPacket . __init__ ( self , header_size , tail_size ) self . load_packet ( aBuffer ) else : ProtocolPacket . __init__ ( self , header_size , tail_size ) self . set_version ( ) self . __set_present ( ) def get_header_length ( self ) : '' self . __update_header_length ( ) return self . header . get_word ( , \"\" ) def get_version ( self ) : '' b = self . header . get_byte ( ) return b def set_version ( self , value ) : '' nb = ( value & ) self . header . set_byte ( , nb ) nb = ( value & ) def get_present ( self , offset = _BASE_PRESENT_FLAGS_OFFSET ) : \"\" present = self . header . get_long ( offset , \"\" ) return present def __set_present ( self , value ) : \"\" self . header . set_long ( , value ) def get_present_bit ( self , field , offset = ) : '' present = self . get_present ( offset ) return not not ( ** field . BIT_NUMBER & present ) def __set_present_bit ( self , field ) : '' npresent = ** field . BIT_NUMBER | self . get_present ( ) self . header . set_long ( , npresent , '' ) def __unset_present_bit ( self , field ) : '' npresent = ~ ( ** field . BIT_NUMBER ) & self . get_present ( ) self . header . set_long ( , npresent , '' ) def __align ( self , val , align ) : return ( ( ( ( val ) + ( ( align ) - ) ) & ~ ( ( align ) - ) ) - val ) def __get_field_position ( self , field ) : offset = RadioTap . _BASE_PRESENT_FLAGS_OFFSET extra_present_flags_count = while self . get_present_bit ( RadioTap . RTF_EXT , offset ) : offset += RadioTap . _PRESENT_FLAGS_SIZE extra_present_flags_count += field_position = self . __HEADER_BASE_SIZE + ( RadioTap . _BASE_PRESENT_FLAGS_OFFSET * extra_present_flags_count ) for f in self . radiotap_fields : field_position += self . __align ( field_position , f . ALIGNMENT ) if f == field : return field_position if self . get_present_bit ( f ) : total_length = struct . calcsize ( f . STRUCTURE ) field_position += total_length return None def unset_field ( self , field ) : is_present = self . get_present_bit ( field ) if is_present is False : return False byte_pos = self . __get_field_position ( field ) if not byte_pos : return False self . __unset_present_bit ( field ) header = self . get_header_as_string ( ) total_length = struct . calcsize ( field . STRUCTURE ) header = header [ : byte_pos ] + header [ byte_pos + total_length : ] self . load_header ( header ) def __get_field_values ( self , field ) : is_present = self . get_present_bit ( field ) if is_present is False : return None byte_pos = self . __get_field_position ( field ) header = self . get_header_as_string ( ) total_length = struct . calcsize ( field . STRUCTURE ) v = header [ byte_pos : byte_pos + total_length ] field_values = struct . unpack ( field . STRUCTURE , v ) return field_values def __set_field_values ( self , field , values ) : if not hasattr ( values , '' ) : raise Exception ( \"\" ) num_fields = len ( field . STRUCTURE . translate ( string . maketrans ( \"\" , \"\" ) , '' ) ) if len ( values ) != num_fields : raise Exception ( \"\" % ( str ( field ) , struct . calcsize ( field . STRUCTURE ) ) ) is_present = self . get_present_bit ( field ) if is_present is False : self . __set_present_bit ( field ) byte_pos = self . __get_field_position ( field ) header = self . get_header_as_string ( ) total_length = struct . calcsize ( field . STRUCTURE ) v = header [ byte_pos : byte_pos + total_length ] new_str = struct . pack ( field . STRUCTURE , * values ) if is_present is True : header = header [ : byte_pos ] + new_str + header [ byte_pos + total_length : ] else : header = header [ : byte_pos ] + new_str + header [ byte_pos : ] self . load_header ( header ) def set_tsft ( self , nvalue ) : \"\" \"\" \"\" self . __set_field_values ( RadioTap . RTF_TSFT , [ nvalue ] ) def get_tsft ( self ) : \"\" \"\" \"\" values = self . __get_field_values ( RadioTap . RTF_TSFT ) if not values : return None return values [ ] def set_flags ( self , nvalue ) : \"\" self . __set_field_values ( self . RTF_FLAGS , [ nvalue ] ) def get_flags ( self ) : \"\" values = self . __get_field_values ( self . RTF_FLAGS ) if not values : return None return values [ ] def set_rate ( self , nvalue ) : \"\" self . __set_field_values ( self . RTF_RATE , [ nvalue ] ) def get_rate ( self ) : \"\" values = self . __get_field_values ( self . RTF_RATE ) if not values : return None return values [ ] def set_channel ( self , freq , flags ) : \"\" self . __set_field_values ( self . RTF_CHANNEL , [ freq , flags ] ) def get_channel ( self ) : \"\" values = self . __get_field_values ( self . RTF_CHANNEL ) return values def set_FHSS ( self , hop_set , hop_pattern ) : \"\" self . __set_field_values ( self . RTF_FHSS , [ hop_set , hop_pattern ] ) def get_FHSS ( self ) : \"\" values = self . __get_field_values ( self . RTF_FHSS ) return values def set_dBm_ant_signal ( self , signal ) : \"\" \"\" self . __set_field_values ( self . RTF_DBM_ANTSIGNAL , [ signal ] ) def get_dBm_ant_signal ( self ) : \"\" \"\" values = self . __get_field_values ( self . RTF_DBM_ANTSIGNAL ) if not values : return None return values [ ] def set_dBm_ant_noise ( self , signal ) : \"\" \"\" self . __set_field_values ( self . RTF_DBM_ANTNOISE , [ signal ] ) def get_dBm_ant_noise ( self ) : \"\" \"\" values = self . __get_field_values ( self . RTF_DBM_ANTNOISE ) if not values : return None return values [ ] def set_lock_quality ( self , quality ) : \"\" \"\" self . __set_field_values ( self . RTF_LOCK_QUALITY , [ quality ] ) def get_lock_quality ( self ) : \"\" \"\" values = self . __get_field_values ( self . RTF_LOCK_QUALITY ) if not values : return None return values [ ] def set_tx_attenuation ( self , power ) : \"\" \"\" self . __set_field_values ( self . RTF_TX_ATTENUATION , [ power ] ) def get_tx_attenuation ( self ) : \"\" \"\" values = self . __get_field_values ( self . RTF_TX_ATTENUATION ) if not values : return None return values [ ] def set_dB_tx_attenuation ( self , power ) : \"\" \"\" self . __set_field_values ( self . RTF_DB_TX_ATTENUATION , [ power ] ) def get_dB_tx_attenuation ( self ) : \"\" \"\" values = self . __get_field_values ( self . RTF_DB_TX_ATTENUATION ) if not values : return None return values [ ] def set_dBm_tx_power ( self , power ) : \"\" \"\" \"\" self . __set_field_values ( self . RTF_DBM_TX_POWER , [ power ] ) def get_dBm_tx_power ( self ) : \"\" \"\" \"\" values = self . __get_field_values ( self . RTF_DBM_TX_POWER ) if not values : return None return values [ ] def set_antenna ( self , antenna_index ) : \"\" \"\" self . __set_field_values ( self . RTF_ANTENNA , [ antenna_index ] ) def get_antenna ( self ) : \"\" \"\" values = self . __get_field_values ( self . RTF_ANTENNA ) if not values : return None return values [ ] def set_dB_ant_signal ( self , signal ) : \"\" \"\" self . __set_field_values ( self . RTF_DB_ANTSIGNAL , [ signal ] ) def get_dB_ant_signal ( self ) : \"\" \"\" values = self . __get_field_values ( self . RTF_DB_ANTSIGNAL ) if not values : return None return values [ ] def set_dB_ant_noise ( self , signal ) : \"\" \"\" self . __set_field_values ( self . RTF_DB_ANTNOISE , [ signal ] ) def get_dB_ant_noise ( self ) : \"\" \"\" values = self . __get_field_values ( self . RTF_DB_ANTNOISE ) if not values : return None return values [ ] def set_FCS_in_header ( self , fcs ) : \"\" \"\" self . __set_field_values ( self . RTF_FCS_IN_HEADER , [ fcs ] ) def get_FCS_in_header ( self ) : \"\" \"\" values = self . __get_field_values ( self . RTF_FCS_IN_HEADER ) if not values : return None return values [ ] def set_RTS_retries ( self , retries ) : \"\" self . __set_field_values ( self . RTF_RTS_RETRIES , [ retries ] ) def get_RTS_retries ( self ) : \"\" values = self . __get_field_values ( self . RTF_RTS_RETRIES ) if not values : return None return values [ ] def set_tx_flags ( self , flags ) : \"\" self . __set_field_values ( self . RTF_TX_FLAGS , [ flags ] ) def get_tx_flags ( self ) : \"\" values = self . __get_field_values ( self . RTF_TX_FLAGS ) if not values : return None return values [ ] def set_xchannel ( self , flags , freq , channel , maxpower ) : \"\" self . __set_field_values ( self . RTF_XCHANNEL , [ flags , freq , channel , maxpower ] ) def get_xchannel ( self ) : \"\" values = self . __get_field_values ( field = self . RTF_XCHANNEL ) return values def set_data_retries ( self , retries ) : \"\" self . __set_field_values ( self . RTF_DATA_RETRIES , [ retries ] ) def get_data_retries ( self ) : \"\" values = self . __get_field_values ( self . RTF_DATA_RETRIES ) if not values : return None return values [ ] def set_hardware_queue ( self , queue ) : \"\" self . __set_field_values ( self . RTF_HARDWARE_QUEUE , [ queue ] ) def __update_header_length ( self ) : '' self . header . set_word ( , self . get_header_size ( ) , \"\" ) def get_packet ( self ) : self . __update_header_length ( ) return ProtocolPacket . get_packet ( self ) class Dot11ManagementFrame ( ProtocolPacket ) : '' def __init__ ( self , aBuffer = None ) : header_size = tail_size = ProtocolPacket . __init__ ( self , header_size , tail_size ) if ( aBuffer ) : self . load_packet ( aBuffer ) def __init__ ( self , aBuffer = None ) : header_size = tail_size = ProtocolPacket . __init__ ( self , header_size , tail_size ) if ( aBuffer ) : self . load_packet ( aBuffer ) def get_duration ( self ) : '' b = self . header . get_word ( , \"\" ) return b def set_duration ( self , value ) : '' nb = value & self . header . set_word ( , nb , \"\" ) def get_destination_address ( self ) : '' return self . header . get_bytes ( ) [ : ] def set_destination_address ( self , value ) : '' for i in range ( , ) : self . header . set_byte ( + i , value [ i ] ) def get_source_address ( self ) : '' return self . header . get_bytes ( ) [ : ] def set_source_address ( self , value ) : '' for i in range ( , ) : self . header . set_byte ( + i , value [ i ] ) def get_bssid ( self ) : '' return self . header . get_bytes ( ) [ : ] def set_bssid ( self , value ) : '' for i in range ( , ) : self . header . set_byte ( + i , value [ i ] ) def get_sequence_control ( self ) : '' b = self . header . get_word ( , \"\" ) return b def set_sequence_control ( self , value ) : '' nb = value & self . header . set_word ( , nb , \"\" ) def get_fragment_number ( self ) : '' b = self . get_sequence_control ( ) return ( b & ) def set_fragment_number ( self , value ) : '' mask = ( ~ ) & masked = self . header . get_word ( , \"\" ) & mask nb = masked | ( value & ) self . header . set_word ( , nb , \"\" ) def get_sequence_number ( self ) : '' b = self . get_sequence_control ( ) return ( ( b >> ) & ) def set_sequence_number ( self , value ) : '' mask = ( ~ ) & masked = self . header . get_word ( , \"\" ) & mask nb = masked | ( ( value & ) << ) self . header . set_word ( , nb , \"\" ) def get_frame_body ( self ) : '' return self . get_body_as_string ( ) def set_frame_body ( self , data ) : '' self . load_body ( data ) class DOT11_MANAGEMENT_ELEMENTS ( ) : SSID = SUPPORTED_RATES = FH_PARAMETER_SET = DS_PARAMETER_SET = CF_PARAMETER_SET = TIM = IBSS_PARAMETER_SET = COUNTRY = HOPPING_PARAMETER = HOPPING_TABLE = REQUEST = BSS_LOAD = EDCA_PARAMETER_SET = TSPEC = TCLAS = SCHEDULE = CHALLENGE_TEXT = POWER_CONSTRAINT = ", "answer": "POWER_CAPABILITY = "}, {"prompt": " \"\"\"\"\"\" __author__ = \"\" __date__ = \"\" import wx if wx . Platform == '' : import Carbon . Appearance from aui_utilities import BitmapFromBits , StepColour , IndentPressedBitmap , ChopText from aui_utilities import GetBaseColour , DrawMACCloseButton , LightColour , TakeScreenShot from aui_utilities import CopyAttributes from aui_constants import * class AuiCommandCapture ( wx . PyEvtHandler ) : \"\"\"\"\"\" def __init__ ( self ) : \"\"\"\"\"\" wx . PyEvtHandler . __init__ ( self ) self . _last_id = def GetCommandId ( self ) : \"\"\"\"\"\" return self . _last_id def ProcessEvent ( self , event ) : \"\"\"\"\"\" if event . GetEventType ( ) == wx . wxEVT_COMMAND_MENU_SELECTED : self . _last_id = event . GetId ( ) return True if self . GetNextHandler ( ) : return self . GetNextHandler ( ) . ProcessEvent ( event ) return False class AuiDefaultTabArt ( object ) : \"\"\"\"\"\" def __init__ ( self ) : \"\"\"\"\"\" self . _normal_font = wx . SystemSettings_GetFont ( wx . SYS_DEFAULT_GUI_FONT ) self . _selected_font = wx . SystemSettings_GetFont ( wx . SYS_DEFAULT_GUI_FONT ) self . _selected_font . SetWeight ( wx . BOLD ) self . _measuring_font = self . _selected_font self . _fixed_tab_width = self . _tab_ctrl_height = self . _buttonRect = wx . Rect ( ) self . SetDefaultColours ( ) if wx . Platform == \"\" : bmp_colour = wx . SystemSettings . GetColour ( wx . SYS_COLOUR_3DDKSHADOW ) self . _active_close_bmp = DrawMACCloseButton ( bmp_colour ) self . _disabled_close_bmp = DrawMACCloseButton ( wx . Colour ( , , ) ) else : self . _active_close_bmp = BitmapFromBits ( nb_close_bits , , , wx . BLACK ) self . _disabled_close_bmp = BitmapFromBits ( nb_close_bits , , , wx . Colour ( , , ) ) self . _hover_close_bmp = self . _active_close_bmp self . _pressed_close_bmp = self . _active_close_bmp self . _active_left_bmp = BitmapFromBits ( nb_left_bits , , , wx . BLACK ) self . _disabled_left_bmp = BitmapFromBits ( nb_left_bits , , , wx . Colour ( , , ) ) self . _active_right_bmp = BitmapFromBits ( nb_right_bits , , , wx . BLACK ) self . _disabled_right_bmp = BitmapFromBits ( nb_right_bits , , , wx . Colour ( , , ) ) self . _active_windowlist_bmp = BitmapFromBits ( nb_list_bits , , , wx . BLACK ) self . _disabled_windowlist_bmp = BitmapFromBits ( nb_list_bits , , , wx . Colour ( , , ) ) if wx . Platform == \"\" : if hasattr ( wx , '' ) : c = wx . MacThemeColour ( Carbon . Appearance . kThemeBrushFocusHighlight ) else : brush = wx . Brush ( wx . BLACK ) brush . MacSetTheme ( Carbon . Appearance . kThemeBrushFocusHighlight ) c = brush . GetColour ( ) self . _focusPen = wx . Pen ( c , , wx . SOLID ) else : self . _focusPen = wx . Pen ( wx . BLACK , , wx . USER_DASH ) self . _focusPen . SetDashes ( [ , ] ) self . _focusPen . SetCap ( wx . CAP_BUTT ) def SetBaseColour ( self , base_colour ) : \"\"\"\"\"\" self . _base_colour = base_colour self . _base_colour_pen = wx . Pen ( self . _base_colour ) self . _base_colour_brush = wx . Brush ( self . _base_colour ) def SetDefaultColours ( self , base_colour = None ) : \"\"\"\"\"\" if base_colour is None : base_colour = GetBaseColour ( ) self . SetBaseColour ( base_colour ) self . _border_colour = StepColour ( base_colour , ) self . _border_pen = wx . Pen ( self . _border_colour ) self . _background_top_colour = StepColour ( self . _base_colour , ) self . _background_bottom_colour = StepColour ( self . _base_colour , ) self . _tab_top_colour = self . _base_colour self . _tab_bottom_colour = wx . WHITE self . _tab_gradient_highlight_colour = wx . WHITE self . _tab_inactive_top_colour = self . _base_colour self . _tab_inactive_bottom_colour = StepColour ( self . _tab_inactive_top_colour , ) self . _tab_text_colour = lambda page : page . text_colour self . _tab_disabled_text_colour = wx . SystemSettings . GetColour ( wx . SYS_COLOUR_GRAYTEXT ) def Clone ( self ) : \"\"\"\"\"\" art = type ( self ) ( ) art . SetNormalFont ( self . GetNormalFont ( ) ) art . SetSelectedFont ( self . GetSelectedFont ( ) ) art . SetMeasuringFont ( self . GetMeasuringFont ( ) ) art = CopyAttributes ( art , self ) return art def SetAGWFlags ( self , agwFlags ) : \"\"\"\"\"\" self . _agwFlags = agwFlags def GetAGWFlags ( self ) : \"\"\"\"\"\" return self . _agwFlags def SetSizingInfo ( self , tab_ctrl_size , tab_count , minMaxTabWidth ) : \"\"\"\"\"\" self . _fixed_tab_width = minTabWidth , maxTabWidth = minMaxTabWidth tot_width = tab_ctrl_size . x - self . GetIndentSize ( ) - agwFlags = self . GetAGWFlags ( ) if agwFlags & AUI_NB_CLOSE_BUTTON : tot_width -= self . _active_close_bmp . GetWidth ( ) if agwFlags & AUI_NB_WINDOWLIST_BUTTON : tot_width -= self . _active_windowlist_bmp . GetWidth ( ) if tab_count > : self . _fixed_tab_width = tot_width / tab_count if self . _fixed_tab_width < : self . _fixed_tab_width = if self . _fixed_tab_width > tot_width / : self . _fixed_tab_width = tot_width / if self . _fixed_tab_width > : self . _fixed_tab_width = if minTabWidth > - : self . _fixed_tab_width = max ( self . _fixed_tab_width , minTabWidth ) if maxTabWidth > - : self . _fixed_tab_width = min ( self . _fixed_tab_width , maxTabWidth ) self . _tab_ctrl_height = tab_ctrl_size . y def DrawBackground ( self , dc , wnd , rect ) : \"\"\"\"\"\" self . _buttonRect = wx . Rect ( ) agwFlags = self . GetAGWFlags ( ) if agwFlags & AUI_NB_BOTTOM : r = wx . Rect ( rect . x , rect . y , rect . width + , rect . height ) else : r = wx . Rect ( rect . x , rect . y , rect . width + , rect . height - ) dc . GradientFillLinear ( r , self . _background_top_colour , self . _background_bottom_colour , wx . SOUTH ) dc . SetPen ( self . _border_pen ) y = rect . GetHeight ( ) w = rect . GetWidth ( ) if agwFlags & AUI_NB_BOTTOM : dc . SetBrush ( wx . Brush ( self . _background_bottom_colour ) ) dc . DrawRectangle ( - , , w + , ) else : dc . SetBrush ( self . _base_colour_brush ) dc . DrawRectangle ( - , y - , w + , ) def DrawTab ( self , dc , wnd , page , in_rect , close_button_state , paint_control = False ) : \"\"\"\"\"\" caption = page . caption if not caption : caption = \"\" dc . SetFont ( self . _selected_font ) selected_textx , selected_texty , dummy = dc . GetMultiLineTextExtent ( caption ) dc . SetFont ( self . _normal_font ) normal_textx , normal_texty , dummy = dc . GetMultiLineTextExtent ( caption ) control = page . control tab_size , x_extent = self . GetTabSize ( dc , wnd , page . caption , page . bitmap , page . active , close_button_state , control ) tab_height = self . _tab_ctrl_height - tab_width = tab_size [ ] tab_x = in_rect . x tab_y = in_rect . y + in_rect . height - tab_height caption = page . caption if page . active : dc . SetFont ( self . _selected_font ) textx , texty = selected_textx , selected_texty else : dc . SetFont ( self . _normal_font ) textx , texty = normal_textx , normal_texty if not page . enabled : dc . SetTextForeground ( self . _tab_disabled_text_colour ) pagebitmap = page . dis_bitmap else : dc . SetTextForeground ( self . _tab_text_colour ( page ) ) pagebitmap = page . bitmap clip_width = tab_width if tab_x + clip_width > in_rect . x + in_rect . width : clip_width = in_rect . x + in_rect . width - tab_x dc . SetClippingRegion ( tab_x , tab_y , clip_width + , tab_height - ) border_points = [ wx . Point ( ) for i in xrange ( ) ] agwFlags = self . GetAGWFlags ( ) if agwFlags & AUI_NB_BOTTOM : border_points [ ] = wx . Point ( tab_x , tab_y ) border_points [ ] = wx . Point ( tab_x , tab_y + tab_height - ) border_points [ ] = wx . Point ( tab_x + , tab_y + tab_height - ) border_points [ ] = wx . Point ( tab_x + tab_width - , tab_y + tab_height - ) border_points [ ] = wx . Point ( tab_x + tab_width , tab_y + tab_height - ) border_points [ ] = wx . Point ( tab_x + tab_width , tab_y ) else : border_points [ ] = wx . Point ( tab_x , tab_y + tab_height - ) border_points [ ] = wx . Point ( tab_x , tab_y + ) border_points [ ] = wx . Point ( tab_x + , tab_y ) border_points [ ] = wx . Point ( tab_x + tab_width - , tab_y ) border_points [ ] = wx . Point ( tab_x + tab_width , tab_y + ) border_points [ ] = wx . Point ( tab_x + tab_width , tab_y + tab_height - ) drawn_tab_yoff = border_points [ ] . y drawn_tab_height = border_points [ ] . y - border_points [ ] . y if page . active : r = wx . Rect ( tab_x , tab_y , tab_width , tab_height ) dc . SetPen ( self . _base_colour_pen ) dc . SetBrush ( self . _base_colour_brush ) dc . DrawRectangle ( r . x + , r . y + , r . width - , r . height - ) dc . SetPen ( wx . Pen ( self . _tab_gradient_highlight_colour ) ) dc . SetBrush ( wx . Brush ( self . _tab_gradient_highlight_colour ) ) dc . DrawRectangle ( r . x + , r . y + , r . width - , r . height - ) dc . SetPen ( self . _base_colour_pen ) dc . DrawPoint ( r . x + , r . y + ) dc . DrawPoint ( r . x + r . width - , r . y + ) r . SetHeight ( r . GetHeight ( ) / ) r . x += r . width -= r . y += r . height r . y -= top_colour = self . _tab_bottom_colour bottom_colour = self . _tab_top_colour dc . GradientFillLinear ( r , bottom_colour , top_colour , wx . NORTH ) else : r = wx . Rect ( tab_x , tab_y + , tab_width , tab_height - ) r . x += r . y += r . width -= r . height /= r . height -= top_colour = self . _tab_inactive_top_colour bottom_colour = self . _tab_inactive_bottom_colour dc . GradientFillLinear ( r , bottom_colour , top_colour , wx . NORTH ) r . y += r . height r . y -= top_colour = self . _tab_inactive_bottom_colour bottom_colour = self . _tab_inactive_bottom_colour dc . GradientFillLinear ( r , top_colour , bottom_colour , wx . SOUTH ) dc . SetPen ( self . _border_pen ) dc . SetBrush ( wx . TRANSPARENT_BRUSH ) dc . DrawPolygon ( border_points ) if page . active : if agwFlags & AUI_NB_BOTTOM : dc . SetPen ( wx . Pen ( self . _background_bottom_colour ) ) else : dc . SetPen ( self . _base_colour_pen ) dc . DrawLine ( border_points [ ] . x + , border_points [ ] . y , border_points [ ] . x , border_points [ ] . y ) text_offset = tab_x + close_button_width = if close_button_state != AUI_BUTTON_STATE_HIDDEN : close_button_width = self . _active_close_bmp . GetWidth ( ) if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT : text_offset += close_button_width - bitmap_offset = if pagebitmap . IsOk ( ) : bitmap_offset = tab_x + if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT and close_button_width : bitmap_offset += close_button_width - dc . DrawBitmap ( pagebitmap , bitmap_offset , drawn_tab_yoff + ( drawn_tab_height / ) - ( pagebitmap . GetHeight ( ) / ) , True ) text_offset = bitmap_offset + pagebitmap . GetWidth ( ) text_offset += else : if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT == or not close_button_width : text_offset = tab_x + draw_text = ChopText ( dc , caption , tab_width - ( text_offset - tab_x ) - close_button_width ) ypos = drawn_tab_yoff + ( drawn_tab_height ) / - ( texty / ) - offset_focus = text_offset if control is not None : if control . GetPosition ( ) != wx . Point ( text_offset + , ypos ) : control . SetPosition ( wx . Point ( text_offset + , ypos ) ) if not control . IsShown ( ) : control . Show ( ) if paint_control : bmp = TakeScreenShot ( control . GetScreenRect ( ) ) dc . DrawBitmap ( bmp , text_offset + , ypos , True ) controlW , controlH = control . GetSize ( ) text_offset += controlW + textx += controlW + rectx , recty , dummy = dc . GetMultiLineTextExtent ( draw_text ) dc . DrawLabel ( draw_text , wx . Rect ( text_offset , ypos , rectx , recty ) ) if ( agwFlags & AUI_NB_NO_TAB_FOCUS ) == : self . DrawFocusRectangle ( dc , page , wnd , draw_text , offset_focus , bitmap_offset , drawn_tab_yoff , drawn_tab_height , rectx , recty ) out_button_rect = wx . Rect ( ) if close_button_state != AUI_BUTTON_STATE_HIDDEN : bmp = self . _disabled_close_bmp if close_button_state == AUI_BUTTON_STATE_HOVER : bmp = self . _hover_close_bmp elif close_button_state == AUI_BUTTON_STATE_PRESSED : bmp = self . _pressed_close_bmp shift = ( agwFlags & AUI_NB_BOTTOM and [ ] or [ ] ) [ ] if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT : rect = wx . Rect ( tab_x + , tab_y + ( tab_height - bmp . GetHeight ( ) ) / - shift , close_button_width , tab_height ) else : rect = wx . Rect ( tab_x + tab_width - close_button_width - , tab_y + ( tab_height - bmp . GetHeight ( ) ) / - shift , close_button_width , tab_height ) rect = IndentPressedBitmap ( rect , close_button_state ) dc . DrawBitmap ( bmp , rect . x , rect . y , True ) out_button_rect = rect out_tab_rect = wx . Rect ( tab_x , tab_y , tab_width , tab_height ) dc . DestroyClippingRegion ( ) return out_tab_rect , out_button_rect , x_extent def SetCustomButton ( self , bitmap_id , button_state , bmp ) : \"\"\"\"\"\" if bitmap_id == AUI_BUTTON_CLOSE : if button_state == AUI_BUTTON_STATE_NORMAL : self . _active_close_bmp = bmp self . _hover_close_bmp = self . _active_close_bmp self . _pressed_close_bmp = self . _active_close_bmp self . _disabled_close_bmp = self . _active_close_bmp elif button_state == AUI_BUTTON_STATE_HOVER : self . _hover_close_bmp = bmp elif button_state == AUI_BUTTON_STATE_PRESSED : self . _pressed_close_bmp = bmp else : self . _disabled_close_bmp = bmp elif bitmap_id == AUI_BUTTON_LEFT : if button_state & AUI_BUTTON_STATE_DISABLED : self . _disabled_left_bmp = bmp else : self . _active_left_bmp = bmp elif bitmap_id == AUI_BUTTON_RIGHT : if button_state & AUI_BUTTON_STATE_DISABLED : self . _disabled_right_bmp = bmp else : self . _active_right_bmp = bmp elif bitmap_id == AUI_BUTTON_WINDOWLIST : if button_state & AUI_BUTTON_STATE_DISABLED : self . _disabled_windowlist_bmp = bmp else : self . _active_windowlist_bmp = bmp def GetIndentSize ( self ) : \"\"\"\"\"\" return def GetTabSize ( self , dc , wnd , caption , bitmap , active , close_button_state , control = None ) : \"\"\"\"\"\" dc . SetFont ( self . _measuring_font ) measured_textx , measured_texty , dummy = dc . GetMultiLineTextExtent ( caption ) tab_width = measured_textx tab_height = measured_texty if close_button_state != AUI_BUTTON_STATE_HIDDEN : tab_width += self . _active_close_bmp . GetWidth ( ) + if bitmap . IsOk ( ) : tab_width += bitmap . GetWidth ( ) tab_width += tab_height = max ( tab_height , bitmap . GetHeight ( ) ) tab_width += tab_height += agwFlags = self . GetAGWFlags ( ) if agwFlags & AUI_NB_TAB_FIXED_WIDTH : tab_width = self . _fixed_tab_width if control is not None : tab_width += control . GetSize ( ) . GetWidth ( ) + x_extent = tab_width return ( tab_width , tab_height ) , x_extent def DrawButton ( self , dc , wnd , in_rect , button , orientation ) : \"\"\"\"\"\" bitmap_id , button_state = button . id , button . cur_state if bitmap_id == AUI_BUTTON_CLOSE : if button_state & AUI_BUTTON_STATE_DISABLED : bmp = self . _disabled_close_bmp elif button_state & AUI_BUTTON_STATE_HOVER : bmp = self . _hover_close_bmp elif button_state & AUI_BUTTON_STATE_PRESSED : bmp = self . _pressed_close_bmp else : bmp = self . _active_close_bmp elif bitmap_id == AUI_BUTTON_LEFT : if button_state & AUI_BUTTON_STATE_DISABLED : bmp = self . _disabled_left_bmp else : bmp = self . _active_left_bmp elif bitmap_id == AUI_BUTTON_RIGHT : if button_state & AUI_BUTTON_STATE_DISABLED : bmp = self . _disabled_right_bmp else : bmp = self . _active_right_bmp elif bitmap_id == AUI_BUTTON_WINDOWLIST : if button_state & AUI_BUTTON_STATE_DISABLED : bmp = self . _disabled_windowlist_bmp else : bmp = self . _active_windowlist_bmp else : if button_state & AUI_BUTTON_STATE_DISABLED : bmp = button . dis_bitmap else : bmp = button . bitmap if not bmp . IsOk ( ) : return rect = wx . Rect ( * in_rect ) if orientation == wx . LEFT : rect . SetX ( in_rect . x ) rect . SetY ( ( ( in_rect . y + in_rect . height ) / ) - ( bmp . GetHeight ( ) / ) ) rect . SetWidth ( bmp . GetWidth ( ) ) rect . SetHeight ( bmp . GetHeight ( ) ) else : rect = wx . Rect ( in_rect . x + in_rect . width - bmp . GetWidth ( ) , ( ( in_rect . y + in_rect . height ) / ) - ( bmp . GetHeight ( ) / ) , bmp . GetWidth ( ) , bmp . GetHeight ( ) ) rect = IndentPressedBitmap ( rect , button_state ) dc . DrawBitmap ( bmp , rect . x , rect . y , True ) out_rect = rect if bitmap_id == AUI_BUTTON_RIGHT : self . _buttonRect = wx . Rect ( rect . x , rect . y , , rect . height ) return out_rect def DrawFocusRectangle ( self , dc , page , wnd , draw_text , text_offset , bitmap_offset , drawn_tab_yoff , drawn_tab_height , textx , texty ) : \"\"\"\"\"\" if self . GetAGWFlags ( ) & AUI_NB_NO_TAB_FOCUS : return if page . active and wx . Window . FindFocus ( ) == wnd : focusRectText = wx . Rect ( text_offset , ( drawn_tab_yoff + ( drawn_tab_height ) / - ( texty / ) ) , textx , texty ) if page . bitmap . IsOk ( ) : focusRectBitmap = wx . Rect ( bitmap_offset , drawn_tab_yoff + ( drawn_tab_height / ) - ( page . bitmap . GetHeight ( ) / ) , page . bitmap . GetWidth ( ) , page . bitmap . GetHeight ( ) ) if page . bitmap . IsOk ( ) and draw_text == \"\" : focusRect = wx . Rect ( * focusRectBitmap ) elif not page . bitmap . IsOk ( ) and draw_text != \"\" : focusRect = wx . Rect ( * focusRectText ) elif page . bitmap . IsOk ( ) and draw_text != \"\" : focusRect = focusRectText . Union ( focusRectBitmap ) focusRect . Inflate ( , ) dc . SetBrush ( wx . TRANSPARENT_BRUSH ) dc . SetPen ( self . _focusPen ) dc . DrawRoundedRectangleRect ( focusRect , ) def GetBestTabCtrlSize ( self , wnd , pages , required_bmp_size ) : \"\"\"\"\"\" dc = wx . ClientDC ( wnd ) dc . SetFont ( self . _measuring_font ) measure_bmp = wx . NullBitmap if required_bmp_size . IsFullySpecified ( ) : measure_bmp = wx . EmptyBitmap ( required_bmp_size . x , required_bmp_size . y ) max_y = for page in pages : if measure_bmp . IsOk ( ) : bmp = measure_bmp else : bmp = page . bitmap s , x_ext = self . GetTabSize ( dc , wnd , page . caption , bmp , True , AUI_BUTTON_STATE_HIDDEN , None ) max_y = max ( max_y , s [ ] ) if page . control : controlW , controlH = page . control . GetSize ( ) max_y = max ( max_y , controlH + ) return max_y + def SetNormalFont ( self , font ) : \"\"\"\"\"\" self . _normal_font = font def SetSelectedFont ( self , font ) : \"\"\"\"\"\" self . _selected_font = font def SetMeasuringFont ( self , font ) : \"\"\"\"\"\" self . _measuring_font = font def GetNormalFont ( self ) : \"\"\"\"\"\" return self . _normal_font def GetSelectedFont ( self ) : \"\"\"\"\"\" return self . _selected_font def GetMeasuringFont ( self ) : \"\"\"\"\"\" return self . _measuring_font def ShowDropDown ( self , wnd , pages , active_idx ) : \"\"\"\"\"\" useImages = self . GetAGWFlags ( ) & AUI_NB_USE_IMAGES_DROPDOWN menuPopup = wx . Menu ( ) longest = for i , page in enumerate ( pages ) : caption = page . caption if caption == \"\" : caption = \"\" width = wnd . GetTextExtent ( caption ) [ ] if width > longest : longest = width if useImages : menuItem = wx . MenuItem ( menuPopup , + i , caption ) if page . bitmap : menuItem . SetBitmap ( page . bitmap ) menuPopup . AppendItem ( menuItem ) else : menuPopup . AppendCheckItem ( + i , caption ) menuPopup . Enable ( + i , page . enabled ) if active_idx != - and not useImages : menuPopup . Check ( + active_idx , True ) cli_rect = wnd . GetClientRect ( ) if wx . Platform in [ '' , '' ] : longest += longest += if self . GetAGWFlags ( ) & AUI_NB_CLOSE_BUTTON : longest += pt = wx . Point ( cli_rect . x + cli_rect . GetWidth ( ) - longest , cli_rect . y + cli_rect . height ) cc = AuiCommandCapture ( ) wnd . PushEventHandler ( cc ) wnd . PopupMenu ( menuPopup , pt ) command = cc . GetCommandId ( ) wnd . PopEventHandler ( True ) if command >= : return command - return - class AuiSimpleTabArt ( object ) : \"\"\"\"\"\" def __init__ ( self ) : \"\"\"\"\"\" self . _normal_font = wx . SystemSettings . GetFont ( wx . SYS_DEFAULT_GUI_FONT ) self . _selected_font = wx . SystemSettings . GetFont ( wx . SYS_DEFAULT_GUI_FONT ) self . _selected_font . SetWeight ( wx . BOLD ) self . _measuring_font = self . _selected_font self . _agwFlags = self . _fixed_tab_width = base_colour = wx . SystemSettings . GetColour ( wx . SYS_COLOUR_3DFACE ) background_colour = base_colour normaltab_colour = base_colour selectedtab_colour = wx . WHITE self . _bkbrush = wx . Brush ( background_colour ) self . _normal_bkbrush = wx . Brush ( normaltab_colour ) self . _normal_bkpen = wx . Pen ( normaltab_colour ) self . _selected_bkbrush = wx . Brush ( selectedtab_colour ) self . _selected_bkpen = wx . Pen ( selectedtab_colour ) self . _active_close_bmp = BitmapFromBits ( nb_close_bits , , , wx . BLACK ) self . _disabled_close_bmp = BitmapFromBits ( nb_close_bits , , , wx . Colour ( , , ) ) self . _active_left_bmp = BitmapFromBits ( nb_left_bits , , , wx . BLACK ) self . _disabled_left_bmp = BitmapFromBits ( nb_left_bits , , , wx . Colour ( , , ) ) self . _active_right_bmp = BitmapFromBits ( nb_right_bits , , , wx . BLACK ) self . _disabled_right_bmp = BitmapFromBits ( nb_right_bits , , , wx . Colour ( , , ) ) self . _active_windowlist_bmp = BitmapFromBits ( nb_list_bits , , , wx . BLACK ) self . _disabled_windowlist_bmp = BitmapFromBits ( nb_list_bits , , , wx . Colour ( , , ) ) def Clone ( self ) : \"\"\"\"\"\" art = type ( self ) ( ) art . SetNormalFont ( self . GetNormalFont ( ) ) art . SetSelectedFont ( self . GetSelectedFont ( ) ) art . SetMeasuringFont ( self . GetMeasuringFont ( ) ) art = CopyAttributes ( art , self ) return art def SetAGWFlags ( self , agwFlags ) : \"\"\"\"\"\" self . _agwFlags = agwFlags def GetAGWFlags ( self ) : \"\"\"\"\"\" return self . _agwFlags def SetSizingInfo ( self , tab_ctrl_size , tab_count , minMaxTabWidth ) : \"\"\"\"\"\" self . _fixed_tab_width = minTabWidth , maxTabWidth = minMaxTabWidth tot_width = tab_ctrl_size . x - self . GetIndentSize ( ) - if self . _agwFlags & AUI_NB_CLOSE_BUTTON : tot_width -= self . _active_close_bmp . GetWidth ( ) if self . _agwFlags & AUI_NB_WINDOWLIST_BUTTON : tot_width -= self . _active_windowlist_bmp . GetWidth ( ) if tab_count > : self . _fixed_tab_width = tot_width / tab_count if self . _fixed_tab_width < : self . _fixed_tab_width = if self . _fixed_tab_width > tot_width / : self . _fixed_tab_width = tot_width / if self . _fixed_tab_width > : self . _fixed_tab_width = if minTabWidth > - : self . _fixed_tab_width = max ( self . _fixed_tab_width , minTabWidth ) if maxTabWidth > - : self . _fixed_tab_width = min ( self . _fixed_tab_width , maxTabWidth ) self . _tab_ctrl_height = tab_ctrl_size . y def DrawBackground ( self , dc , wnd , rect ) : \"\"\"\"\"\" dc . SetBrush ( self . _bkbrush ) dc . SetPen ( wx . TRANSPARENT_PEN ) dc . DrawRectangle ( - , - , rect . GetWidth ( ) + , rect . GetHeight ( ) + ) dc . SetPen ( wx . GREY_PEN ) dc . DrawLine ( , rect . GetHeight ( ) - , rect . GetWidth ( ) , rect . GetHeight ( ) - ) def DrawTab ( self , dc , wnd , page , in_rect , close_button_state , paint_control = False ) : \"\"\"\"\"\" caption = page . caption if caption == \"\" : caption = \"\" agwFlags = self . GetAGWFlags ( ) dc . SetFont ( self . _selected_font ) selected_textx , selected_texty , dummy = dc . GetMultiLineTextExtent ( caption ) dc . SetFont ( self . _normal_font ) normal_textx , normal_texty , dummy = dc . GetMultiLineTextExtent ( caption ) control = page . control tab_size , x_extent = self . GetTabSize ( dc , wnd , page . caption , page . bitmap , page . active , close_button_state , control ) tab_height = tab_size [ ] tab_width = tab_size [ ] tab_x = in_rect . x tab_y = in_rect . y + in_rect . height - tab_height caption = page . caption if page . active : dc . SetPen ( self . _selected_bkpen ) dc . SetBrush ( self . _selected_bkbrush ) dc . SetFont ( self . _selected_font ) textx = selected_textx texty = selected_texty else : dc . SetPen ( self . _normal_bkpen ) dc . SetBrush ( self . _normal_bkbrush ) dc . SetFont ( self . _normal_font ) textx = normal_textx texty = normal_texty if not page . enabled : dc . SetTextForeground ( wx . SystemSettings . GetColour ( wx . SYS_COLOUR_GRAYTEXT ) ) else : dc . SetTextForeground ( page . text_colour ) points = [ wx . Point ( ) for i in xrange ( ) ] points [ ] . x = tab_x points [ ] . y = tab_y + tab_height - points [ ] . x = tab_x + tab_height - points [ ] . y = tab_y + points [ ] . x = tab_x + tab_height + points [ ] . y = tab_y points [ ] . x = tab_x + tab_width - points [ ] . y = tab_y points [ ] . x = tab_x + tab_width points [ ] . y = tab_y + points [ ] . x = tab_x + tab_width points [ ] . y = tab_y + tab_height - points [ ] = points [ ] dc . SetClippingRect ( in_rect ) dc . DrawPolygon ( points ) dc . SetPen ( wx . GREY_PEN ) dc . DrawLines ( points ) close_button_width = if close_button_state != AUI_BUTTON_STATE_HIDDEN : close_button_width = self . _active_close_bmp . GetWidth ( ) if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT : if control : text_offset = tab_x + ( tab_height / ) + close_button_width - ( textx / ) - else : text_offset = tab_x + ( tab_height / ) + ( ( tab_width + close_button_width ) / ) - ( textx / ) - else : if control : text_offset = tab_x + ( tab_height / ) + close_button_width - ( textx / ) else : text_offset = tab_x + ( tab_height / ) + ( ( tab_width - close_button_width ) / ) - ( textx / ) else : text_offset = tab_x + ( tab_height / ) + ( tab_width / ) - ( textx / ) if control : if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT : text_offset = tab_x + ( tab_height / ) - ( textx / ) + close_button_width + else : text_offset = tab_x + ( tab_height / ) - ( textx / ) if text_offset < tab_x + tab_height : text_offset = tab_x + tab_height if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT : draw_text = ChopText ( dc , caption , tab_width - ( text_offset - tab_x ) ) else : draw_text = ChopText ( dc , caption , tab_width - ( text_offset - tab_x ) - close_button_width ) ypos = ( tab_y + tab_height ) / - ( texty / ) + if control is not None : if control . GetPosition ( ) != wx . Point ( text_offset + , ypos ) : control . SetPosition ( wx . Point ( text_offset + , ypos ) ) if not control . IsShown ( ) : control . Show ( ) if paint_control : bmp = TakeScreenShot ( control . GetScreenRect ( ) ) dc . DrawBitmap ( bmp , text_offset + , ypos , True ) controlW , controlH = control . GetSize ( ) text_offset += controlW + rectx , recty , dummy = dc . GetMultiLineTextExtent ( draw_text ) dc . DrawLabel ( draw_text , wx . Rect ( text_offset , ypos , rectx , recty ) ) if page . active and wx . Window . FindFocus ( ) == wnd and ( agwFlags & AUI_NB_NO_TAB_FOCUS ) == : focusRect = wx . Rect ( text_offset , ( ( tab_y + tab_height ) / - ( texty / ) + ) , selected_textx , selected_texty ) focusRect . Inflate ( , ) out_button_rect = wx . Rect ( ) if close_button_state != AUI_BUTTON_STATE_HIDDEN : if page . active : bmp = self . _active_close_bmp else : bmp = self . _disabled_close_bmp if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT : rect = wx . Rect ( tab_x + tab_height - , tab_y + ( tab_height / ) - ( bmp . GetHeight ( ) / ) + , close_button_width , tab_height - ) else : rect = wx . Rect ( tab_x + tab_width - close_button_width - , tab_y + ( tab_height / ) - ( bmp . GetHeight ( ) / ) + , close_button_width , tab_height - ) self . DrawButtons ( dc , rect , bmp , wx . WHITE , close_button_state ) out_button_rect = wx . Rect ( * rect ) out_tab_rect = wx . Rect ( tab_x , tab_y , tab_width , tab_height ) dc . DestroyClippingRegion ( ) return out_tab_rect , out_button_rect , x_extent def DrawButtons ( self , dc , _rect , bmp , bkcolour , button_state ) : \"\"\"\"\"\" rect = wx . Rect ( * _rect ) if button_state == AUI_BUTTON_STATE_PRESSED : rect . x += rect . y += if button_state in [ AUI_BUTTON_STATE_HOVER , AUI_BUTTON_STATE_PRESSED ] : dc . SetBrush ( wx . Brush ( StepColour ( bkcolour , ) ) ) dc . SetPen ( wx . Pen ( StepColour ( bkcolour , ) ) ) dc . DrawRectangle ( rect . x , rect . y , , ) dc . DrawBitmap ( bmp , rect . x , rect . y , True ) def GetIndentSize ( self ) : \"\"\"\"\"\" return def GetTabSize ( self , dc , wnd , caption , bitmap , active , close_button_state , control = None ) : \"\"\"\"\"\" dc . SetFont ( self . _measuring_font ) measured_textx , measured_texty , dummy = dc . GetMultiLineTextExtent ( caption ) tab_height = measured_texty + tab_width = measured_textx + tab_height + if close_button_state != AUI_BUTTON_STATE_HIDDEN : tab_width += self . _active_close_bmp . GetWidth ( ) if self . _agwFlags & AUI_NB_TAB_FIXED_WIDTH : tab_width = self . _fixed_tab_width if control is not None : controlW , controlH = control . GetSize ( ) tab_width += controlW + x_extent = tab_width - ( tab_height / ) - return ( tab_width , tab_height ) , x_extent def DrawButton ( self , dc , wnd , in_rect , button , orientation ) : \"\"\"\"\"\" bitmap_id , button_state = button . id , button . cur_state if bitmap_id == AUI_BUTTON_CLOSE : if button_state & AUI_BUTTON_STATE_DISABLED : bmp = self . _disabled_close_bmp else : bmp = self . _active_close_bmp elif bitmap_id == AUI_BUTTON_LEFT : if button_state & AUI_BUTTON_STATE_DISABLED : bmp = self . _disabled_left_bmp else : bmp = self . _active_left_bmp elif bitmap_id == AUI_BUTTON_RIGHT : if button_state & AUI_BUTTON_STATE_DISABLED : bmp = self . _disabled_right_bmp else : bmp = self . _active_right_bmp elif bitmap_id == AUI_BUTTON_WINDOWLIST : if button_state & AUI_BUTTON_STATE_DISABLED : bmp = self . _disabled_windowlist_bmp else : bmp = self . _active_windowlist_bmp else : if button_state & AUI_BUTTON_STATE_DISABLED : bmp = button . dis_bitmap else : bmp = button . bitmap if not bmp . IsOk ( ) : return rect = wx . Rect ( * in_rect ) if orientation == wx . LEFT : rect . SetX ( in_rect . x ) rect . SetY ( ( ( in_rect . y + in_rect . height ) / ) - ( bmp . GetHeight ( ) / ) ) rect . SetWidth ( bmp . GetWidth ( ) ) rect . SetHeight ( bmp . GetHeight ( ) ) else : rect = wx . Rect ( in_rect . x + in_rect . width - bmp . GetWidth ( ) , ( ( in_rect . y + in_rect . height ) / ) - ( bmp . GetHeight ( ) / ) , bmp . GetWidth ( ) , bmp . GetHeight ( ) ) self . DrawButtons ( dc , rect , bmp , wx . WHITE , button_state ) out_rect = wx . Rect ( * rect ) return out_rect def ShowDropDown ( self , wnd , pages , active_idx ) : \"\"\"\"\"\" menuPopup = wx . Menu ( ) useImages = self . GetAGWFlags ( ) & AUI_NB_USE_IMAGES_DROPDOWN for i , page in enumerate ( pages ) : if useImages : menuItem = wx . MenuItem ( menuPopup , + i , page . caption ) if page . bitmap : menuItem . SetBitmap ( page . bitmap ) menuPopup . AppendItem ( menuItem ) else : menuPopup . AppendCheckItem ( + i , page . caption ) menuPopup . Enable ( + i , page . enabled ) if active_idx != - and not useImages : menuPopup . Check ( + active_idx , True ) pt = wx . GetMousePosition ( ) pt = wnd . ScreenToClient ( pt ) if pt . x < : pt . x = else : pt . x -= cli_rect = wnd . GetClientRect ( ) pt . y = cli_rect . y + cli_rect . height cc = AuiCommandCapture ( ) wnd . PushEventHandler ( cc ) wnd . PopupMenu ( menuPopup , pt ) command = cc . GetCommandId ( ) wnd . PopEventHandler ( True ) if command >= : return command - return - def GetBestTabCtrlSize ( self , wnd , pages , required_bmp_size ) : \"\"\"\"\"\" dc = wx . ClientDC ( wnd ) dc . SetFont ( self . _measuring_font ) s , x_extent = self . GetTabSize ( dc , wnd , \"\" , wx . NullBitmap , True , AUI_BUTTON_STATE_HIDDEN , None ) max_y = s [ ] for page in pages : if page . control : controlW , controlH = page . control . GetSize ( ) max_y = max ( max_y , controlH + ) textx , texty , dummy = dc . GetMultiLineTextExtent ( page . caption ) max_y = max ( max_y , texty ) return max_y + def SetNormalFont ( self , font ) : \"\"\"\"\"\" self . _normal_font = font def SetSelectedFont ( self , font ) : \"\"\"\"\"\" self . _selected_font = font def SetMeasuringFont ( self , font ) : \"\"\"\"\"\" self . _measuring_font = font def GetNormalFont ( self ) : \"\"\"\"\"\" return self . _normal_font def GetSelectedFont ( self ) : \"\"\"\"\"\" return self . _selected_font def GetMeasuringFont ( self ) : \"\"\"\"\"\" return self . _measuring_font def SetCustomButton ( self , bitmap_id , button_state , bmp ) : \"\"\"\"\"\" if bitmap_id == AUI_BUTTON_CLOSE : if button_state == AUI_BUTTON_STATE_NORMAL : self . _active_close_bmp = bmp self . _hover_close_bmp = self . _active_close_bmp self . _pressed_close_bmp = self . _active_close_bmp self . _disabled_close_bmp = self . _active_close_bmp elif button_state == AUI_BUTTON_STATE_HOVER : self . _hover_close_bmp = bmp elif button_state == AUI_BUTTON_STATE_PRESSED : self . _pressed_close_bmp = bmp else : self . _disabled_close_bmp = bmp elif bitmap_id == AUI_BUTTON_LEFT : if button_state & AUI_BUTTON_STATE_DISABLED : self . _disabled_left_bmp = bmp else : self . _active_left_bmp = bmp elif bitmap_id == AUI_BUTTON_RIGHT : if button_state & AUI_BUTTON_STATE_DISABLED : self . _disabled_right_bmp = bmp else : self . _active_right_bmp = bmp elif bitmap_id == AUI_BUTTON_WINDOWLIST : if button_state & AUI_BUTTON_STATE_DISABLED : self . _disabled_windowlist_bmp = bmp else : self . _active_windowlist_bmp = bmp class VC71TabArt ( AuiDefaultTabArt ) : \"\"\"\"\"\" def __init__ ( self ) : \"\"\"\"\"\" AuiDefaultTabArt . __init__ ( self ) def Clone ( self ) : \"\"\"\"\"\" art = type ( self ) ( ) art . SetNormalFont ( self . GetNormalFont ( ) ) art . SetSelectedFont ( self . GetSelectedFont ( ) ) art . SetMeasuringFont ( self . GetMeasuringFont ( ) ) art = CopyAttributes ( art , self ) return art def DrawTab ( self , dc , wnd , page , in_rect , close_button_state , paint_control = False ) : \"\"\"\"\"\" control = page . control tab_size , x_extent = self . GetTabSize ( dc , wnd , page . caption , page . bitmap , page . active , close_button_state , control ) tab_height = self . _tab_ctrl_height - tab_width = tab_size [ ] tab_x = in_rect . x tab_y = in_rect . y + in_rect . height - tab_height clip_width = tab_width if tab_x + clip_width > in_rect . x + in_rect . width - : clip_width = ( in_rect . x + in_rect . width ) - tab_x - dc . SetClippingRegion ( tab_x , tab_y , clip_width + , tab_height - ) agwFlags = self . GetAGWFlags ( ) if agwFlags & AUI_NB_BOTTOM : tab_y -= dc . SetPen ( ( page . active and [ wx . Pen ( wx . SystemSettings . GetColour ( wx . SYS_COLOUR_3DHIGHLIGHT ) ) ] or [ wx . Pen ( wx . SystemSettings . GetColour ( wx . SYS_COLOUR_3DSHADOW ) ) ] ) [ ] ) dc . SetBrush ( ( page . active and [ wx . Brush ( wx . SystemSettings . GetColour ( wx . SYS_COLOUR_3DFACE ) ) ] or [ wx . TRANSPARENT_BRUSH ] ) [ ] ) if page . active : tabH = tab_height - dc . DrawRectangle ( tab_x , tab_y , tab_width , tabH ) rightLineY1 = ( agwFlags & AUI_NB_BOTTOM and [ vertical_border_padding - ] or [ vertical_border_padding - ] ) [ ] rightLineY2 = tabH + dc . SetPen ( wx . Pen ( wx . SystemSettings . GetColour ( wx . SYS_COLOUR_3DSHADOW ) ) ) dc . DrawLine ( tab_x + tab_width - , rightLineY1 + , tab_x + tab_width - , rightLineY2 ) if agwFlags & AUI_NB_BOTTOM : dc . DrawLine ( tab_x + , rightLineY2 - , tab_x + tab_width - , rightLineY2 - ) dc . SetPen ( wx . Pen ( wx . SystemSettings . GetColour ( wx . SYS_COLOUR_3DDKSHADOW ) ) ) dc . DrawLine ( tab_x + tab_width , rightLineY1 , tab_x + tab_width , rightLineY2 ) if agwFlags & AUI_NB_BOTTOM : dc . DrawLine ( tab_x , rightLineY2 - , tab_x + tab_width , rightLineY2 - ) else : blackLineY1 = ( agwFlags & AUI_NB_BOTTOM and [ vertical_border_padding + ] or [ vertical_border_padding + ] ) [ ] blackLineY2 = tab_height - dc . DrawLine ( tab_x + tab_width , blackLineY1 , tab_x + tab_width , blackLineY2 ) border_points = [ , ] if agwFlags & AUI_NB_BOTTOM : border_points [ ] = wx . Point ( tab_x , tab_y ) border_points [ ] = wx . Point ( tab_x , tab_y + tab_height - ) else : border_points [ ] = wx . Point ( tab_x , tab_y + tab_height - ) border_points [ ] = wx . Point ( tab_x , tab_y + ) drawn_tab_yoff = border_points [ ] . y drawn_tab_height = border_points [ ] . y - border_points [ ] . y text_offset = tab_x + close_button_width = if close_button_state != AUI_BUTTON_STATE_HIDDEN : close_button_width = self . _active_close_bmp . GetWidth ( ) if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT : text_offset += close_button_width - if not page . enabled : dc . SetTextForeground ( wx . SystemSettings . GetColour ( wx . SYS_COLOUR_GRAYTEXT ) ) pagebitmap = page . dis_bitmap else : dc . SetTextForeground ( page . text_colour ) pagebitmap = page . bitmap shift = if agwFlags & AUI_NB_BOTTOM : shift = ( page . active and [ ] or [ ] ) [ ] bitmap_offset = if pagebitmap . IsOk ( ) : bitmap_offset = tab_x + if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT and close_button_width : bitmap_offset += close_button_width - dc . DrawBitmap ( pagebitmap , bitmap_offset , drawn_tab_yoff + ( drawn_tab_height / ) - ( pagebitmap . GetHeight ( ) / ) + shift , True ) text_offset = bitmap_offset + pagebitmap . GetWidth ( ) text_offset += else : if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT == or not close_button_width : text_offset = tab_x + caption = page . caption if caption == \"\" : caption = \"\" if page . active : dc . SetFont ( self . _selected_font ) textx , texty , dummy = dc . GetMultiLineTextExtent ( caption ) else : dc . SetFont ( self . _normal_font ) textx , texty , dummy = dc . GetMultiLineTextExtent ( caption ) draw_text = ChopText ( dc , caption , tab_width - ( text_offset - tab_x ) - close_button_width ) ypos = drawn_tab_yoff + ( drawn_tab_height ) / - ( texty / ) - + shift offset_focus = text_offset if control is not None : if control . GetPosition ( ) != wx . Point ( text_offset + , ypos ) : control . SetPosition ( wx . Point ( text_offset + , ypos ) ) if not control . IsShown ( ) : control . Show ( ) if paint_control : bmp = TakeScreenShot ( control . GetScreenRect ( ) ) dc . DrawBitmap ( bmp , text_offset + , ypos , True ) controlW , controlH = control . GetSize ( ) text_offset += controlW + textx += controlW + rectx , recty , dummy = dc . GetMultiLineTextExtent ( draw_text ) dc . DrawLabel ( draw_text , wx . Rect ( text_offset , ypos , rectx , recty ) ) out_button_rect = wx . Rect ( ) if ( agwFlags & AUI_NB_NO_TAB_FOCUS ) == : self . DrawFocusRectangle ( dc , page , wnd , draw_text , offset_focus , bitmap_offset , drawn_tab_yoff + shift , drawn_tab_height + shift , rectx , recty ) if close_button_state != AUI_BUTTON_STATE_HIDDEN : close_button_width = self . _active_close_bmp . GetWidth ( ) bmp = self . _disabled_close_bmp if close_button_state == AUI_BUTTON_STATE_HOVER : bmp = self . _hover_close_bmp elif close_button_state == AUI_BUTTON_STATE_PRESSED : bmp = self . _pressed_close_bmp if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT : rect = wx . Rect ( tab_x + , drawn_tab_yoff + ( drawn_tab_height / ) - ( bmp . GetHeight ( ) / ) + shift , close_button_width , tab_height ) else : rect = wx . Rect ( tab_x + tab_width - close_button_width - , drawn_tab_yoff + ( drawn_tab_height / ) - ( bmp . GetHeight ( ) / ) + shift , close_button_width , tab_height ) rect = IndentPressedBitmap ( rect , close_button_state ) dc . DrawBitmap ( bmp , rect . x , rect . y , True ) out_button_rect = rect out_tab_rect = wx . Rect ( tab_x , tab_y , tab_width , tab_height ) dc . DestroyClippingRegion ( ) return out_tab_rect , out_button_rect , x_extent class FF2TabArt ( AuiDefaultTabArt ) : \"\"\"\"\"\" def __init__ ( self ) : \"\"\"\"\"\" AuiDefaultTabArt . __init__ ( self ) def Clone ( self ) : \"\"\"\"\"\" art = type ( self ) ( ) art . SetNormalFont ( self . GetNormalFont ( ) ) art . SetSelectedFont ( self . GetSelectedFont ( ) ) art . SetMeasuringFont ( self . GetMeasuringFont ( ) ) art = CopyAttributes ( art , self ) return art def GetTabSize ( self , dc , wnd , caption , bitmap , active , close_button_state , control ) : \"\"\"\"\"\" tab_size , x_extent = AuiDefaultTabArt . GetTabSize ( self , dc , wnd , caption , bitmap , active , close_button_state , control ) tab_width , tab_height = tab_size tab_height += return ( tab_width , tab_height ) , x_extent def DrawTab ( self , dc , wnd , page , in_rect , close_button_state , paint_control = False ) : \"\"\"\"\"\" control = page . control tab_size , x_extent = self . GetTabSize ( dc , wnd , page . caption , page . bitmap , page . active , close_button_state , control ) tab_height = self . _tab_ctrl_height - tab_width = tab_size [ ] tab_x = in_rect . x tab_y = in_rect . y + in_rect . height - tab_height clip_width = tab_width if tab_x + clip_width > in_rect . x + in_rect . width - : clip_width = ( in_rect . x + in_rect . width ) - tab_x - dc . SetClippingRegion ( tab_x , tab_y , clip_width + , tab_height - ) tabPoints = [ wx . Point ( ) for i in xrange ( ) ] adjust = if not page . active : adjust = agwFlags = self . GetAGWFlags ( ) tabPoints [ ] . x = tab_x + tabPoints [ ] . y = ( agwFlags & AUI_NB_BOTTOM and [ ] or [ tab_height - ] ) [ ] tabPoints [ ] . x = tabPoints [ ] . x tabPoints [ ] . y = ( agwFlags & AUI_NB_BOTTOM and [ tab_height - ( vertical_border_padding + ) - adjust ] or [ ( vertical_border_padding + ) + adjust ] ) [ ] tabPoints [ ] . x = tabPoints [ ] . x + tabPoints [ ] . y = ( agwFlags & AUI_NB_BOTTOM and [ tab_height - vertical_border_padding - adjust ] or [ vertical_border_padding + adjust ] ) [ ] tabPoints [ ] . x = tab_x + tab_width - tabPoints [ ] . y = tabPoints [ ] . y tabPoints [ ] . x = tabPoints [ ] . x + tabPoints [ ] . y = tabPoints [ ] . y tabPoints [ ] . x = tabPoints [ ] . x tabPoints [ ] . y = tabPoints [ ] . y tabPoints [ ] . x = tabPoints [ ] . x tabPoints [ ] . y = tabPoints [ ] . y rr = wx . RectPP ( tabPoints [ ] , tabPoints [ ] ) self . DrawTabBackground ( dc , rr , page . active , ( agwFlags & AUI_NB_BOTTOM ) == ) dc . SetBrush ( wx . TRANSPARENT_BRUSH ) dc . SetPen ( wx . Pen ( wx . SystemSettings_GetColour ( wx . SYS_COLOUR_BTNSHADOW ) ) ) dc . DrawPolygon ( tabPoints ) if page . active : dc . DrawLine ( tabPoints [ ] . x + , tabPoints [ ] . y , tabPoints [ ] . x , tabPoints [ ] . y ) drawn_tab_yoff = tabPoints [ ] . y drawn_tab_height = tabPoints [ ] . y - tabPoints [ ] . y text_offset = tab_x + close_button_width = if close_button_state != AUI_BUTTON_STATE_HIDDEN : close_button_width = self . _active_close_bmp . GetWidth ( ) if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT : text_offset += close_button_width - if not page . enabled : dc . SetTextForeground ( wx . SystemSettings . GetColour ( wx . SYS_COLOUR_GRAYTEXT ) ) pagebitmap = page . dis_bitmap else : dc . SetTextForeground ( page . text_colour ) pagebitmap = page . bitmap shift = - if agwFlags & AUI_NB_BOTTOM : shift = bitmap_offset = if pagebitmap . IsOk ( ) : bitmap_offset = tab_x + if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT and close_button_width : bitmap_offset += close_button_width - dc . DrawBitmap ( pagebitmap , bitmap_offset , drawn_tab_yoff + ( drawn_tab_height / ) - ( pagebitmap . GetHeight ( ) / ) + shift , True ) text_offset = bitmap_offset + pagebitmap . GetWidth ( ) text_offset += else : if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT == or not close_button_width : text_offset = tab_x + caption = page . caption if caption == \"\" : caption = \"\" if page . active : dc . SetFont ( self . _selected_font ) textx , texty , dummy = dc . GetMultiLineTextExtent ( caption ) else : dc . SetFont ( self . _normal_font ) textx , texty , dummy = dc . GetMultiLineTextExtent ( caption ) if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT : draw_text = ChopText ( dc , caption , tab_width - ( text_offset - tab_x ) - close_button_width + ) else : draw_text = ChopText ( dc , caption , tab_width - ( text_offset - tab_x ) - close_button_width ) ypos = drawn_tab_yoff + drawn_tab_height / - texty / - + shift offset_focus = text_offset if control is not None : if control . GetPosition ( ) != wx . Point ( text_offset + , ypos ) : control . SetPosition ( wx . Point ( text_offset + , ypos ) ) if not control . IsShown ( ) : control . Show ( ) if paint_control : bmp = TakeScreenShot ( control . GetScreenRect ( ) ) dc . DrawBitmap ( bmp , text_offset + , ypos , True ) controlW , controlH = control . GetSize ( ) text_offset += controlW + textx += controlW + rectx , recty , dummy = dc . GetMultiLineTextExtent ( draw_text ) dc . DrawLabel ( draw_text , wx . Rect ( text_offset , ypos , rectx , recty ) ) if ( agwFlags & AUI_NB_NO_TAB_FOCUS ) == : self . DrawFocusRectangle ( dc , page , wnd , draw_text , offset_focus , bitmap_offset , drawn_tab_yoff + shift , drawn_tab_height , rectx , recty ) out_button_rect = wx . Rect ( ) if close_button_state != AUI_BUTTON_STATE_HIDDEN : close_button_width = self . _active_close_bmp . GetWidth ( ) bmp = self . _disabled_close_bmp if close_button_state == AUI_BUTTON_STATE_HOVER : bmp = self . _hover_close_bmp elif close_button_state == AUI_BUTTON_STATE_PRESSED : bmp = self . _pressed_close_bmp if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT : rect = wx . Rect ( tab_x + , drawn_tab_yoff + ( drawn_tab_height / ) - ( bmp . GetHeight ( ) / ) + shift , close_button_width , tab_height ) else : rect = wx . Rect ( tab_x + tab_width - close_button_width - , drawn_tab_yoff + ( drawn_tab_height / ) - ( bmp . GetHeight ( ) / ) + shift , close_button_width , tab_height ) rect = IndentPressedBitmap ( rect , close_button_state ) dc . DrawBitmap ( bmp , rect . x , rect . y , True ) out_button_rect = rect out_tab_rect = wx . Rect ( tab_x , tab_y , tab_width , tab_height ) dc . DestroyClippingRegion ( ) return out_tab_rect , out_button_rect , x_extent def DrawTabBackground ( self , dc , rect , focus , upperTabs ) : \"\"\"\"\"\" regPts = [ wx . Point ( ) for indx in xrange ( ) ] if focus : if upperTabs : leftPt = wx . Point ( rect . x , rect . y + ( rect . height / ) * ) rightPt = wx . Point ( rect . x + rect . width - , rect . y + ( rect . height / ) * ) else : leftPt = wx . Point ( rect . x , rect . y + ( rect . height / ) * ) rightPt = wx . Point ( rect . x + rect . width - , rect . y + ( rect . height / ) * ) else : leftPt = wx . Point ( rect . x , rect . y + ( rect . height / ) ) rightPt = wx . Point ( rect . x + rect . width - , rect . y + ( rect . height / ) ) top = wx . RectPP ( rect . GetTopLeft ( ) , rightPt ) bottom = wx . RectPP ( leftPt , rect . GetBottomRight ( ) ) topStartColour = wx . WHITE if not focus : topStartColour = LightColour ( wx . SystemSettings_GetColour ( wx . SYS_COLOUR_3DFACE ) , ) topEndColour = wx . SystemSettings_GetColour ( wx . SYS_COLOUR_3DFACE ) bottomStartColour = topEndColour bottomEndColour = topEndColour if upperTabs : if focus : dc . GradientFillLinear ( top , topStartColour , topEndColour , wx . SOUTH ) dc . GradientFillLinear ( bottom , bottomStartColour , bottomEndColour , wx . SOUTH ) else : dc . GradientFillLinear ( top , topEndColour , topStartColour , wx . SOUTH ) dc . GradientFillLinear ( bottom , bottomStartColour , bottomEndColour , wx . SOUTH ) else : if focus : dc . GradientFillLinear ( bottom , topEndColour , bottomEndColour , wx . SOUTH ) dc . GradientFillLinear ( top , topStartColour , topStartColour , wx . SOUTH ) else : dc . GradientFillLinear ( bottom , bottomStartColour , bottomEndColour , wx . SOUTH ) dc . GradientFillLinear ( top , topEndColour , topStartColour , wx . SOUTH ) dc . SetBrush ( wx . TRANSPARENT_BRUSH ) class VC8TabArt ( AuiDefaultTabArt ) : \"\"\"\"\"\" def __init__ ( self ) : \"\"\"\"\"\" AuiDefaultTabArt . __init__ ( self ) def Clone ( self ) : \"\"\"\"\"\" art = type ( self ) ( ) art . SetNormalFont ( self . GetNormalFont ( ) ) art . SetSelectedFont ( self . GetSelectedFont ( ) ) art . SetMeasuringFont ( self . GetMeasuringFont ( ) ) art = CopyAttributes ( art , self ) return art def SetSizingInfo ( self , tab_ctrl_size , tab_count , minMaxTabWidth ) : \"\"\"\"\"\" AuiDefaultTabArt . SetSizingInfo ( self , tab_ctrl_size , tab_count , minMaxTabWidth ) minTabWidth , maxTabWidth = minMaxTabWidth if minTabWidth > - : self . _fixed_tab_width = max ( self . _fixed_tab_width , minTabWidth ) if maxTabWidth > - : self . _fixed_tab_width = min ( self . _fixed_tab_width , maxTabWidth ) self . _fixed_tab_width -= def GetTabSize ( self , dc , wnd , caption , bitmap , active , close_button_state , control = None ) : \"\"\"\"\"\" tab_size , x_extent = AuiDefaultTabArt . GetTabSize ( self , dc , wnd , caption , bitmap , active , close_button_state , control ) tab_width , tab_height = tab_size tab_width += if not bitmap . IsOk ( ) : tab_width += tab_height += return ( tab_width , tab_height ) , x_extent def DrawTab ( self , dc , wnd , page , in_rect , close_button_state , paint_control = False ) : \"\"\"\"\"\" control = page . control tab_size , x_extent = self . GetTabSize ( dc , wnd , page . caption , page . bitmap , page . active , close_button_state , control ) tab_height = self . _tab_ctrl_height - tab_width = tab_size [ ] tab_x = in_rect . x tab_y = in_rect . y + in_rect . height - tab_height clip_width = tab_width + if tab_x + clip_width > in_rect . x + in_rect . width - : clip_width = ( in_rect . x + in_rect . width ) - tab_x - tabPoints = [ wx . Point ( ) for i in xrange ( ) ] adjust = if not page . active : adjust = agwFlags = self . GetAGWFlags ( ) tabPoints [ ] . x = ( agwFlags & AUI_NB_BOTTOM and [ tab_x ] or [ tab_x + adjust ] ) [ ] tabPoints [ ] . y = ( agwFlags & AUI_NB_BOTTOM and [ ] or [ tab_height - ] ) [ ] tabPoints [ ] . x = tabPoints [ ] . x + tab_height - vertical_border_padding - - adjust tabPoints [ ] . y = ( agwFlags & AUI_NB_BOTTOM and [ tab_height - ( vertical_border_padding + ) ] or [ ( vertical_border_padding + ) ] ) [ ] tabPoints [ ] . x = tabPoints [ ] . x + tabPoints [ ] . y = ( agwFlags & AUI_NB_BOTTOM and [ tab_height - vertical_border_padding ] or [ vertical_border_padding ] ) [ ] tabPoints [ ] . x = tabPoints [ ] . x + tab_width - tab_height + vertical_border_padding tabPoints [ ] . y = ( agwFlags & AUI_NB_BOTTOM and [ tab_height - vertical_border_padding ] or [ vertical_border_padding ] ) [ ] tabPoints [ ] . x = tabPoints [ ] . x + tabPoints [ ] . y = ( agwFlags & AUI_NB_BOTTOM and [ tabPoints [ ] . y - ] or [ tabPoints [ ] . y + ] ) [ ] tabPoints [ ] . x = tabPoints [ ] . x + tabPoints [ ] . y = ( agwFlags & AUI_NB_BOTTOM and [ ( tabPoints [ ] . y - ) ] or [ tabPoints [ ] . y + ] ) [ ] tabPoints [ ] . x = tabPoints [ ] . x + tab_width - tab_height + + vertical_border_padding tabPoints [ ] . y = tabPoints [ ] . y tabPoints [ ] . x = tabPoints [ ] . x tabPoints [ ] . y = tabPoints [ ] . y self . FillVC8GradientColour ( dc , tabPoints , page . active ) dc . SetBrush ( wx . TRANSPARENT_BRUSH ) dc . SetPen ( wx . Pen ( wx . SystemSettings . GetColour ( wx . SYS_COLOUR_BTNSHADOW ) ) ) dc . DrawPolygon ( tabPoints ) if page . active : dc . SetPen ( wx . WHITE_PEN ) dc . DrawLine ( tabPoints [ ] . x , tabPoints [ ] . y , tabPoints [ ] . x , tabPoints [ ] . y ) dc . SetClippingRegion ( tab_x , tab_y , clip_width + , tab_height - ) drawn_tab_yoff = tabPoints [ ] . y drawn_tab_height = tabPoints [ ] . y - tabPoints [ ] . y text_offset = tab_x + close_button_width = if close_button_state != AUI_BUTTON_STATE_HIDDEN : close_button_width = self . _active_close_bmp . GetWidth ( ) if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT : text_offset += close_button_width if not page . enabled : dc . SetTextForeground ( wx . SystemSettings . GetColour ( wx . SYS_COLOUR_GRAYTEXT ) ) pagebitmap = page . dis_bitmap else : dc . SetTextForeground ( page . text_colour ) pagebitmap = page . bitmap shift = if agwFlags & AUI_NB_BOTTOM : shift = ( page . active and [ ] or [ ] ) [ ] bitmap_offset = if pagebitmap . IsOk ( ) : bitmap_offset = tab_x + if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT and close_button_width : bitmap_offset += close_button_width dc . DrawBitmap ( pagebitmap , bitmap_offset , drawn_tab_yoff + ( drawn_tab_height / ) - ( pagebitmap . GetHeight ( ) / ) + shift , True ) text_offset = bitmap_offset + pagebitmap . GetWidth ( ) text_offset += else : if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT == or not close_button_width : text_offset = tab_x + tab_height caption = page . caption if caption == \"\" : caption = \"\" if page . active : dc . SetFont ( self . _selected_font ) textx , texty , dummy = dc . GetMultiLineTextExtent ( caption ) else : dc . SetFont ( self . _normal_font ) textx , texty , dummy = dc . GetMultiLineTextExtent ( caption ) if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT : draw_text = ChopText ( dc , caption , tab_width - ( text_offset - tab_x ) ) else : draw_text = ChopText ( dc , caption , tab_width - ( text_offset - tab_x ) - close_button_width ) ypos = drawn_tab_yoff + drawn_tab_height / - texty / - + shift offset_focus = text_offset if control is not None : if control . GetPosition ( ) != wx . Point ( text_offset + , ypos ) : control . SetPosition ( wx . Point ( text_offset + , ypos ) ) if not control . IsShown ( ) : control . Show ( ) if paint_control : bmp = TakeScreenShot ( control . GetScreenRect ( ) ) dc . DrawBitmap ( bmp , text_offset + , ypos , True ) controlW , controlH = control . GetSize ( ) text_offset += controlW + textx += controlW + rectx , recty , dummy = dc . GetMultiLineTextExtent ( draw_text ) dc . DrawLabel ( draw_text , wx . Rect ( text_offset , ypos , rectx , recty ) ) if ( agwFlags & AUI_NB_NO_TAB_FOCUS ) == : self . DrawFocusRectangle ( dc , page , wnd , draw_text , offset_focus , bitmap_offset , drawn_tab_yoff + shift , drawn_tab_height + shift , rectx , recty ) out_button_rect = wx . Rect ( ) if close_button_state != AUI_BUTTON_STATE_HIDDEN : close_button_width = self . _active_close_bmp . GetWidth ( ) bmp = self . _disabled_close_bmp if close_button_state == AUI_BUTTON_STATE_HOVER : bmp = self . _hover_close_bmp elif close_button_state == AUI_BUTTON_STATE_PRESSED : bmp = self . _pressed_close_bmp if page . active : xpos = tab_x + tab_width - close_button_width + else : xpos = tab_x + tab_width - close_button_width - if agwFlags & AUI_NB_CLOSE_ON_TAB_LEFT : rect = wx . Rect ( tab_x + , drawn_tab_yoff + ( drawn_tab_height / ) - ( bmp . GetHeight ( ) / ) + shift , close_button_width , tab_height ) else : rect = wx . Rect ( xpos , drawn_tab_yoff + ( drawn_tab_height / ) - ( bmp . GetHeight ( ) / ) + shift , close_button_width , tab_height ) rect = IndentPressedBitmap ( rect , close_button_state ) dc . DrawBitmap ( bmp , rect . x , rect . y , True ) out_button_rect = rect out_tab_rect = wx . Rect ( tab_x , tab_y , x_extent , tab_height ) dc . DestroyClippingRegion ( ) return out_tab_rect , out_button_rect , x_extent def FillVC8GradientColour ( self , dc , tabPoints , active ) : \"\"\"\"\"\" xList = [ pt . x for pt in tabPoints ] yList = [ pt . y for pt in tabPoints ] minx , maxx = min ( xList ) , max ( xList ) miny , maxy = min ( yList ) , max ( yList ) rect = wx . Rect ( minx , maxy , maxx - minx , miny - maxy + ) region = wx . RegionFromPoints ( tabPoints ) if self . _buttonRect . width > : buttonRegion = wx . Region ( * self . _buttonRect ) region . XorRegion ( buttonRegion ) dc . SetClippingRegionAsRegion ( region ) if active : bottom_colour = top_colour = wx . WHITE else : bottom_colour = StepColour ( self . _base_colour , ) top_colour = StepColour ( self . _base_colour , ) dc . GradientFillLinear ( rect , top_colour , bottom_colour , wx . SOUTH ) dc . DestroyClippingRegion ( ) class ChromeTabArt ( AuiDefaultTabArt ) : \"\"\"\"\"\" def __init__ ( self ) : \"\"\"\"\"\" AuiDefaultTabArt . __init__ ( self ) self . SetBitmaps ( mirror = False ) closeBmp = tab_close . GetBitmap ( ) closeHBmp = tab_close_h . GetBitmap ( ) closePBmp = tab_close_p . GetBitmap ( ) self . SetCustomButton ( AUI_BUTTON_CLOSE , AUI_BUTTON_STATE_NORMAL , closeBmp ) self . SetCustomButton ( AUI_BUTTON_CLOSE , AUI_BUTTON_STATE_HOVER , closeHBmp ) self . SetCustomButton ( AUI_BUTTON_CLOSE , AUI_BUTTON_STATE_PRESSED , closePBmp ) def SetAGWFlags ( self , agwFlags ) : \"\"\"\"\"\" if agwFlags & AUI_NB_TOP : self . SetBitmaps ( mirror = False ) elif agwFlags & AUI_NB_BOTTOM : self . SetBitmaps ( mirror = True ) AuiDefaultTabArt . SetAGWFlags ( self , agwFlags ) def SetBitmaps ( self , mirror ) : \"\"\"\"\"\" bmps = [ tab_active_left . GetBitmap ( ) , tab_active_center . GetBitmap ( ) , tab_active_right . GetBitmap ( ) , tab_inactive_left . GetBitmap ( ) , tab_inactive_center . GetBitmap ( ) , tab_inactive_right . GetBitmap ( ) ] if mirror : for indx , bmp in enumerate ( bmps ) : img = bmp . ConvertToImage ( ) img = img . Mirror ( horizontally = False ) bmps [ indx ] = img . ConvertToBitmap ( ) self . _leftActiveBmp = bmps [ ] self . _centerActiveBmp = bmps [ ] ", "answer": "self . _rightActiveBmp = bmps [ ]"}, {"prompt": " \"\"\"\"\"\" VERSION = ( , , , '' ) ", "answer": "__version__ = \"\" . join ( map ( str , VERSION [ : - ] ) )"}, {"prompt": " from south . utils import datetime_utils as datetime from south . db import db from south . v2 import DataMigration from django . db import models class Migration ( DataMigration ) : def forwards ( self , orm ) : \"\" orm . Journal . objects . filter ( medline_title = None ) . update ( medline_title = '' ) def backwards ( self , orm ) : \"\" orm . Journal . objects . filter ( medline_title = '' ) . update ( medline_title = None ) models = { '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) } , '' : { '' : { '' : \"\" , '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) } , '' : { '' : { '' : \"\" , '' : \"\" , '' : '' , '' : \"\" } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : '' , '' : [ '' ] } , '' : ( '' , [ ] , { '' : \"\" , '' : \"\" } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : \"\" } ) } , '' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : \"\" , '' : \"\" , '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) } , '' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) } , '' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : '' , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' , '' : \"\" , '' : '' , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : \"\" } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : \"\" } ) , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : \"\" , '' : '' } , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : '' } ) } , '' : { '' : { '' : '' } , '' : ( '' , [ ] , { '' : '' , '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : '' } ) , '' : ( '' , [ ] , { '' : \"\" , '' : \"\" } ) , '' : ( '' , [ ] , { '' : '' } ) } , '' : { '' : { '' : '' } , ", "answer": "'' : ( '' , [ ] , { '' : \"\" , '' : \"\" } ) ,"}, {"prompt": " \"\"\"\"\"\" class V2_0Constants ( object ) : ", "answer": "XML_NS = ''"}, {"prompt": " import numpy as np from nose . tools import raises from numpy . testing import assert_allclose from menpo . shape import PointCloud from menpo . image import MaskedImage , BooleanImage def test_constrain_mask_to_landmarks_pwa ( ) : img = MaskedImage . init_blank ( ( , ) ) img . landmarks [ '' ] = PointCloud ( np . array ( [ [ , ] , [ , ] , [ , ] , [ , ] ] ) ) img . constrain_mask_to_landmarks ( group = '' ) example_mask = BooleanImage . init_blank ( ( , ) , fill = False ) example_mask . pixels [ , : , : ] = True assert ( img . mask . n_true ( ) == ) assert_allclose ( img . mask . pixels , example_mask . pixels ) def test_constrain_mask_to_landmarks_pwa_batched ( ) : img = MaskedImage . init_blank ( ( , ) ) img . landmarks [ '' ] = PointCloud ( np . array ( [ [ , ] , [ , ] , [ , ] , [ , ] ] ) ) img . constrain_mask_to_landmarks ( group = '' , batch_size = ) example_mask = BooleanImage . init_blank ( ( , ) , fill = False ) example_mask . pixels [ , : , : ] = True assert ( img . mask . n_true ( ) == ) assert_allclose ( img . mask . pixels , example_mask . pixels ) def test_constrain_mask_to_landmarks_convex_hull ( ) : img = MaskedImage . init_blank ( ( , ) ) img . landmarks [ '' ] = PointCloud ( np . array ( [ [ , ] , [ , ] , [ , ] , [ , ] ] ) ) img . constrain_mask_to_landmarks ( group = '' , point_in_pointcloud = '' ) example_mask = BooleanImage . init_blank ( ( , ) , fill = False ) example_mask . pixels [ , : , : ] = True assert ( img . mask . n_true ( ) == ) assert_allclose ( img . mask . pixels , example_mask . pixels ) def test_constrain_mask_to_landmarks_callable ( ) : def bounding_box ( _ , indices ) : return np . ones ( indices . shape [ ] , dtype = np . bool ) img = MaskedImage . init_blank ( ( , ) ) img . landmarks [ '' ] = PointCloud ( np . array ( [ [ , ] , [ , ] , [ , ] , [ , ] ] ) ) img . constrain_mask_to_landmarks ( group = '' , point_in_pointcloud = bounding_box ) example_mask = BooleanImage . init_blank ( ( , ) , fill = False ) example_mask . pixels [ , : , : ] = True assert ( img . mask . n_true ( ) == ) assert_allclose ( img . mask . pixels , example_mask . pixels ) @ raises ( ValueError ) def test_constrain_mask_to_landmarks_non_2d ( ) : img = MaskedImage . init_blank ( ( , , ) ) img . landmarks [ '' ] = PointCloud ( np . array ( [ [ , , ] ] ) ) img . constrain_mask_to_landmarks ( ) @ raises ( ValueError ) def test_constrain_mask_to_landmarks_unknown_key ( ) : img = MaskedImage . init_blank ( ( , ) ) img . landmarks [ '' ] = PointCloud ( np . array ( [ [ , , ] ] ) ) img . constrain_mask_to_landmarks ( point_in_pointcloud = '' ) def test_erode ( ) : img = MaskedImage . init_blank ( ( , ) ) img2 = img . erode ( ) assert ( img2 . mask . n_true ( ) == ) img3 = img . erode ( n_pixels = ) assert ( img3 . mask . n_true ( ) == ) def test_dilate ( ) : img = MaskedImage . init_blank ( ( , ) ) img = img . erode ( n_pixels = ) img2 = img . dilate ( ) assert ( img2 . mask . n_true ( ) == ) img3 = img . dilate ( n_pixels = ) assert ( img3 . mask . n_true ( ) == ) ", "answer": "def test_init_from_rolled_channels ( ) :"}, {"prompt": " from __future__ import with_statement import logging import os import re import shutil from os . path import splitext from . import image , utils from . settings import get_thumb , Status from . utils import call_subprocess , is_valid_html5_video class SubprocessException ( Exception ) : pass def check_subprocess ( cmd , source , outname ) : \"\"\"\"\"\" logger = logging . getLogger ( __name__ ) try : returncode , stdout , stderr = call_subprocess ( cmd ) except KeyboardInterrupt : logger . debug ( '' , outname ) if os . path . isfile ( outname ) : os . remove ( outname ) raise if returncode : logger . debug ( '' , stdout ) logger . debug ( '' , stderr ) if os . path . isfile ( outname ) : logger . debug ( '' , outname ) os . remove ( outname ) raise SubprocessException ( '' + source ) def video_size ( source ) : \"\"\"\"\"\" ret , stdout , stderr = call_subprocess ( [ '' , '' , source ] ) pattern = re . compile ( r'' ) match = pattern . search ( stderr ) if match : x , y = int ( match . groups ( ) [ ] ) , int ( match . groups ( ) [ ] ) else : x = y = return x , y def generate_video ( source , outname , settings , options = None ) : \"\"\"\"\"\" logger = logging . getLogger ( __name__ ) w_src , h_src = video_size ( source ) w_dst , h_dst = settings [ '' ] logger . debug ( '' , w_src , h_src , w_dst , h_dst ) base , src_ext = splitext ( source ) base , dst_ext = splitext ( outname ) if dst_ext == src_ext and w_src <= w_dst and h_src <= h_dst : logger . debug ( '' ) shutil . copy ( source , outname ) return if h_dst * w_src < h_src * w_dst : resize_opt = [ '' , \"\" % h_dst ] else : resize_opt = [ '' , \"\" % w_dst ] if w_src <= w_dst and h_src <= h_dst : resize_opt = [ ] cmd = [ '' , '' , source , '' ] if options is not None : cmd += options cmd += resize_opt + [ outname ] logger . debug ( '' , '' . join ( cmd ) ) check_subprocess ( cmd , source , outname ) def generate_thumbnail ( source , outname , box , delay , fit = True , options = None ) : ", "answer": "\"\"\"\"\"\""}, {"prompt": " import time try : import MySQLdb except ImportError : MySQLdb = None from nagcat import log , merlintest , nagios def available ( ) : \"\"\"\"\"\" return MySQLdb is not None class NagcatMerlin ( nagios . NagcatNagios ) : \"\"\"\"\"\" def __init__ ( self , config , nagios_cfg , merlin_db_info = { } , ** kwargs ) : assert available ( ) nagios . NagcatNagios . __init__ ( self , config , nagios_cfg , ** kwargs ) self . _test_index = self . _merlin_db_info = merlin_db_info self . _peer_id = None self . _peer_id_timestamp = None self . _num_peers = None self . _update_peer_id ( ) def new_test ( self , config ) : new = merlintest . MerlinTest ( self , config , self . _test_index ) self . _test_index += self . register ( new ) if self . trend : self . trend . setup_test_trending ( new , config ) return new def _set_peer_id_and_timestamp ( self ) : \"\"\"\"\"\" try : db = MySQLdb . connect ( user = self . _merlin_db_info [ '' ] , host = self . _merlin_db_info [ '' ] , passwd = self . _merlin_db_info [ '' ] , db = self . _merlin_db_info [ '' ] ) curs = db . cursor ( ) num_rows = curs . execute ( \"\"\"\"\"\" ) self . _num_peers = num_rows log . debug ( \"\" , self . _num_peers ) for i in range ( num_rows ) : row = curs . fetchone ( ) if row [ ] == \"\" : self . _peer_id = row [ ] self . _peer_id_timestamp = time . time ( ) log . debug ( ( \"\" , str ( self . _peer_id ) ) + ( \"\" , self . _peer_id_timestamp ) ) except MySQLdb . Error , e : log . error ( \"\" % ( e . args [ ] , e . args [ ] ) ) def _update_peer_id ( self ) : log . debug ( \"\" , self . _merlin_db_info ) if self . _peer_id and self . _peer_id_timestamp : if time . time ( ) - self . _peer_id_timestamp >= : self . _set_peer_id_and_timestamp ( ) else : ", "answer": "return"}, {"prompt": " from nodeconductor . openstack import views def register_in ( router ) : router . register ( r'' , views . OpenStackServiceViewSet , base_name = '' ) router . register ( r'' , views . ImageViewSet , base_name = '' ) router . register ( r'' , views . FlavorViewSet , base_name = '' ) router . register ( r'' , views . InstanceViewSet , base_name = '' ) router . register ( r'' , views . TenantViewSet , base_name = '' ) router . register ( r'' , views . OpenStackServiceProjectLinkViewSet , base_name = '' ) router . register ( r'' , views . SecurityGroupViewSet , base_name = '' ) router . register ( r'' , views . FloatingIPViewSet , base_name = '' ) router . register ( r'' , views . BackupScheduleViewSet , base_name = '' ) ", "answer": "router . register ( r'' , views . BackupViewSet , base_name = '' )"}, {"prompt": " from oslo_config import cfg from oslo_log import log as logging from nova . api . openstack import extensions as base_extensions from nova . i18n import _LW STANDARD_EXTENSIONS = ( '' + '' ) ext_opts = [ cfg . MultiStrOpt ( '' , default = [ STANDARD_EXTENSIONS ] , help = '' '' '' , deprecated_for_removal = True ) , ] CONF = cfg . CONF CONF . register_opts ( ext_opts ) LOG = logging . getLogger ( __name__ ) class ExtensionManager ( base_extensions . ExtensionManager ) : def __init__ ( self ) : self . cls_list = CONF . osapi_compute_extension ", "answer": "if ( len ( self . cls_list ) > and"}, {"prompt": " from __future__ import unicode_literals template = { \"\" : \"\" , \"\" : \"\" , \"\" : { \"\" : { \"\" : \"\" , ", "answer": "\"\" : {"}, {"prompt": " \"\"\"\"\"\" api_keys = [ '' , '' , '' ] ", "answer": "service_discovery = {"}, {"prompt": " from __future__ import absolute_import from functools import wraps import json import requests from . auth . client_credentials import ClientCredentialsMixin from . auth . authorization_code import AuthorizationCodeMixin from . upload import UploadMixin class VimeoClient ( ClientCredentialsMixin , AuthorizationCodeMixin , UploadMixin ) : \"\"\"\"\"\" API_ROOT = \"\" HTTP_METHODS = { '' , '' , '' , '' , '' , '' , '' } ACCEPT_HEADER = \"\" USER_AGENT = \"\" def __init__ ( self , token = None , key = None , secret = None , * args , ** kwargs ) : \"\"\"\"\"\" self . token = token self . app_info = ( key , secret ) self . _requests_methods = dict ( ) assert token is not None or ( key is not None and secret is not None ) @ property def token ( self ) : return self . _token . token @ token . setter def token ( self , value ) : self . _token = _BearerToken ( value ) if value else None def __getattr__ ( self , name ) : \"\"\"\"\"\" if name not in self . HTTP_METHODS : ", "answer": "raise AttributeError ( \"\" % name )"}, {"prompt": " from msrest . serialization import Model class JobListPreparationAndReleaseTaskStatusOptions ( Model ) : \"\"\"\"\"\" def __init__ ( self , filter = None , select = None , max_results = None , timeout = , client_request_id = None , return_client_request_id = None , ocp_date = None ) : self . filter = filter self . select = select self . max_results = max_results self . timeout = timeout self . client_request_id = client_request_id self . return_client_request_id = return_client_request_id ", "answer": "self . ocp_date = ocp_date "}, {"prompt": " COMMON = { '' : { '' : '' , '' : '' , } , '' : { '' : , '' : , } } READ_PAGE_DATA = [ { '' : '' , '' : } , { '' : '' , '' : } , { '' : '' , '' : False } ] INPUT_WORDS = { '' : { '' : [ u'' , u'' ] , '' : [ u'' ] , '' : [ u'' , u'' '' '' , u'' '' '' '' ] , '' : [ u'' , u'' , u'' ] , } , '' : { '' : [ u'' ] , '' : [ ] , } , '' : { '' : [ u'' ] , '' : [ ] , } , '' : { '' : [ u'' '' ", "answer": "'' ] ,"}, {"prompt": " import json __author__ = '' from google . appengine . ext import db class Course ( db . Model ) : courseName = db . StringProperty ( required = True ) campusId = db . IntegerProperty ( required = True ) master_id = db . IntegerProperty ( required = True ) startDate = db . DateProperty ( required = True ) endDate = db . DateProperty ( required = True ) membersId = db . StringListProperty ( required = True ) def to_JSON ( self ) : data = { '' : self . courseName , '' : self . campusId , '' : self . master_id , '' : { '' : self . startDate . year , '' : self . startDate . month , '' : self . startDate . day , } , '' : { '' : self . endDate . year , ", "answer": "'' : self . endDate . month ,"}, {"prompt": " import collections import multiprocessing import threading import time from six . moves import queue as Queue from rally . common import logging from rally . common import utils from rally import consts from rally . task import runner LOG = logging . getLogger ( __name__ ) def _worker_process ( queue , iteration_gen , timeout , rps , times , max_concurrent , context , cls , method_name , args , aborted , info ) : \"\"\"\"\"\" pool = collections . deque ( ) sleep = / rps runner . _log_worker_info ( times = times , rps = rps , timeout = timeout , cls = cls , method_name = method_name , args = args ) time . sleep ( ( sleep * info [ \"\" ] ) / info [ \"\" ] ) start = time . time ( ) timeout_queue = Queue . Queue ( ) if timeout : collector_thr_by_timeout = threading . Thread ( target = utils . timeout_thread , args = ( timeout_queue , ) ) collector_thr_by_timeout . start ( ) i = while i < times and not aborted . is_set ( ) : scenario_context = runner . _get_scenario_context ( next ( iteration_gen ) , context ) worker_args = ( queue , cls , method_name , scenario_context , args ) thread = threading . Thread ( target = runner . _worker_thread , args = worker_args ) i += thread . start ( ) if timeout : timeout_queue . put ( ( thread . ident , time . time ( ) + timeout ) ) pool . append ( thread ) time_gap = time . time ( ) - start real_rps = i / time_gap if time_gap else \"\" LOG . debug ( \"\" % ( i , real_rps , rps ) ) while i / ( time . time ( ) - start ) > rps or len ( pool ) >= max_concurrent : if pool : pool [ ] . join ( ) if not pool [ ] . isAlive ( ) : pool . popleft ( ) else : time . sleep ( ) while pool : thr = pool . popleft ( ) thr . join ( ) if timeout : timeout_queue . put ( ( None , None , ) ) collector_thr_by_timeout . join ( ) @ runner . configure ( name = \"\" ) class RPSScenarioRunner ( runner . ScenarioRunner ) : \"\"\"\"\"\" CONFIG_SCHEMA = { \"\" : \"\" , \"\" : consts . JSON_SCHEMA , \"\" : { \"\" : { \"\" : \"\" } , \"\" : { \"\" : \"\" , \"\" : } , ", "answer": "\"\" : {"}, {"prompt": " \"\"\"\"\"\" from ftplib import FTP from datetime import datetime , timedelta import tempfile import subprocess import datasets import dbio import re table = \"\" def dates ( dbname ) : dts = datasets . dates ( dbname , table ) return dts def download ( dbname , dts , bbox ) : \"\"\"\"\"\" url = \"\" ftp = FTP ( url ) ftp . login ( '' , '' ) ftp . cwd ( \"\" ) outpath = tempfile . mkdtemp ( ) for dt in [ dts [ ] + timedelta ( t ) for t in range ( ( dts [ ] - dts [ ] ) . days + ) ] : try : ftp . cwd ( \"\" . format ( dt . year , dt . month ) ) filenames = [ f for f in ftp . nlst ( ) if re . match ( r\"\" . format ( dt . strftime ( \"\" ) ) , f ) is not None ] if len ( filenames ) > : fname = filenames [ ] with open ( \"\" . format ( outpath , fname ) , '' ) as f : ftp . retrbinary ( \"\" . format ( fname ) , f . write ) with open ( \"\" . format ( outpath , fname . replace ( \"\" , \"\" ) ) , '' ) as f : ftp . retrbinary ( \"\" . format ( fname . replace ( \"\" , \"\" ) ) , f . write ) tfname = fname . replace ( \"\" , \"\" ) fname = datasets . uncompress ( fname , outpath ) datasets . uncompress ( tfname , outpath ) subprocess . call ( [ \"\" , \"\" , \"\" , \"\" . format ( outpath , fname ) , \"\" . format ( outpath ) ] ) if bbox is not None : subprocess . call ( [ \"\" , \"\" , \"\" , \"\" , \"\" . format ( bbox [ ] ) , \"\" . format ( bbox [ ] ) , \"\" . format ( bbox [ ] ) , \"\" . format ( bbox [ ] ) , \"\" . format ( outpath ) , \"\" . format ( outpath ) ] ) else : subprocess . call ( [ \"\" , \"\" , \"\" , \"\" . format ( outpath ) , \"\" . format ( outpath ) ] ) ", "answer": "cmd = \"\" . join ( [ \"\" , \"\" , \"\" . format ( outpath ) , \"\" . format ( outpath ) , \"\" ] )"}, {"prompt": " from __future__ import print_function import re from collections import defaultdict import os import sys sys . path . insert ( , os . path . join ( os . path . dirname ( __file__ ) , '' ) ) from zerver . lib . user_agent import parse_user_agent user_agents_parsed = defaultdict ( int ) user_agents_path = os . path . join ( os . path . dirname ( __file__ ) , \"\" ) parse_errors = for line in open ( user_agents_path ) . readlines ( ) : line = line . strip ( ) match = re . match ( '' , line ) if match is None : print ( line ) continue groupdict = match . groupdict ( ) count = groupdict [ \"\" ] user_agent = groupdict [ \"\" ] ", "answer": "ret = parse_user_agent ( user_agent )"}, {"prompt": " \"\"\"\"\"\" from oslo_log import log as logging from ironic . common import fsm LOG = logging . getLogger ( __name__ ) ", "answer": "VERBS = {"}, {"prompt": " \"\"\"\"\"\" try : any except NameError : from genshi . util import any import re from genshi . core import Attrs , QName , stripentities from genshi . core import END , START , TEXT , COMMENT __all__ = [ '' , '' ] __docformat__ = '' class HTMLFormFiller ( object ) : \"\"\"\"\"\" def __init__ ( self , name = None , id = None , data = None , passwords = False ) : \"\"\"\"\"\" self . name = name self . id = id if data is None : data = { } self . data = data self . passwords = passwords def __call__ ( self , stream ) : \"\"\"\"\"\" in_form = in_select = in_option = in_textarea = False select_value = option_value = textarea_value = None option_start = None option_text = [ ] no_option_value = False for kind , data , pos in stream : if kind is START : tag , attrs = data tagname = tag . localname if tagname == '' and ( self . name and attrs . get ( '' ) == self . name or self . id and attrs . get ( '' ) == self . id or not ( self . id or self . name ) ) : in_form = True elif in_form : if tagname == '' : type = attrs . get ( '' , '' ) . lower ( ) if type in ( '' , '' ) : name = attrs . get ( '' ) if name and name in self . data : value = self . data [ name ] declval = attrs . get ( '' ) checked = False if isinstance ( value , ( list , tuple ) ) : if declval is not None : checked = declval in [ str ( v ) for v in value ] else : checked = any ( value ) else : if declval is not None : checked = declval == str ( value ) elif type == '' : checked = bool ( value ) if checked : attrs |= [ ( QName ( '' ) , '' ) ] elif '' in attrs : attrs -= '' elif type in ( '' , '' , '' ) or type == '' and self . passwords : name = attrs . get ( '' ) if name and name in self . data : value = self . data [ name ] if isinstance ( value , ( list , tuple ) ) : value = value [ ] if value is not None : attrs |= [ ( QName ( '' ) , str ( value ) ) ] elif tagname == '' : name = attrs . get ( '' ) if name in self . data : select_value = self . data [ name ] in_select = True elif tagname == '' : name = attrs . get ( '' ) if name in self . data : textarea_value = self . data . get ( name ) if isinstance ( textarea_value , ( list , tuple ) ) : textarea_value = textarea_value [ ] in_textarea = True elif in_select and tagname == '' : option_start = kind , data , pos option_value = attrs . get ( '' ) if option_value is None : no_option_value = True option_value = '' in_option = True continue yield kind , ( tag , attrs ) , pos elif in_form and kind is TEXT : if in_select and in_option : if no_option_value : option_value += data option_text . append ( ( kind , data , pos ) ) continue elif in_textarea : continue yield kind , data , pos elif in_form and kind is END : tagname = data . localname if tagname == '' : in_form = False elif tagname == '' : in_select = False select_value = None elif in_select and tagname == '' : if isinstance ( select_value , ( tuple , list ) ) : selected = option_value in [ str ( v ) for v in select_value ] else : selected = option_value == str ( select_value ) okind , ( tag , attrs ) , opos = option_start if selected : attrs |= [ ( QName ( '' ) , '' ) ] elif '' in attrs : attrs -= '' yield okind , ( tag , attrs ) , opos if option_text : for event in option_text : yield event in_option = False no_option_value = False option_start = option_value = None option_text = [ ] elif in_textarea and tagname == '' : if textarea_value : yield TEXT , str ( textarea_value ) , pos textarea_value = None in_textarea = False yield kind , data , pos else : yield kind , data , pos class HTMLSanitizer ( object ) : \"\"\"\"\"\" SAFE_TAGS = frozenset ( [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ] ) SAFE_ATTRS = frozenset ( [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' ] ) SAFE_CSS = frozenset ( [ '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , '' , ] ) SAFE_SCHEMES = frozenset ( [ '' , '' , '' , '' , '' , None ] ) URI_ATTRS = frozenset ( [ '' , '' , '' , '' , '' , '' ] ) def __init__ ( self , safe_tags = SAFE_TAGS , safe_attrs = SAFE_ATTRS , safe_schemes = SAFE_SCHEMES , uri_attrs = URI_ATTRS , safe_css = SAFE_CSS ) : \"\"\"\"\"\" self . safe_tags = safe_tags self . safe_attrs = safe_attrs self . safe_css = safe_css self . uri_attrs = uri_attrs self . safe_schemes = safe_schemes _EXPRESSION_SEARCH = re . compile ( \"\"\"\"\"\" , re . VERBOSE ) . search _URL_FINDITER = re . compile ( '' ) . finditer def __call__ ( self , stream ) : \"\"\"\"\"\" waiting_for = None for kind , data , pos in stream : if kind is START : if waiting_for : continue tag , attrs = data if not self . is_safe_elem ( tag , attrs ) : waiting_for = tag continue new_attrs = [ ] for attr , value in attrs : value = stripentities ( value ) if attr not in self . safe_attrs : continue elif attr in self . uri_attrs : if not self . is_safe_uri ( value ) : continue elif attr == '' : decls = self . sanitize_css ( value ) if not decls : continue value = '' . join ( decls ) new_attrs . append ( ( attr , value ) ) yield kind , ( tag , Attrs ( new_attrs ) ) , pos elif kind is END : tag = data if waiting_for : if waiting_for == tag : waiting_for = None else : yield kind , data , pos elif kind is not COMMENT : if not waiting_for : yield kind , data , pos def is_safe_css ( self , propname , value ) : \"\"\"\"\"\" if propname not in self . safe_css : return False if propname . startswith ( '' ) and '' in value : return False return True def is_safe_elem ( self , tag , attrs ) : \"\"\"\"\"\" if tag not in self . safe_tags : return False if tag . localname == '' : input_type = attrs . get ( '' , '' ) . lower ( ) if input_type == '' : return False return True def is_safe_uri ( self , uri ) : \"\"\"\"\"\" if '' in uri : uri = uri . split ( '' , ) [ ] if '' not in uri : return True chars = [ char for char in uri . split ( '' , ) [ ] if char . isalnum ( ) ] return '' . join ( chars ) . lower ( ) in self . safe_schemes def sanitize_css ( self , text ) : \"\"\"\"\"\" decls = [ ] text = self . _strip_css_comments ( self . _replace_unicode_escapes ( text ) ) for decl in text . split ( '' ) : decl = decl . strip ( ) if not decl : continue try : propname , value = decl . split ( '' , ) except ValueError : continue if not self . is_safe_css ( propname . strip ( ) . lower ( ) , value . strip ( ) ) : continue is_evil = False if self . _EXPRESSION_SEARCH ( value ) : is_evil = True for match in self . _URL_FINDITER ( value ) : if not self . is_safe_uri ( match . group ( ) ) : is_evil = True break if not is_evil : decls . append ( decl . strip ( ) ) return decls _NORMALIZE_NEWLINES = re . compile ( r'' ) . sub _UNICODE_ESCAPE = re . compile ( r\"\"\"\"\"\" , re . UNICODE ) . sub def _replace_unicode_escapes ( self , text ) : def _repl ( match ) : t = match . group ( ) if t : ", "answer": "return chr ( int ( t , ) )"}, {"prompt": " \"\"\"\"\"\" import fnmatch import itertools import re class Handler ( object ) : \"\"\"\"\"\" ALL_PROPERTIES = [ '' , '' , '' , '' , '' , '' ] def __init__ ( self , pattern ) : self . pattern = pattern def _GetPattern ( self ) : return self . _pattern def _SetPattern ( self , the_pattern ) : self . _pattern = the_pattern self . _regex = re . compile ( re . escape ( the_pattern ) . replace ( '' , '' ) + '' ) self . is_literal = '' not in the_pattern pattern = property ( _GetPattern , _SetPattern ) @ property def regex ( self ) : return self . _regex def Regexify ( self ) : \"\"\"\"\"\" return self . pattern . replace ( '' , '' ) . replace ( '' , '' ) ", "answer": "def MatchesString ( self , pattern_str ) :"}, {"prompt": " from __future__ import division , print_function , absolute_import __usage__ = \"\"\"\"\"\" from numpy . testing import ( TestCase , assert_equal , assert_almost_equal , assert_array_almost_equal , run_module_suite ) from scipy . fftpack import ( diff , fft , ifft , tilbert , itilbert , hilbert , ihilbert , shift , fftfreq , cs_diff , sc_diff , ss_diff , cc_diff ) import numpy as np from numpy import arange , sin , cos , pi , exp , tanh , sum , sign from numpy . random import random def direct_diff ( x , k = , period = None ) : fx = fft ( x ) n = len ( fx ) if period is None : period = * pi w = fftfreq ( n ) * * pi / period * n if k < : w = / w ** k w [ ] = else : w = w ** k if n > : w [ : n - ] = return ifft ( w * fx ) . real def direct_tilbert ( x , h = , period = None ) : fx = fft ( x ) n = len ( fx ) if period is None : period = * pi w = fftfreq ( n ) * h * * pi / period * n w [ ] = w = / tanh ( w ) w [ ] = return ifft ( w * fx ) def direct_itilbert ( x , h = , period = None ) : fx = fft ( x ) n = len ( fx ) if period is None : period = * pi w = fftfreq ( n ) * h * * pi / period * n w = - * tanh ( w ) return ifft ( w * fx ) def direct_hilbert ( x ) : fx = fft ( x ) n = len ( fx ) w = fftfreq ( n ) * n w = * sign ( w ) return ifft ( w * fx ) def direct_ihilbert ( x ) : return - direct_hilbert ( x ) def direct_shift ( x , a , period = None ) : n = len ( x ) if period is None : k = fftfreq ( n ) * * n else : k = fftfreq ( n ) * * pi / period * n return ifft ( fft ( x ) * exp ( k * a ) ) . real class TestDiff ( TestCase ) : def test_definition ( self ) : for n in [ , , , , ] : x = arange ( n ) * * pi / n assert_array_almost_equal ( diff ( sin ( x ) ) , direct_diff ( sin ( x ) ) ) assert_array_almost_equal ( diff ( sin ( x ) , ) , direct_diff ( sin ( x ) , ) ) assert_array_almost_equal ( diff ( sin ( x ) , ) , direct_diff ( sin ( x ) , ) ) assert_array_almost_equal ( diff ( sin ( x ) , ) , direct_diff ( sin ( x ) , ) ) assert_array_almost_equal ( diff ( sin ( x ) , ) , direct_diff ( sin ( x ) , ) ) assert_array_almost_equal ( diff ( sin ( * x ) , ) , direct_diff ( sin ( * x ) , ) ) assert_array_almost_equal ( diff ( sin ( * x ) , ) , direct_diff ( sin ( * x ) , ) ) assert_array_almost_equal ( diff ( cos ( x ) ) , direct_diff ( cos ( x ) ) ) assert_array_almost_equal ( diff ( cos ( x ) , ) , direct_diff ( cos ( x ) , ) ) assert_array_almost_equal ( diff ( cos ( x ) , ) , direct_diff ( cos ( x ) , ) ) assert_array_almost_equal ( diff ( cos ( x ) , ) , direct_diff ( cos ( x ) , ) ) assert_array_almost_equal ( diff ( cos ( * x ) ) , direct_diff ( cos ( * x ) ) ) assert_array_almost_equal ( diff ( sin ( x * n / ) ) , direct_diff ( sin ( x * n / ) ) ) assert_array_almost_equal ( diff ( cos ( x * n / ) ) , direct_diff ( cos ( x * n / ) ) ) for k in range ( ) : assert_array_almost_equal ( diff ( sin ( * x ) , k ) , direct_diff ( sin ( * x ) , k ) ) assert_array_almost_equal ( diff ( cos ( * x ) , k ) , direct_diff ( cos ( * x ) , k ) ) def test_period ( self ) : for n in [ , ] : x = arange ( n ) / float ( n ) assert_array_almost_equal ( diff ( sin ( * pi * x ) , period = ) , * pi * cos ( * pi * x ) ) assert_array_almost_equal ( diff ( sin ( * pi * x ) , , period = ) , - ( * pi ) ** * cos ( * pi * x ) ) def test_sin ( self ) : for n in [ , , ] : x = arange ( n ) * * pi / n assert_array_almost_equal ( diff ( sin ( x ) ) , cos ( x ) ) assert_array_almost_equal ( diff ( cos ( x ) ) , - sin ( x ) ) assert_array_almost_equal ( diff ( sin ( x ) , ) , - sin ( x ) ) assert_array_almost_equal ( diff ( sin ( x ) , ) , sin ( x ) ) assert_array_almost_equal ( diff ( sin ( * x ) ) , * cos ( * x ) ) assert_array_almost_equal ( diff ( sin ( sin ( x ) ) ) , cos ( x ) * cos ( sin ( x ) ) ) def test_expr ( self ) : for n in [ , , , , , , , , , ] [ : ] : x = arange ( n ) * * pi / n f = sin ( x ) * cos ( * x ) + exp ( sin ( * x ) ) df = cos ( x ) * cos ( * x ) - * sin ( x ) * sin ( * x ) + * cos ( * x ) * exp ( sin ( * x ) ) ddf = - * sin ( x ) * cos ( * x ) - * cos ( x ) * sin ( * x ) - * sin ( * x ) * exp ( sin ( * x ) ) + * cos ( * x ) ** * exp ( sin ( * x ) ) d1 = diff ( f ) assert_array_almost_equal ( d1 , df ) assert_array_almost_equal ( diff ( df ) , ddf ) assert_array_almost_equal ( diff ( f , ) , ddf ) assert_array_almost_equal ( diff ( ddf , - ) , df ) def test_expr_large ( self ) : for n in [ , ] : x = arange ( n ) * * pi / n f = sin ( x ) * cos ( * x ) + exp ( sin ( * x ) ) df = cos ( x ) * cos ( * x ) - * sin ( x ) * sin ( * x ) + * cos ( * x ) * exp ( sin ( * x ) ) ddf = - * sin ( x ) * cos ( * x ) - * cos ( x ) * sin ( * x ) - * sin ( * x ) * exp ( sin ( * x ) ) + * cos ( * x ) ** * exp ( sin ( * x ) ) assert_array_almost_equal ( diff ( f ) , df ) assert_array_almost_equal ( diff ( df ) , ddf ) assert_array_almost_equal ( diff ( ddf , - ) , df ) assert_array_almost_equal ( diff ( f , ) , ddf ) def test_int ( self ) : n = x = arange ( n ) * * pi / n assert_array_almost_equal ( diff ( sin ( x ) , - ) , - cos ( x ) ) assert_array_almost_equal ( diff ( sin ( x ) , - ) , - sin ( x ) ) assert_array_almost_equal ( diff ( sin ( x ) , - ) , sin ( x ) ) assert_array_almost_equal ( diff ( * cos ( * x ) , - ) , sin ( * x ) ) def test_random_even ( self ) : for k in [ , , , ] : for n in [ , , , , ] : f = random ( ( n , ) ) af = sum ( f , axis = ) / n f = f - af f = diff ( diff ( f , ) , - ) assert_almost_equal ( sum ( f , axis = ) , ) assert_array_almost_equal ( diff ( diff ( f , k ) , - k ) , f ) assert_array_almost_equal ( diff ( diff ( f , - k ) , k ) , f ) def test_random_odd ( self ) : for k in [ , , , , , , ] : for n in [ , , ] : f = random ( ( n , ) ) af = sum ( f , axis = ) / n f = f - af assert_almost_equal ( sum ( f , axis = ) , ) assert_array_almost_equal ( diff ( diff ( f , k ) , - k ) , f ) assert_array_almost_equal ( diff ( diff ( f , - k ) , k ) , f ) def test_zero_nyquist ( self ) : for k in [ , , , , , , ] : for n in [ , , , , ] : f = random ( ( n , ) ) af = sum ( f , axis = ) / n f = f - af f = diff ( diff ( f , ) , - ) assert_almost_equal ( sum ( f , axis = ) , ) assert_array_almost_equal ( diff ( diff ( f , k ) , - k ) , f ) assert_array_almost_equal ( diff ( diff ( f , - k ) , k ) , f ) class TestTilbert ( TestCase ) : def test_definition ( self ) : for h in [ , , , , ] : for n in [ , , , ] : x = arange ( n ) * * pi / n y = tilbert ( sin ( x ) , h ) y1 = direct_tilbert ( sin ( x ) , h ) assert_array_almost_equal ( y , y1 ) assert_array_almost_equal ( tilbert ( sin ( x ) , h ) , direct_tilbert ( sin ( x ) , h ) ) assert_array_almost_equal ( tilbert ( sin ( * x ) , h ) , direct_tilbert ( sin ( * x ) , h ) ) def test_random_even ( self ) : for h in [ , , , , ] : for n in [ , , ] : f = random ( ( n , ) ) af = sum ( f , axis = ) / n f = f - af assert_almost_equal ( sum ( f , axis = ) , ) assert_array_almost_equal ( direct_tilbert ( direct_itilbert ( f , h ) , h ) , f ) def test_random_odd ( self ) : for h in [ , , , , ] : for n in [ , , ] : f = random ( ( n , ) ) af = sum ( f , axis = ) / n f = f - af assert_almost_equal ( sum ( f , axis = ) , ) assert_array_almost_equal ( itilbert ( tilbert ( f , h ) , h ) , f ) assert_array_almost_equal ( tilbert ( itilbert ( f , h ) , h ) , f ) class TestITilbert ( TestCase ) : def test_definition ( self ) : for h in [ , , , , ] : for n in [ , , , ] : x = arange ( n ) * * pi / n y = itilbert ( sin ( x ) , h ) ", "answer": "y1 = direct_itilbert ( sin ( x ) , h )"}, {"prompt": " from __future__ import division , print_function , absolute_import import numpy as np from numpy . testing import assert_ , assert_equal , assert_array_almost_equal from scipy . special import lambertw from numpy import nan , inf , pi , e , isnan , log , r_ , array , complex_ from scipy . special . _testutils import FuncData def test_values ( ) : assert_ ( isnan ( lambertw ( nan ) ) ) assert_equal ( lambertw ( inf , ) . real , inf ) assert_equal ( lambertw ( inf , ) . imag , * pi ) assert_equal ( lambertw ( - inf , ) . real , inf ) assert_equal ( lambertw ( - inf , ) . imag , * pi ) assert_equal ( lambertw ( ) , lambertw ( , ) ) data = [ ( , , ) , ( + , , ) , ( inf , , inf ) , ( , - , - inf ) , ( , , - inf ) , ( , , - inf ) , ( e , , ) , ( , , ) , ( - pi / , , * pi / ) , ( - log ( ) / , , - log ( ) ) , ( , , ) , ( - , , - ) , ( - / , , - ) , ( - , - , - ) , ( , - , - - ) , ( - , - , - ) , ( , , - + ) , ( - , , - + ) , ( - , , + ) , ( - , , - + ) , ( - , - , - ) , ( , , ) , ( , , + ) , ( , - , - ) , ( , , + ) , ( + , , + ) , ( - + , , - + ) , ( + , , - + ) , ( + , - , - ) , ", "answer": "( - , - , - - ) ,"}, {"prompt": " from . client import UberClient , UberException , UberLocationNotFound from . models import * ", "answer": "from . geolocation import geolocate , GeolocationExcetion "}, {"prompt": " '''''' from grovepi import * from grove_oled import * dht_sensor_port = oled_init ( ) oled_clearDisplay ( ) oled_setNormalDisplay ( ) oled_setVerticalMode ( ) time . sleep ( ) while True : try : [ temp , hum ] = dht ( dht_sensor_port , ) print ( \"\" , temp , \"\" , hum , \"\" ) t = str ( temp ) h = str ( hum ) oled_setTextXY ( , ) oled_putString ( \"\" ) ", "answer": "oled_setTextXY ( , )"}, {"prompt": " from django . contrib . auth . models import User from django . http import HttpRequest from django . test import TestCase from tastypie . api import Api from tastypie . exceptions import NotRegistered , BadRequest from tastypie . resources import Resource , ModelResource from core . models import Note class NoteResource ( ModelResource ) : class Meta : resource_name = '' queryset = Note . objects . filter ( is_active = True ) class UserResource ( ModelResource ) : class Meta : resource_name = '' queryset = User . objects . all ( ) class ApiTestCase ( TestCase ) : urls = '' def test_register ( self ) : api = Api ( ) self . assertEqual ( len ( api . _registry ) , ) api . register ( NoteResource ( ) ) self . assertEqual ( len ( api . _registry ) , ) self . assertEqual ( sorted ( api . _registry . keys ( ) ) , [ '' ] ) api . register ( UserResource ( ) ) self . assertEqual ( len ( api . _registry ) , ) self . assertEqual ( sorted ( api . _registry . keys ( ) ) , [ '' , '' ] ) api . register ( UserResource ( ) ) self . assertEqual ( len ( api . _registry ) , ) self . assertEqual ( sorted ( api . _registry . keys ( ) ) , [ '' , '' ] ) self . assertEqual ( len ( api . _canonicals ) , ) api . register ( UserResource ( ) , canonical = False ) self . assertEqual ( len ( api . _registry ) , ) self . assertEqual ( sorted ( api . _registry . keys ( ) ) , [ '' , '' ] ) self . assertEqual ( len ( api . _canonicals ) , ) def test_global_registry ( self ) : api = Api ( ) ", "answer": "self . assertEqual ( len ( api . _registry ) , )"}, {"prompt": " from tests . config import * from nsxramlclient . client import NsxClient __author__ = '' def configure_nat ( session , edgeid = '' , oadd = '' , tadd = '' , oport = , tport = ) : nat_spec = session . extract_resource_body_schema ( '' , '' ) nat_spec [ '' ] [ '' ] [ '' ] [ '' ] = nat_spec [ '' ] [ '' ] [ '' ] [ '' ] = '' nat_spec [ '' ] [ '' ] [ '' ] [ '' ] = nat_spec [ '' ] [ '' ] [ '' ] [ '' ] = oadd nat_spec [ '' ] [ '' ] [ '' ] [ '' ] = tadd nat_spec [ '' ] [ '' ] [ '' ] [ '' ] = '' nat_spec [ '' ] [ '' ] [ '' ] [ '' ] = '' nat_spec [ '' ] [ '' ] [ '' ] [ '' ] = '' nat_spec [ '' ] [ '' ] [ '' ] [ '' ] = '' nat_spec [ '' ] [ '' ] [ '' ] [ '' ] = oport nat_spec [ '' ] [ '' ] [ '' ] [ '' ] = tport create_response = session . update ( '' , uri_parameters = { '' : edgeid } , request_body_dict = nat_spec ) session . view_response ( create_response ) def append_nat ( session , edgeid = '' , oadd = '' , tadd = '' , oport = , tport = ) : nat_spec = session . extract_resource_body_schema ( '' , '' ) nat_spec [ '' ] [ '' ] [ '' ] = '' nat_spec [ '' ] [ '' ] [ '' ] = nat_spec [ '' ] [ '' ] [ '' ] = oadd nat_spec [ '' ] [ '' ] [ '' ] = tadd nat_spec [ '' ] [ '' ] [ '' ] = '' nat_spec [ '' ] [ '' ] [ '' ] = '' nat_spec [ '' ] [ '' ] [ '' ] = '' nat_spec [ '' ] [ '' ] [ '' ] = '' nat_spec [ '' ] [ '' ] [ '' ] = oport nat_spec [ '' ] [ '' ] [ '' ] = tport create_response = session . create ( '' , uri_parameters = { '' : edgeid } , request_body_dict = nat_spec ) session . view_response ( create_response ) def update_nat ( session , rule_id , edgeid = '' , oadd = '' , tadd = '' , oport = , tport = ) : nat_spec = session . extract_resource_body_schema ( '' , '' ) nat_spec [ '' ] [ '' ] = '' ", "answer": "nat_spec [ '' ] [ '' ] = "}, {"prompt": " from pyswagger import SwaggerApp , SwaggerSecurity from . . utils import get_test_data_folder import unittest app = SwaggerApp . _create_ ( get_test_data_folder ( version = '' , which = '' ) ) class BasicAuthAndApiKeyTestCase ( unittest . TestCase ) : \"\"\"\"\"\" def setUp ( self ) : self . s = SwaggerSecurity ( app ) self . s . update_with ( '' , '' ) self . s . update_with ( '' , ( '' , '' ) ) self . s . update_with ( '' , ( '' , '' ) ) self . s . update_with ( '' , '' ) def test_deleteUser ( self ) : \"\"\"\"\"\" req , _ = app . op [ '' ] ( username = '' ) self . s ( req ) . prepare ( ) self . assertTrue ( '' in req . header ) self . assertEqual ( req . header [ '' ] , '' ) def test_getUserByName ( self ) : \"\"\"\"\"\" ", "answer": "req , _ = app . op [ '' ] ( username = '' )"}, {"prompt": " from setuptools import setup , find_packages setup ( name = '' , ", "answer": "version = '' ,"}, {"prompt": " from muntjac . demo . sampler . features . dragndrop . DragDropHtml5FromDesktop import DragDropHtml5FromDesktop from muntjac . demo . sampler . features . dragndrop . DragDropTableTree import DragDropTableTree from muntjac . demo . sampler . features . dragndrop . DragDropServerValidation import DragDropServerValidation from muntjac . ui . tree import Tree from muntjac . event . dd . drop_handler import IDropHandler from muntjac . demo . sampler . features . dragndrop . DragDropRearrangeComponents import DragDropRearrangeComponents from muntjac . demo . sampler . APIResource import APIResource from muntjac . demo . sampler . Feature import Feature , Version class DragDropTreeSorting ( Feature ) : def getSinceVersion ( self ) : return Version . V63 def getName ( self ) : return '' def getDescription ( self ) : return ( '' '' '' '' ) def getRelatedAPI ( self ) : return [ APIResource ( Tree ) , APIResource ( IDropHandler ) ] def getRelatedFeatures ( self ) : return [ DragDropTableTree , DragDropServerValidation , DragDropRearrangeComponents , DragDropHtml5FromDesktop ] ", "answer": "def getRelatedResources ( self ) :"}, {"prompt": " from __future__ import absolute_import from willow . image import ( Image , JPEGImageFile , PNGImageFile , GIFImageFile , BMPImageFile , RGBImageBuffer , RGBAImageBuffer , ) def _PIL_Image ( ) : import PIL . Image return PIL . Image class PillowImage ( Image ) : def __init__ ( self , image ) : self . image = image @ classmethod def check ( cls ) : _PIL_Image ( ) @ Image . operation def get_size ( self ) : return self . image . size @ Image . operation def has_alpha ( self ) : img = self . image return img . mode in ( '' , '' ) or ( img . mode == '' and '' in img . info ) @ Image . operation def has_animation ( self ) : return False @ Image . operation def resize ( self , size ) : if self . image . mode in [ '' , '' ] : if self . has_alpha ( ) : image = self . image . convert ( '' ) else : image = self . image . convert ( '' ) else : image = self . image return PillowImage ( image . resize ( size , _PIL_Image ( ) . ANTIALIAS ) ) @ Image . operation def crop ( self , rect ) : return PillowImage ( self . image . crop ( rect ) ) @ Image . operation def save_as_jpeg ( self , f , quality = ) : if self . image . mode in [ '' , '' ] : image = self . image . convert ( '' ) else : image = self . image image . save ( f , '' , quality = quality ) return JPEGImageFile ( f ) @ Image . operation def save_as_png ( self , f ) : self . image . save ( f , '' ) return PNGImageFile ( f ) @ Image . operation def save_as_gif ( self , f ) : image = self . image if image . mode not in [ '' , '' ] : image = image . convert ( '' , palette = _PIL_Image ( ) . ADAPTIVE ) if '' in image . info : image . save ( f , '' , transparency = image . info [ '' ] ) else : image . save ( f , '' ) return GIFImageFile ( f ) @ Image . operation def auto_orient ( self ) : image = self . image if hasattr ( image , '' ) : try : exif = image . _getexif ( ) except Exception : exif = None if exif is not None : orientation = exif . get ( , ) if <= orientation <= : Image = _PIL_Image ( ) ORIENTATION_TO_TRANSPOSE = { : ( ) , : ( Image . FLIP_LEFT_RIGHT , ) , : ( Image . ROTATE_180 , ) , : ( Image . ROTATE_180 , Image . FLIP_LEFT_RIGHT ) , : ( Image . ROTATE_270 , Image . FLIP_LEFT_RIGHT ) , : ( Image . ROTATE_270 , ) , : ( Image . ROTATE_90 , Image . FLIP_LEFT_RIGHT ) , : ( Image . ROTATE_90 , ) , } for transpose in ORIENTATION_TO_TRANSPOSE [ orientation ] : image = image . transpose ( transpose ) return PillowImage ( image ) @ Image . operation def get_pillow_image ( self ) : return self . image @ classmethod @ Image . converter_from ( JPEGImageFile ) @ Image . converter_from ( PNGImageFile ) @ Image . converter_from ( GIFImageFile , cost = ) @ Image . converter_from ( BMPImageFile ) def open ( cls , image_file ) : ", "answer": "image_file . f . seek ( )"}, {"prompt": " class Listener ( object ) : ", "answer": "def close ( self ) :"}]