text
stringlengths
29
91.9k
<s> from __future__ import absolute_import <EOL> import weakref <EOL> import operator <EOL> from . compat import threading , itertools_filterfalse <EOL> from . import py2k <EOL> import types <EOL> EMPTY_SET = frozenset ( ) <EOL> class KeyedTuple ( tuple ) : <EOL> def __new__ ( cls , vals , labels = None ) : <EOL> t = tuple . __new__ ( cls , vals ) <EOL> t . _labels = [ ] <EOL> if labels : <EOL> t . __dict__ . update ( zip ( labels , vals ) ) <EOL> t . _labels = labels <EOL> return t <EOL> def keys ( self ) : <EOL> return [ l for l in self . _labels if l is not None ] <EOL> @ property <EOL> def _fields ( self ) : <EOL> return tuple ( self . keys ( ) ) <EOL> def _asdict ( self ) : <EOL> return dict ( ( key , self . __dict__ [ key ] ) for key in self . keys ( ) ) <EOL> class ImmutableContainer ( object ) : <EOL> def _immutable ( self , * arg , ** kw ) : <EOL> raise TypeError ( "" % self . __class__ . __name__ ) <EOL> __delitem__ = __setitem__ = __setattr__ = _immutable <EOL> class immutabledict ( ImmutableContainer , dict ) : <EOL> clear = pop = popitem = setdefault = update = ImmutableContainer . _immutable <EOL> def __new__ ( cls , * args ) : <EOL> new = dict . __new__ ( cls ) <EOL> dict . __init__ ( new , * args ) <EOL> return new <EOL> def __init__ ( self , * args ) : <EOL> pass <EOL> def __reduce__ ( self ) : <EOL> return immutabledict , ( dict ( self ) , ) <EOL> def union ( self , d ) : <EOL> if not self : <EOL> return immutabledict ( d ) <EOL> else : <EOL> d2 = immutabledict ( self ) <EOL> dict . update ( d2 , d ) <EOL> return d2 <EOL> def __repr__ ( self ) : <EOL> return "" % dict . __repr__ ( self ) <EOL> class Properties ( object ) : <EOL> def __init__ ( self , data ) : <EOL> self . __dict__ [ '_data' ] = data <EOL> def __len__ ( self ) : <EOL> return len ( self . _data ) <EOL> def __iter__ ( self ) : <EOL> return iter ( list ( self . _data . values ( ) ) ) <EOL> def __add__ ( self , other ) : <EOL> return list ( self ) + list ( other ) <EOL> def __setitem__ ( self , key , object ) : <EOL> self . _data [ key ] = object <EOL> def __getitem__ ( self , key ) : <EOL> return self . _data [ key ] <EOL> def __delitem__ ( self , key ) : <EOL> del self . _data [ key ] <EOL> def __setattr__ ( self , key , object ) : <EOL> self . _data [ key ] = object <EOL> def __getstate__ ( self ) : <EOL> return { '_data' : self . __dict__ [ '_data' ] } <EOL> def __setstate__ ( self , state ) : <EOL> self . __dict__ [ '_data' ] = state [ '_data' ] <EOL> def __getattr__ ( self , key ) : <EOL> try : <EOL> return self . _data [ key ] <EOL> except KeyError : <EOL> raise AttributeError ( key ) <EOL> def __contains__ ( self , key ) : <EOL> return key in self . _data <EOL> def as_immutable ( self ) : <EOL> return ImmutableProperties ( self . _data ) <EOL> def update ( self , value ) : <EOL> self . _data . update ( value ) <EOL> def get ( self , key , default = None ) : <EOL> if key in self : <EOL> return self [ key ] <EOL> else : <EOL> return default <EOL> def keys ( self ) : <EOL> return list ( self . _data ) <EOL> def values ( self ) : <EOL> return list ( self . _data . values ( ) ) <EOL> def items ( self ) : <EOL> return list ( self . _data . items ( ) ) <EOL> def has_key ( self , key ) : <EOL> return key in self . _data <EOL> def clear ( self ) : <EOL> self . _data . clear ( ) <EOL> class OrderedProperties ( Properties ) : <EOL> def __init__ ( self ) : <EOL> Properties . __init__ ( self , OrderedDict ( ) ) <EOL> class ImmutableProperties ( ImmutableContainer , Properties ) : <EOL> class OrderedDict ( dict ) : <EOL> def __init__ ( self , ____sequence = None , ** kwargs ) : <EOL> self . _list = [ ] <EOL> if ____sequence is None : <EOL> if kwargs : <EOL> self . update ( ** kwargs ) <EOL> else : <EOL> self . update ( ____sequence , ** kwargs ) <EOL> def clear ( self ) : <EOL> self . _list = [ ] <EOL> dict . clear ( self ) <EOL> def copy ( self ) : <EOL> return self . __copy__ ( ) <EOL> def __copy__ ( self ) : <EOL> return OrderedDict ( self ) <EOL> def sort ( self , * arg , ** kw ) : <EOL> self . _list . sort ( * arg , ** kw ) <EOL> def update ( self , ____sequence = None , ** kwargs ) : <EOL> if ____sequence is not None : <EOL> if hasattr ( ____sequence , 'keys' ) : <EOL> for key in ____sequence . keys ( ) : <EOL> self . __setitem__ ( key , ____sequence [ key ] ) <EOL> else : <EOL> for key , value in ____sequence : <EOL> self [ key ] = value <EOL> if kwargs : <EOL> self . update ( kwargs ) <EOL> def setdefault ( self , key , value ) : <EOL> if key not in self : <EOL> self . __setitem__ ( key , value ) <EOL> return value <EOL> else : <EOL> return self . __getitem__ ( key ) <EOL> def __iter__ ( self ) : <EOL> return iter ( self . _list ) <EOL> def keys ( self ) : <EOL> return list ( self ) <EOL> def values ( self ) : <EOL> return [ self [ key ] for key in self . _list ] <EOL> def items ( self ) : <EOL> return [ ( key , self [ key ] ) for key in self . _list ] <EOL> if py2k : <EOL> def itervalues ( self ) : <EOL> return iter ( self . values ( ) ) <EOL> def iterkeys ( self ) : <EOL> return iter ( self ) <EOL> def iteritems ( self ) : <EOL> return iter ( self . items ( ) ) <EOL> def __setitem__ ( self , key , object ) : <EOL> if key not in self : <EOL> try : <EOL> self . _list . append ( key ) <EOL> except AttributeError : <EOL> self . _list = [ key ] <EOL> dict . __setitem__ ( self , key , object ) <EOL> def __delitem__ ( self , key ) : <EOL> dict . __delitem__ ( self , key ) <EOL> self . _list . remove ( key ) <EOL> def pop ( self , key , * default ) : <EOL> present = key in self <EOL> value = dict . pop ( self , key , * default ) <EOL> if present : <EOL> self . _list . remove ( key ) <EOL> return value <EOL> def popitem ( self ) : <EOL> item = dict . popitem ( self ) <EOL> self . _list . remove ( item [ 0 ] ) <EOL> return item <EOL> class OrderedSet ( set ) : <EOL> def __init__ ( self , d = None ) : <EOL> set . __init__ ( self ) <EOL> self . _list = [ ] <EOL> if d is not None : <EOL>
<s> import diamond . collector <EOL> import os <EOL> import time <EOL> from diamond . collector import str_to_bool <EOL> try : <EOL> import psutil <EOL> except ImportError : <EOL> psutil = None <EOL> class CPUCollector ( diamond . collector . Collector ) : <EOL> PROC = '/proc/stat' <EOL> INTERVAL = 1 <EOL> MAX_VALUES = { <EOL> 'user' : diamond . collector . MAX_COUNTER , <EOL> 'nice' : diamond . collector . MAX_COUNTER , <EOL> 'system' : diamond . collector . MAX_COUNTER , <EOL> 'idle' : diamond . collector . MAX_COUNTER , <EOL> 'iowait' : diamond . collector . MAX_COUNTER , <EOL> 'irq' : diamond . collector . MAX_COUNTER , <EOL> 'softirq' : diamond . collector . MAX_COUNTER , <EOL> 'steal' : diamond . collector . MAX_COUNTER , <EOL> 'guest' : diamond . collector . MAX_COUNTER , <EOL> 'guest_nice' : diamond . collector . MAX_COUNTER , <EOL> } <EOL> def get_default_config_help ( self ) : <EOL> config_help = super ( CPUCollector , self ) . get_default_config_help ( ) <EOL> config_help . update ( { <EOL> 'percore' : '' , <EOL> 'simple' : '' , <EOL> 'normalize' : '' , <EOL> } ) <EOL> return config_help <EOL> def get_default_config ( self ) : <EOL> config = super ( CPUCollector , self ) . get_default_config ( ) <EOL> config . update ( { <EOL> 'path' : 'cpu' , <EOL> 'percore' : 'True' , <EOL> 'xenfix' : None , <EOL> 'simple' : 'False' , <EOL> 'normalize' : 'False' , <EOL> } ) <EOL> return config <EOL> def collect ( self ) : <EOL> def cpu_time_list ( ) : <EOL> statFile = open ( self . PROC , "r" ) <EOL> timeList = statFile . readline ( ) . split ( " " ) [ 2 : 6 ] <EOL> for i in range ( len ( timeList ) ) : <EOL> timeList [ i ] = int ( timeList [ i ] ) <EOL> statFile . close ( ) <EOL> return timeList <EOL> def cpu_delta_time ( interval ) : <EOL> pre_check = cpu_time_list ( ) <EOL> time . sleep ( interval ) <EOL> post_check = cpu_time_list ( ) <EOL> for i in range ( len ( pre_check ) ) : <EOL> post_check [ i ] -= pre_check [ i ] <EOL> return post_check <EOL> if os . access ( self . PROC , os . R_OK ) : <EOL> if str_to_bool ( self . config [ 'simple' ] ) : <EOL> dt = cpu_delta_time ( self . INTERVAL ) <EOL> cpuPct = 100 - ( dt [ len ( dt ) - 1 ] * 100.00 / sum ( dt ) ) <EOL> self . publish ( 'percent' , str ( '%.4f' % cpuPct ) ) <EOL> return True <EOL> results = { } <EOL> file = open ( self . PROC ) <EOL> ncpus = - 1 <EOL> for line in file : <EOL> if not line . startswith ( 'cpu' ) : <EOL> continue <EOL> ncpus += 1 <EOL> elements = line . split ( ) <EOL> cpu = elements [ 0 ] <EOL> if cpu == 'cpu' : <EOL> cpu = 'cpu.total' <EOL> elif not str_to_bool ( self . config [ 'percore' ] ) : <EOL> continue <EOL> results [ cpu ] = { } <EOL> if len ( elements ) >= 2 : <EOL> results [ cpu ] [ 'user' ] = elements [ 1 ] <EOL> if len ( elements ) >= 3 : <EOL> results [ cpu ] [ 'nice' ] = elements [ 2 ] <EOL> if len ( elements ) >= 4 : <EOL> results [ cpu ] [ 'system' ] = elements [ 3 ] <EOL> if len ( elements ) >= 5 : <EOL> results [ cpu ] [ 'idle' ] = elements [ 4 ] <EOL> if len ( elements ) >= 6 : <EOL> results [ cpu ] [ 'iowait' ] = elements [ 5 ] <EOL> if len ( elements ) >= 7 : <EOL> results [ cpu ] [ 'irq' ] = elements [ 6 ] <EOL> if len ( elements ) >= 8 : <EOL> results [ cpu ] [ 'softirq' ] = elements [ 7 ] <EOL> if len ( elements ) >= 9 : <EOL> results [ cpu ] [ 'steal' ] = elements [ 8 ] <EOL> if len ( elements ) >= 10 : <EOL> results [ cpu ] [ 'guest' ] = elements [ 9 ] <EOL> if len ( elements ) >= 11 : <EOL> results [ cpu ] [ 'guest_nice' ] = elements [ 10 ] <EOL> file . close ( ) <EOL> metrics = { } <EOL> for
<s> try : <EOL> from cStringIO import StringIO <EOL> except ImportError : <EOL> from io import StringIO <EOL> class StringIOTree ( object ) : <EOL> def __init__ ( self , stream = None ) : <EOL> self . prepended_children = [ ] <EOL> if stream is None : <EOL> stream = StringIO ( ) <EOL> self . stream = stream <EOL> self . write = stream . write <EOL> self . markers = [ ] <EOL> def getvalue (
<s> import json <EOL> from django . db . models import Q <EOL> from rest_framework import serializers <EOL> from geokey . core . serializers import FieldSelectorSerializer <EOL> from geokey . categories . serializers import CategorySerializer <EOL> from geokey . subsets . serializers import SubsetSerializer <EOL> from geokey . contributions . models import Location <EOL> from . models import Project <EOL> class ProjectSerializer ( FieldSelectorSerializer ) : <EOL> num_locations = serializers . SerializerMethodField ( ) <EOL> categories = serializers . SerializerMethodField ( ) <EOL> contribution_info = serializers . SerializerMethodField ( ) <EOL> user_info = serializers . SerializerMethodField ( ) <EOL> geographic_extent = serializers . SerializerMethodField ( ) <EOL> subsets = serializers . SerializerMethodField ( ) <EOL> class Meta : <EOL> model = Project <EOL> depth = 1 <EOL> fields = ( 'id' , 'name' , 'description' , 'isprivate' , 'islocked' , <EOL> 'status' , 'created_at' , 'categories' , 'subsets' , <EOL> '' , 'user_info' , 'num_locations' , <EOL> '' ) <EOL> read_only_fields = ( 'id' , 'name' ) <EOL> def get_subsets ( self , project ) : <EOL> serializer = SubsetSerializer ( project . subsets . all ( ) , many = True ) <EOL> return serializer . data <EOL> def get_categories ( self , project ) : <EOL> serializer = CategorySerializer ( <EOL> project . categories . all ( ) . exclude ( fields = None ) , many = True ) <EOL> return serializer . data <EOL> def get_geographic_extent ( self , project ) : <EOL> if project . geographic_extent is not None : <EOL> return json . loads ( project . geographic_extent . json ) <EOL> else : <EOL> return None <EOL> def get_num_locations ( self , project ) : <EOL> locations = Location . objects . filter ( <EOL> Q ( private = False ) | <EOL> Q ( private_for_project = project ) ) . count ( ) <EOL> return locations <EOL> def get_num_contributions ( self , project ) : <EOL> return project . observations . exclude ( <EOL> status = 'draft' ) . exclude ( status = 'pending' ) . count ( ) <EOL> def get_user_contributions ( self , project ) : <EOL> user = self . context . get ( 'user' ) <EOL> if not user . is_anonymous ( ) : <EOL> return project . observations . filter ( creator = user ) . count ( ) <EOL>
<s> class GCConnectionStatus : <EOL> GCConnectionStatus_HAVE_SESSION = 999 <EOL> GCConnectionStatus_GC_GOING_DOWN = 1 <EOL> GCConnectionStatus_NO_SESSION = 2 <EOL> GCConnectionStatus_NO_SESSION_IN_LOGON_QUEUE = 3 <EOL> GCConnectionStatus_NO_STEAM = 4 <EOL> class EGCSystemMsg : <EOL> k_EGCMsgInvalid = 0 <EOL> k_EGCMsgMulti = 1 <EOL> k_EGCMsgGenericReply = 10 <EOL> k_EGCMsgSystemBase = 50 <EOL> k_EGCMsgAchievementAwarded = 51 <EOL> k_EGCMsgConCommand = 52 <EOL> k_EGCMsgStartPlaying = 53 <EOL> k_EGCMsgStopPlaying = 54 <EOL> k_EGCMsgStartGameserver = 55 <EOL> k_EGCMsgStopGameserver = 56 <EOL> k_EGCMsgWGRequest = 57 <EOL> k_EGCMsgWGResponse = 58 <EOL> k_EGCMsgGetUserGameStatsSchema = 59 <EOL> k_EGCMsgGetUserGameStatsSchemaResponse = 60 <EOL> k_EGCMsgGetUserStatsDEPRECATED = 61 <EOL> k_EGCMsgGetUserStatsResponse = 62 <EOL> k_EGCMsgAppInfoUpdated = 63 <EOL> k_EGCMsgValidateSession = 64 <EOL> k_EGCMsgValidateSessionResponse = 65 <EOL> k_EGCMsgLookupAccountFromInput = 66 <EOL> k_EGCMsgSendHTTPRequest = 67 <EOL> k_EGCMsgSendHTTPRequestResponse = 68 <EOL> k_EGCMsgPreTestSetup = 69 <EOL> k_EGCMsgRecordSupportAction = 70 <EOL> k_EGCMsgGetAccountDetails_DEPRECATED = 71 <EOL> k_EGCMsgReceiveInterAppMessage = 73 <EOL> k_EGCMsgFindAccounts = 74 <EOL> k_EGCMsgPostAlert = 75 <EOL> k_EGCMsgGetLicenses = 76 <EOL> k_EGCMsgGetUserStats = 77 <EOL> k_EGCMsgGetCommands = 78 <EOL> k_EGCMsgGetCommandsResponse = 79 <EOL> k_EGCMsgAddFreeLicense = 80 <EOL> k_EGCMsgAddFreeLicenseResponse = 81 <EOL> k_EGCMsgGetIPLocation = 82 <EOL> k_EGCMsgGetIPLocationResponse = 83 <EOL> k_EGCMsgSystemStatsSchema = 84 <EOL> k_EGCMsgGetSystemStats = 85 <EOL> k_EGCMsgGetSystemStatsResponse = 86 <EOL> k_EGCMsgSendEmail = 87 <EOL> k_EGCMsgSendEmailResponse = 88 <EOL> k_EGCMsgGetEmailTemplate = 89 <EOL> k_EGCMsgGetEmailTemplateResponse = 90 <EOL> k_EGCMsgGrantGuestPass = 91 <EOL> k_EGCMsgGrantGuestPassResponse = 92 <EOL> k_EGCMsgGetAccountDetails = 93 <EOL> k_EGCMsgGetAccountDetailsResponse = 94 <EOL> k_EGCMsgGetPersonaNames = 95 <EOL> k_EGCMsgGetPersonaNamesResponse = 96 <EOL> k_EGCMsgMultiplexMsg = 97 <EOL> k_EGCMsgWebAPIRegisterInterfaces = 101 <EOL> k_EGCMsgWebAPIJobRequest = 102 <EOL> k_EGCMsgWebAPIJobRequestHttpResponse = 104 <EOL> k_EGCMsgWebAPIJobRequestForwardResponse = 105 <EOL> k_EGCMsgMemCachedGet = 200 <EOL> k_EGCMsgMemCachedGetResponse = 201 <EOL> k_EGCMsgMemCachedSet = 202 <EOL> k_EGCMsgMemCachedDelete = 203 <EOL> k_EGCMsgMemCachedStats = 204 <EOL> k_EGCMsgMemCachedStatsResponse = 205 <EOL> k_EGCMsgMasterSetDirectory = 220 <EOL> k_EGCMsgMasterSetDirectoryResponse = 221 <EOL> k_EGCMsgMasterSetWebAPIRouting = 222 <EOL> k_EGCMsgMasterSetWebAPIRoutingResponse = 223 <EOL> k_EGCMsgMasterSetClientMsgRouting = 224 <EOL> k_EGCMsgMasterSetClientMsgRoutingResponse = 225 <EOL> k_EGCMsgSetOptions = 226 <EOL> k_EGCMsgSetOptionsResponse = 227 <EOL> k_EGCMsgSystemBase2 = 500 <EOL> k_EGCMsgGetPurchaseTrustStatus = 501 <EOL> k_EGCMsgGetPurchaseTrustStatusResponse = 502 <EOL> k_EGCMsgUpdateSession = 503 <EOL> k_EGCMsgGCAccountVacStatusChange = 504 <EOL> k_EGCMsgCheckFriendship = 505 <EOL> k_EGCMsgCheckFriendshipResponse = 506 <EOL> class ESOMsg : <EOL> k_ESOMsg_Create = 21 <EOL> k_ESOMsg_Update = 22 <EOL> k_ESOMsg_Destroy = 23 <EOL> k_ESOMsg_CacheSubscribed = 24 <EOL> k_ESOMsg_CacheUnsubscribed = 25 <EOL> k_ESOMsg_UpdateMultiple = 26 <EOL> k_ESOMsg_CacheSubscriptionCheck = 27 <EOL> k_ESOMsg_CacheSubscriptionRefresh = 28 <EOL> class EGCBaseClientMsg : <EOL> k_EMsgGCClientWelcome = 4004 <EOL> k_EMsgGCServerWelcome
<s> import unittest <EOL> import os <EOL> import time <EOL> import logging <EOL> from decimal import Decimal <EOL> from event_loop import Timer , TimerManager , EventLoop <EOL> from packet_reader import PacketReader <EOL> class TestingTimeFunction ( object ) : <EOL> def __init__ ( self ) : <EOL> self . time = 0 <EOL> def __call__ ( self ) : <EOL> return self . time + 42.25 <EOL> class MockCallback ( object ) : <EOL> def __init__ ( self ) : <EOL> self . nb_calls = 0 <EOL> def __call__ ( self ) : <EOL> self . nb_calls += 1 <EOL> class FileLike ( object ) : <EOL> def __init__ ( self , fd ) : <EOL> self . fd = fd <EOL> def fileno ( self ) : <EOL> return self . fd <EOL> class TestTimer ( unittest . TestCase ) : <EOL> def test_non_repeating ( self ) : <EOL> self . _non_repeating ( decorate = False ) <EOL> def test_decorate ( self ) : <EOL> self . _non_repeating ( decorate = False ) <EOL> def _non_repeating ( self , decorate ) : <EOL> for delay in ( 0 , 1 ) : <EOL> time = TestingTimeFunction ( ) <EOL> callback = MockCallback ( ) <EOL> if decorate : <EOL> timer = Timer . decorate ( 10 , _time_function = time ) ( callback ) <EOL> else : <EOL> timer = Timer ( callback , 10 , _time_function = time ) <EOL> still_alive = timer . run ( ) <EOL> assert still_alive <EOL> assert callback . nb_calls == 0 <EOL> assert timer . sleep_time ( ) == 10 <EOL> time . time = 9 <EOL> still_alive = timer . run ( ) <EOL> assert still_alive <EOL> assert callback . nb_calls == 0 <EOL> assert timer . sleep_time ( ) == 1 <EOL> time . time = 10 + delay <EOL> assert timer . sleep_time ( ) == 0 <EOL> still_alive = timer . run ( ) <EOL> assert not still_alive <EOL> assert callback . nb_calls == 1 <EOL> assert timer . sleep_time ( ) == Decimal ( 'inf' ) <EOL> still_alive = timer . run ( ) <EOL> assert not still_alive <EOL> assert callback . nb_calls == 1 <EOL> assert timer . sleep_time ( ) == Decimal ( 'inf' ) <EOL> time . time = 15 <EOL> still_alive = timer . run ( ) <EOL> assert not still_alive <EOL> assert callback . nb_calls == 1 <EOL> assert timer . sleep_time ( ) == Decimal ( 'inf' ) <EOL> def test_cancel ( self ) : <EOL> time = TestingTimeFunction ( ) <EOL> callback = MockCallback ( ) <EOL> timer = Timer ( callback , 10 , _time_function = time ) <EOL> time . time = 9 <EOL> still_alive = timer . run ( ) <EOL> assert still_alive <EOL> assert timer . sleep_time ( ) == 1 <EOL> timer . cancel ( ) <EOL> still_alive = timer . run ( ) <EOL> assert not still_alive <EOL> assert callback . nb_calls == 0 <EOL> assert timer . sleep_time ( ) == Decimal ( 'inf' ) <EOL> def test_reset_early ( self ) : <EOL> time = TestingTimeFunction ( ) <EOL> callback = MockCallback ( ) <EOL> timer = Timer ( callback , 10 , _time_function = time ) <EOL> time . time = 7 <EOL> assert timer . sleep_time ( ) == 3 <EOL> timer . reset ( ) <EOL> assert timer . sleep_time ( ) == 10 <EOL> time . time = 16 <EOL> still_alive = timer . run ( ) <EOL> assert still_alive <EOL> assert callback . nb_calls == 0 <EOL> assert timer . sleep_time ( ) == 1 <EOL> time . time = 17 <EOL> assert timer . sleep_time ( ) == 0 <EOL> still_alive = timer . run ( ) <EOL> assert not still_alive <EOL> assert callback . nb_calls == 1 <EOL> assert timer . sleep_time ( ) == Decimal ( 'inf' ) <EOL> def test_reset_late ( self ) : <EOL> time = TestingTimeFunction ( ) <EOL> callback = MockCallback ( ) <EOL> timer = Timer ( callback , 10 , _time_function = time ) <EOL> time . time = 13 <EOL> assert timer . sleep_time ( ) == 0 <EOL> still_alive = timer . run ( ) <EOL> assert not still_alive <EOL> assert callback . nb_calls == 1 <EOL> assert timer . sleep_time ( ) == Decimal ( 'inf' ) <EOL> timer . reset ( ) <EOL> still_alive = timer . run ( ) <EOL> assert still_alive <EOL> assert callback . nb_calls == 1 <EOL> assert timer . sleep_time ( ) == 10 <EOL> time . time = 21 <EOL> still_alive = timer . run ( ) <EOL> assert still_alive <EOL> assert callback . nb_calls == 1 <EOL> assert timer . sleep_time ( ) == 2 <EOL> time . time = 30 <EOL> assert timer . sleep_time ( ) == 0 <EOL> still_alive = timer . run ( ) <EOL> assert not still_alive <EOL> assert callback . nb_calls == 2 <EOL> assert timer . sleep_time ( ) == Decimal ( 'inf' ) <EOL> def test_repeating ( self ) : <EOL> time = TestingTimeFunction ( ) <EOL> callback = MockCallback ( ) <EOL> timer = Timer ( callback , 10 , repeat = True , _time_function = time ) <EOL> time . time = 7 <EOL> still_alive = timer . run ( ) <EOL> assert still_alive <EOL> assert callback . nb_calls == 0 <EOL> assert timer . sleep_time ( ) == 3 <EOL> time . time = 34 <EOL> still_alive = timer . run ( ) <EOL> assert still_alive <EOL> assert callback . nb_calls == 1 <EOL> assert timer . sleep_time ( ) == 6 <EOL> time . time = 40 <EOL> still_alive = timer . run ( ) <EOL> assert still_alive <EOL> assert callback . nb_calls == 2 <EOL> assert timer . sleep_time ( ) == 10 <EOL> def test_cancel_repeating ( self ) : <EOL> time = TestingTimeFunction ( ) <EOL> callback = MockCallback ( ) <EOL> timer = Timer ( callback , 10 , repeat = True , _time_function = time ) <EOL> time . time = 10 <EOL> timer . run ( ) <EOL> time . time = 34 <EOL> still_alive = timer . run ( ) <EOL> assert still_alive <EOL> assert callback . nb_calls == 2 <EOL> assert timer . sleep_time ( ) == 6 <EOL> time . time = 40 <EOL> timer . cancel ( ) <EOL> for time . time in ( 40 , 43 , 60 , 138 ) : <EOL> still_alive = timer . run ( ) <EOL> assert not still_alive <EOL> assert callback . nb_calls == 2 <EOL> assert timer . sleep_time ( ) == Decimal ( 'inf' ) <EOL> def test_reset_repeating ( self ) : <EOL> time = TestingTimeFunction ( ) <EOL> callback = MockCallback ( ) <EOL> timer = Timer ( callback , 10 , repeat = True , _time_function = time ) <EOL> time . time = 12 <EOL> still_alive = timer . run ( ) <EOL> assert still_alive <EOL> assert callback . nb_calls == 1 <EOL> assert timer . sleep_time ( ) == 8 <EOL> timer . reset ( ) <EOL> assert timer . sleep_time ( ) == 10 <EOL> time . time = 34 <EOL> assert timer . sleep_time ( ) == 0 <EOL> timer . reset ( ) <EOL> assert timer . sleep_time ( ) == 10 <EOL> still_alive = timer . run ( ) <EOL> assert still_alive <EOL> assert callback . nb_calls == 1 <EOL> assert timer . sleep_time ( ) == 10 <EOL> class TestTimerManager ( unittest . TestCase ) : <EOL> def test_empty_timer_list ( self ) : <EOL> manager = TimerManager ( ) <EOL> assert manager . sleep_time ( ) == Decimal ( 'inf' ) <EOL> def test_invalid_timeouts ( self ) : <EOL> manager = TimerManager ( ) <EOL> self . assertRaises ( AssertionError , manager . add_timer , 0 , None ) <EOL> self . assertRaises ( AssertionError , manager . add_timer , - 1 , None ) <EOL> def test_single_timer ( self ) : <EOL> time = TestingTimeFunction ( ) <EOL> manager = TimerManager ( _time_function = time ) <EOL> callback = MockCallback ( ) <EOL> manager . add_timer ( 30 , callback ) <EOL> assert manager . sleep_time ( ) == 30 <EOL> assert callback . nb_calls == 0 <EOL> manager . run ( ) <EOL> assert callback . nb_calls == 0 <EOL> time . time = 22 <EOL> assert manager . sleep_time ( ) == 8 <EOL> manager . run ( ) <EOL> assert callback . nb_calls == 0 <EOL> time . time = 30 <EOL> assert manager . sleep_time ( ) == 0 <EOL> manager . run ( ) <EOL> assert callback . nb_calls == 1 <EOL> assert manager . sleep_time ( ) == Decimal ( 'inf' ) <EOL> time . time = 100 <EOL> manager . run ( ) <EOL> assert callback . nb_calls == 1 <EOL> def test_single_repeating_timer ( self ) : <EOL> time = TestingTimeFunction ( ) <EOL> manager = TimerManager ( _time_function = time ) <EOL> callback = MockCallback ( ) <EOL> manager . add_timer ( 30 , callback , repeat = True ) <EOL> assert manager . sleep_time ( ) == 30 <EOL> assert callback . nb_calls == 0 <EOL> manager . run ( ) <EOL> assert callback . nb_calls == 0 <EOL> time . time = 22 <EOL> assert manager . sleep_time ( ) == 8 <EOL> manager . run ( ) <EOL> assert callback . nb_calls == 0 <EOL> time . time = 30 <EOL> assert manager . sleep_time ( ) == 0 <EOL> manager . run ( ) <EOL> assert callback . nb_calls == 1 <EOL> assert manager . sleep_time ( ) == 30 <EOL> time . time = 71 <EOL> assert manager . sleep_time ( ) == 0 <EOL> manager . run ( ) <EOL> assert callback . nb_calls == 2 <EOL> assert manager . sleep_time ( ) == 19 <EOL> time . time = 200 <EOL> assert manager . sleep_time ( ) == 0 <EOL> manager . run ( ) <EOL> assert callback . nb_calls == 3 <EOL> assert manager . sleep_time ( ) == 10 <EOL> def test_long_callback ( self ) : <EOL> time = TestingTimeFunction ( ) <EOL> manager = TimerManager ( _time_function = time ) <EOL> def loose_time ( ) : <EOL> time . time += 11 <EOL> manager . add_timer ( 2 , loose_time , repeat = True ) <EOL> manager . run ( ) <EOL> assert time . time == 0 <EOL> time . time = 2 <EOL> manager . run ( ) <EOL> assert time . time == 13 <EOL> assert manager . sleep_time ( ) == 0 <EOL> def test_many ( self ) : <EOL> time = TestingTimeFunction ( ) <EOL> manager = TimerManager ( _time_function = time ) <EOL> c5 = MockCallback ( ) <EOL> manager . add_timer ( 5 , c5 , repeat = True ) <EOL> c7 = MockCallback ( ) <EOL> manager . add_timer ( 7 , c7 , repeat = True ) <EOL> c13 = MockCallback ( ) <EOL> manager . add_timer ( 13 , c13 , repeat = True ) <EOL> nb_sleeps = 0 <EOL> while 1 : <EOL> time . time += manager . sleep_time ( ) <EOL> if time . time >= 100 : <EOL> break <EOL> nb_sleeps += 1 <EOL> manager . run ( ) <EOL> assert c5 . nb_calls == 19 <EOL> assert c7 . nb_calls == 14 <EOL> assert c13 . nb_calls == 7 <EOL> assert nb_sleeps == ( c5 . nb_calls + c7 . nb_calls + c13 . nb_calls - 4 ) <EOL> def test_contsant_sleep ( self ) : <EOL> time = TestingTimeFunction ( ) <EOL> manager = TimerManager ( _time_function = time ) <EOL> c5 = MockCallback ( ) <EOL>
<s> import itertools <EOL> import os <EOL> import urlparse <EOL> from github3 import GitHubError <EOL> import markupsafe <EOL> from modularodm import fields <EOL> from framework . auth import Auth <EOL> from website import settings <EOL> from website . util import web_url_for <EOL> from website . addons . base import exceptions <EOL> from website . addons . base import AddonOAuthUserSettingsBase , AddonOAuthNodeSettingsBase <EOL> from website . addons . base import StorageAddonBase <EOL> from website . addons . github import utils <EOL> from website . addons . github . api import GitHubClient <EOL> from website . addons . github . serializer import GitHubSerializer <EOL> from website . addons . github import settings as github_settings <EOL> from website . addons . github . exceptions import ApiError , NotFoundError <EOL> from website . oauth . models import ExternalProvider <EOL> hook_domain = github_settings . HOOK_DOMAIN or settings . DOMAIN <EOL> class GitHubProvider ( ExternalProvider ) : <EOL> name = 'GitHub' <EOL> short_name = 'github' <EOL> client_id = github_settings . CLIENT_ID <EOL> client_secret = github_settings . CLIENT_SECRET <EOL> auth_url_base = github_settings . OAUTH_AUTHORIZE_URL <EOL> callback_url = github_settings . OAUTH_ACCESS_TOKEN_URL <EOL> default_scopes = github_settings . SCOPE <EOL> def handle_callback ( self , response ) : <EOL> client = GitHubClient ( <EOL> access_token = response [ 'access_token' ] <EOL> ) <EOL> user_info = client . user ( ) <EOL> return { <EOL> 'provider_id' : str ( user_info . id ) , <EOL> 'profile_url' : user_info . html_url , <EOL> 'display_name' : user_info . login <EOL> } <EOL> class GitHubUserSettings ( AddonOAuthUserSettingsBase ) : <EOL> oauth_provider = GitHubProvider <EOL> serializer = GitHubSerializer <EOL> def revoke_remote_oauth_access ( self , external_account ) : <EOL> connection = GitHubClient ( external_account = external_account ) <EOL> try : <EOL> connection . revoke_token ( ) <EOL> except GitHubError : <EOL> pass <EOL> @ property <EOL> def public_id ( self ) : <EOL> gh_accounts = [ <EOL> a for a in self . owner . external_accounts <EOL> if a . provider == self . oauth_provider . short_name <EOL> ] <EOL> if gh_accounts : <EOL> return gh_accounts [ 0 ] . display_name <EOL> return None <EOL> class GitHubNodeSettings ( StorageAddonBase , AddonOAuthNodeSettingsBase ) : <EOL> oauth_provider = GitHubProvider <EOL> serializer = GitHubSerializer <EOL> user = fields . StringField ( ) <EOL> repo = fields . StringField ( ) <EOL> hook_id = fields . StringField ( ) <EOL> hook_secret = fields . StringField ( ) <EOL> registration_data = fields . DictionaryField ( ) <EOL> @ property <EOL> def folder_id ( self ) : <EOL> return self . repo or None <EOL> @ property <EOL> def folder_name ( self ) : <EOL> if self . complete : <EOL> return '{}/{}' . format ( self . user , self . repo ) <EOL> return None <EOL> @ property <EOL> def folder_path ( self ) : <EOL> return self . repo or None <EOL> @ property <EOL> def has_auth ( self ) : <EOL> return bool ( self . user_settings and self . user_settings . has_auth ) <EOL> @ property <EOL> def complete ( self ) : <EOL> return self . has_auth and self . repo is not None and self . user is not None <EOL> def authorize ( self , user_settings , save = False ) : <EOL> self . user_settings = user_settings <EOL> self . owner . add_log ( <EOL> action = '' , <EOL> params = { <EOL> 'project' : self . owner . parent_id , <EOL> 'node' : self . owner . _id , <EOL> } , <EOL> auth = Auth ( user_settings . owner ) , <EOL> ) <EOL> if save : <EOL> self . save ( ) <EOL> def clear_settings ( self ) : <EOL> self . user = None <EOL> self . repo = None <EOL> self . hook_id = None <EOL> self . hook_secret = None <EOL> self . registration_data = None <EOL> def deauthorize ( self , auth = None , log = True ) : <EOL> self . delete_hook ( save = False ) <EOL> self . clear_settings ( ) <EOL> if log : <EOL> self . owner . add_log ( <EOL> action = '' , <EOL> params = { <EOL> 'project' : self . owner . parent_id , <EOL> 'node' : self .
<s> __author__ = '' <EOL> import json <EOL> from tornado import gen <EOL> from viewfinder . backend . db import vf_schema <EOL> from viewfinder . backend . db . asset_id import IdPrefix , ConstructTimestampAssetId , DeconstructTimestampAssetId , VerifyAssetId <EOL> from viewfinder . backend . db . base import DBObject <EOL> from viewfinder . backend . db . operation import Operation <EOL> from viewfinder . backend . db . range_base import DBRangeObject <EOL> @ DBObject . map_table_attributes <EOL> class Activity ( DBRangeObject ) : <EOL> __slots__ = [ ] <EOL> _table = DBObject . _schema . GetTable ( vf_schema . ACTIVITY ) <EOL> def MakeMetadataDict ( self ) : <EOL> activity_dict = self . _asdict ( ) <EOL> activity_dict [ activity_dict . pop ( 'name' ) ] = json . loads ( activity_dict . pop ( 'json' ) ) <EOL> return activity_dict <EOL> @ classmethod <EOL> def ConstructActivityId ( cls , timestamp , device_id , uniquifier ) : <EOL> return ConstructTimestampAssetId ( IdPrefix . Activity , timestamp , device_id , uniquifier ) <EOL> @ classmethod <EOL> def ConstructActivityIdFromOperationId ( cls , timestamp , operation_id ) : <EOL> device_id , uniquifier = Operation . DeconstructOperationId ( operation_id ) <EOL> return Activity . ConstructActivityId ( timestamp , device_id , uniquifier ) <EOL> @ classmethod <EOL> def DeconstructActivityId ( cls , activity_id ) : <EOL> return DeconstructTimestampAssetId ( IdPrefix . Activity , activity_id ) <EOL> @ classmethod <EOL> @ gen . coroutine <EOL> def VerifyActivityId ( cls , client , user_id , device_id , activity_id ) : <EOL> yield VerifyAssetId ( client , user_id , device_id , IdPrefix . Activity , activity_id , has_timestamp = True ) <EOL> @ classmethod <EOL> @ gen . coroutine <EOL> def CreateAddFollowers ( cls , client , user_id , viewpoint_id , activity_id , timestamp , <EOL> update_seq , follower_ids ) : <EOL> args_dict = { 'follower_ids' : follower_ids } <EOL> activity = yield Activity . _CreateActivity ( client , <EOL> user_id , <EOL> viewpoint_id , <EOL> activity_id , <EOL> timestamp , <EOL> update_seq , <EOL> 'add_followers' , <EOL> args_dict ) <EOL> raise gen . Return ( activity ) <EOL> @ classmethod <EOL> @ gen . coroutine <EOL> def CreateMergeAccounts ( cls , client , user_id , viewpoint_id , activity_id , timestamp , <EOL> update_seq , target_user_id , source_user_id ) : <EOL> args_dict = { 'target_user_id' : target_user_id , <EOL> 'source_user_id' : source_user_id } <EOL> activity = yield Activity . _CreateActivity ( client , <EOL> user_id , <EOL> viewpoint_id , <EOL> activity_id , <EOL> timestamp , <EOL> update_seq , <EOL> 'merge_accounts' , <EOL> args_dict ) <EOL> raise gen . Return ( activity ) <EOL> @ classmethod <EOL> @ gen . coroutine <EOL> def CreatePostComment ( cls , client , user_id , viewpoint_id , activity_id , timestamp , <EOL> update_seq , cm_dict ) : <EOL> args_dict = { 'comment_id' : cm_dict [ 'comment_id' ] } <EOL> activity = yield Activity . _CreateActivity ( client , <EOL> user_id , <EOL> viewpoint_id , <EOL> activity_id , <EOL> timestamp , <EOL> update_seq , <EOL> 'post_comment' , <EOL> args_dict ) <EOL> raise gen . Return ( activity ) <EOL> @ classmethod <EOL> @ gen . coroutine <EOL> def CreateRemoveFollowers ( cls , client , user_id , viewpoint_id , activity_id , timestamp , <EOL> update_seq , follower_ids ) : <EOL> args_dict = { 'follower_ids' : follower_ids } <EOL> activity = yield Activity . _CreateActivity ( client , <EOL> user_id , <EOL> viewpoint_id , <EOL> activity_id , <EOL> timestamp , <EOL> update_seq , <EOL> '' , <EOL> args_dict ) <EOL> raise gen . Return ( activity ) <EOL> @ classmethod <EOL> @ gen . coroutine <EOL> def CreateRemovePhotos ( cls , client , user_id , viewpoint_id , activity_id , timestamp , <EOL> update_seq , ep_dicts ) : <EOL> args_dict = { 'episodes' : [ { 'episode_id' : ep_dict [ 'new_episode_id' ] , <EOL> 'photo_ids' : ep_dict [ 'photo_ids' ] } <EOL> for ep_dict in ep_dicts ] } <EOL> activity = yield Activity . _CreateActivity ( client , <EOL> user_id , <EOL> viewpoint_id , <EOL> activity_id , <EOL> timestamp , <EOL> update_seq , <EOL> 'remove_photos' , <EOL> args_dict ) <EOL> raise gen . Return ( activity ) <EOL> @ classmethod <EOL> @ gen . coroutine <EOL> def CreateSavePhotos ( cls , client , user_id , viewpoint_id , activity_id , timestamp , <EOL> update_seq , ep_dicts ) : <EOL> args_dict = { 'episodes' : [ { 'episode_id' : ep_dict [ 'new_episode_id' ] , <EOL> 'photo_ids' : ep_dict [ 'photo_ids' ] } <EOL> for ep_dict in ep_dicts ] } <EOL> activity = yield Activity . _CreateActivity ( client , <EOL> user_id , <EOL> viewpoint_id , <EOL> activity_id , <EOL> timestamp , <EOL> update_seq , <EOL> 'save_photos' , <EOL> args_dict ) <EOL> raise gen . Return ( activity ) <EOL> @ classmethod <EOL> @ gen . coroutine <EOL> def CreateShareExisting ( cls , client , user_id , viewpoint_id , activity_id , timestamp , <EOL> update_seq , ep_dicts ) : <EOL> args_dict = { 'episodes' : [ { 'episode_id' : ep_dict [ 'new_episode_id' ] , <EOL> 'photo_ids' : ep_dict [ 'photo_ids' ] } <EOL> for ep_dict in ep_dicts ] } <EOL> activity = yield Activity . _CreateActivity ( client , <EOL> user_id , <EOL> viewpoint_id , <EOL> activity_id , <EOL> timestamp , <EOL> update_seq , <EOL> 'share_existing' , <EOL> args_dict ) <EOL> raise gen . Return ( activity ) <EOL> @ classmethod <EOL> @ gen . coroutine <EOL> def CreateShareNew ( cls , client , user_id , viewpoint_id , activity_id , timestamp , <EOL> update_seq , ep_dicts , follower_ids ) : <EOL> args_dict = { 'episodes' : [ { 'episode_id' : ep_dict [ 'new_episode_id' ] , <EOL> 'photo_ids' : ep_dict [ 'photo_ids' ] } <EOL> for ep_dict in ep_dicts ] , <EOL> 'follower_ids' : follower_ids } <EOL> activity = yield Activity . _CreateActivity ( client , <EOL> user_id , <EOL> viewpoint_id , <EOL> activity_id , <EOL> timestamp , <EOL> update_seq , <EOL> 'share_new' , <EOL> args_dict ) <EOL> raise gen . Return ( activity ) <EOL> @ classmethod <EOL> @ gen . coroutine <EOL> def CreateUnshare ( cls , client , user_id , viewpoint_id , activity_id , timestamp , <EOL> update_seq , ep_dicts ) : <EOL> args_dict = { 'episodes'
<s> from . utils import ( tree_walk , match_regexes , move_path , minified_filename , <EOL> get_extension , default_minifier , should_update_key ) <EOL> from . exceptions import MinifierError <EOL> import re <EOL> import subprocess <EOL> from boto . s3 . connection import S3Connection <EOL> from boto . exception import S3ResponseError <EOL> from boto . s3 . key import Key <EOL> class StaticDir ( object ) : <EOL> def __init__ ( self , directory ) : <EOL> self . directory = directory <EOL> self . input_directory = None <EOL> self . minifier = default_minifier ( ) <EOL> self . force_update = False <EOL> self . ignore = [ ] <EOL> self . metadata = { } <EOL> def update ( self , bucket_name ) : <EOL> self . minify_files ( ) <EOL> files = self . enumerate_files ( self . directory ) <EOL> conn = self . connect_s3 ( ) <EOL> self . upload_files ( files , bucket_name , conn ) <EOL> return <EOL> def enumerate_files ( self , directory ) : <EOL> files = tree_walk ( directory ) <EOL> files = self . filter_files ( files ) <EOL> return files <EOL> def filter_files ( self , files ) : <EOL> tests = [ re . compile ( x ) for x in self . ignore ] <EOL> if tests : <EOL> files = [ name for name in files if not match_regexes ( tests , name ) ] <EOL> return files <EOL> def minify_files ( self ) : <EOL> if self . input_directory : <EOL> files = self . enumerate_files ( self . input_directory ) <EOL> else : <EOL> files = self . enumerate_files ( self . directory ) <EOL> if isinstance ( self . minifier , basestring ) : <EOL> minifier = { 'css' : self . minifier , 'js' : self . minifier } <EOL> else : <EOL> minifier = self . minifier <EOL> for name in files : <EOL> try : <EOL> command = minifier [ get_extension ( name ) ] <EOL> command = command . format ( in_name = name , <EOL> out_name = self . get_output_name ( name ) ) <EOL> rc = subprocess . call ( command , shell = True ) <EOL> if rc != 0 : <EOL> raise MinifierError ( "" ) <EOL> except KeyError : <EOL> continue <EOL> return <EOL> def get_output_name ( self , input_filename ) : <EOL> if self . input_directory : <EOL> filename = move_path ( self . input_directory , <EOL> self . directory , <EOL> input_filename ) <EOL> filename = minified_filename ( filename ) <EOL> else : <EOL> filename = minified_filename ( input_filename ) <EOL> return filename <EOL> def connect_s3 ( self ) : <EOL> return S3Connection ( ) <EOL> def upload_files
<s> from __future__ import print_function <EOL> import os <EOL> import sys <EOL> import subprocess <EOL> from os import environ as env <EOL> from shellpython import config <EOL> _colorama_intialized = False <EOL> _colorama_available = True <EOL> try : <EOL> import colorama <EOL> from colorama import Fore , Style <EOL> except ImportError : <EOL> _colorama_available = False <EOL> def _is_colorama_enabled ( ) : <EOL> return _colorama_available and config . COLORAMA_ENABLED <EOL> def _print_stdout ( text ) : <EOL> print ( text ) <EOL> def _print_stderr ( text ) : <EOL> print ( text , file = sys . stderr ) <EOL> _PARAM_PRINT_STDOUT = 'p' <EOL> _PARAM_PRINT_STDERR = 'e' <EOL> _PARAM_INTERACTIVE = 'i' <EOL> _PARAM_NO_THROW = 'n' <EOL> def exe ( cmd , params ) : <EOL> global _colorama_intialized <EOL> if _is_colorama_enabled ( ) and not _colorama_intialized : <EOL> _colorama_intialized = True <EOL> colorama . init ( ) <EOL> if config . PRINT_ALL_COMMANDS : <EOL> if _is_colorama_enabled ( ) : <EOL> _print_stdout ( Fore . GREEN + '>>> ' + cmd + Style . RESET_ALL ) <EOL> else : <EOL> _print_stdout ( '>>> ' + cmd ) <EOL> if _is_param_set ( params , _PARAM_INTERACTIVE ) : <EOL> return _create_interactive_result ( cmd , params ) <EOL> else : <EOL> return _create_result ( cmd , params ) <EOL> def _is_param_set ( params , param ) : <EOL> return True if params . find ( param ) != - 1 else False <EOL> class ShellpyError ( Exception ) : <EOL> pass <EOL> class NonZeroReturnCodeError ( ShellpyError ) : <EOL> def __init__ ( self , cmd , result ) : <EOL> self . cmd = cmd <EOL> self . result = result <EOL> def __str__ ( self ) : <EOL> if _is_colorama_enabled ( ) : <EOL> return '' . format ( red = Fore . RED , end = Style . RESET_ALL , cmd = self . cmd , code = self . result . returncode , <EOL> stderr = self . result . stderr ) <EOL> else : <EOL> return '' . format ( <EOL> cmd = self . cmd , code = self . result . returncode , stderr = self . result . stderr ) <EOL> class Stream : <EOL> def __init__ ( self , file , encoding , print_out_stream = False , color = None ) : <EOL> self . _file = file <EOL> self . _encoding = encoding <EOL> self . _print_out_stream = print_out_stream <EOL> self . _color = color <EOL> def __iter__ ( self ) : <EOL> return self <EOL> def next ( self ) : <EOL> return self . sreadline ( ) <EOL> __next__ = next <EOL> def sreadline ( self ) : <EOL> line = self . _file . readline ( ) <EOL> if sys . version_info [ 0 ] == 3 : <EOL> line = line . decode ( self . _encoding ) <EOL> if line == '' : <EOL> raise StopIteration <EOL> else : <EOL> line = line . rstrip ( os . linesep ) <EOL> if self . _print_out_stream : <EOL> if self . _color is None : <EOL> _print_stdout ( line ) <EOL> else : <EOL> _print_stdout ( self . _color + line + Style . RESET_ALL ) <EOL> return line <EOL> def swriteline ( self , text ) : <EOL> text_with_linesep = text + os . linesep <EOL> if sys . version_info [ 0 ] == 3 : <EOL> text_with_linesep = text_with_linesep . encode ( self . _encoding ) <EOL> self . _file . write ( text_with_linesep ) <EOL> self . _file . flush ( ) <EOL> class InteractiveResult : <EOL> def __init__ ( self , process , params ) : <EOL> self . _process = process <EOL> self . _params = params <EOL> self . stdin = Stream ( process . stdin , sys . stdin . encoding ) <EOL> print_stdout = _is_param_set ( params , _PARAM_PRINT_STDOUT ) or config . PRINT_STDOUT_ALWAYS <EOL> self . stdout = Stream ( process . stdout , sys . stdout . encoding , print_stdout ) <EOL> print_stderr = _is_param_set ( params , _PARAM_PRINT_STDERR ) or config . PRINT_STDERR_ALWAYS <EOL> color = None if not _is_colorama_enabled ( ) else Fore . RED <EOL> self . stderr = Stream ( process . stderr , sys . stderr . encoding , print_stderr , color ) <EOL> def sreadline ( self ) : <EOL> return self . stdout . sreadline ( ) <EOL> def swriteline ( self , text ) : <EOL> self . stdin . swriteline ( text ) <EOL> @ property <EOL> def returncode ( self ) : <EOL> self . _process . wait ( ) <EOL> return self .
<s> import cefpython3 . wx . chromectrl as chrome <EOL> import wx <EOL> import wx . lib . agw . flatnotebook as fnb <EOL> import platform <EOL> import sys <EOL> ROOT_NAME = "My Locations" <EOL> URLS = [ "" , <EOL> "" , <EOL> "" , <EOL> "" , <EOL> "" , <EOL> "" , <EOL> "" <EOL> ] <EOL> class MainFrame ( wx . Frame ) : <EOL> def __init__ ( self ) : <EOL> wx . Frame . __init__ ( self , parent = None , id = wx . ID_ANY , <EOL> title = 'cefwx example2' , size = ( 800 , 600 ) ) <EOL> self . initComponents ( ) <EOL> self . layoutComponents ( ) <EOL> self . initEventHandlers ( ) <EOL> if len ( sys . argv ) == 2 and sys . argv [ 1 ] == "test-launch" : <EOL> wx . CallLater ( 500 , self . testLaunch ) <EOL> def testLaunch ( self ) : <EOL> print ( "" ) <EOL> self . Close ( ) <EOL> def initComponents ( self ) : <EOL> self . tree = wx . TreeCtrl ( self , id = - 1 , size = ( 200 , - 1 ) ) <EOL> self . root = self . tree . AddRoot ( ROOT_NAME ) <EOL> for url in URLS : <EOL> self . tree . AppendItem ( self . root , url ) <EOL> self . tree . Expand ( self . root ) <EOL> self . tabs = fnb . FlatNotebook ( self , wx . ID_ANY , <EOL> agwStyle = fnb . FNB_NODRAG | fnb . FNB_X_ON_TAB ) <EOL> self . tabs . SetWindowStyleFlag ( wx . WANTS_CHARS ) <EOL> def layoutComponents ( self ) : <EOL> sizer = wx . BoxSizer ( wx . HORIZONTAL ) <EOL> sizer . Add ( self . tree , 0 , wx . EXPAND ) <EOL> sizer . Add ( self . tabs , 1 , wx . EXPAND ) <EOL> self . SetSizer ( sizer ) <EOL> def initEventHandlers ( self ) : <EOL> self . Bind ( wx . EVT_TREE_SEL_CHANGED , self . OnSelChanged , self . tree ) <EOL> self . Bind ( fnb . EVT_FLATNOTEBOOK_PAGE_CLOSING , self . OnPageClosing ) <EOL> self . Bind ( wx . EVT_CLOSE , self . OnClose ) <EOL> def
<s> from __future__ import absolute_import <EOL> import httpretty <EOL> import pygerduty <EOL> import textwrap <EOL> @ httpretty . activate <EOL> def test_get_user ( ) : <EOL> httpretty . register_uri ( <EOL> httpretty . GET , "" , <EOL> body = textwrap . dedent ( ) , status = 200 ) <EOL> p = pygerduty . PagerDuty ( "contosso" , "password" ) <EOL> user = p . users . show ( "PIJ90N7" ) <EOL> assert user .
<s> __author__ = '' <EOL> import rethinkdb as r <EOL> class Pair ( object ) : <EOL> def __init__ ( self , timestamp1 , timestamp2 , direction ) : <EOL> self . timestamp1 = timestamp1 <EOL> self . timestamp2 = timestamp2 <EOL> self . direction = direction <EOL> def makeit_dict ( obj ) : <EOL> if isinstance ( obj , set ) : <EOL> return list ( obj ) <EOL> return obj . __dict__ <EOL> class MapperUtil ( ) : <EOL> @ staticmethod <EOL> def add_pair ( timestamp1 , timestamp2 , direction ) : <EOL> conn = r . connect ( "localhost" , 28015 ) <EOL> r . db ( 'test' ) . table ( "" ) . insert ( [ <EOL> { "timestamp1" : timestamp1 , <EOL> "timestamp2" : timestamp2 , <EOL> "direction" : direction <EOL> } <EOL> ] ) . run ( conn ) <EOL> conn . close ( ) <EOL> @ staticmethod <EOL> def get_pair_by_direction ( direction ) : <EOL> conn = r . connect ( "localhost" , 28015 ) <EOL> cursor = r . db ( 'test' ) . table ( "" ) . filter ( { 'direction'
<s> from __future__ import absolute_import , unicode_literals <EOL> from django . contrib . contenttypes . models import ContentType <EOL> from django . db import connection <EOL> from django . db . models . query import get_prefetcher <EOL> from django . test import TestCase <EOL> from django . test . utils import override_settings <EOL> from django . utils import six <EOL> from django . utils . encoding import force_text <EOL> from . models import ( Author , Book , Reader , Qualification , Teacher , Department , <EOL> TaggedItem , Bookmark , AuthorAddress , FavoriteAuthors , AuthorWithAge , <EOL> BookWithYear , BookReview , Person , House , Room , Employee , Comment , <EOL> LessonEntry , WordEntry , Author2 ) <EOL> class PrefetchRelatedTests ( TestCase ) : <EOL> def setUp ( self ) : <EOL> self . book1 = Book . objects . create ( title = "Poems" ) <EOL> self . book2 = Book . objects . create ( title = "Jane Eyre" ) <EOL> self . book3 = Book . objects . create ( title = "" ) <EOL> self . book4 = Book . objects . create ( title = "" ) <EOL> self . author1 = Author . objects . create ( name = "Charlotte" , <EOL> first_book = self . book1 ) <EOL> self . author2 = Author . objects . create ( name = "Anne" , <EOL> first_book = self . book1 ) <EOL> self . author3 = Author . objects . create ( name = "Emily" , <EOL> first_book = self . book1 ) <EOL> self . author4 = Author . objects . create ( name = "Jane" , <EOL> first_book = self . book4 ) <EOL> self . book1 . authors . add ( self . author1 , self . author2 , self . author3 ) <EOL> self . book2 . authors . add ( self . author1 ) <EOL> self . book3 . authors . add ( self . author3 ) <EOL> self . book4 . authors . add ( self . author4 ) <EOL> self . reader1 = Reader . objects . create ( name = "Amy" ) <EOL> self . reader2 = Reader . objects . create ( name = "Belinda" ) <EOL> self . reader1 . books_read . add ( self . book1 , self . book4 ) <EOL> self . reader2 . books_read . add ( self . book2 , self . book4 ) <EOL> def test_m2m_forward ( self ) : <EOL> with self . assertNumQueries ( 2 ) : <EOL> lists = [ list ( b . authors . all ( ) ) for b in Book . objects . prefetch_related ( 'authors' ) ] <EOL> normal_lists = [ list ( b . authors . all ( ) ) for b in Book . objects . all ( ) ] <EOL> self . assertEqual ( lists , normal_lists ) <EOL> def test_m2m_reverse ( self ) : <EOL> with self . assertNumQueries ( 2 ) : <EOL> lists = [ list ( a . books . all ( ) ) for a in Author . objects . prefetch_related ( 'books' ) ] <EOL> normal_lists = [ list ( a . books . all ( ) ) for a in Author . objects . all ( ) ] <EOL> self . assertEqual ( lists , normal_lists ) <EOL> def test_foreignkey_forward ( self ) : <EOL> with self . assertNumQueries ( 2 ) : <EOL> books = [ a . first_book for a in Author . objects . prefetch_related ( 'first_book' ) ] <EOL> normal_books = [ a . first_book for a in Author . objects . all ( ) ] <EOL> self . assertEqual ( books , normal_books ) <EOL> def test_foreignkey_reverse ( self ) : <EOL> with self . assertNumQueries ( 2 ) : <EOL> lists = [ list ( b . first_time_authors . all ( ) ) <EOL> for b in Book . objects . prefetch_related ( '' ) ] <EOL> self . assertQuerysetEqual ( self . book2 . authors . all ( ) , [ "" ] ) <EOL> def test_onetoone_reverse_no_match ( self ) : <EOL> with self . assertNumQueries ( 2 ) : <EOL> book = Book . objects . prefetch_related ( 'bookwithyear' ) . all ( ) [ 0 ] <EOL> with self . assertNumQueries ( 0 ) : <EOL> with self . assertRaises ( BookWithYear . DoesNotExist ) : <EOL> book . bookwithyear <EOL> def test_survives_clone ( self ) : <EOL> with self . assertNumQueries ( 2 ) : <EOL> lists = [ list ( b . first_time_authors . all ( ) ) <EOL> for b in Book . objects . prefetch_related ( '' ) . exclude ( id = 1000 ) ] <EOL> def test_len ( self ) : <EOL> with self . assertNumQueries ( 2 ) : <EOL> qs = Book . objects . prefetch_related ( '' ) <EOL> length = len ( qs ) <EOL> lists = [ list ( b . first_time_authors . all ( ) ) <EOL> for b in qs ] <EOL> def test_bool ( self ) : <EOL> with self . assertNumQueries ( 2 ) : <EOL> qs = Book . objects . prefetch_related ( '' ) <EOL> x = bool ( qs ) <EOL> lists = [ list ( b . first_time_authors . all ( ) ) <EOL> for b in qs ] <EOL> def test_count ( self ) : <EOL> with self . assertNumQueries ( 2 ) : <EOL> qs = Book . objects . prefetch_related ( '' ) <EOL> [ b . first_time_authors . count ( ) for b in qs ] <EOL> def test_exists ( self ) : <EOL> with self . assertNumQueries ( 2 ) : <EOL> qs = Book . objects . prefetch_related ( '' ) <EOL> [ b . first_time_authors . exists ( ) for b in qs ] <EOL> def test_in_and_prefetch_related ( self ) : <EOL> qs = Book . objects . prefetch_related ( '' ) <EOL> self . assertTrue ( qs [ 0 ] in qs ) <EOL> def test_clear ( self ) : <EOL> with self . assertNumQueries ( 5 ) : <EOL> with_prefetch = Author . objects . prefetch_related ( 'books' ) <EOL> without_prefetch = with_prefetch . prefetch_related ( None ) <EOL> lists = [ list ( a . books . all ( ) ) for a in without_prefetch ] <EOL> def test_m2m_then_m2m ( self ) : <EOL> with self . assertNumQueries ( 3 ) : <EOL> qs = Author . objects . prefetch_related ( 'books__read_by' ) <EOL> lists = [ [ [ six . text_type ( r ) for r in b . read_by . all ( ) ] <EOL> for b in a . books . all ( ) ] <EOL> for a in qs ] <EOL> self . assertEqual ( lists , <EOL> [ <EOL> [ [ "Amy" ] , [ "Belinda" ] ] , <EOL> [ [ "Amy" ] ] , <EOL> [ [ "Amy" ] , [ ] ] , <EOL> [ [ "Amy" , "Belinda" ] ] , <EOL> ] ) <EOL> def test_overriding_prefetch ( self ) : <EOL> with self . assertNumQueries ( 3 ) : <EOL> qs = Author . objects . prefetch_related ( 'books' , 'books__read_by' ) <EOL> lists = [ [ [ six . text_type ( r ) for r in b . read_by . all ( ) ] <EOL> for b in a . books . all ( ) ] <EOL> for a in qs ] <EOL> self . assertEqual ( lists , <EOL> [ <EOL> [ [ "Amy" ] , [ "Belinda" ] ] , <EOL> [ [ "Amy" ] ] , <EOL> [ [ "Amy" ] , [ ] ] , <EOL> [ [ "Amy" , "Belinda" ] ] , <EOL> ] ) <EOL> with self . assertNumQueries ( 3 ) : <EOL> qs = Author . objects . prefetch_related ( 'books__read_by' , 'books' ) <EOL> lists = [ [ [ six . text_type ( r ) for r in b . read_by . all ( ) ] <EOL> for b in a . books . all ( ) ] <EOL> for a in qs ] <EOL> self . assertEqual ( lists , <EOL> [ <EOL> [ [ "Amy" ] , [ "Belinda" ] ] , <EOL> [ [ "Amy" ] ] , <EOL> [ [ "Amy" ] , [ ] ] , <EOL> [ [ "Amy" , "Belinda" ] ] , <EOL> ] ) <EOL> def test_get ( self ) : <EOL> with self . assertNumQueries ( 3 ) : <EOL> author = Author . objects . prefetch_related ( 'books__read_by' ) . get ( name = "Charlotte" ) <EOL> lists = [ [ six . text_type ( r ) for r in b . read_by . all ( ) ] <EOL> for b in author . books . all ( ) ] <EOL> self . assertEqual ( lists , [ [ "Amy" ] , [ "Belinda" ] ] ) <EOL> def test_foreign_key_then_m2m ( self ) : <EOL> with self . assertNumQueries ( 2 ) : <EOL> qs = Author . objects . select_related ( 'first_book' ) . prefetch_related ( '' ) <EOL> lists = [ [ six . text_type ( r ) for r in a . first_book . read_by . all ( ) ] <EOL> for a in qs ] <EOL> self . assertEqual ( lists , [ [ "Amy" ] , <EOL> [ "Amy" ] , <EOL> [ "Amy" ] , <EOL> [ "Amy" , "Belinda" ] ] ) <EOL> def test_attribute_error ( self ) : <EOL> qs = Reader . objects . all ( ) . prefetch_related ( '' ) <EOL> with self . assertRaises ( AttributeError ) as cm : <EOL> list ( qs ) <EOL> self . assertTrue ( '' in str ( cm . exception ) ) <EOL> def test_invalid_final_lookup ( self ) : <EOL> qs = Book . objects . prefetch_related ( 'authors__name' ) <EOL> with self . assertRaises ( ValueError ) as cm : <EOL> list ( qs ) <EOL> self . assertTrue ( '' in str ( cm . exception ) ) <EOL> self . assertTrue ( "name" in str ( cm . exception ) ) <EOL> class DefaultManagerTests ( TestCase ) : <EOL> def setUp ( self ) : <EOL> self . qual1 = Qualification . objects . create ( name = "BA" ) <EOL> self . qual2 = Qualification . objects . create ( name = "BSci" ) <EOL> self . qual3 = Qualification . objects . create ( name = "MA" ) <EOL> self . qual4 = Qualification . objects . create ( name = "PhD" ) <EOL> self . teacher1 = Teacher . objects . create ( name = "Mr Cleese" ) <EOL> self . teacher2 = Teacher . objects . create ( name = "Mr Idle" ) <EOL> self . teacher3 = Teacher . objects . create ( name = "Mr Chapman" ) <EOL> self . teacher1 . qualifications . add ( self . qual1 , self . qual2 , self . qual3 , self . qual4 ) <EOL> self . teacher2 . qualifications . add ( self . qual1 ) <EOL> self . teacher3 . qualifications . add ( self . qual2 ) <EOL> self . dept1 = Department . objects . create ( name = "English" ) <EOL> self . dept2 = Department . objects . create ( name = "Physics" ) <EOL> self . dept1 . teachers . add ( self . teacher1 , self . teacher2 ) <EOL> self . dept2 . teachers . add ( self . teacher1 , self . teacher3 ) <EOL> def test_m2m_then_m2m ( self ) : <EOL> with self . assertNumQueries ( 3 ) : <EOL> qs = Department . objects .
<s> import os . path <EOL> head = os . path . dirname ( __file__ ) <EOL> puremvc = os . path . join ( head , '..' , '..' , 'employeeadmin' ) <EOL> TARGETS = { <EOL> 'Blog.py' : dict ( <EOL> path = 'media' , <EOL> options = [ <EOL> '--library_dir' , <EOL> os . path . join ( puremvc , '' , 'src' ) , <EOL> ] , <EOL> downloads = [ <EOL> dict ( <EOL> url = '' , <EOL> dst = os . path . join ( puremvc , '' ) , <EOL> unzip = True , <EOL> ) <EOL> ] , <EOL> ) , <EOL> } <EOL> PACKAGE = { <EOL> 'title' : '' , <EOL> 'desc' : '' , <EOL> } <EOL> def setup ( targets ) : <EOL> util . setup ( targets ) <EOL> def translate ( ) : <EOL> util . translate
<s> import binascii <EOL> from zope . interface import implements <EOL> from twisted . cred import credentials , error <EOL> from twisted . web . iweb import ICredentialFactory <EOL> class BasicCredentialFactory ( object ) : <EOL> implements ( ICredentialFactory ) <EOL> scheme = 'basic' <EOL> def __init__ ( self , authenticationRealm ) : <EOL> self . authenticationRealm = authenticationRealm <EOL> def getChallenge ( self , request ) : <EOL> return { 'realm' : self . authenticationRealm } <EOL> def decode ( self , response , request ) : <EOL> try : <EOL>
<s> import sys , os <EOL> sys . path . insert ( 0 , os . path . abspath ( '..' ) ) <EOL> extensions = [ '' ] <EOL> templates_path = [ '_templates' ] <EOL>
<s> import dpkt <EOL> AUTH_NONE = 0 <EOL> AUTH_PASSWORD = 1 <EOL> AUTH_CRYPTO = 2 <EOL> class OSPF ( dpkt . Packet ) : <EOL> __hdr__ = ( <EOL> ( 'v' , 'B' , 0 ) , <EOL> ( 'type' , 'B' , 0 ) , <EOL> ( 'len' , 'H' , 0 ) , <EOL> ( 'router' , 'I' , 0 ) , <EOL> ( 'area' , 'I' , 0 ) , <EOL> ( 'sum' , 'H' , 0 ) , <EOL> ( 'atype' , 'H'
<s> from django . core . exceptions import ObjectDoesNotExist <EOL> from django . db import connection <EOL> from django . db . models import signals <EOL> from django . db import models , router <EOL> from django . db . models . fields . related import RelatedField , Field , ManyToManyRel <EOL> from django . db . models . loading import get_model <EOL> from django . forms import ModelForm <EOL> from django . forms . models import BaseModelFormSet , modelformset_factory , save_instance <EOL> from django . contrib . admin . options import InlineModelAdmin , flatten_fieldsets <EOL> from django . utils . encoding import smart_unicode <EOL> class GenericForeignKey ( object ) : <EOL> def __init__ ( self , ct_field = "content_type" , fk_field = "object_id" ) : <EOL> self . ct_field = ct_field <EOL> self . fk_field = fk_field <EOL> def contribute_to_class ( self , cls , name ) : <EOL> self . name = name <EOL> self . model = cls <EOL> self . cache_attr = "_%s_cache" % name <EOL> cls . _meta . add_virtual_field ( self ) <EOL> signals . pre_init . connect ( self . instance_pre_init , sender = cls , weak = False ) <EOL> setattr ( cls , name , self ) <EOL> def instance_pre_init ( self , signal , sender , args , kwargs , ** _kwargs ) : <EOL> if self . name in kwargs : <EOL> value = kwargs . pop ( self . name ) <EOL> kwargs [ self . ct_field ] = self . get_content_type ( obj = value ) <EOL> kwargs [ self . fk_field ] = value . _get_pk_val ( ) <EOL> def get_content_type ( self , obj = None , id = None , using = None ) : <EOL> ContentType = get_model ( "contenttypes" , "contenttype" ) <EOL> if obj : <EOL> return ContentType . objects . db_manager ( obj . _state . db ) . get_for_model ( obj ) <EOL> elif id : <EOL> return ContentType . objects . db_manager ( using ) . get_for_id ( id ) <EOL> else : <EOL> raise Exception ( "" ) <EOL> def __get__ ( self , instance , instance_type = None ) : <EOL> if instance is None : <EOL> return self <EOL> try : <EOL> return getattr ( instance , self . cache_attr ) <EOL> except AttributeError : <EOL> rel_obj = None <EOL> f = self . model . _meta . get_field ( self . ct_field ) <EOL> ct_id = getattr ( instance , f . get_attname ( ) , None ) <EOL> if ct_id : <EOL> ct = self . get_content_type ( id = ct_id , using = instance . _state . db ) <EOL> try : <EOL> rel_obj = ct . get_object_for_this_type ( pk = getattr ( instance , self . fk_field ) ) <EOL> except ObjectDoesNotExist : <EOL> pass <EOL> setattr ( instance , self . cache_attr , rel_obj ) <EOL> return rel_obj <EOL> def __set__ ( self , instance , value ) : <EOL> if instance is None : <EOL> raise AttributeError ( u"" % self . related . opts . object_name ) <EOL> ct = None <EOL> fk = None <EOL> if value is not None : <EOL> ct = self . get_content_type ( obj = value ) <EOL> fk = value . _get_pk_val ( ) <EOL> setattr ( instance , self . ct_field , ct ) <EOL> setattr ( instance , self . fk_field , fk ) <EOL> setattr ( instance , self . cache_attr , value ) <EOL> class GenericRelation ( RelatedField , Field ) : <EOL> def __init__ ( self , to , ** kwargs ) : <EOL> kwargs [ 'verbose_name' ] = kwargs . get ( 'verbose_name' , None ) <EOL> kwargs [ 'rel' ] = GenericRel ( to , <EOL> related_name = kwargs . pop ( 'related_name' , None ) , <EOL> limit_choices_to = kwargs . pop ( '' , None ) , <EOL> symmetrical = kwargs . pop ( 'symmetrical' , True ) ) <EOL> self . object_id_field_name = kwargs . pop ( "" , "object_id" ) <EOL> self . content_type_field_name = kwargs . pop ( "" , "content_type" ) <EOL> kwargs [ 'blank' ] = True <EOL> kwargs [ 'editable' ] = False <EOL> kwargs [ 'serialize' ] = False <EOL> Field . __init__ ( self , ** kwargs ) <EOL> def get_choices_default ( self ) : <EOL> return Field . get_choices ( self , include_blank = False ) <EOL> def value_to_string ( self , obj ) : <EOL> qs = getattr ( obj , self . name ) . all ( ) <EOL> return smart_unicode ( [ instance . _get_pk_val ( ) for instance in qs ] ) <EOL> def m2m_db_table ( self ) : <EOL> return self . rel . to . _meta . db_table <EOL> def m2m_column_name ( self ) : <EOL> return self . object_id_field_name <EOL> def m2m_reverse_name ( self ) : <EOL> return self . rel . to . _meta . pk . column <EOL> def m2m_target_field_name ( self ) : <EOL> return self . model . _meta . pk . name <EOL> def m2m_reverse_target_field_name ( self ) : <EOL> return self . rel . to . _meta . pk . name <EOL> def contribute_to_class ( self , cls , name ) : <EOL> super ( GenericRelation , self ) . contribute_to_class ( cls , name ) <EOL> self . model = cls <EOL> setattr ( cls , self . name , ReverseGenericRelatedObjectsDescriptor ( self ) ) <EOL> def contribute_to_related_class ( self , cls , related ) : <EOL> pass <EOL> def set_attributes_from_rel ( self ) : <EOL> pass <EOL> def get_internal_type ( self ) : <EOL> return "" <EOL> def db_type ( self , connection ) : <EOL> return None <EOL> def extra_filters ( self , pieces , pos , negate ) : <EOL> if negate : <EOL> return [ ] <EOL> ContentType = get_model ( "contenttypes" , "contenttype" ) <EOL> content_type = ContentType . objects . get_for_model ( self . model ) <EOL> prefix = "__" . join ( pieces [ : pos + 1 ] ) <EOL> return [ ( "%s__%s" % ( prefix , self . content_type_field_name ) , <EOL> content_type ) ] <EOL> class ReverseGenericRelatedObjectsDescriptor ( object ) : <EOL> def __init__ ( self , field ) : <EOL> self . field = field <EOL> def __get__ ( self , instance , instance_type = None ) : <EOL> if instance is None : <EOL> return self <EOL> from django . contrib . contenttypes . models import ContentType <EOL> rel_model = self . field . rel . to <EOL> superclass = rel_model . _default_manager . __class__ <EOL> RelatedManager = create_generic_related_manager ( superclass ) <EOL> qn = connection . ops . quote_name <EOL> manager = RelatedManager ( <EOL> model = rel_model , <EOL> instance = instance , <EOL> symmetrical = ( self . field . rel . symmetrical and instance . __class__ == rel_model ) , <EOL> join_table = qn ( self . field . m2m_db_table ( ) ) , <EOL> source_col_name = qn ( self . field . m2m_column_name ( ) ) , <EOL> target_col_name = qn ( self . field . m2m_reverse_name ( ) ) , <EOL> content_type = ContentType . objects . db_manager ( instance . _state . db ) . get_for_model ( instance ) , <EOL> content_type_field_name = self . field . content_type_field_name , <EOL> object_id_field_name = self . field . object_id_field_name <EOL> ) <EOL> return manager <EOL> def __set__ ( self , instance , value ) : <EOL> if instance is None : <EOL> raise AttributeError ( "" ) <EOL> manager = self . __get__ ( instance ) <EOL> manager . clear ( ) <EOL> for obj in value : <EOL> manager . add ( obj ) <EOL> def create_generic_related_manager ( superclass ) : <EOL> class GenericRelatedObjectManager ( superclass ) : <EOL> def __init__ ( self , model = None , core_filters = None , instance = None , symmetrical = None , <EOL> join_table = None , source_col_name = None , target_col_name = None , content_type = None , <EOL> content_type_field_name = None , object_id_field_name = None ) : <EOL> super ( GenericRelatedObjectManager , self ) . __init__ ( ) <EOL> self . core_filters = core_filters or { } <EOL> self . model = model <EOL> self . content_type = content_type <EOL> self . symmetrical = symmetrical <EOL> self . instance = instance <EOL> self . join_table = join_table <EOL> self . join_table = model . _meta . db_table <EOL> self . source_col_name = source_col_name <EOL> self . target_col_name = target_col_name <EOL> self . content_type_field_name = content_type_field_name <EOL> self . object_id_field_name = object_id_field_name <EOL> self . pk_val = self . instance . _get_pk_val ( ) <EOL> def get_query_set ( self ) : <EOL> db = self . _db or router . db_for_read ( self . model , instance = self . instance ) <EOL> query = { <EOL> '%s__pk' % self . content_type_field_name : self . content_type . id , <EOL> '%s__exact' % self . object_id_field_name : self . pk_val , <EOL> } <EOL> return superclass . get_query_set ( self ) . using ( db ) . filter ( ** query ) <EOL> def add ( self , * objs ) : <EOL> for obj in objs : <EOL> if not isinstance ( obj , self . model ) : <EOL> raise TypeError ( "" % self . model . _meta . object_name ) <EOL> setattr ( obj , self . content_type_field_name , self . content_type ) <EOL> setattr ( obj , self . object_id_field_name , self . pk_val ) <EOL> obj . save ( ) <EOL> add . alters_data = True <EOL> def remove ( self , * objs ) : <EOL> db = router . db_for_write ( self . model , instance = self . instance ) <EOL> for obj in objs : <EOL> obj . delete ( using = db ) <EOL> remove . alters_data = True <EOL> def clear ( self ) : <EOL> db = router . db_for_write ( self . model , instance = self . instance ) <EOL> for obj in self . all ( ) : <EOL> obj . delete ( using = db ) <EOL> clear . alters_data = True <EOL> def create ( self , ** kwargs ) : <EOL> kwargs [ self . content_type_field_name ] = self . content_type <EOL> kwargs [ self . object_id_field_name ] = self . pk_val <EOL> db = router . db_for_write ( self . model , instance = self . instance ) <EOL> return super ( GenericRelatedObjectManager , self ) . using ( db ) . create ( ** kwargs ) <EOL> create . alters_data = True <EOL> return GenericRelatedObjectManager <EOL> class GenericRel ( ManyToManyRel ) : <EOL> def __init__ ( self , to , related_name = None , limit_choices_to = None , symmetrical = True ) : <EOL> self . to = to <EOL> self . related_name = related_name <EOL> self . limit_choices_to = limit_choices_to or { } <EOL> self . symmetrical = symmetrical <EOL> self . multiple = True <EOL> self . through = None <EOL> class BaseGenericInlineFormSet ( BaseModelFormSet ) : <EOL> def __init__ ( self , data = None , files = None , instance = None , save_as_new = None , <EOL> prefix = None , queryset = None ) : <EOL> from django . contrib . contenttypes . models import ContentType <EOL> opts = self . model . _meta <EOL> self . instance = instance <EOL> self . rel_name = '-' . join ( ( <EOL> opts . app_label , opts . object_name . lower ( ) , <EOL>
<s> from cloudcafe . common . tools . datagen import rand_name <EOL> from cloudcafe . glance . common . constants import Messages <EOL> from cloudcafe . glance . common . types import ImageMemberStatus , ImageType <EOL> from cloudroast . glance . fixtures import ImagesIntegrationFixture <EOL> class ImageSharing ( ImagesIntegrationFixture ) : <EOL> @ classmethod <EOL> def setUpClass ( cls ) : <EOL> super ( ImageSharing , cls ) . setUpClass ( ) <EOL> cls . alt_one_member_id = cls . images_alt_one . auth . tenant_id <EOL> cls . alt_two_member_id = cls . images_alt_two . auth . tenant_id <EOL> created_images = cls . images . behaviors . create_images_via_task ( <EOL> image_properties = { 'name' : rand_name ( 'image_sharing' ) } , count = 6 ) <EOL> cls . single_member_image = created_images . pop ( ) <EOL> cls . multiple_members_image = created_images . pop ( ) <EOL> cls . delete_access_image = created_images . pop ( ) <EOL> cls . images . client . create_image_member ( <EOL> cls . delete_access_image . id_ , cls . alt_one_member_id ) <EOL> cls . shared_image = created_images . pop ( ) <EOL> cls . images . client . create_image_member ( <EOL> cls . shared_image . id_ , cls . alt_one_member_id ) <EOL> cls . images_alt_one . client . update_image_member ( <EOL> cls . shared_image . id_ , cls . alt_one_member_id , <EOL> ImageMemberStatus . ACCEPTED ) <EOL> image = created_images . pop ( ) <EOL> cls . images . client . create_image_member ( image . id_ , cls . alt_one_member_id ) <EOL> cls . images_alt_one . client . update_image_member ( <EOL> image . id_ , cls . alt_one_member_id , ImageMemberStatus . ACCEPTED ) <EOL> cls . images_admin . client . deactivate_image ( image . id_ ) <EOL> cls . shared_deactivated_image = ( <EOL> cls . images . client . get_image_details ( image . id_ ) . entity ) <EOL> alt_image = created_images . pop ( ) <EOL> cls . images . client . create_image_member ( <EOL> alt_image . id_ , cls . alt_one_member_id ) <EOL> cls . images_alt_one . client . update_image_member ( <EOL> alt_image . id_ , cls . alt_one_member_id , ImageMemberStatus . ACCEPTED ) <EOL> cls . images_admin . client . deactivate_image ( alt_image . id_ ) <EOL> cls . images_admin . client . reactivate_image ( alt_image . id_ ) <EOL> cls . shared_reactivated_image = ( <EOL> cls . images . client . get_image_details ( alt_image . id_ ) . entity ) <EOL> cls . imported_image = cls . images . behaviors . create_image_via_task ( <EOL> image_properties = { 'name' : rand_name ( 'image_sharing' ) } , <EOL> import_from = cls . images . config . import_from_bootable ) <EOL> cls . images . client . create_image_member ( <EOL> cls . imported_image . id_ , cls . alt_one_member_id ) <EOL> cls . snapshot_image = cls . images . behaviors . create_image_via_task ( <EOL> image_properties = { 'name' : rand_name ( 'image_sharing' ) } , <EOL> import_from = cls . images . config . import_from_bootable ) <EOL> cls . images . client . create_image_member ( <EOL> cls . snapshot_image . id_ , cls . alt_one_member_id ) <EOL> cls . snapshot_server = ( <EOL> cls . compute_alt_one_servers_behaviors . create_active_server ( <EOL> name = rand_name ( '' ) , <EOL> image_ref = cls . snapshot_image . id_ ) ) . entity <EOL> cls . resources . add ( <EOL> cls . snapshot_server . id , <EOL> cls . compute_alt_one_servers_client . delete_server ) <EOL> @ classmethod <EOL> def tearDownClass ( cls ) : <EOL> cls . images . behaviors . resources . release ( ) <EOL> cls . resources . release ( ) <EOL> super ( ImageSharing , cls ) . tearDownClass ( ) <EOL> def test_delete_shared_image_accessibility ( self ) : <EOL> resp = self . images . client . get_image_member ( <EOL> self . delete_access_image . id_ , self . alt_one_member_id ) <EOL> self . assertTrue ( resp . ok , Messages . OK_RESP_MSG . format ( resp . status_code ) ) <EOL> get_member = resp . entity <EOL> self . assertEqual ( get_member . status , ImageMemberStatus . PENDING ) <EOL> resp = self . images_alt_one . client . delete_image ( <EOL> self . delete_access_image . id_ ) <EOL> self . assertEqual ( <EOL> resp . status_code , 403 , <EOL> Messages . STATUS_CODE_MSG . format ( 403 , resp . status_code ) ) <EOL> resp = self . images_alt_one . client . update_image_member ( <EOL> self . delete_access_image . id_ , self . alt_one_member_id , <EOL> ImageMemberStatus . ACCEPTED ) <EOL> updated_member = resp . entity <EOL> self . assertEqual ( updated_member . status , ImageMemberStatus . ACCEPTED ) <EOL> resp = self . images_alt_one . client . delete_image ( <EOL> self . delete_access_image . id_ ) <EOL> self . assertEqual ( <EOL> resp . status_code , 403 , <EOL> Messages . STATUS_CODE_MSG . format ( 403 , resp . status_code ) ) <EOL> resp = self . images . client . delete_image ( <EOL> self . delete_access_image . id_ ) <EOL> self . assertTrue ( resp . ok , Messages . OK_RESP_MSG . format ( resp . status_code ) ) <EOL> resp = self . images_alt_one . client . get_image_details ( <EOL> self . delete_access_image . id_ ) <EOL> self . assertEqual ( <EOL> resp . status_code , 404 , <EOL> Messages . STATUS_CODE_MSG . format ( 404 , resp . status_code ) ) <EOL> def test_share_image_with_single_member ( self ) : <EOL> image_member_ids = [ ] <EOL> resp = self . images . client . get_image_details ( <EOL> self . single_member_image . id_ ) <EOL> self . assertTrue ( resp . ok , Messages . OK_RESP_MSG . format ( resp . status_code ) ) <EOL> get_image_as_owner = resp . entity <EOL> errors = self . images . behaviors . validate_image ( get_image_as_owner ) <EOL> self . assertEqual ( <EOL> errors , [ ] , <EOL> msg = ( '' <EOL> 'Received: {0}' ) . format ( errors ) ) <EOL> resp = self . images_alt_one . client . get_image_details ( <EOL> self . single_member_image . id_ ) <EOL> self . assertEqual ( <EOL> resp . status_code , 404 , <EOL> Messages . STATUS_CODE_MSG . format ( 404 , resp . status_code ) ) <EOL> listed_images = self . images_alt_one . behaviors . list_all_images ( ) <EOL> self . assertNotIn ( <EOL> self . single_member_image , listed_images , <EOL> msg = '' <EOL> '' . format ( self . single_member_image ) ) <EOL> resp = self . images . client . create_image_member ( <EOL> self . single_member_image . id_ , self . alt_one_member_id ) <EOL> self . assertTrue ( resp . ok , Messages . OK_RESP_MSG . format ( resp . status_code ) ) <EOL> member = resp . entity <EOL> self . assertEqual ( member . status , ImageMemberStatus . PENDING ) <EOL> resp = self . images_alt_one . client . get_image_details ( <EOL> self . single_member_image . id_ ) <EOL> self . assertTrue ( resp . ok , Messages . OK_RESP_MSG . format ( resp . status_code ) ) <EOL> get_image_as_member = resp . entity <EOL> self . assertEqual ( <EOL> get_image_as_member , get_image_as_owner , <EOL> msg = '' <EOL> '' <EOL> '' . format ( get_image_as_member , <EOL> get_image_as_owner ) ) <EOL> listed_images = self . images_alt_one . behaviors . list_all_images ( ) <EOL> self . assertNotIn ( <EOL> self . single_member_image , listed_images , <EOL> msg = '' <EOL> '' . format ( self . single_member_image ) ) <EOL> resp = self . images_alt_one . client . update_image_member ( <EOL> self . single_member_image . id_ , self . alt_one_member_id , <EOL> ImageMemberStatus . ACCEPTED ) <EOL> updated_member = resp . entity <EOL> self . assertEqual ( updated_member . status , ImageMemberStatus . ACCEPTED ) <EOL> resp = self . images_alt_one . client . get_image_details ( <EOL> self . single_member_image . id_ ) <EOL> self . assertTrue ( resp . ok , Messages . OK_RESP_MSG . format ( resp . status_code ) ) <EOL> get_image_as_member_updated = resp . entity <EOL> self . assertEqual ( <EOL> get_image_as_member_updated , get_image_as_member , <EOL> msg = '' <EOL> '' <EOL> '' . format ( get_image_as_member_updated , <EOL> get_image_as_member ) ) <EOL> listed_images = self . images_alt_one . behaviors . list_all_images ( ) <EOL> self . assertIn ( <EOL> self . single_member_image , listed_images , <EOL> msg = '' <EOL> 'Received: ' <EOL> '' . format ( self . single_member_image ) ) <EOL> resp = self . images . client . list_image_members ( <EOL> self . single_member_image . id_ ) <EOL> self . assertTrue ( resp . ok , Messages . OK_RESP_MSG . format ( resp . status_code ) ) <EOL> listed_image_members = resp . entity <EOL> self . assertEqual ( <EOL> len ( listed_image_members ) , 1 , <EOL> msg = ( '' <EOL> 'Received: {0}' ) . format ( len ( listed_image_members ) ) ) <EOL> [ image_member_ids . append ( image_member . member_id ) <EOL> for image_member in listed_image_members ] <EOL> self . assertIn ( <EOL> self . alt_one_member_id , image_member_ids , <EOL> msg = ( '' <EOL> 'image members ' <EOL> 'Received: {1}' ) . format ( self . alt_one_member_id , <EOL> image_member_ids ) ) <EOL> def test_share_image_with_multiple_members ( self ) : <EOL> image_member_ids = [ ] <EOL> resp = self . images_alt_one . client . get_image_details ( <EOL> self . multiple_members_image . id_ ) <EOL> self . assertEqual ( <EOL> resp . status_code , 404 , <EOL> Messages . STATUS_CODE_MSG . format ( 404 , resp . status_code ) ) <EOL> listed_images = self . images_alt_one . behaviors . list_all_images ( ) <EOL> self . assertNotIn ( <EOL> self . multiple_members_image , listed_images , <EOL> msg = '' <EOL>
<s> import sys , os , textwrap , getopt , re , struct <EOL> class OptDict : <EOL> def __init__ ( self ) : <EOL> self . _opts = { } <EOL> def __setitem__ ( self , k , v ) : <EOL> if k . startswith ( 'no-' ) or k . startswith ( 'no_' ) : <EOL> k = k [ 3 : ] <EOL> v = not v <EOL> self . _opts [ k ] = v <EOL> def __getitem__ ( self , k ) : <EOL> if k . startswith ( 'no-' ) or k . startswith ( 'no_' ) : <EOL> return not self . _opts [ k [ 3 : ] ] <EOL> return self . _opts [ k ] <EOL> def __getattr__ ( self , k ) : <EOL> return self [ k ] <EOL> def _default_onabort ( msg ) : <EOL> sys . exit ( 97 ) <EOL> def _intify ( v ) : <EOL> try : <EOL> vv = int ( v or '' ) <EOL> if str ( vv ) == v : <EOL> return vv <EOL> except ValueError : <EOL> pass <EOL> return v <EOL> def _atoi ( v ) : <EOL> try : <EOL> return int ( v or 0 ) <EOL> except ValueError : <EOL> return 0 <EOL> def _remove_negative_kv ( k , v ) : <EOL> if k . startswith ( 'no-' ) or k . startswith ( 'no_' ) : <EOL> return k [ 3 : ] , not v <EOL> return k , v <EOL> def _remove_negative_k ( k ) : <EOL> return _remove_negative_kv ( k , None ) [ 0 ] <EOL> def _tty_width ( ) : <EOL> s = struct . pack ( "HHHH" , 0 , 0 , 0 , 0 ) <EOL> try : <EOL> import fcntl , termios <EOL> s = fcntl . ioctl ( sys . stderr . fileno ( ) , termios . TIOCGWINSZ , s ) <EOL> except ( IOError , ImportError ) : <EOL> return _atoi ( os . environ . get ( 'WIDTH' ) ) or 70 <EOL> ( ysize , xsize
<s> import objc <EOL> from AddressBook import * <EOL> import re <EOL> from time import time , gmtime <EOL> from urllib import quote <EOL> import json <EOL> from Utilities import * <EOL> from Provider import * <EOL> Provider . addProvider ( "BasicProvider" ) <EOL> Provider . addProvider ( "" ) <EOL> Provider . addProvider ( "" ) <EOL> Provider . addProvider ( "DopplrProvider" ) <EOL> Provider . addProvider ( "LastFmProvider" ) <EOL> Provider . addProvider ( "FlickrProvider" ) <EOL> Provider . addProvider ( "FeedProvider" ) <EOL> class Clue ( object ) : <EOL> CACHE = { } <EOL> @ classmethod <EOL> def forPerson ( cls , person ) : <EOL> if person . uniqueId ( ) in Clue . CACHE : <EOL> print_info ( "" ) <EOL> return Clue . CACHE [ person . uniqueId ( ) ] <EOL> print_info ( "" ) <EOL> Clue . CACHE [ person . uniqueId ( ) ] = Clue ( person ) <EOL> return Clue . CACHE [ person . uniqueId ( ) ] <EOL> @ classmethod <EOL> def forUrl ( cls , url ) : <EOL> for clue in Clue . CACHE . values ( ) : <EOL> if normalize_url ( url ) in [ normalize_url ( u ) for u in clue . urls ( ) ] : <EOL> return clue <EOL> def __init__ ( self , person ) : <EOL> self . person = person <EOL> self . delegate = None <EOL> self . extra_urls = [ ] <EOL> if NSUserDefaults . standardUserDefaults ( ) . boolForKey_ ( "" ) : <EOL> self . getMoreUrls ( ) <EOL> self . providers = [ cls ( self ) for cls in Provider . providers ( ) ] <EOL> def setDelegate_ ( self , delegate ) : <EOL> self . delegate = delegate <EOL> def start ( self ) : <EOL> self . boring_urls = self . urls ( ) <EOL> for provider in self . providers : <EOL> provider . provide ( ) <EOL> self . changed ( ) <EOL> def getMoreUrls ( self ) : <EOL> if not self . ab_urls ( ) : return <EOL> api = "" + "," . join ( [ quote ( url ) for url in self . ab_urls ( ) ] ) <EOL> print_info ( "" + api ) <EOL> Cache . getContentOfUrlAndCallback ( callback = self . gotSocialGraphData , url = api , timeout = 3600 * 48 , wantStale = False , delay = 2 ) <EOL> def gotSocialGraphData ( self , raw , isStale ) : <EOL> try : <EOL> data = json . loads ( raw ) <EOL> except ValueError : <EOL> return <EOL> urls = data [ 'nodes' ] . keys ( ) <EOL> self . addExtraUrls ( urls ) <EOL> self . start ( ) <EOL> def addExtraUrls ( self , urls ) : <EOL> if not urls : return <EOL> dedupe = { } <EOL> for url in self . extra_urls + urls : <EOL> if re . match ( r'http' , url ) : <EOL> if not normalize_url ( url ) in dedupe : <EOL> dedupe [ normalize_url ( url ) ] = url <EOL> self . extra_urls = dedupe . values ( ) <EOL> known_urls = [ normalize_url ( url ) for url in self . ab_urls ( ) ] <EOL> for url in [ u for u in self . extra_urls ] : <EOL> if normalize_url ( url ) in known_urls : <EOL> self . extra_urls . remove ( url ) <EOL> print_info ( "" % ( ", " . join ( self . ab_urls ( ) ) ) ) <EOL> print_info ( "" % ( ", " . join ( self . extra_urls ) ) ) <EOL> def changed ( self ) : <EOL> if self . delegate : <EOL> self . delegate . updateWebContent_fromClue_ ( self . content ( ) , self ) <EOL> def content ( self ) : <EOL> atoms = [ ] <EOL> for p in self . providers : <EOL> atoms += p . atoms <EOL> atoms . sort ( lambda a , b : cmp ( b . sortOrder ( ) , a . sortOrder ( ) ) ) <EOL> content = "" . join ( [ atom . content ( ) for atom in atoms ] ) <EOL> if content : return content <EOL> return "" <EOL> def stop ( self ) : <EOL> NSObject . cancelPreviousPerformRequestsWithTarget_ ( self ) <EOL> for current in self . providers : <EOL> current . stop ( ) <EOL> def takeUrls ( self , pattern ) : <EOL> interesting = [ ] <EOL> for u in self . urls ( ) : <EOL> if re . search ( pattern , u ) : <EOL> interesting . append ( u ) <EOL> for u in interesting : <EOL> if u in self . boring_urls : <EOL> self . boring_urls . remove ( u ) <EOL> return interesting <EOL> def __eq__ ( self , other ) : <EOL>
<s> from sympy . polys . polyfuncs import ( <EOL> symmetrize , horner , interpolate , rational_interpolate , viete , <EOL> ) <EOL> from sympy . polys . polyerrors import ( <EOL> MultivariatePolynomialError , <EOL> ) <EOL> from sympy import symbols <EOL> from sympy . utilities . pytest import raises <EOL> from sympy . abc import a , b , c , d , e , x , y , z <EOL> def test_symmetrize ( ) : <EOL> assert symmetrize ( 0 , x , y , z ) == ( 0 , 0 ) <EOL> assert symmetrize ( 1 , x , y , z ) == ( 1 , 0 ) <EOL> s1 = x + y + z <EOL> s2 = x * y + x * z + y * z <EOL> s3 = x * y * z <EOL> assert symmetrize ( 1 ) == ( 1 , 0 ) <EOL> assert symmetrize ( 1 , formal = True ) == ( 1 , 0 , [ ] ) <EOL> assert symmetrize ( x ) == ( x , 0 ) <EOL> assert symmetrize ( x + 1 ) == ( x + 1 , 0 ) <EOL> assert symmetrize ( x , x , y ) == ( x + y , - y ) <EOL> assert symmetrize ( x + 1 , x , y ) == ( x + y + 1 , - y ) <EOL> assert symmetrize ( x , x , y , z ) == ( s1 , - y - z ) <EOL> assert symmetrize ( x + 1 , x , y , z ) == ( s1 + 1 , - y - z ) <EOL> assert symmetrize ( x ** 2 , x , y , z ) == ( s1 ** 2 - 2 * s2 , - y ** 2 - z ** 2 ) <EOL> assert symmetrize ( x ** 2 + y ** 2 ) == ( - 2 * x * y + ( x + y ) ** 2 , 0 ) <EOL> assert symmetrize ( x ** 2 - y ** 2 ) == ( - 2 * x * y + ( x + y ) ** 2 , - 2 * y ** 2 ) <EOL> assert symmetrize ( x ** 3 + y ** 2 + a * x ** 2 + b * y ** 3 , x , y ) == ( - 3 * x * y * ( x + y ) - 2 * a * x * y + a * ( x + y ) ** 2 + ( x + y ) ** 3 , <EOL> y ** 2 * ( 1 - a ) + y ** 3 * ( b - 1 ) ) <EOL> U = [ u0 , u1 , u2 ] = symbols ( 'u:3' ) <EOL> assert symmetrize ( x + 1 , x , y , z , formal = True , symbols = U ) == ( u0 + 1 , - y - z , [ ( u0 , x + y + z ) , ( u1 , x * y + x * z + y * z ) , ( u2 , x * y * z ) ] ) <EOL> assert symmetrize ( [ 1 , 2 , 3 ] ) == [ ( 1 , 0 ) , ( 2 , 0 ) , ( 3 , 0 ) ] <EOL> assert symmetrize ( [ 1 , 2 , 3 ] , formal = True ) == ( [ ( 1 , 0 ) , ( 2 , 0 ) , ( 3 , 0 ) ] , [ ] ) <EOL> assert symmetrize ( [ x + y , x - y ] ) == [ ( x + y , 0 ) , ( x + y , - 2 * y ) ] <EOL> def test_horner ( ) : <EOL> assert horner ( 0 ) == 0 <EOL> assert horner ( 1 ) == 1 <EOL> assert horner ( x ) == x <EOL> assert horner ( x + 1 ) == x + 1 <EOL> assert horner ( x ** 2 + 1 ) == x ** 2 + 1 <EOL> assert horner ( x ** 2 + x ) == ( x + 1 ) * x <EOL> assert horner ( x ** 2 + x + 1 ) == ( x + 1 ) * x + 1 <EOL> assert horner ( <EOL> 9 * x ** 4 + 8 * x ** 3 + 7 * x ** 2 + 6 * x + 5 ) ==
<s> def selection_sort ( a ) : <EOL> for i in range ( len ( a ) ) : <EOL> for j in range ( i , len ( a ) ) : <EOL> if ( a [ j ] < a [ i ] ) : <EOL> a [ i ] , a
<s> from django . core import validators <EOL> from django . db import models <EOL> from django . contrib . sites . models import Site <EOL> from django . utils . translation import gettext_lazy as _ <EOL> class FlatPage ( models . Model ) : <EOL> url = models . CharField ( _ ( 'URL' ) , maxlength = 100 , validator_list = [ validators . isAlphaNumericURL ] , <EOL> help_text = _ (
<s> from . setup import TestPygletGUI <EOL> from pyglet_gui . core import Viewer <EOL> from pyglet_gui . manager import Manager <EOL> from pyglet_gui . containers import VerticalContainer <EOL> class TestVerticalContainer ( TestPygletGUI ) : <EOL> def setUp ( self ) : <EOL> super ( TestVerticalContainer , self ) . setUp ( ) <EOL> self . container = VerticalContainer ( [ Viewer ( width = 50 , height = 50 ) , <EOL> Viewer ( width = 50 , height = 50 ) ] ) <EOL> self . manager = Manager ( self . container , window = self . window , batch = self . batch , theme = self . theme ) <EOL> def _test_content_position ( self ) : <EOL> self . assertEqual ( self . container . content [ 0 ] . y , <EOL> self . container . y + self . container . height - self . container . content [ 0 ] . height ) <EOL> self . assertEqual ( self . container . content [ 1 ] . y , <EOL> self . container . y + self .
<s> import sys <EOL> import os <EOL> import shlex <EOL> import re <EOL> import sphinx_rtd_theme <EOL> extensions = [ ] <EOL> templates_path = [ '_templates' ] <EOL> source_suffix = '.rst' <EOL> master_doc = 'index' <EOL> project = u'prettyconf' <EOL> copyright = u'' <EOL> author = u'' <EOL> _here = os . path . abspath ( os . path . dirname ( __file__ ) ) <EOL> version = '0.0.0' <EOL> with open ( os . path . join ( _here , "../.." , "CHANGES.txt" ) ) as changes : <EOL> for line in changes : <EOL> version = line . strip ( ) <EOL> if re . search ( '' , version ) : <EOL> break <EOL> release = version <EOL> language = None <EOL> exclude_patterns = [ ] <EOL> pygments_style = 'sphinx' <EOL> todo_include_todos = False <EOL> html_theme = "" <EOL> html_theme_path = [ sphinx_rtd_theme . get_html_theme_path ( ) ] <EOL> html_static_path = [ '_static' ] <EOL> htmlhelp_basename = 'prettyconfdoc' <EOL>
<s> from __future__ import absolute_import <EOL> from collections import namedtuple <EOL> import logging <EOL> from multiprocessing import Process , Manager as MPManager <EOL> import time <EOL> import warnings <EOL> from six . moves import queue <EOL> from . . common import KafkaError <EOL> from . base import ( <EOL> Consumer , <EOL> AUTO_COMMIT_MSG_COUNT , AUTO_COMMIT_INTERVAL , <EOL> NO_MESSAGES_WAIT_TIME_SECONDS , <EOL> FULL_QUEUE_WAIT_TIME_SECONDS , <EOL> MAX_BACKOFF_SECONDS , <EOL> ) <EOL> from . simple import SimpleConsumer <EOL> log = logging . getLogger ( __name__ ) <EOL> Events = namedtuple ( "Events" , [ "start" , "pause" , "exit" ] ) <EOL> def _mp_consume ( client , group , topic , message_queue , size , events , ** consumer_options ) : <EOL> interval = 1 <EOL> while not events . exit . is_set ( ) : <EOL> try : <EOL> client . reinit ( ) <EOL> consumer = SimpleConsumer ( client , group , topic , <EOL> auto_commit = False , <EOL> auto_commit_every_n = None , <EOL> auto_commit_every_t = None , <EOL> ** consumer_options ) <EOL> consumer . provide_partition_info ( ) <EOL> while True : <EOL> events . start . wait ( ) <EOL> if events . exit . is_set ( ) : <EOL> break <EOL> count = 0 <EOL> message = consumer . get_message ( ) <EOL> if message : <EOL> while True : <EOL> try : <EOL> message_queue . put ( message , timeout = FULL_QUEUE_WAIT_TIME_SECONDS ) <EOL> break <EOL> except queue . Full : <EOL> if events . exit . is_set ( ) : break <EOL> count += 1 <EOL> if count == size . value : <EOL> events . pause . wait ( ) <EOL> else : <EOL> time . sleep ( NO_MESSAGES_WAIT_TIME_SECONDS ) <EOL> consumer . stop ( ) <EOL> except KafkaError as e : <EOL> log . error ( "" % ( e , interval ) ) <EOL> time . sleep ( interval ) <EOL> interval = interval * 2 if interval * 2 < MAX_BACKOFF_SECONDS else MAX_BACKOFF_SECONDS <EOL> class MultiProcessConsumer ( Consumer ) : <EOL> def __init__ ( self , client , group , topic , <EOL> partitions = None , <EOL> auto_commit = True , <EOL> auto_commit_every_n = AUTO_COMMIT_MSG_COUNT , <EOL> auto_commit_every_t = AUTO_COMMIT_INTERVAL , <EOL> num_procs = 1 , <EOL> partitions_per_proc = 0 , <EOL> ** simple_consumer_options ) : <EOL> warnings . warn ( '' <EOL> '' , <EOL> DeprecationWarning ) <EOL> super ( MultiProcessConsumer , self ) . __init__ ( <EOL> client , group , topic , <EOL> partitions = partitions , <EOL> auto_commit = auto_commit , <EOL> auto_commit_every_n = auto_commit_every_n , <EOL> auto_commit_every_t = auto_commit_every_t ) <EOL> manager = MPManager ( ) <EOL> self . queue = manager . Queue ( 1024 ) <EOL> self . events = Events ( <EOL> start = manager . Event ( ) , <EOL> exit = manager . Event ( ) , <EOL> pause = manager . Event ( ) ) <EOL> self . size = manager . Value ( 'i' , 0 ) <EOL> partitions = list ( self . offsets . copy ( ) . keys ( ) ) <EOL> if partitions_per_proc : <EOL> num_procs = len ( partitions ) / partitions_per_proc <EOL> if num_procs * partitions_per_proc < len ( partitions ) : <EOL> num_procs += 1 <EOL> chunks = [ partitions [ proc : : num_procs ] for proc in range ( num_procs ) ] <EOL> self . procs = [ ] <EOL> for chunk in chunks : <EOL> options = { 'partitions' : list ( chunk ) } <EOL> if simple_consumer_options : <EOL> simple_consumer_options . pop ( 'partitions' , None ) <EOL> options . update ( simple_consumer_options ) <EOL> args = ( client . copy ( ) , self . group , self . topic , self . queue , <EOL> self . size , self . events ) <EOL> proc = Process ( target = _mp_consume , args = args , kwargs = options ) <EOL> proc . daemon = True <EOL> proc . start ( ) <EOL> self . procs . append ( proc ) <EOL> def __repr__ ( self ) : <EOL> return '' % ( self . group , self . topic , len ( self . procs ) ) <EOL> def stop ( self ) : <EOL> self . events . exit . set ( ) <EOL> self . events . pause . set ( ) <EOL> self . events . start . set ( ) <EOL> for proc in self . procs : <EOL> proc . join ( ) <EOL> proc . terminate ( ) <EOL> super ( MultiProcessConsumer , self ) . stop ( ) <EOL> def __iter__ ( self ) : <EOL> self . size . value = 0 <EOL>
<s> from django . test import TestCase <EOL> from seed . models import CanonicalBuilding <EOL> from surveys . models import ( <EOL> Survey , <EOL> SurveyQuestion , <EOL> SurveyAnswer , <EOL> SurveyBuilding , <EOL> ) <EOL> class TestSurveyModels ( TestCase ) : <EOL> def setUp ( self ) : <EOL>
<s> import numpy as np <EOL> from scipy import ndimage <EOL> import mahotas . center_of_mass <EOL> np . random . seed ( 2321 ) <EOL> def _mean_out ( img , axis ) : <EOL> if len ( img . shape ) == 2 : return img . mean ( 1 - axis ) <EOL> if axis == 0 : <EOL> return _mean_out ( img . mean ( 1 ) , 0 ) <EOL> return _mean_out ( img . mean ( 0 ) , axis - 1 ) <EOL> def slow_center_of_mass ( img ) : <EOL> xs = [ ] <EOL> for axis , si in enumerate ( img . shape ) : <EOL> xs . append ( np . mean ( _mean_out ( img , axis ) * np . arange ( si ) ) ) <EOL> xs = np . array ( xs ) <EOL> xs /= img . mean ( ) <EOL> return xs <EOL> def test_cmp_ndimage ( ) : <EOL> R = ( 255 * np . random . rand ( 128 , 256 ) ) . astype ( np . uint16 ) <EOL> R += np . arange ( 256 , dtype = np .
<s> import datetime <EOL> from south . db import db <EOL> from south . v2 import SchemaMigration <EOL> from django . db import models <EOL> class Migration ( SchemaMigration ) : <EOL> def forwards ( self , orm ) : <EOL> pass <EOL> def backwards ( self , orm ) : <EOL> pass <EOL> models = { <EOL> u'auth.group' : { <EOL> 'Meta' : { 'object_name' : 'Group' } , <EOL> u'id' : ( '' , [ ] , { 'primary_key' : 'True' } ) , <EOL> 'name' : ( '' , [ ] , { 'unique' : 'True' , 'max_length' : '80' } ) , <EOL> 'permissions' : ( '' , [ ] , { 'to' : u"" , 'symmetrical' : 'False' , 'blank' : 'True' } ) <EOL> } , <EOL> u'' : { <EOL> 'Meta' : { 'ordering' : "" , '' : "" , 'object_name' : 'Permission' } , <EOL> 'codename' : ( '' , [ ] , { 'max_length' : '100' } ) , <EOL> 'content_type' : ( '' , [ ] , { 'to' : u"" } ) , <EOL> u'id' : ( '' , [ ] , { 'primary_key' : 'True' } ) , <EOL> 'name' : ( '' , [ ] , { 'max_length' : '50' } ) <EOL> } , <EOL> 'sentry.user' : { <EOL> 'Meta' : { 'object_name' : 'User' , 'db_table' : "'auth_user'" } , <EOL> 'date_joined' : ( '' , [ ] , { 'default' : '' } ) , <EOL> 'email' : ( '' , [ ] , { 'max_length' : '75' , 'blank' : 'True' } ) , <EOL> 'first_name' : ( '' , [ ] , { 'max_length' : '30' , 'blank' : 'True' } ) , <EOL> 'id' : ( '' , [ ] , { 'primary_key' : 'True' } ) , <EOL> 'is_active' : ( '' , [ ] , { 'default' : 'True' } ) , <EOL> 'is_staff' : ( '' , [ ] , { 'default' : 'False' } ) , <EOL> 'is_superuser' : ( '' , [ ] , { 'default' : 'False' } ) , <EOL> 'last_login' : ( '' , [ ] , { 'default' : '' } ) , <EOL> 'last_name' : ( '' , [ ] , { 'max_length' : '30' , 'blank' : 'True' } ) , <EOL> 'password' : ( '' , [ ] , { 'max_length' : '128' } ) , <EOL> 'username' : ( '' , [ ] , { 'unique' : 'True' , 'max_length' : '30' } ) <EOL> } , <EOL> u'' : { <EOL> 'Meta' : { 'ordering' : "('name',)" , '' : "" , 'object_name' : 'ContentType' , 'db_table' : "" } , <EOL> 'app_label' : ( '' , [ ] , { 'max_length' : '100' } ) , <EOL> u'id' : ( '' , [ ] , { 'primary_key' : 'True' } ) , <EOL> 'model' : ( '' , [ ] , { 'max_length' : '100' } ) , <EOL> 'name' : ( '' , [ ] , { 'max_length' : '100' } ) <EOL> } , <EOL> u'' : { <EOL> 'Meta' : { '' : "" , 'object_name' : 'AccessGroup' } , <EOL> 'data' : ( '' , [ ] , { 'null' : 'True' , 'blank' : 'True' } ) , <EOL> 'date_added' : ( '' , [ ] , { 'default' : '' } ) , <EOL> 'id' : ( '' , [ ] , { 'primary_key' : 'True' } ) , <EOL> 'managed' : ( '' , [ ] , { 'default' : 'False' } ) , <EOL> 'members' : ( '' , [ ] , { 'to' : u"" , 'symmetrical' : 'False' } ) , <EOL> 'name' : ( '' , [ ] , { 'max_length' : '64' } ) , <EOL> 'projects' : ( '' , [ ] , { 'to' : u"" , 'symmetrical' : 'False' } ) , <EOL> 'team' : ( '' , [ ] , { 'to' : u"" } ) , <EOL> 'type' : ( '' , [ ] , { 'default' : '50' } ) <EOL> } , <EOL> u'' : { <EOL> 'Meta' : { 'object_name' : 'Activity' } , <EOL> 'data' : ( '' , [ ] , { 'null' : 'True' } ) , <EOL> 'datetime' : ( '' , [ ] , { 'default' : '' } ) , <EOL> 'event' : ( '' , [ ] , { 'to' : u"" , 'null' : 'True' } ) , <EOL> 'group' : ( '' , [ ] , { 'to' : u"" , 'null' : 'True' } ) , <EOL> 'id' : ( '' , [ ] , { 'primary_key' : 'True' } ) , <EOL> 'ident' : ( '' , [ ] , { 'max_length' : '64' , 'null' : 'True' } ) , <EOL> 'project' : ( '' , [ ] , { 'to' : u"" } ) , <EOL> 'type' : ( '' , [ ] , { } ) , <EOL> 'user' : ( '' , [ ] , { 'to' : u"" , 'null' : 'True' } ) <EOL> } , <EOL> u'sentry.alert' : { <EOL> 'Meta' : { 'object_name' : 'Alert' } , <EOL> 'data' : ( '' , [ ] , { 'null' : 'True' } ) , <EOL> 'datetime' : ( '' , [ ] , { 'default' : '' } ) , <EOL> 'group' : ( '' , [ ] , { 'to' : u"" , 'null' : 'True' } ) , <EOL> 'id' : ( '' , [ ] , { 'primary_key' : 'True' } ) , <EOL> 'message' : ( '' , [ ] , { } ) , <EOL> 'project' : ( '' , [ ] , { 'to' : u"" } ) , <EOL> 'related_groups' : ( '' , [ ] , { 'related_name' : "" , 'symmetrical' : 'False' , 'through' : u"" , 'to' : u"" } ) , <EOL> 'status' : ( '' , [ ] , { 'default' : '0' , 'db_index' : 'True' } ) <EOL> } , <EOL> u'' : { <EOL> 'Meta' : { '' : "" , 'object_name' : '' } , <EOL> 'alert' : ( '' , [ ] , { 'to' : u"" } ) , <EOL> 'data' : ( '' , [ ] , { 'null' : 'True' } ) , <EOL> 'group' : ( '' , [ ] , { 'to' : u"" } ) , <EOL> 'id' : ( '' , [ ] , { 'primary_key' : 'True' } ) <EOL> } , <EOL> u'sentry.event' : { <EOL> 'Meta' : { '' : "" , 'object_name' : 'Event' , 'db_table' : "" } , <EOL> 'checksum' : ( '' , [ ] , { 'max_length' : '32' , 'db_index' : 'True' } ) , <EOL> 'culprit' : ( '' , [ ] , { 'max_length' : '200' , 'null' : 'True' , 'db_column' : "'view'" , 'blank' : 'True' } ) , <EOL> 'data' : ( '' , [ ] , { 'null' : 'True' , 'blank' : 'True' } ) , <EOL> 'datetime' : ( '' , [ ] , { 'default' : '' , 'db_index' : 'True' } ) , <EOL> 'event_id' : ( '' , [ ] , { 'max_length' : '32' , 'null' : 'True' , 'db_column' : "'message_id'" } ) , <EOL> 'group' : ( '' , [ ] , { 'blank' : 'True' , 'related_name' : "'event_set'" , 'null' : 'True' , 'to' : u"" } ) , <EOL> 'id' : ( '' , [ ] , { 'primary_key' : 'True' } ) , <EOL> 'level' : ( '' , [ ] , { 'default' : '40' , 'db_index' : 'True' , 'blank' : 'True' } ) , <EOL> 'logger' : ( '' , [ ] , { 'default' : "'root'" , 'max_length' : '64' , 'db_index' : 'True' , 'blank' : 'True' } ) , <EOL> 'message' : ( '' , [ ] , { } ) , <EOL> 'num_comments' : ( '' , [ ] , { 'default' : '0' , 'null' : 'True' } ) , <EOL> 'platform' : ( '' , [ ] , { 'max_length' : '64' , 'null' : 'True' } ) , <EOL> 'project' : ( '' , [ ] , { 'to' : u"" , 'null' : 'True' } ) , <EOL> 'server_name' : ( '' , [ ] , { 'max_length' : '128' , 'null' : 'True' , 'db_index' : 'True' } ) , <EOL> 'site' : ( '' , [ ] , { 'max_length' : '128' , 'null' : 'True' , 'db_index' : 'True' } ) , <EOL> 'time_spent' : ( '' , [ ] , { 'null' : 'True' } ) <EOL> } , <EOL> u'' : { <EOL> 'Meta' : { '' : "" , 'object_name' : 'EventMapping' } , <EOL> 'date_added' : (
<s> from __future__ import absolute_import , unicode_literals <EOL> import mock <EOL> from django . test import TestCase <EOL> from physical . tests import factory as factory_physical <EOL> from drivers . fake import FakeDriver <EOL> from . . models import Credential <EOL> from . import factory as factory_logical <EOL> class CredentialTestCase ( TestCase ) : <EOL> def setUp ( self ) : <EOL> self . instance = factory_physical . InstanceFactory ( ) <EOL> self . databaseinfra = self . instance . databaseinfra <EOL> self . database = factory_logical . DatabaseFactory ( <EOL> databaseinfra = self . databaseinfra ) <EOL> def tearDown ( self ) : <EOL> self . database . delete ( ) <EOL> def test_create_credential ( self ) : <EOL> credential = Credential . objects . create ( <EOL> user = "super" , password = "super" , database = self . database ) <EOL> self . assertTrue ( credential . pk ) <EOL> def test_slugify_user_credential ( self ) : <EOL> credential = Credential .
<s> from suds . client import Client as SudsClient <EOL> from suds . sax . element import Element <EOL> wsse = ( 'wsse' , '' ) <EOL> security = Element ( 'Security' , ns = wsse ) <EOL> usernametoken = Element ( 'UsernameToken' , ns = wsse ) <EOL> uname = Element ( 'Username' , ns = wsse ) . setText ( 'myusername' ) <EOL> passwd = Element
<s> from south . utils import datetime_utils as datetime <EOL> from south . db import db <EOL> from south . v2 import SchemaMigration <EOL> from django . db import models <EOL> class Migration ( SchemaMigration ) : <EOL> def forwards ( self , orm ) : <EOL> db . delete_table ( u'' ) <EOL> db . delete_table ( db . shorten_name ( u'' ) ) <EOL> db . delete_table ( u'' ) <EOL> db . delete_table ( db . shorten_name ( u'' ) ) <EOL> def backwards ( self , orm ) : <EOL> raise RuntimeError ( "" ) <EOL> models = { <EOL> u'auth.group' : { <EOL> 'Meta' : { 'object_name' : 'Group' } , <EOL> u'id' : ( '' , [ ] , { 'primary_key' : 'True' } ) , <EOL> 'name' : ( '' , [ ] , { 'unique' : 'True' , 'max_length' : '80' } ) , <EOL> 'permissions' : ( '' , [ ] , { 'to' : u"" , 'symmetrical' : 'False' , 'blank' : 'True' } ) <EOL> } , <EOL> u'' : { <EOL> 'Meta' : { 'ordering' : "" , '' : "" , 'object_name' : 'Permission' } , <EOL> 'codename' : ( '' , [ ] , { 'max_length' : '100' } ) , <EOL> 'content_type' : ( '' , [ ] , { 'to' : u"" } ) , <EOL> u'id' : ( '' , [ ] , { 'primary_key' : 'True' } ) , <EOL> 'name' : ( '' , [ ] , { 'max_length' : '50' } ) <EOL> } , <EOL> u'auth.user' : { <EOL> 'Meta' : { 'object_name' : 'User' } , <EOL> 'date_joined' : ( '' , [ ] , { 'default' : '' } ) , <EOL> 'email' : ( '' , [ ] , { 'max_length' : '75' , 'blank' : 'True' } ) , <EOL> 'first_name' : ( '' , [ ] , { 'max_length' : '30' , 'blank'
<s> from __future__ import absolute_import <EOL> import glob <EOL> import sys <EOL> import os <EOL> import salt . utils <EOL> from ctypes import cdll , c_char_p , c_int , c_void_p , pointer , create_string_buffer <EOL> from ctypes . util import find_library <EOL> def _load_libcrypto ( ) : <EOL> if sys . platform . startswith ( 'win' ) : <EOL> return cdll . LoadLibrary ( 'libeay32' ) <EOL> elif getattr ( sys , 'frozen' , False ) and salt . utils . is_smartos ( ) : <EOL> return cdll . LoadLibrary ( glob . glob ( os . path . join ( <EOL> os . path . dirname ( sys . executable ) , <EOL> 'libcrypto.so*' ) ) [ 0 ] ) <EOL> else : <EOL> lib = find_library ( 'crypto' ) <EOL> if not lib and salt . utils . is_smartos ( ) : <EOL> lib = glob . glob ( os . path . join ( <EOL> '/opt/local/lib' , <EOL> 'libcrypto.so*' ) ) <EOL> lib = lib [ 0 ] if len ( lib ) > 0 else None <EOL> if lib : <EOL> return cdll . LoadLibrary ( lib ) <EOL> raise OSError ( '' ) <EOL> def _init_libcrypto ( ) : <EOL> libcrypto = _load_libcrypto ( ) <EOL> libcrypto . RSA_new . argtypes = ( ) <EOL> libcrypto . RSA_new . restype = c_void_p <EOL> libcrypto . RSA_free . argtypes = ( c_void_p , ) <EOL> libcrypto . RSA_size . argtype = ( c_void_p ) <EOL> libcrypto . BIO_new_mem_buf . argtypes = ( c_char_p , c_int ) <EOL> libcrypto . BIO_new_mem_buf . restype = c_void_p <EOL> libcrypto . BIO_free . argtypes = ( c_void_p , ) <EOL> libcrypto . PEM_read_bio_RSAPrivateKey . argtypes = ( c_void_p , c_void_p , c_void_p , c_void_p ) <EOL> libcrypto . PEM_read_bio_RSAPrivateKey . restype = c_void_p <EOL> libcrypto . PEM_read_bio_RSA_PUBKEY . argtypes = ( c_void_p , c_void_p , c_void_p , c_void_p ) <EOL> libcrypto . PEM_read_bio_RSA_PUBKEY . restype = c_void_p <EOL> libcrypto . RSA_private_encrypt . argtypes = ( c_int , c_char_p , c_char_p , c_void_p , c_int ) <EOL> libcrypto . RSA_public_decrypt . argtypes = ( c_int , c_char_p , c_char_p , c_void_p , c_int ) <EOL> libcrypto . OPENSSL_no_config ( ) <EOL> libcrypto . OPENSSL_add_all_algorithms_noconf ( ) <EOL> return libcrypto <EOL> libcrypto = _init_libcrypto ( ) <EOL> RSA_X931_PADDING = 5 <EOL> class RSAX931Signer ( object ) : <EOL> def __init__ ( self , keydata ) : <EOL> keydata = salt . utils . to_bytes ( keydata , 'ascii' ) <EOL> self . _bio = libcrypto . BIO_new_mem_buf ( keydata , len ( keydata ) ) <EOL> self . _rsa = c_void_p ( libcrypto . RSA_new ( ) ) <EOL> if not libcrypto . PEM_read_bio_RSAPrivateKey ( self . _bio , pointer ( self . _rsa ) , None , None ) : <EOL> raise ValueError ( '' ) <EOL> def __del__ ( self ) : <EOL> libcrypto . BIO_free ( self . _bio ) <EOL> libcrypto . RSA_free ( self . _rsa ) <EOL> def sign ( self , msg ) : <EOL> buf = create_string_buffer ( libcrypto . RSA_size ( self . _rsa ) ) <EOL> msg = salt . utils . to_bytes ( msg ) <EOL> size = libcrypto . RSA_private_encrypt ( len ( msg ) , msg , buf , self . _rsa , RSA_X931_PADDING ) <EOL> if size < 0 : <EOL>
<s> import time <EOL> import os <EOL> from stat import S_IFDIR <EOL> from errno import ENOENT <EOL> from fuse import FuseOSError <EOL> from gitfs . log import log <EOL> from gitfs . cache import lru_cache <EOL> from . read_only import ReadOnlyView <EOL> class HistoryView ( ReadOnlyView ) : <EOL> def getattr ( self , path , fh = None ) : <EOL> if path not in self . repo . get_commit_dates ( ) and path != '/' : <EOL> raise FuseOSError ( ENOENT ) <EOL> attrs = super ( HistoryView , self ) . getattr ( path , fh ) <EOL> attrs . update ( { <EOL> 'st_mode' : S_IFDIR | 0o555 , <EOL> 'st_nlink' : 2 , <EOL> 'st_ctime' : self . _get_first_commit_time ( ) , <EOL> 'st_mtime' : self . _get_last_commit_time ( ) , <EOL> } ) <EOL> return attrs <EOL> def access ( self , path , mode ) : <EOL> if getattr ( self , 'date' , None ) : <EOL> log . info ( 'PATH: %s' , path ) <EOL> if path == '/' : <EOL> available_dates = self . repo . get_commit_dates ( ) <EOL> if self . date not in available_dates : <EOL> raise FuseOSError ( ENOENT ) <EOL> else : <EOL> commits = self . repo . get_commits_by_date ( self . date ) <EOL> dirname = os .
<s> import os <EOL> import qisys . sh <EOL> from qidoc . test . test_qidoc_build import write_french_po <EOL> def test_install_translated ( qidoc_action , tmpdir ) : <EOL> translateme_proj = qidoc_action . add_test_project ( "translateme" ) <EOL> qidoc_action ( "intl-update" , "translateme" ) <EOL> write_french_po ( translateme_proj . path ) <EOL> qidoc_action ( "install" , "translateme" , tmpdir . strpath , "--language" , "fr" ) <EOL> index_html = tmpdir . join ( "index.html" ) <EOL> assert "Bienvenue" in index_html . read ( ) <EOL>
<s> from __future__ import absolute_import , print_function , division <EOL> import numpy <EOL> import unittest <EOL> import theano <EOL> from theano . tensor import Tensor , TensorType <EOL> from theano . compile . sharedvalue import shared <EOL> from theano . compile . sharedvalue import SharedVariable <EOL> from theano . compile . sharedvalue import generic <EOL> class Test_SharedVariable ( unittest . TestCase ) : <EOL> def test_ctors ( self ) : <EOL> if theano . configdefaults . python_int_bitwidth ( ) == 32 : <EOL> assert shared ( 7 ) . type == theano . tensor . iscalar , shared ( 7 ) . type <EOL> else : <EOL> assert shared ( 7 ) . type == theano . tensor . lscalar , shared ( 7 ) . type <EOL> assert shared ( 7.0 ) . type == theano . tensor . dscalar <EOL> assert shared ( numpy . float32 ( 7 ) ) . type == theano . tensor . fscalar <EOL> b = shared ( numpy . zeros ( ( 5 , 5 ) , dtype = 'int32' ) ) <EOL> assert b . type == TensorType ( 'int32' , broadcastable = [ False , False ] ) <EOL> b = shared ( numpy . random . rand ( 4 , 5 ) ) <EOL> assert b . type == TensorType ( 'float64' , broadcastable = [ False , False ] ) <EOL> b = shared ( numpy . random . rand ( 5 , 1 , 2 ) ) <EOL> assert b . type == TensorType ( 'float64' , broadcastable = [ False , False , False ] ) <EOL> assert shared ( [ ] ) . type == generic <EOL> def badfunc ( ) : <EOL> shared ( 7 , bad_kw = False ) <EOL> self . assertRaises ( TypeError , badfunc ) <EOL> def test_strict_generic ( self ) : <EOL> u = shared ( 'asdf' , strict = False ) <EOL> v = shared ( 'asdf' , strict = True ) <EOL> u . set_value ( 88 ) <EOL> v . set_value ( 88 ) <EOL> def test_create_numpy_strict_false ( self ) : <EOL> SharedVariable ( <EOL> name = 'u' , <EOL> type = Tensor ( broadcastable = [ False ] , dtype = 'float64' ) , <EOL> value = numpy . asarray ( [ 1. , 2. ] ) , <EOL> strict = False ) <EOL> SharedVariable ( <EOL> name = 'u' , <EOL> type = Tensor ( broadcastable = [ False ] , dtype = 'float64' ) , <EOL> value = [ 1. , 2. ] , <EOL> strict = False ) <EOL> SharedVariable ( <EOL> name = 'u' , <EOL> type = Tensor ( broadcastable = [ False ] , dtype = 'float64' ) , <EOL> value = [ 1 , 2 ] , <EOL> strict = False ) <EOL> try : <EOL> SharedVariable ( <EOL> name = 'u' , <EOL> type = Tensor ( broadcastable = [ False ] , dtype = 'float64' ) , <EOL> value = dict ( ) , <EOL> strict = False ) <EOL> assert 0 <EOL> except TypeError : <EOL> pass <EOL> def test_use_numpy_strict_false ( self ) : <EOL> u = SharedVariable ( <EOL> name = 'u' , <EOL> type = Tensor ( broadcastable = [ False ] , dtype = 'float64' ) , <EOL> value = numpy . asarray ( [ 1. , 2. ] ) , <EOL> strict = False ) <EOL> u . set_value ( [ 3 , 4 ] ) <EOL> assert type ( u . get_value ( ) ) is numpy . ndarray <EOL> assert str ( u . get_value ( borrow = True ) . dtype ) == 'float64' <EOL> assert numpy . all ( u . get_value ( ) == [ 3 , 4 ] ) <EOL> try : <EOL> u . set_value ( 'adsf' ) <EOL> assert 0 <EOL> except ValueError : <EOL> pass <EOL> uval = theano . _asarray ( [ 5 , 6 , 7 , 8 ] , dtype = 'float64' ) <EOL> u . set_value ( uval , borrow = True ) <EOL> assert u . get_value ( borrow = True ) is uval <EOL> def test_scalar_strict ( self ) : <EOL> def f ( var , val ) : <EOL> var . set_value ( val ) <EOL> b = shared ( numpy . int64 ( 7 ) , strict = True ) <EOL> assert b . type == theano . tensor . lscalar <EOL> self . assertRaises ( TypeError , f , b , 8.23 ) <EOL> b = shared ( numpy . int32 ( 7 ) , strict = True ) <EOL> assert b . type == theano . tensor . iscalar <EOL> self . assertRaises ( TypeError , f , b , 8.23 ) <EOL> b = shared ( numpy . int16 ( 7 ) , strict = True ) <EOL> assert b . type == theano . tensor . wscalar <EOL> self . assertRaises ( TypeError , f , b , 8.23 ) <EOL> b = shared ( numpy . int8 ( 7 ) , strict = True ) <EOL> assert b . type == theano . tensor . bscalar <EOL> self . assertRaises ( TypeError , f , b , 8.23 ) <EOL> b = shared ( numpy . float64 ( 7.234 ) , strict = True ) <EOL> assert b . type == theano . tensor . dscalar <EOL> self . assertRaises ( TypeError , f , b , 8 ) <EOL> b = shared ( numpy . float32 ( 7.234 ) , strict = True ) <EOL> assert b . type == theano . tensor . fscalar <EOL> self . assertRaises ( TypeError , f , b , 8 ) <EOL> b = shared ( numpy . float ( 7.234 ) , strict = True ) <EOL> assert b . type == theano . tensor . dscalar <EOL> self . assertRaises ( TypeError , f , b , 8 ) <EOL> b = shared ( 7.234 , strict = True ) <EOL> assert b . type == theano . tensor . dscalar <EOL> self . assertRaises ( TypeError , f , b , 8 ) <EOL> b = shared ( numpy . zeros ( ( 5 , 5 ) , dtype = 'float32' ) ) <EOL> self . assertRaises ( TypeError , f , b , numpy . random . rand ( 5 , 5 ) ) <EOL> def test_tensor_strict ( self ) : <EOL> def f ( var , val ) : <EOL> var . set_value ( val ) <EOL> b = shared ( numpy . int64 ( [ 7 ] ) , strict = True ) <EOL> assert b . type == theano . tensor . lvector <EOL> self . assertRaises ( TypeError , f , b , 8.23 ) <EOL> b = shared ( numpy . int32 ( [ 7 ] ) , strict = True ) <EOL> assert b . type == theano . tensor . ivector <EOL> self . assertRaises ( TypeError , f , b , 8.23 ) <EOL> b = shared ( numpy . int16 ( [ 7 ] ) , strict = True ) <EOL> assert b . type == theano . tensor . wvector <EOL> self . assertRaises ( TypeError , f , b , 8.23 ) <EOL> b = shared ( numpy . int8 ( [ 7 ] ) , strict = True ) <EOL> assert b . type == theano . tensor . bvector <EOL> self . assertRaises ( TypeError , f , b , 8.23 ) <EOL> b = shared ( numpy . float64 ( [ 7.234 ] ) , strict = True ) <EOL> assert b . type == theano . tensor . dvector <EOL> self . assertRaises ( TypeError , f , b , 8 ) <EOL> b = shared ( numpy . float32 ( [ 7.234 ] ) , strict = True ) <EOL> assert b . type == theano . tensor . fvector <EOL> self . assertRaises ( TypeError , f , b , 8 ) <EOL> b = shared ( numpy . zeros ( ( 5 , 5 ) , dtype = 'float32' ) ) <EOL> self . assertRaises ( TypeError , f , b , numpy . random . rand ( 5 , 5 ) ) <EOL> def test_scalar_floatX ( self ) : <EOL> def f ( var , val ) : <EOL> var . set_value ( val ) <EOL> b = shared ( numpy . int64 ( 7 ) , allow_downcast = True ) <EOL> assert b . type == theano . tensor . lscalar <EOL> f ( b , 8.23 ) <EOL> assert b . get_value ( ) == 8 <EOL> b = shared ( numpy . int32 ( 7 ) , allow_downcast = True ) <EOL> assert b . type == theano . tensor . iscalar <EOL> f ( b , 8.23 ) <EOL> assert b . get_value ( ) == 8 <EOL> b = shared ( numpy . int16 ( 7 ) , allow_downcast = True ) <EOL> assert b . type == theano . tensor . wscalar <EOL> f ( b , 8.23 ) <EOL> assert b . get_value ( ) == 8 <EOL> b = shared ( numpy . int8 ( 7 ) , allow_downcast = True ) <EOL> assert b . type == theano . tensor . bscalar <EOL> f ( b , 8.23 ) <EOL> assert b . get_value ( ) == 8 <EOL> b = shared ( numpy . float64 ( 7.234 ) , allow_downcast = True ) <EOL> assert b . type == theano . tensor . dscalar <EOL> f ( b , 8 ) <EOL> assert b . get_value ( ) == 8 <EOL> b = shared ( numpy . float32 (
<s> import uuid <EOL> import sys <EOL> from twisted . python import log <EOL> from twisted . internet import reactor <EOL> from twisted . web . server import Site <EOL> from twisted . web . wsgi import WSGIResource <EOL> from flask import Flask , render_template <EOL> from
<s> from django . core . management . base import CommandError <EOL> from django . core . management . templates import TemplateCommand <EOL> from django . utils . crypto import get_random_string <EOL> from django . utils . importlib import import_module <EOL> class Command ( TemplateCommand ) : <EOL> help = ( "" <EOL> "" <EOL> "" ) <EOL> def handle ( self , project_name = None , target = None , * args , ** options ) : <EOL> self . validate_name ( project_name , "project" ) <EOL> try : <EOL> import_module ( project_name ) <EOL> except ImportError : <EOL> pass <EOL> else : <EOL> raise CommandError ( "" <EOL> "" <EOL> "" % <EOL> project_name ) <EOL> chars
<s> import os <EOL> import unittest <EOL> from robotide . context import IS_WINDOWS <EOL> from robotide . utils import is_same_drive <EOL> if IS_WINDOWS : <EOL> class IsSameDriveTestCase ( unittest . TestCase ) : <EOL> def test_same_drive_is_case_insensitive ( self ) : <EOL> self . assertTrue ( is_same_drive ( 'D:' , 'd:' ) ) <EOL> self . assertFalse ( is_same_drive ( 'x:'
<s> __author__ = 'Danyang' <EOL> class Solution ( object ) : <EOL> def solve ( self , cipher ) : <EOL> matrix , pattern = cipher <EOL> R1 , C1 = len ( matrix ) , len ( matrix [ 0 ] ) <EOL> R2 , C2 = len ( pattern ) , len ( pattern [ 0 ] ) <EOL> dp = [ [ 0 for _ in xrange ( C1 + 1 ) ] for _ in xrange ( R1 + 1 ) ] <EOL> for i in xrange ( 1 , R1 + 1 ) : <EOL> for j in xrange ( 1 , C1 + 1 ) : <EOL> dp [ i ] [ j ] = dp [ i - 1 ] [ j ] + dp [ i ] [ j - 1 ] - dp [ i - 1 ] [ j - 1 ] + matrix [ i - 1 ] [ j - 1 ] <EOL> pattern_sum = sum ( [ sum ( pattern [ i ] ) for i in xrange ( R2 ) ] ) <EOL> for i in xrange ( R1 - R2 + 1 ) : <EOL> for j in xrange ( C1 - C2 + 1 ) : <EOL> bottom = i + R2 <EOL> left = j + C2 <EOL> candidate_sum = dp [ bottom ] [ left ] - dp [ bottom ] [ j ] - dp [ i ] [ left ] + dp [ i ] [ j ] <EOL> if candidate_sum == pattern_sum : <EOL> matched = True <EOL> for a in xrange ( R2 ) : <EOL> for b in xrange ( C2 ) : <EOL> if matrix [ i + a ] [ j + b ] != pattern [ a ] [ b ] : <EOL> matched = False <EOL> break <EOL> if not matched : <EOL> break <EOL> if matched : <EOL> return "YES" <EOL> return "NO" <EOL> if __name__ == "__main__" : <EOL> import sys <EOL> f = open ( "1.in" , "r" ) <EOL> testcases = int ( f . readline ( ) . strip ( ) ) <EOL> for t in xrange ( testcases ) : <EOL>
<s> import warnings <EOL> from django . contrib . sessions . management . commands import clearsessions <EOL> class Command ( clearsessions .
<s> from pypy . conftest import gettestobjspace <EOL> class AppTestNumpy ( object ) : <EOL> def setup_class ( cls ) : <EOL> cls . space = gettestobjspace ( usemodules = ( 'micronumpy' , ) ) <EOL> def test_zeroes ( self ) : <EOL> from numpy import zeros <EOL> ar = zeros ( 3 , dtype = int ) <EOL> assert ar [ 0 ] == 0 <EOL> def test_setitem_getitem ( self ) : <EOL> from numpy import zeros <EOL> ar = zeros ( 8 , dtype = int ) <EOL> assert ar [ 0 ] == 0 <EOL> ar [ 1 ] = 3 <EOL> assert ar [ 1 ] == 3 <EOL> raises ( ( TypeError , ValueError ) , ar . __getitem__ , 'xyz' ) <EOL> raises ( IndexError , ar . __getitem__ , 38 ) <EOL> assert ar [ - 2 ] == 0 <EOL> assert ar [ - 7 ] == 3 <EOL> assert len ( ar ) == 8 <EOL> def test_minimum ( self ) : <EOL> from numpy import zeros , minimum <EOL> ar = zeros ( 5 , dtype = int ) <EOL> ar2 = zeros ( 5 , dtype = int ) <EOL> ar [ 0 ] = 3 <EOL> ar [ 1 ] = - 3 <EOL> ar [ 2 ] = 8 <EOL> ar2 [ 3 ] = - 1 <EOL> ar2 [ 4 ] = 8 <EOL> x = minimum ( ar , ar2 ) <EOL> assert x [ 0 ] == 0 <EOL> assert x [ 1 ] == - 3 <EOL>
<s> import codecs <EOL> def encode ( input , errors = 'strict' ) : <EOL> return ( codecs . BOM_UTF8 + codecs . utf_8_encode ( input , errors ) [ 0 ] , len ( input ) ) <EOL> def decode ( input , errors = 'strict' ) : <EOL> prefix = 0 <EOL> if input [ : 3 ] == codecs . BOM_UTF8 : <EOL> input = input [ 3 : ] <EOL> prefix = 3 <EOL> ( output , consumed ) = codecs . utf_8_decode ( input , errors , True ) <EOL> return ( output , consumed + prefix ) <EOL> class IncrementalEncoder ( codecs . IncrementalEncoder ) : <EOL> def __init__ ( self , errors = 'strict' ) : <EOL> codecs . IncrementalEncoder . __init__ ( self , errors ) <EOL> self . first = True <EOL> def encode ( self , input , final = False ) : <EOL> if self . first : <EOL> self . first = False <EOL> return codecs . BOM_UTF8 + codecs . utf_8_encode ( input , self . errors ) [ 0 ] <EOL> else : <EOL> return codecs . utf_8_encode ( input , self . errors ) [ 0 ] <EOL> def reset ( self ) : <EOL> codecs . IncrementalEncoder . reset ( self ) <EOL> self . first = True <EOL> class IncrementalDecoder ( codecs . BufferedIncrementalDecoder ) : <EOL> def __init__ ( self , errors = 'strict' ) : <EOL> codecs . BufferedIncrementalDecoder . __init__ ( self , errors ) <EOL> self . first = True <EOL> def _buffer_decode ( self , input , errors , final ) : <EOL> if self . first : <EOL> if len ( input ) < 3 : <EOL> if codecs . BOM_UTF8 . startswith ( input ) : <EOL> return ( u"" , 0 ) <EOL> else : <EOL> self . first = None <EOL> else : <EOL> self . first = None <EOL> if input [ : 3 ] ==
<s> __revision__ = "" <EOL> import SCons . Defaults <EOL> from SCons . Scanner . Fortran import FortranScan <EOL> from FortranCommon import add_all_to_env <EOL> def generate ( env ) : <EOL> fscan = FortranScan ( "FORTRANPATH" ) <EOL> SCons . Tool . SourceFileScanner . add_scanner ( '.i' , fscan ) <EOL> SCons . Tool . SourceFileScanner . add_scanner ( '.i90' , fscan ) <EOL> if '' not in env : <EOL> env [ '' ] = [ '.i' ] <EOL>
<s> from rest_framework . decorators import api_view <EOL> from rest_framework . response import Response <EOL> from rest_framework . reverse import reverse <EOL> from rest_framework import serializers <EOL> from rest_framework import generics <EOL> from rest_framework import viewsets <EOL> from rest_framework import status <EOL> from rest_framework . decorators import detail_route , list_route <EOL> from rest_framework . views import APIView <EOL> from core . models import * <EOL> from django . forms import widgets <EOL> from django . conf . urls import patterns , url <EOL> from services . cord . models import VOLTTenant , VBNGTenant , CordSubscriberRoot <EOL> from api . xosapi_helpers import PlusModelSerializer , XOSViewSet , ReadOnlyField <EOL> from django . shortcuts import get_object_or_404 <EOL> from xos . apibase import XOSListCreateAPIView , XOSRetrieveUpdateDestroyAPIView , XOSPermissionDenied <EOL> from xos . exceptions import * <EOL> import json <EOL> import subprocess <EOL> from django . views . decorators . csrf import ensure_csrf_cookie <EOL> class CordSubscriberNew ( CordSubscriberRoot ) : <EOL> class Meta : <EOL> proxy = True <EOL> app_label = "cord" <EOL> def __init__ ( self , * args , ** kwargs ) : <EOL> super ( CordSubscriberNew , self ) . __init__ ( * args , ** kwargs ) <EOL> def __unicode__ ( self ) : <EOL> return u"" % str ( self . id ) <EOL> @ property <EOL> def features ( self ) : <EOL> return { "cdn" : self . cdn_enable , <EOL> "uplink_speed" : self . uplink_speed , <EOL> "downlink_speed" : self . downlink_speed , <EOL> "uverse" : self . enable_uverse , <EOL> "status" : self . status } <EOL> @ features . setter <EOL> def features ( self , value ) : <EOL> self . cdn_enable = value . get ( "cdn" , self . get_default_attribute ( "cdn_enable" ) ) <EOL> self . uplink_speed = value . get ( "uplink_speed" , self . get_default_attribute ( "uplink_speed" ) ) <EOL> self . downlink_speed = value . get ( "downlink_speed" , self . get_default_attribute ( "downlink_speed" ) ) <EOL> self . enable_uverse = value . get ( "uverse" , self . get_default_attribute ( "enable_uverse" ) ) <EOL> self . status = value . get ( "status" , self . get_default_attribute ( "status" ) ) <EOL> def update_features ( self , value ) : <EOL> d = self . features <EOL> d . update ( value ) <EOL> self . features = d <EOL> @ property <EOL> def identity ( self ) : <EOL> return { "account_num" : self . service_specific_id , <EOL> "name" : self . name } <EOL> @ identity . setter <EOL> def identity ( self , value ) : <EOL> self . service_specific_id = value . get ( "account_num" , self . service_specific_id ) <EOL> self . name = value . get ( "name" , self . name ) <EOL> def update_identity ( self , value ) : <EOL> d = self . identity <EOL> d . update ( value ) <EOL> self . identity = d <EOL> @ property <EOL> def related ( self ) : <EOL> related = { } <EOL> if self . volt : <EOL> related [ "volt_id" ] = self . volt . id <EOL> related [ "s_tag" ] = self . volt . s_tag <EOL> related [ "c_tag" ] = self . volt . c_tag <EOL> if self . volt . vcpe : <EOL> related [ "vsg_id" ] = self . volt . vcpe . id <EOL> if self . volt . vcpe . instance : <EOL> related [ "instance_id" ] = self . volt . vcpe . instance . id <EOL> related [ "instance_name" ] = self . volt . vcpe . instance . name <EOL> related [ "" ] = self . volt .
<s> print ( __doc__ ) <EOL> from sklearn . svm import SVC <EOL> from sklearn . datasets import load_digits <EOL> from sklearn . feature_selection import RFE <EOL> import matplotlib . pyplot as plt <EOL> digits = load_digits ( ) <EOL> X = digits . images . reshape ( ( len ( digits . images ) , - 1 ) ) <EOL> y = digits . target <EOL> svc = SVC ( kernel = "linear" , C = 1 ) <EOL> rfe = RFE ( estimator
<s> import numpy as np <EOL> from theano import tensor as T <EOL> import theano <EOL> from sklearn . datasets import make_classification <EOL> from sklearn . cross_validation import train_test_split <EOL> from sklearn . metrics import classification_report <EOL> rng = np . random . RandomState ( 1999 ) <EOL> X , y = make_classification ( n_samples = 400 , n_features = 25 , n_informative = 10 , <EOL> n_classes = 2 , n_clusters_per_class = 2 , <EOL> random_state = 1999 ) <EOL> X_train , X_test , y_train , y_test = train_test_split ( X , y , train_size = .8 ) <EOL> n_samples , n_features = X_train . shape <EOL> x = T . matrix ( 'x' ) <EOL> y = T . vector ( 'y' ) <EOL> w = theano . shared ( rng . randn ( n_features ) , name = 'w' ) <EOL> b = theano . shared ( 0. , name = 'b' ) <EOL> print ( "Initial model" ) <EOL> print ( w . get_value ( ) , b . get_value ( ) ) <EOL> learning_rate = 0.01 <EOL> reg = .1 <EOL> n_iter = 10000 <EOL> prob = 1 / ( 1 + T . exp ( - T . dot ( x , w ) - b ) ) <EOL> pred = prob > 0.5 <EOL> loss = - y * T . log ( prob ) - ( 1 - y ) * T . log ( 1 - prob ) <EOL> penalty = reg * abs ( w ) . sum ( ) <EOL> cost = loss . mean ( ) + penalty <EOL> gw , gb = T . grad ( cost
<s> from __future__ import print_function <EOL> import gc <EOL> from numba import jit , int32 <EOL> from numba import unittest_support as unittest <EOL> def foo ( a , b ) : <EOL> return a + b <EOL> def bar ( a , b ) : <EOL> return cfoo ( a , b ) + b <EOL> @ jit <EOL> def inner ( x , y ) : <EOL> return x + y <EOL> @ jit ( nopython = True ) <EOL> def outer ( x , y ) : <EOL> return inner ( x , y ) <EOL> class TestInterProc ( unittest . TestCase ) : <EOL> def test_bar_call_foo ( self ) : <EOL> global cfoo <EOL> cfoo = jit ( ( int32 , int32 ) , nopython = True ) ( foo ) <EOL> cbar = jit ( ( int32 , int32 ) , nopython = True ) ( bar ) <EOL> self . assertTrue ( cbar ( 1 , 2 ) , 1 + 2 + 2 ) <EOL> def test_bar_call_foo_compiled_twice ( self ) : <EOL> global cfoo <EOL> for i
<s> import hashlib <EOL> import os <EOL> import re <EOL> import time <EOL> import uuid <EOL> from datetime import datetime <EOL> from django . conf import settings <EOL> from django . core . cache import cache <EOL> from django . db import connection , models <EOL> import caching . base as caching <EOL> from olympia import amo <EOL> from olympia . amo . models import ManagerBase , ModelBase <EOL> from olympia . access import acl <EOL> from olympia . addons . models import Addon <EOL> from olympia . amo . helpers import absolutify , user_media_path , user_media_url <EOL> from olympia . amo . urlresolvers import reverse <EOL> from olympia . amo . utils import sorted_groupby <EOL> from olympia . translations . fields import ( <EOL> LinkifiedField , save_signal , NoLinksNoMarkupField , TranslatedField ) <EOL> from olympia . users . models import UserProfile <EOL> SPECIAL_SLUGS = amo . COLLECTION_SPECIAL_SLUGS <EOL> class TopTags ( object ) : <EOL> def key ( self , obj ) : <EOL> return '%s:top-tags:%s' % ( settings . CACHE_PREFIX , obj . id ) <EOL> def __get__ ( self , obj , type = None ) : <EOL> if obj is None : <EOL> return self <EOL> return cache . get ( self . key ( obj ) , [ ] ) <EOL> def __set__ ( self , obj , value ) : <EOL> two_days = 60 * 60 * 24 * 2 <EOL> cache . set ( self . key ( obj ) , value , two_days ) <EOL> class CollectionQuerySet ( caching . CachingQuerySet ) : <EOL> def with_has_addon ( self , addon_id ) : <EOL> has_addon = <EOL> return self . extra ( <EOL> select = { 'has_addon' : has_addon } , <EOL> select_params = ( addon_id , ) ) <EOL> class CollectionManager ( ManagerBase ) : <EOL> def get_queryset ( self ) : <EOL> qs = super ( CollectionManager , self ) . get_queryset ( ) <EOL> qs = qs . _clone ( klass = CollectionQuerySet ) <EOL> return qs . transform ( Collection . transformer ) <EOL> def manual ( self ) : <EOL> types = ( amo . COLLECTION_NORMAL , amo . COLLECTION_FAVORITES , <EOL> amo . COLLECTION_FEATURED , ) <EOL> return self . filter ( type__in = types ) <EOL> def listed ( self ) : <EOL> return self . filter ( listed = True ) <EOL> def publishable_by ( self , user ) : <EOL> owned_by = models . Q ( author = user . id ) <EOL> publishable_by = models . Q ( users = user . id ) <EOL> collections = self . filter ( owned_by | publishable_by ) <EOL> return collections . distinct ( ) . order_by ( '' ) <EOL> class Collection ( ModelBase ) : <EOL> TYPE_CHOICES = amo . COLLECTION_CHOICES . items ( ) <EOL> uuid = models . CharField ( max_length = 36 , blank = True , unique = True ) <EOL> name = TranslatedField ( require_locale = False ) <EOL> nickname = models . CharField ( max_length = 30 , blank = True , unique = True , <EOL> null = True ) <EOL> slug = models . CharField ( max_length = 30 , blank = True , null = True ) <EOL> description = NoLinksNoMarkupField ( require_locale = False ) <EOL> default_locale = models . CharField ( max_length = 10 , default = 'en-US' , <EOL> db_column = 'defaultlocale' ) <EOL> type = models . PositiveIntegerField ( db_column = '' , <EOL> choices = TYPE_CHOICES , default = 0 ) <EOL> icontype = models . CharField ( max_length = 25 , blank = True ) <EOL> listed = models . BooleanField ( <EOL> default = True , help_text = '' ) <EOL> subscribers = models . PositiveIntegerField ( default = 0 ) <EOL> downloads = models . PositiveIntegerField ( default = 0 ) <EOL> weekly_subscribers = models . PositiveIntegerField ( default = 0 ) <EOL> monthly_subscribers = models . PositiveIntegerField ( default = 0 ) <EOL> application = models . PositiveIntegerField ( choices = amo . APPS_CHOICES , <EOL> db_column = 'application_id' , <EOL> null = True ) <EOL> addon_count = models . PositiveIntegerField ( default = 0 , <EOL> db_column = 'addonCount' ) <EOL> upvotes = models . PositiveIntegerField ( default = 0 ) <EOL> downvotes = models . PositiveIntegerField ( default = 0 ) <EOL> rating = models . FloatField ( default = 0 ) <EOL> all_personas = models . BooleanField ( <EOL> default = False , <EOL> help_text = '' ) <EOL> addons = models . ManyToManyField ( Addon , through = '' , <EOL> related_name = 'collections' ) <EOL> author = models . ForeignKey ( UserProfile , null = True , <EOL> related_name = 'collections' ) <EOL> users = models . ManyToManyField ( UserProfile , through = 'CollectionUser' , <EOL> related_name = '' ) <EOL> addon_index = models . CharField ( <EOL> max_length = 40 , null = True , db_index = True , <EOL> help_text = '' ) <EOL> objects = CollectionManager ( ) <EOL> top_tags = TopTags ( ) <EOL> class Meta ( ModelBase . Meta ) : <EOL> db_table = 'collections' <EOL> unique_together = ( ( 'author' , 'slug' ) , ) <EOL> def __unicode__ ( self ) : <EOL> return u'%s (%s)' % ( self . name , self . addon_count ) <EOL> @ classmethod <EOL> def make_index ( cls , addon_ids ) : <EOL> ids = ':' . join ( map ( str , sorted ( addon_ids ) ) ) <EOL> return hashlib . md5 ( ids ) . hexdigest ( ) <EOL> def flush_urls ( self ) : <EOL> urls = [ '*%s' % self . get_url_path ( ) , <EOL> self . icon_url ] <EOL> return urls <EOL> def save ( self , ** kw ) : <EOL> if not self . uuid : <EOL> self . uuid = unicode ( uuid . uuid4 ( ) ) <EOL> if not self . slug : <EOL> self . slug = self . uuid [ : 30 ] <EOL> self . clean_slug ( ) <EOL> if self . id : <EOL> ids = self . addons . values_list ( 'id' , flat = True ) <EOL> self . addon_index = self . make_index ( ids ) <EOL> super ( Collection , self ) . save ( ** kw ) <EOL> def clean_slug ( self ) : <EOL> if self . type in SPECIAL_SLUGS : <EOL> self . slug = SPECIAL_SLUGS [ self . type ] <EOL> return <EOL> if self . slug in SPECIAL_SLUGS . values ( ) : <EOL> self . slug += '~' <EOL> if not self . author : <EOL> return <EOL> qs = self . author . collections . using ( 'default' ) <EOL> slugs = dict ( ( slug , id ) for slug , id in qs . values_list ( 'slug' , 'id' ) ) <EOL> if self . slug in slugs and slugs [ self . slug ] != self . id : <EOL> for idx in range ( len ( slugs ) ) : <EOL> new = '%s-%s' % ( self . slug , idx + 1 ) <EOL> if new not in slugs : <EOL> self . slug = new <EOL> return <EOL> def get_url_path ( self ) : <EOL> return reverse ( '' , <EOL> args = [ self . author_username , self . slug ] ) <EOL> def get_abs_url ( self ) : <EOL> return absolutify ( self . get_url_path ( ) ) <EOL> def get_img_dir ( self ) : <EOL> return os . path . join ( user_media_path ( '' ) , <EOL> str ( self . id / 1000 ) ) <EOL> def upvote_url ( self ) : <EOL> return reverse ( '' , <EOL> args = [ self . author_username , self . slug , 'up' ] ) <EOL> def downvote_url ( self ) : <EOL> return reverse ( '' , <EOL> args = [ self . author_username , self . slug , 'down' ] ) <EOL> def edit_url ( self ) : <EOL> return reverse ( '' , <EOL> args = [ self . author_username , self . slug ] ) <EOL> def watch_url ( self ) : <EOL> return reverse ( '' , <EOL> args = [ self . author_username , self . slug ] ) <EOL> def delete_url ( self ) : <EOL> return reverse ( '' , <EOL> args = [ self . author_username , self . slug ] ) <EOL> def delete_icon_url ( self ) : <EOL> return reverse ( '' , <EOL> args = [ self . author_username , self . slug ] ) <EOL> def share_url ( self ) : <EOL> return reverse ( '' , <EOL> args = [ self . author_username , self . slug ] ) <EOL> def feed_url ( self ) : <EOL> return reverse ( '' , <EOL> args = [ self . author_username , self . slug ] ) <EOL> def stats_url ( self ) : <EOL> return reverse ( '' , <EOL> args = [ self . author_username , self . slug ] ) <EOL> @ property <EOL> def author_username ( self ) : <EOL> return self . author . username if self . author else 'anonymous' <EOL> @ classmethod <EOL> def get_fallback ( cls ) : <EOL> return cls . _meta . get_field ( 'default_locale' ) <EOL> @ property <EOL> def url_slug ( self ) : <EOL> return self . nickname or self . uuid <EOL> @ property <EOL> def icon_url ( self ) : <EOL> modified = int ( time . mktime ( self . modified . timetuple ( ) ) ) <EOL> if self . icontype : <EOL> split_id = re . match ( r'' , str ( self . id ) ) <EOL> path = "/" . join ( [ <EOL> split_id . group ( 2 ) or '0' , <EOL> "%s.png?m=%s" % ( self . id , modified ) <EOL> ] ) <EOL> return user_media_url ( '' ) + path <EOL> elif self . type == amo . COLLECTION_FAVORITES : <EOL> return settings . STATIC_URL + '' <EOL> else : <EOL> return settings . STATIC_URL + '' <EOL> def set_addons ( self , addon_ids , comments = { } ) : <EOL> order = dict ( ( a , idx ) for idx , a in enumerate ( addon_ids ) ) <EOL> existing = set ( self . addons . using ( 'default' ) <EOL> . values_list ( 'id' , flat = True ) ) <EOL> add , update = [ ] , [ ] <EOL> for addon in addon_ids : <EOL> bucket = update if addon in existing else add <EOL> bucket . append ( ( addon , order [ addon ] ) ) <EOL> remove = existing . difference ( addon_ids ) <EOL> cursor = connection . cursor ( ) <EOL> now = datetime . now ( ) <EOL> if remove : <EOL> cursor . execute ( "" <EOL> "" % <EOL> ( self . id , ',' . join ( map ( str , remove ) ) ) ) <EOL> if self . listed : <EOL> for addon in remove : <EOL> amo . log ( amo . LOG . REMOVE_FROM_COLLECTION , <EOL> ( Addon , addon ) , self ) <EOL> if add : <EOL> insert = '' <EOL> values = [ insert % ( a , self . id , idx ) for a , idx in add ] <EOL> cursor . execute ( % ',' . join ( values ) ) <EOL> if self . listed : <EOL> for addon_id , idx in add : <EOL> amo . log ( amo . LOG . ADD_TO_COLLECTION , <EOL> ( Addon , addon_id ) , self ) <EOL> for addon , ordering in update : <EOL> ( CollectionAddon . objects . filter ( collection = self . id , addon = addon ) <EOL> . update ( ordering = ordering , modified = now ) ) <EOL> for addon , comment in comments . iteritems ( ) : <EOL> try : <EOL> c = ( CollectionAddon . objects . using ( 'default' ) <EOL> . get ( collection = self . id , addon = addon ) ) <EOL> except CollectionAddon . DoesNotExist : <EOL> pass <EOL> else : <EOL> c . comments = comment <EOL> c . save ( force_update = True ) <EOL> self . save ( ) <EOL> def is_subscribed ( self , user ) : <EOL> return self . following . filter ( user = user ) . exists ( ) <EOL> def add_addon ( self , addon ) : <EOL> "" <EOL> CollectionAddon . objects . get_or_create ( addon = addon , collection = self ) <EOL> if self . listed : <EOL> amo . log ( amo . LOG . ADD_TO_COLLECTION , addon , self ) <EOL> self . save ( ) <EOL> def remove_addon ( self , addon ) : <EOL> CollectionAddon . objects . filter ( addon = addon , collection = self ) . delete ( ) <EOL> if self . listed : <EOL> amo . log ( amo . LOG . REMOVE_FROM_COLLECTION , addon , self ) <EOL> self . save ( ) <EOL> def owned_by ( self , user ) : <EOL> return ( user . id == self . author_id ) <EOL> def can_view_stats ( self , request ) : <EOL> if request and request . user : <EOL> return ( self . publishable_by ( request . user ) or <EOL> acl . action_allowed ( request , '' , 'View' ) ) <EOL> return False <EOL> @ caching . cached_method <EOL> def publishable_by ( self , user ) : <EOL> return bool ( self . owned_by ( user ) or self . users . filter ( pk = user . id ) ) <EOL> @ staticmethod <EOL> def transformer ( collections ) : <EOL> if not collections : <EOL> return <EOL> author_ids = set ( c . author_id for c in collections ) <EOL> authors = dict ( ( u . id , u ) for u in <EOL> UserProfile . objects . filter ( id__in = author_ids ) ) <EOL> for c in collections : <EOL> c . author = authors . get ( c . author_id ) <EOL> @ staticmethod <EOL> def post_save ( sender , instance , ** kwargs ) : <EOL> from . import tasks <EOL> if kwargs . get ( 'raw' ) : <EOL> return <EOL> tasks . collection_meta . delay ( instance . id , using = 'default' ) <EOL> tasks . index_collections . delay ( [ instance . id ] ) <EOL> @ staticmethod <EOL> def post_delete ( sender , instance , ** kwargs ) : <EOL> from . import tasks <EOL> if kwargs . get ( 'raw' ) : <EOL> return <EOL> tasks . unindex_collections . delay ( [ instance . id ] ) <EOL> def check_ownership ( self , request , require_owner , require_author , <EOL> ignore_disabled , admin ) : <EOL> from olympia . access import acl <EOL> return acl . check_collection_ownership ( request , self , require_owner ) <EOL> models . signals . post_save . connect ( Collection . post_save , sender = Collection , <EOL> dispatch_uid = 'coll.post_save' ) <EOL> models . signals . pre_save . connect ( save_signal , sender = Collection , <EOL> dispatch_uid = '' ) <EOL> models . signals . post_delete . connect ( Collection . post_delete , sender = Collection , <EOL> dispatch_uid = '' ) <EOL> class CollectionAddon ( ModelBase ) : <EOL> addon = models . ForeignKey ( Addon ) <EOL> collection = models . ForeignKey ( Collection ) <EOL> comments = LinkifiedField ( null = True ) <EOL> downloads = models . PositiveIntegerField ( default = 0 ) <EOL> user = models . ForeignKey ( UserProfile , null = True ) <EOL> ordering = models . PositiveIntegerField ( <EOL> default = 0 , <EOL> help_text = '' <EOL> '' ) <EOL> class Meta ( ModelBase . Meta ) : <EOL> db_table = '' <EOL> unique_together = ( ( 'addon' , 'collection' ) , ) <EOL> @ staticmethod <EOL> def post_save_or_delete ( sender , instance , ** kwargs ) : <EOL> from . import tasks <EOL> tasks . collection_meta . delay ( instance . collection_id , using = 'default' ) <EOL> models . signals . pre_save . connect ( save_signal , sender = CollectionAddon , <EOL> dispatch_uid = '' ) <EOL> models . signals . post_save . connect ( CollectionAddon . post_save_or_delete , <EOL> sender = CollectionAddon , <EOL> dispatch_uid = 'coll.post_save' ) <EOL> models . signals . post_delete . connect ( CollectionAddon . post_save_or_delete , <EOL> sender = CollectionAddon , <EOL> dispatch_uid = 'coll.post_save' ) <EOL> class CollectionFeature ( ModelBase ) : <EOL> title = TranslatedField ( ) <EOL> tagline = TranslatedField ( ) <EOL> class Meta
<s> import unittest <EOL> from test . test_support import verbose , import_module <EOL> dl = import_module ( 'dl' , deprecated = True ) <EOL> sharedlibs = [ <EOL> ( '' , 'getpid' ) , <EOL> ( '/lib/libc.so.6' , 'getpid' ) , <EOL> ( '' , 'getpid' ) , <EOL> ( '' , 'getpid' ) , <EOL> ] <EOL> def test_main ( ) : <EOL>
<s> from django . core . exceptions import ImproperlyConfigured <EOL> from django . db import models <EOL> class DummyField ( models . Field ) : <EOL> def __init__ ( self , dim = None ,
<s> from django import template <EOL> register = template . Library ( ) <EOL> @ register . inclusion_tag ( '' , <EOL> takes_context = True ) <EOL> def breadcrumb_nav ( context ) : <EOL> return { 'actions' : context . get ( 'actions' ) , <EOL> 'breadcrumb' : context . get ( '' ) , <EOL> 'url' :
<s> from distutils . core import setup <EOL> __version__ = '1.0.0' <EOL> setup ( <EOL> name = 'ernie' , <EOL> version = __version__ , <EOL> description = '' , <EOL> author = 'Ken Robertson' , <EOL> author_email = '' , <EOL> url =
<s> import re <EOL> from werkzeug . wrappers import BaseRequest , BaseResponse <EOL> from werkzeug . exceptions import HTTPException , MethodNotAllowed , NotImplemented , NotFound <EOL> class Request ( BaseRequest ) : <EOL> class Response ( BaseResponse ) : <EOL> class View ( object ) : <EOL> def __init__ ( self , app , req ) : <EOL> self . app = app <EOL> self . req = req <EOL> def GET ( self ) : <EOL> raise MethodNotAllowed ( ) <EOL> POST = DELETE = PUT = GET <EOL> def HEAD ( self ) : <EOL> return self . GET ( ) <EOL> class WebPyApp ( object ) : <EOL> def __init__ ( self , urls , views ) : <EOL> self . urls = [ ( re . compile ( '^%s$' % urls [ i ] ) , urls [ i + 1 ] ) <EOL> for i in xrange ( 0 , len ( urls ) , 2 ) ] <EOL> self . views = views <EOL> def __call__ ( self , environ , start_response ) : <EOL> try : <EOL> req = Request ( environ ) <EOL> for regex , view in self . urls : <EOL> match = regex . match ( req . path ) <EOL> if match is not None : <EOL>
<s> import time <EOL> from calvin . utilities import calvinlogger <EOL> from calvin . utilities import calvinuuid <EOL> from calvin . utilities import calvinconfig <EOL> _conf = calvinconfig . get ( ) <EOL> _log = calvinlogger . get_logger ( __name__ ) <EOL> _metering = None <EOL> def get_metering ( ) : <EOL> global _metering <EOL> return _metering <EOL> def set_metering ( metering ) : <EOL> global _metering <EOL> if _metering is None : <EOL> _metering = metering <EOL> return _metering <EOL> class Metering ( object ) : <EOL> def __init__ ( self , node ) : <EOL> super ( Metering , self ) . __init__ ( ) <EOL> self . node = node <EOL> self . timeout = _conf . get ( None , '' ) <EOL> self . aggregated_timeout = _conf . get ( None , '' ) <EOL> self . actors_log = { } <EOL> self . actors_meta = { } <EOL> self . actors_destroyed = { } <EOL> self . active = False <EOL> self . users = { } <EOL> self . oldest = time . time ( ) <EOL> self . last_forget = time . time ( ) <EOL> self . next_forget_aggregated = time . time ( ) <EOL> self . actors_aggregated = { } <EOL> self . actors_aggregated_time = { } <EOL> def fired ( self , actor_id , action_name ) : <EOL> t = time . time ( ) <EOL> if self . aggregated_timeout > 0.0 : <EOL> self . actors_aggregated . setdefault ( actor_id , <EOL> { action : 0 for action in self . actors_meta [ actor_id ] } ) [ action_name ] += 1 <EOL> self . actors_aggregated_time . setdefault ( actor_id , [ t , t ] ) [ 1 ] = t <EOL> if self . next_forget_aggregated <= t : <EOL> self . forget_aggregated ( t ) <EOL> if self . active and self . timeout > 0.0 : <EOL> self . actors_log [ actor_id ] . append ( ( t , action_name ) ) <EOL> if self . oldest < t - self . timeout and self . last_forget < t - 1.0 : <EOL> self . forget ( t ) <EOL> def register ( self , user_id = None ) : <EOL> if not user_id : <EOL> user_id = calvinuuid . uuid ( "METERING" ) <EOL> if user_id in self . users : <EOL> raise Exception ( "" ) <EOL> self . users [ user_id ] = time . time ( ) <EOL> self . active = True <EOL> return user_id <EOL> def unregister ( self , user_id ) : <EOL> if user_id in self . users : <EOL> self . users . pop ( user_id ) <EOL> self . active = bool ( self . users ) <EOL> self . forget ( time . time ( ) ) <EOL> else : <EOL> raise Exception ( "" ) <EOL> def get_timed_meter ( self , user_id ) : <EOL> if user_id not in self . users : <EOL> _log . debug ( "" ) <EOL> raise Exception ( "" ) <EOL> t = time . time ( ) <EOL> response = { actor_id : [ d for d in data if d [ 0 ] > self . users [ user_id ] ] <EOL> for actor_id , data in self . actors_log . iteritems ( ) } <EOL> self . users [ user_id ] = t <EOL> self . forget ( t ) <EOL> return response <EOL> def get_aggregated_meter ( self , user_id ) : <EOL> if user_id not in self . users : <EOL> _log . debug ( "" ) <EOL> raise Exception ( "" ) <EOL> response = { 'activity' : self . actors_aggregated , 'time' : self . actors_aggregated_time } <EOL> return response <EOL> def forget ( self , current ) : <EOL> self . last_forget = current <EOL> if not self . active : <EOL> self . actors_log = { } <EOL> self . oldest = current <EOL> return <EOL> t = min ( self . users . values ( ) ) <EOL> if t < current - self . timeout : <EOL> t = current - self . timeout <EOL> self . oldest = t <EOL> for actor_id , data in self . actors_log . iteritems ( ) : <EOL> self . actors_log [ actor_id ] = [ d for d in data if d [ 0 ] > t ] <EOL> def forget_aggregated ( self , current ) : <EOL> et = current - ( self . timeout * 2 ) - self . aggregated_timeout <EOL> for actor_id , dt in self . actors_destroyed . iteritems ( ) : <EOL> if dt < et : <EOL> self . actors_meta . pop ( actor_id ) <EOL> try : <EOL> self . actors_aggregated_time . pop ( actor_id ) <EOL> self . actors_aggregated . pop ( actor_id ) <EOL> except : <EOL> pass <EOL> self . actors_destroyed = { actor_id : dt for actor_id , dt in self . actors_destroyed . iteritems ( ) if dt >= et } <EOL> if self . actors_destroyed : <EOL> self
<s> class AppSettings ( object ) : <EOL> class AuthenticationMethod : <EOL> USERNAME = 'username' <EOL> EMAIL = 'email' <EOL> USERNAME_EMAIL = 'username_email' <EOL> class EmailVerificationMethod : <EOL> MANDATORY = 'mandatory' <EOL> OPTIONAL = 'optional' <EOL> NONE = 'none' <EOL> def __init__ ( self , prefix ) : <EOL> self . prefix = prefix <EOL> assert ( not self . AUTHENTICATION_METHOD == <EOL> self . AuthenticationMethod . EMAIL ) or self . EMAIL_REQUIRED <EOL> assert ( self . AUTHENTICATION_METHOD == <EOL> self . AuthenticationMethod . USERNAME ) or self . UNIQUE_EMAIL <EOL> assert ( self . EMAIL_VERIFICATION != <EOL> self . EmailVerificationMethod . MANDATORY ) or self . EMAIL_REQUIRED <EOL> if not self . USER_MODEL_USERNAME_FIELD : <EOL> assert not self . USERNAME_REQUIRED <EOL> assert self . AUTHENTICATION_METHOD not in ( self . AuthenticationMethod . USERNAME , <EOL> self . AuthenticationMethod . USERNAME_EMAIL ) <EOL> def _setting ( self , name , dflt ) : <EOL> from django . conf import settings <EOL> getter = getattr ( settings , <EOL> '' , <EOL> lambda name , dflt : getattr ( settings , name , dflt ) ) <EOL> return getter ( self . prefix + name , dflt ) <EOL> @ property <EOL> def DEFAULT_HTTP_PROTOCOL ( self ) : <EOL> return self . _setting ( "" , "http" ) . lower ( ) <EOL> @ property <EOL> def EMAIL_CONFIRMATION_EXPIRE_DAYS ( self ) : <EOL> from django . conf import settings <EOL> return self . _setting ( "" , <EOL> getattr ( settings , "" , 3 ) ) <EOL> @ property <EOL> def EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL ( self ) : <EOL> return self . _setting ( "" , <EOL> None ) <EOL> @ property <EOL> def EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL ( self ) : <EOL> from django . conf import settings <EOL> return self . _setting ( "" , <EOL> settings . LOGIN_URL ) <EOL> @ property <EOL> def EMAIL_REQUIRED ( self ) : <EOL> return self . _setting ( "EMAIL_REQUIRED" , False ) <EOL> @ property <EOL> def EMAIL_VERIFICATION ( self ) : <EOL> ret = self . _setting ( "" , <EOL> self . EmailVerificationMethod . OPTIONAL ) <EOL> if ret is True : <EOL> ret = self . EmailVerificationMethod . MANDATORY <EOL> elif ret is False : <EOL> ret = self . EmailVerificationMethod . OPTIONAL <EOL> return ret <EOL> @ property <EOL> def AUTHENTICATION_METHOD ( self ) : <EOL> from django . conf import settings <EOL> if hasattr ( settings , "" ) : <EOL> import warnings <EOL> warnings . warn ( "" <EOL> "" , <EOL> DeprecationWarning ) <EOL> if getattr ( settings , "" ) : <EOL> ret = self . AuthenticationMethod . EMAIL <EOL> else : <EOL> ret = self . AuthenticationMethod . USERNAME <EOL> else : <EOL>
<s> import mock <EOL> from elastic_recheck . cmd import graph <EOL> from elastic_recheck . tests import unit <EOL> class FakeResponse ( object ) : <EOL> def __init__ ( self , response_text ) : <EOL> super ( FakeResponse , self ) . __init__ ( ) <EOL> self . text = ")]}'\n" + response_text <EOL> class TestGraphCmd ( unit . UnitTestCase ) : <EOL> def test_get_open_reviews_empty ( self ) : <EOL> with mock . patch
<s> from django . conf import settings as django_settings <EOL> from django . utils import timezone <EOL> from django . template import Context <EOL> from django import template <EOL> from datetime import datetime <EOL> dummy_context = Context ( ) <EOL> def get_now ( ) : <EOL> if django_settings . USE_TZ : <EOL> return datetime . utcnow ( ) . replace ( tzinfo = timezone . utc ) <EOL> else : <EOL> return datetime . now ( ) <EOL> def get_placeholders ( template_name ) : <EOL> dummy_context . template = template . Template ( "" ) <EOL> try : <EOL> temp_wrapper = template . loader . get_template ( template_name ) <EOL> except template . TemplateDoesNotExist : <EOL> return [ ] <EOL> plist , blist = [ ] , [ ] <EOL> temp = temp_wrapper . template <EOL> _placeholders_recursif ( temp . nodelist , plist , blist ) <EOL> previous = { } <EOL> block_to_remove = [ ] <EOL> for block in blist : <EOL> if block . name in previous : <EOL> if not hasattr ( block , 'has_super_var' ) : <EOL> block_to_remove . append ( previous [ block . name ] ) <EOL> previous [ block . name ] = block <EOL> def keep ( p ) : <EOL>
<s> from __future__ import division <EOL> import sys <EOL> import numpy <EOL> from numpy . core import numeric <EOL> import uncertainties <EOL> from uncertainties import umath <EOL> from uncertainties import __author__ <EOL> __all__ = [ <EOL> 'uarray' , 'umatrix' , <EOL> 'nominal_values' , 'std_devs' , <EOL> 'matrix' <EOL> ] <EOL> to_nominal_values = numpy . vectorize ( <EOL> uncertainties . nominal_value , <EOL> otypes = [ float ] , <EOL> doc = ( "" <EOL> "" ) ) <EOL> to_std_devs = numpy . vectorize ( <EOL> uncertainties . std_dev , <EOL> otypes = [ float ] , <EOL> doc = ( "" <EOL> "" ) ) <EOL> def unumpy_to_numpy_matrix ( arr ) : <EOL> return arr . view ( numpy . matrix ) if isinstance ( arr , matrix ) else arr <EOL> def nominal_values ( arr ) : <EOL> return unumpy_to_numpy_matrix ( to_nominal_values ( arr ) ) <EOL> def std_devs ( arr ) : <EOL> return unumpy_to_numpy_matrix ( to_std_devs ( arr ) ) <EOL> def derivative ( u , var ) : <EOL> if isinstance ( u , uncertainties . AffineScalarFunc ) : <EOL> try : <EOL> return u . derivatives [ var ] <EOL> except KeyError : <EOL> return 0. <EOL> else : <EOL> return 0. <EOL> def wrap_array_func ( func ) : <EOL> @ uncertainties . set_doc ( % ( func . __name__ , func . __doc__ ) ) <EOL> def wrapped_func ( arr , * args ) : <EOL> arr_nominal_value = nominal_values ( arr ) <EOL> func_nominal_value = func ( arr_nominal_value , * args ) <EOL> variables = set ( ) <EOL> for element in arr . flat : <EOL> if isinstance ( element , uncertainties . AffineScalarFunc ) : <EOL> variables |= set ( element . derivatives . iterkeys ( ) ) <EOL> if not variables : <EOL> return func_nominal_value <EOL> derivatives = numpy . vectorize ( lambda _ : { } ) ( func_nominal_value ) <EOL> for var in variables : <EOL> shift_var = max ( var . _std_dev / 1e5 , 1e-8 * abs ( var . _nominal_value ) ) <EOL> if not shift_var : <EOL> shift_var = 1e-8 <EOL> shift_arr = array_derivative ( arr , var ) * shift_var <EOL> shifted_arr_values = arr_nominal_value + shift_arr <EOL> func_shifted = func ( shifted_arr_values , * args ) <EOL> numerical_deriv = ( func_shifted - func_nominal_value ) / shift_var <EOL> for ( derivative_dict , derivative_value ) in ( <EOL> zip ( derivatives . flat , numerical_deriv . flat ) ) : <EOL> if derivative_value : <EOL> derivative_dict [ var ] = derivative_value <EOL> return numpy . vectorize ( uncertainties . AffineScalarFunc ) ( <EOL> func_nominal_value , derivatives ) <EOL> wrapped_func . __name__ = func . __name__ <EOL> return wrapped_func <EOL> _uarray = numpy . vectorize ( lambda v , s : uncertainties . Variable ( v , s ) , <EOL> otypes = [ object ] ) <EOL> def uarray ( ( values , std_devs ) ) : <EOL> return _uarray ( values , std_devs ) <EOL> def array_derivative ( array_like , var ) : <EOL> return numpy . vectorize ( lambda u : derivative ( u , var ) , <EOL> otypes = [ float ] ) ( array_like ) <EOL> def func_with_deriv_to_uncert_func ( func_with_derivatives ) : <EOL> def wrapped_func ( array_like , * args ) : <EOL> array_version = numpy . asarray ( array_like ) <EOL> variables = set ( ) <EOL> for element in array_version . flat : <EOL> if isinstance ( element , uncertainties . AffineScalarFunc ) : <EOL> variables |= set ( element . derivatives . iterkeys ( ) ) <EOL> array_nominal = nominal_values ( array_version ) <EOL> func_and_derivs = func_with_derivatives ( <EOL> array_nominal , <EOL> type ( array_like ) , <EOL> ( array_derivative ( array_version , var ) for var in variables ) , <EOL> * args ) <EOL> func_nominal_value = func_and_derivs . next ( ) <EOL> if not variables : <EOL> return func_nominal_value <EOL> derivatives = numpy . array ( <EOL> [ { } for _ in xrange ( func_nominal_value . size ) ] , dtype = object ) <EOL> derivatives . resize ( func_nominal_value . shape ) <EOL> for ( var , deriv_wrt_var ) in zip ( variables , func_and_derivs ) : <EOL> for ( derivative_dict , derivative_value ) in zip ( <EOL> derivatives . flat , deriv_wrt_var . flat ) : <EOL> if derivative_value : <EOL> derivative_dict [ var ] = derivative_value <EOL> result = numpy . vectorize ( uncertainties . AffineScalarFunc ) ( <EOL> func_nominal_value , derivatives ) <EOL> if isinstance ( result , numpy . matrix ) : <EOL> result = result . view ( matrix ) <EOL> return result <EOL> return wrapped_func <EOL> def inv_with_derivatives ( arr , input_type , derivatives ) : <EOL> inverse = numpy . linalg . inv ( arr ) <EOL> if issubclass ( input_type , numpy . matrix ) : <EOL> inverse = inverse . view ( numpy . matrix ) <EOL> yield inverse <EOL> inverse_mat = numpy . asmatrix ( inverse ) <EOL> for derivative in derivatives : <EOL> derivative_mat = numpy . asmatrix ( derivative ) <EOL> yield - inverse_mat * derivative_mat * inverse_mat <EOL> _inv = func_with_deriv_to_uncert_func ( inv_with_derivatives ) <EOL> _inv . __doc__ = % numpy . linalg . inv . __doc__ <EOL> def pinv_with_derivatives ( arr , input_type , derivatives , rcond ) : <EOL> inverse = numpy . linalg . pinv ( arr , rcond ) <EOL> if issubclass ( input_type , numpy . matrix ) : <EOL> inverse = inverse . view ( numpy . matrix ) <EOL> yield inverse <EOL> inverse_mat = numpy . asmatrix ( inverse ) <EOL> PA = arr * inverse_mat <EOL> AP = inverse_mat * arr <EOL> factor21 = inverse_mat * inverse_mat . H <EOL> factor22 = numpy . eye ( arr . shape [ 0 ] ) - PA <EOL> factor31 =
<s> import os <EOL> import orca <EOL> import pandas as pd <EOL> from activitysim import activitysim as asim <EOL> from . util . vectorize_tour_scheduling import vectorize_tour_scheduling <EOL> @ orca . table ( ) <EOL> def tdd_alts ( configs_dir ) : <EOL> f = os . path . join ( configs_dir , "configs" , <EOL> "" ) <EOL> return pd . read_csv ( f ) <EOL> @ orca . column ( "tdd_alts" ) <EOL> def duration ( tdd_alts ) : <EOL> return tdd_alts . end - tdd_alts . start <EOL> @ orca . table ( ) <EOL> def tdd_work_spec ( configs_dir ) : <EOL> f = os . path . join ( configs_dir , 'configs' , <EOL> '' ) <EOL> return asim . read_model_spec ( f ) . fillna ( 0 ) <EOL> @ orca . table ( ) <EOL> def tdd_school_spec ( configs_dir ) : <EOL> f = os . path . join ( configs_dir , 'configs' , <EOL> '' ) <EOL> return asim .
<s> import os <EOL> import unittest <EOL> from django . conf import settings <EOL> from django . db . models . loading import get_app <EOL> from django . contrib . staticfiles . finders import AppDirectoriesFinder <EOL> class TestStaticfiles ( unittest . TestCase ) : <EOL> def setUp ( self ) : <EOL> pass <EOL> def tearDown ( self ) : <EOL> pass <EOL> def test_staticfiles ( self ) : <EOL> suffix = 'css/icons.css' <EOL> for addons_root in settings . ADDONS_ROOTS : <EOL> ref = os . path . realpath ( '' % ( addons_root
<s> from django . conf . urls import include , url <EOL> from . utils import URLObject <EOL> from . views import empty_view , view_class_instance <EOL> testobj3 = URLObject ( 'testapp' , 'test-ns3' ) <EOL> testobj4 = URLObject ( 'testapp' , 'test-ns4' ) <EOL> urlpatterns = [ <EOL>
<s> import argparse <EOL> import cv2 <EOL> import tensorflow as tf <EOL> import imp <EOL> from tensorpack . utils import * <EOL> from tensorpack . utils import sessinit <EOL> from tensorpack . dataflow import * <EOL> parser = argparse . ArgumentParser ( ) <EOL> parser . add_argument ( dest = 'config' ) <EOL> parser . add_argument ( dest = 'model' ) <EOL> parser . add_argument ( dest = 'output' ) <EOL> args = parser . parse_args ( ) <EOL> get_config_func =
<s> import os <EOL> import datetime <EOL> APP_ROOT_DIR = os . path . abspath ( os . path . dirname ( __file__ ) ) <EOL> SETTINGS = { <EOL> "company_name" : "" , <EOL> "base_currency" : "AUD" , <EOL> "" : "" , <EOL> "template_path" : APP_ROOT_DIR + '/templates/' , <EOL> "" : "file_upload" , <EOL> } <EOL> ACCOUNTS = { <EOL> "" : { <EOL> "" : "<<username>>" , <EOL> "" : "<<password>>" , <EOL> } <EOL> } <EOL> PRODUCTS
<s> import collections <EOL> from dcos . errors import DCOSException <EOL> Command = collections . namedtuple ( <EOL> 'Command' , <EOL> [ 'hierarchy' , 'arg_keys' , 'function' ] ) <EOL>
<s> from openid . extensions import sreg <EOL> from openid . yadis import xri <EOL> import datetime <EOL> hex_to_int = lambda s : int ( s , 16 ) <EOL> int_to_hex = lambda i : hex ( i ) . replace ( '0x' , '' ) . lower ( ) . replace ( 'l' , '' ) <EOL> class OpenID : <EOL> def __init__ ( self , openid , issued , sreg = None ) : <EOL> self . openid = openid <EOL> self . issued = issued <EOL> self . sreg = sreg or { } <EOL> def is_iname ( self ) : <EOL> return xri
<s> from __future__ import unicode_literals <EOL> from rest_framework import serializers <EOL> from rest_framework . exceptions import ValidationError <EOL> from rest_framework . reverse import reverse <EOL> from django . utils . translation import ugettext_lazy as _ <EOL> from documents . models import Document <EOL> from documents . serializers import DocumentSerializer <EOL> from user_management . serializers import UserSerializer <EOL> from . models import Folder <EOL> class FolderSerializer ( serializers . HyperlinkedModelSerializer ) : <EOL> documents = serializers . HyperlinkedIdentityField ( <EOL> view_name = '' <EOL> ) <EOL> documents_count = serializers . SerializerMethodField ( ) <EOL> user = UserSerializer ( read_only = True ) <EOL> class Meta : <EOL> extra_kwargs = { <EOL> 'url' : { 'view_name' : '' } , <EOL> 'user' : { 'view_name' : '' } <EOL> } <EOL> fields = ( <EOL> '' , 'documents' , '' , 'id' , 'label' , <EOL> 'url' , 'user' <EOL> ) <EOL> model = Folder <EOL> def get_documents_count ( self , obj ) : <EOL> return obj . documents . count ( ) <EOL> class NewFolderSerializer ( serializers . Serializer ) : <EOL> label = serializers . CharField ( ) <EOL>
<s> import traceback <EOL> def shell ( ) : <EOL> from config import get_version <EOL> print % ( get_version ( ) ) <EOL> while True : <EOL> cmd = raw_input ( '>>> ' ) <EOL> try : <EOL> exec ( cmd ) <EOL> except Exception ,
<s> import json <EOL> from django . contrib . auth . models import User <EOL> from django . test import TestCase <EOL> from restlib2 . http import codes <EOL> from . base import TransactionBaseTestCase <EOL> class PreviewResourceProcessorTestCase ( TransactionBaseTestCase ) : <EOL> def test_no_processor ( self ) : <EOL> response = self . client . get ( '' , <EOL> HTTP_ACCEPT = '' ) <EOL> self . assertEqual ( response . status_code , codes . ok ) <EOL> content = json . loads ( response . content ) <EOL> self . assertEqual ( len ( content [ 'items' ] ) , 6 ) <EOL> response = self . client . get ( '' , <EOL> HTTP_ACCEPT = '' ) <EOL> self . assertEqual ( response . status_code , codes . ok ) <EOL> content = json . loads ( response . content ) <EOL> self . assertEqual ( len ( content [ 'items' ] ) , 6 ) <EOL> response = self . client . get ( '' , <EOL> HTTP_ACCEPT = '' ) <EOL> self . assertEqual ( response . status_code , codes . ok ) <EOL> content = json . loads ( response . content ) <EOL> self . assertEqual ( len ( content [ 'items' ] ) , 1 ) <EOL> class PreviewResourceTestCase ( TestCase ) : <EOL> def test_delete ( self ) : <EOL> self . client . get ( '' ) <EOL> response = self . client . delete ( '' ) <EOL> self . assertEqual ( response . status_code , codes . ok ) <EOL> self . assertTrue ( 'canceled' in json . loads ( response . content ) ) <EOL> def test_get ( self ) : <EOL> response = self . client . get ( '' , <EOL> HTTP_ACCEPT = '' ) <EOL> self . assertEqual ( response . status_code , codes . ok ) <EOL> self . assertEqual ( response [ 'Content-Type' ] , '' ) <EOL> self . assertEqual ( json . loads ( response . content ) , { <EOL> 'item_name' : 'employee' , <EOL> 'items' : [ ] , <EOL> 'keys' : [ ] , <EOL> 'limit' : None , <EOL> '' : 'employees' , <EOL> 'page' : None , <EOL> } ) <EOL> def test_get_invalid ( self ) : <EOL> response = self . client . get ( '' , <EOL> HTTP_ACCEPT = '' ) <EOL> self . assertEqual ( response . status_code , codes . not_found ) <EOL> def test_get_page ( self ) : <EOL> response = self . client . get ( '' , <EOL> HTTP_ACCEPT = '' ) <EOL> self . assertEqual ( response . status_code , codes . ok ) <EOL> self . assertEqual ( response [ 'Content-Type' ] , '' ) <EOL> self . assertEqual ( json . loads ( response . content ) , { <EOL> 'item_name' : 'employee' , <EOL> 'items' : [ ] , <EOL> 'keys' : [ ] , <EOL> '' : 'employees' , <EOL> 'limit' : 20 , <EOL> 'page' : 7 , <EOL> } ) <EOL> def test_get_page_range_equal ( self ) : <EOL> response = self . client . get ( '' , <EOL> HTTP_ACCEPT = '' ) <EOL> self . assertEqual ( response . status_code , codes . ok ) <EOL> self . assertEqual ( response [ 'Content-Type' ] , '' ) <EOL> self . assertEqual ( json . loads ( response . content ) , { <EOL> 'item_name' : 'employee' , <EOL> 'items' : [ ] , <EOL> 'keys' : [ ] , <EOL> '' : 'employees' , <EOL> 'limit' : 20 , <EOL> 'page' : 3 , <EOL> } ) <EOL> self . assertEqual ( response [ 'Link' ] , ( <EOL> '' <EOL> '' <EOL> '' <EOL> '' <EOL> '' <EOL> ) ) <EOL> def test_get_page_range ( self ) : <EOL> response = self . client . get ( '' , <EOL> HTTP_ACCEPT = '' ) <EOL> self . assertEqual ( response . status_code , codes . ok ) <EOL> self . assertEqual ( response [ 'Content-Type' ]
<s> from __future__ import unicode_literals <EOL> from django . db import models , migrations <EOL> import django . core . validators <EOL> class Migration ( migrations . Migration ) : <EOL> dependencies = [ <EOL>
<s> __version__ = '0.2.2' <EOL> import getopt <EOL> import inspect <EOL> import re <EOL> import string <EOL> import sys <EOL> class Error ( Exception ) : <EOL> class Usage ( Exception ) : <EOL> class TextFSMError ( Error ) : <EOL> class TextFSMTemplateError ( Error ) : <EOL> class FSMAction ( Exception ) : <EOL> class SkipRecord ( FSMAction ) : <EOL> class SkipValue ( FSMAction ) : <EOL> class TextFSMOptions ( object ) : <EOL> class OptionBase ( object ) : <EOL> def __init__ ( self , value ) : <EOL> self . value = value <EOL> @ property <EOL> def name ( self ) : <EOL> return self . __class__ . __name__ . replace ( 'option' , '' ) <EOL> def OnCreateOptions ( self ) : <EOL> def OnClearVar ( self ) : <EOL> def OnClearAllVar ( self ) : <EOL> def OnAssignVar ( self ) : <EOL> def OnGetValue ( self ) : <EOL> def OnSaveRecord ( self ) : <EOL> @ classmethod <EOL> def ValidOptions ( cls ) : <EOL> valid_options = [ ] <EOL> for obj_name in dir ( cls ) : <EOL> obj = getattr ( cls , obj_name ) <EOL> if inspect . isclass ( obj ) and issubclass ( obj , cls . OptionBase ) : <EOL> valid_options . append ( obj_name ) <EOL> return valid_options <EOL> @ classmethod <EOL> def GetOption ( cls , name ) : <EOL> return getattr ( cls , name ) <EOL> class Required ( OptionBase ) : <EOL> def OnSaveRecord ( self ) : <EOL> if not self . value . value : <EOL> raise SkipRecord <EOL> class Filldown ( OptionBase ) : <EOL> def OnCreateOptions ( self ) : <EOL> self . _myvar = None <EOL> def OnAssignVar ( self ) : <EOL> self . _myvar = self . value . value <EOL> def OnClearVar ( self ) : <EOL> self . value . value = self . _myvar <EOL> def OnClearAllVar ( self ) : <EOL> self . _myvar = None <EOL> class Fillup ( OptionBase ) : <EOL> def OnAssignVar ( self ) : <EOL> if self . value . value : <EOL> value_idx = self . value . fsm . values . index ( self . value ) <EOL> for result in reversed ( self . value . fsm . _result ) : <EOL> if result [ value_idx ] : <EOL> break <EOL> result [ value_idx ] = self . value . value <EOL> class Key ( OptionBase ) : <EOL> class List ( OptionBase ) : <EOL> def OnCreateOptions ( self ) : <EOL> self . OnClearAllVar ( ) <EOL> def OnAssignVar ( self ) : <EOL> self . _value . append ( self . value . value ) <EOL> def OnClearVar ( self ) : <EOL> if 'Filldown' not in self . value . OptionNames ( ) : <EOL> self . _value = [ ] <EOL> def OnClearAllVar ( self ) : <EOL> self . _value = [ ] <EOL> def OnSaveRecord ( self ) : <EOL> self . value . value = list ( self . _value ) <EOL> class TextFSMValue ( object ) : <EOL> def __init__ ( self , fsm = None , max_name_len = 48 , options_class = None ) : <EOL> self . max_name_len = max_name_len <EOL> self . name = None <EOL> self . options = [ ] <EOL> self . regex = None <EOL> self . value = None <EOL> self . fsm = fsm <EOL> self . _options_cls = options_class <EOL> def AssignVar ( self , value ) : <EOL> self . value = value <EOL> [ option . OnAssignVar ( ) for option in self . options ] <EOL> def ClearVar ( self ) : <EOL> self . value = None <EOL> [ option . OnClearVar ( ) for option in self . options ] <EOL> def ClearAllVar ( self ) : <EOL> self . value = None <EOL> [ option . OnClearAllVar ( ) for option in self . options ] <EOL> def Header ( self ) : <EOL> [ option . OnGetValue ( ) for option in self . options ] <EOL> return self . name <EOL> def OptionNames ( self ) : <EOL> return [ option . name for option in self . options ] <EOL> def Parse ( self , value ) : <EOL> value_line = value . split ( ' ' ) <EOL> if len ( value_line ) < 3 : <EOL> raise TextFSMTemplateError ( '' ) <EOL> if not value_line [ 2 ] . startswith ( '(' ) : <EOL> options = value_line [ 1 ] <EOL> for option in options . split ( ',' ) : <EOL> self . _AddOption ( option ) <EOL> [ option . OnCreateOptions ( ) for option in self . options ] <EOL> self . name = value_line [ 2 ] <EOL> self . regex = ' ' . join ( value_line [ 3 : ] ) <EOL> else : <EOL> self . name = value_line [ 1 ] <EOL> self . regex = ' ' . join ( value_line [ 2 : ] ) <EOL> if len ( self . name ) > self . max_name_len : <EOL> raise TextFSMTemplateError ( <EOL> "" % self . name ) <EOL> if ( not re . match ( r'^\(.*\)$' , self . regex ) or <EOL> self . regex . count ( '(' ) != self . regex . count ( ')' ) ) : <EOL> raise TextFSMTemplateError ( <EOL> "" % self . regex ) <EOL> self . template = re . sub ( r'^\(' , '(?P<%s>' % self . name , self . regex ) <EOL> def _AddOption ( self , name ) : <EOL> if name in [ option . name for option in self . options ] : <EOL> raise TextFSMTemplateError ( '' % name ) <EOL> try : <EOL> option = self . _options_cls . GetOption ( name ) ( self ) <EOL> except AttributeError : <EOL> raise TextFSMTemplateError ( '' % name ) <EOL> self . options . append ( option ) <EOL> def OnSaveRecord ( self ) : <EOL> [ option . OnSaveRecord ( ) for option in self . options ] <EOL> def __str__ ( self ) : <EOL> if self . options : <EOL> return 'Value %s %s %s' % ( <EOL> ',' . join ( self . OptionNames ( ) ) , <EOL> self . name , <EOL> self . regex ) <EOL> else : <EOL> return 'Value %s %s' % ( self . name , self . regex ) <EOL> class CopyableRegexObject ( object ) : <EOL> def __init__ ( self , pattern ) : <EOL> self . pattern = pattern <EOL> self . regex = re . compile ( pattern ) <EOL> def match ( self , * args , ** kwargs ) : <EOL> return self . regex . match ( * args , ** kwargs ) <EOL> def sub ( self , * args , ** kwargs ) : <EOL> return self . regex . sub ( * args , ** kwargs ) <EOL> def __copy__ ( self ) : <EOL> return CopyableRegexObject ( self . pattern ) <EOL> def __deepcopy__ ( self , unused_memo ) : <EOL> return self . __copy__ ( ) <EOL> class TextFSMRule ( object ) : <EOL> MATCH_ACTION = re . compile ( '' ) <EOL> LINE_OP = ( 'Continue' , 'Next' , 'Error' ) <EOL> RECORD_OP = ( 'Clear' , 'Clearall' , 'Record' , 'NoRecord' ) <EOL> LINE_OP_RE = '(?P<ln_op>%s)' % '|' . join ( LINE_OP ) <EOL> RECORD_OP_RE = '(?P<rec_op>%s)' % '|' . join ( RECORD_OP ) <EOL> OPERATOR_RE = '(%s(\.%s)?)' % ( LINE_OP_RE , RECORD_OP_RE ) <EOL> NEWSTATE_RE = '' <EOL> ACTION_RE = re . compile ( '\s+%s(\s+%s)?$' % ( OPERATOR_RE , NEWSTATE_RE ) ) <EOL> ACTION2_RE = re . compile ( '\s+%s(\s+%s)?$' % ( RECORD_OP_RE , NEWSTATE_RE ) ) <EOL> ACTION3_RE = re . compile ( '(\s+%s)?$' % ( NEWSTATE_RE ) ) <EOL> def __init__ ( self , line , line_num = - 1 , var_map = None ) : <EOL> self . match = '' <EOL> self . regex = '' <EOL> self . regex_obj = None <EOL> self . line_op = '' <EOL> self . record_op = '' <EOL> self . new_state = '' <EOL> self . line_num = line_num <EOL> line = line . strip ( ) <EOL> if not line : <EOL> raise TextFSMTemplateError ( '' <EOL> % self . line_num ) <EOL> match_action = self . MATCH_ACTION . match ( line ) <EOL> if match_action : <EOL> self . match = match_action . group ( 'match' ) <EOL> else : <EOL> self . match = line <EOL> self . regex = self . match <EOL> if var_map : <EOL> try : <EOL> self . regex = string . Template ( self . match ) . substitute ( var_map ) <EOL> except ( ValueError , KeyError ) : <EOL> raise TextFSMTemplateError ( <EOL> "" % <EOL> ( self . match , self . line_num ) ) <EOL> try : <EOL> self . regex_obj = CopyableRegexObject ( self . regex ) <EOL> except re . error : <EOL> raise TextFSMTemplateError ( <EOL> "" % <EOL> ( self . regex , self . line_num ) ) <EOL> if not match_action : <EOL> return <EOL> action_re = self . ACTION_RE . match ( match_action . group ( 'action' ) ) <EOL> if not action_re : <EOL> action_re = self . ACTION2_RE . match ( match_action . group ( 'action' ) ) <EOL> if not action_re : <EOL> action_re = self . ACTION3_RE . match ( match_action . group ( 'action' ) ) <EOL> if not action_re : <EOL> raise TextFSMTemplateError ( "" % <EOL> ( line , self . line_num ) ) <EOL> if 'ln_op' in action_re . groupdict ( ) and action_re . group ( 'ln_op' ) : <EOL> self . line_op = action_re . group ( 'ln_op' ) <EOL> if 'rec_op' in action_re . groupdict ( ) and action_re . group ( 'rec_op' ) : <EOL> self . record_op = action_re . group ( 'rec_op' ) <EOL> if 'new_state' in action_re . groupdict ( ) and action_re . group ( 'new_state' ) : <EOL> self . new_state = action_re . group ( 'new_state' ) <EOL> if ( self . line_op == 'Continue' and self . new_state ) : <EOL> raise TextFSMTemplateError ( <EOL> "" <EOL> % ( self . line_op , self . new_state , self . line_num ) ) <EOL> if self . line_op != 'Error' and self . new_state : <EOL> if not re . match ( '\w+' , self . new_state ) : <EOL> raise TextFSMTemplateError ( <EOL> '' <EOL> % ( self . line_num ) ) <EOL> def __str__ ( self ) : <EOL> operation = '' <EOL> if self . line_op and self . record_op : <EOL> operation = '.' <EOL> operation = '%s%s%s' % ( self . line_op , operation , self . record_op ) <EOL> if operation and self . new_state : <EOL> new_state = ' ' + self . new_state <EOL> else : <EOL> new_state = self . new_state <EOL> if not ( operation or new_state ) : <EOL> return ' %s' % self . match <EOL> return ' %s -> %s%s' % ( self . match , operation , new_state ) <EOL> class TextFSM ( object ) : <EOL> MAX_NAME_LEN = 48 <EOL> comment_regex = re . compile ( '^\s*#' ) <EOL> state_name_re = re . compile ( '^(\w+)$' ) <EOL> _DEFAULT_OPTIONS = TextFSMOptions <EOL> def __init__ ( self , template , options_class = _DEFAULT_OPTIONS ) : <EOL> self . _options_cls = options_class <EOL> self . states = { } <EOL> self . state_list = [ ] <EOL> self . values = [ ] <EOL> self . value_map = { } <EOL> self . _line_num = 0 <EOL> self . _cur_state = None <EOL> self . _cur_state_name = None <EOL> try : <EOL> self . _Parse ( template ) <EOL> finally : <EOL> template . seek ( 0 ) <EOL> self . Reset ( ) <EOL> def __str__ ( self ) : <EOL> result = '\n' . join ( [ str ( value ) for value in self . values ] ) <EOL> result += '\n' <EOL> for state in self . state_list : <EOL> result += '\n%s\n' % state <EOL> state_rules = '\n' . join ( [ str ( rule ) for rule in self . states [ state ] ] ) <EOL> if state_rules : <EOL> result += state_rules + '\n' <EOL> return result <EOL> def Reset ( self ) : <EOL> self .
<s> import numpy as np <EOL> from random import randrange <EOL> def eval_numerical_gradient ( f , x , verbose = True , h = 0.00001 ) : <EOL> grad = np . zeros_like ( x ) <EOL> it = np . nditer ( x , flags = [ 'multi_index' ] , op_flags = [ 'readwrite' ] ) <EOL> while not it . finished : <EOL> ix = it . multi_index <EOL> oldval = x [ ix ] <EOL> x [ ix ] = oldval + h <EOL> fxph = f ( x ) <EOL> x [ ix ] = oldval - h <EOL> fxmh = f ( x ) <EOL> x [ ix ] = oldval <EOL> grad [ ix ] = ( fxph - fxmh ) / ( 2 * h ) <EOL> if verbose : <EOL> print ix , grad [ ix ] <EOL> it . iternext ( ) <EOL> return grad <EOL> def eval_numerical_gradient_array ( f , x , df , h = 1e-5 ) : <EOL> grad = np . zeros_like ( x ) <EOL> it = np . nditer ( x , flags
<s> from flask import Flask <EOL> from admin import admin <EOL> from frontend import frontend <EOL> from classes import classes <EOL> from lessons import lessons <EOL> from prover import prover <EOL> app = Flask ( __name__ ) <EOL> __all__
<s> from __future__ import absolute_import , division <EOL> import time <EOL> import os <EOL> import sys <EOL> import errno <EOL> from . import ( LockBase , LockFailed , NotLocked , NotMyLock , LockTimeout , <EOL> AlreadyLocked ) <EOL> class MkdirLockFile ( LockBase ) : <EOL> def __init__ ( self , path , threaded = True , timeout = None ) : <EOL> LockBase . __init__ ( self , path , threaded , timeout ) <EOL> self . unique_name = os . path . join ( self . lock_file , <EOL> "%s.%s%s" % ( self . hostname , <EOL> self . tname , <EOL> self . pid ) ) <EOL> def acquire ( self , timeout = None ) : <EOL> timeout = timeout is not None and timeout or self . timeout <EOL> end_time = time . time ( ) <EOL> if timeout is not None and timeout > 0 : <EOL> end_time += timeout <EOL> if timeout is None : <EOL> wait = 0.1 <EOL> else : <EOL> wait = max ( 0 , timeout / 10 ) <EOL> while True : <EOL> try : <EOL> os . mkdir ( self . lock_file ) <EOL> except OSError : <EOL> err = sys . exc_info ( ) [ 1 ] <EOL> if err . errno == errno . EEXIST : <EOL> if os . path . exists ( self . unique_name ) : <EOL> return <EOL> if timeout is not None and time . time ( ) > end_time : <EOL> if timeout > 0 : <EOL> raise LockTimeout ( "" <EOL> " lock for %s" % <EOL> self . path ) <EOL> else : <EOL> raise AlreadyLocked ( "" % <EOL> self . path ) <EOL> time . sleep ( wait ) <EOL> else : <EOL> raise LockFailed
<s> import logging <EOL> import os <EOL> import random <EOL> import struct <EOL> from google . appengine . ext import webapp <EOL> from google . appengine . ext . webapp import util <EOL> import member <EOL> class AssignUser ( webapp . RequestHandler ) : <EOL> def post ( self ) : <EOL> self . response . headers . add_header ( "" , "*" ) <EOL> STR_VERSERVER = '01060000' <EOL> INT_VERCLIENT = 0x01060000 <EOL> STR_VERCLIENT = '1.6' <EOL> if not os . environ . has_key ( 'HTTPS' ) : <EOL> self . resp_simple ( 0 , '' ) <EOL> return <EOL> if not os . environ . has_key ( '' ) : <EOL> self . resp_simple ( 0 , '' ) <EOL> return <EOL> HTTPS = os . environ . get ( 'HTTPS' , 'off' ) <EOL> CURRENT_VERSION_ID = os . environ . get ( '' , STR_VERSERVER ) <EOL> if HTTPS . __str__ ( ) != 'on' : <EOL> self . resp_simple ( 0 , '' ) <EOL> return <EOL> minlen = 4 + 32 <EOL> self . response . headers [ 'Content-Type' ] = '' <EOL> data = self . request . body <EOL> size = str . __len__ ( data ) <EOL> if size < minlen : <EOL> self . resp_simple ( 0 , '' ) <EOL> return <EOL> server = int ( CURRENT_VERSION_ID [ 0 : 8 ] , 16 ) <EOL> client = ( struct . unpack ( "!i" , data [ 0 : 4 ] ) ) [ 0 ] <EOL> data = data [ 4 : ] <EOL> if client < INT_VERCLIENT : <EOL> self . resp_simple ( 0 , ( '' %
<s> from __future__ import print_function <EOL> import os <EOL> import sys <EOL> import pyrax <EOL> import pyrax . exceptions as exc <EOL> pyrax . set_setting ( "identity_type" , "rackspace" ) <EOL> creds_file = os . path . expanduser ( "" ) <EOL> pyrax . set_credential_file ( creds_file ) <EOL> dns = pyrax . cloud_dns <EOL> domain_name = "" <EOL> try : <EOL>
<s> class Error ( Exception ) : <EOL> def __str__ ( self ) : <EOL> return str ( self . message ) <EOL> def _get_message ( self , message ) : <EOL> return self . _message <EOL> def _set_message ( self , message ) : <EOL> self . _message = message <EOL> message = property ( _get_message , _set_message ) <EOL> class ParsingError ( Error ) : <EOL> def __init__ ( self , message , line = None ) : <EOL> if line : <EOL> self . message = message + " at line:" + line <EOL> else : <EOL> self . message = message <EOL> class Match : <EOL> def __init__ ( self ) : <EOL> self . mName = None <EOL> self . contig = None <EOL> self . start = 0 <EOL> self . strand = "+" <EOL> self . mPairInsert = 0 <EOL> self . mPairFlag = 0 <EOL> self . mQuality = 0 <EOL> self . mQualitySingle = 0 <EOL> self . mQualityAlternative = 0 <EOL> self . mNMismatches = 0 <EOL> self . mMismatchQuality = 0 <EOL> self . mNMismatch0 = 0 <EOL> self . mNMismatch1 = 0 <EOL> self . mLength = 0 <EOL> def __str__ ( self ) : <EOL> return "\t" . join ( map ( str , ( self . mName , <EOL> self . contig , <EOL> self . start + 1 , <EOL>
<s> import inspect <EOL> import os <EOL> import platform <EOL> import sys <EOL> from setuptools import setup , find_packages <EOL> from setuptools . command . test import test as TestCommand <EOL> __location__ = os . path . join ( os . getcwd ( ) , os . path . dirname ( inspect . getfile ( inspect . currentframe ( ) ) ) ) <EOL> def read_version ( package ) : <EOL> with open ( os . path . join ( package , '__init__.py' ) , 'r' ) as fd : <EOL> for line in fd : <EOL> if line . startswith ( '__version__ = ' ) : <EOL> return line . split ( ) [ - 1 ] . strip ( ) . strip ( "'" ) <EOL> version = read_version ( 'connexion' ) <EOL> py_major_version , py_minor_version , _ = ( int ( v . rstrip ( '+' ) ) for v in platform . python_version_tuple ( ) ) <EOL> def get_install_requirements ( path ) : <EOL> content = open ( os . path . join ( __location__ , path ) ) . read ( ) <EOL> requires = [ req for req in content . split ( '\\n' ) if req != '' ] <EOL> if py_major_version == 2 or ( py_major_version == 3 and py_minor_version < 4 ) : <EOL> requires . append ( 'pathlib' ) <EOL> return requires <EOL> class PyTest ( TestCommand ) : <EOL> user_options = [ ( 'cov-html=' , None , '' ) ] <EOL> def initialize_options ( self ) : <EOL> TestCommand . initialize_options ( self ) <EOL> self . cov = None <EOL> self . pytest_args = [ '--cov' , 'connexion' , '--cov-report' , 'term-missing' , '-v' ] <EOL> self . cov_html = False <EOL> def finalize_options ( self
<s> import sys , os <EOL> sys . path . insert ( 0 , os . path . abspath ( '../../' ) ) <EOL> from webapi import VERSION <EOL> extensions = [ '' ] <EOL> templates_path = [ '_templates' ] <EOL> source_suffix = '.rst' <EOL> master_doc = 'index' <EOL> project = u'deluge-webapi' <EOL> copyright = u'' <EOL> version = '.' . join ( map ( str , VERSION ) ) <EOL> release = '.' . join ( map ( str ,
<s> from setuptools import setup , find_packages <EOL> import sys , os <EOL> version = '1.1.6' <EOL> setup ( name = 'langid' , <EOL> version = version , <EOL> description = "" , <EOL> long_description = , <EOL> classifiers = [ <EOL> '' , <EOL> '' , <EOL> '' , <EOL> '' , <EOL> '' , <EOL> '' , <EOL> '' , <EOL> '' , <EOL> '' , <EOL> ] , <EOL> keywords = '' , <EOL> author = 'Marco Lui' , <EOL> author_email = '' , <EOL> url = '' , <EOL> license = 'BSD' , <EOL> packages = find_packages ( exclude = [ 'ez_setup' , 'examples' , 'tests' ] ) , <EOL> include_package_data = True , <EOL> zip_safe =
<s> import Queue <EOL> import threading <EOL> import time <EOL> import logging <EOL> from grr . lib import flags <EOL> from grr . lib import stats <EOL> from grr . lib import test_lib <EOL> from grr . lib import threadpool <EOL> from grr . lib import utils <EOL> class ThreadPoolTest ( test_lib . GRRBaseTest ) : <EOL> NUMBER_OF_THREADS = 1 <EOL> MAXIMUM_THREADS = 20 <EOL> NUMBER_OF_TASKS = 1500 <EOL> sleep_time = 0.1 <EOL> def setUp ( self ) : <EOL> super ( ThreadPoolTest , self ) . setUp ( ) <EOL> self . base_thread_count = threading . active_count ( ) <EOL> prefix = "pool-%s" % self . _testMethodName <EOL> self . test_pool = threadpool . ThreadPool . Factory ( <EOL> prefix , self . NUMBER_OF_THREADS , max_threads = self . MAXIMUM_THREADS ) <EOL> self . test_pool . Start ( ) <EOL> def tearDown ( self ) : <EOL> self . test_pool . Stop ( ) <EOL> super ( ThreadPoolTest , self ) . tearDown ( ) <EOL> def WaitUntil ( self , condition_cb , timeout = 5 ) : <EOL> for _ in xrange ( int ( timeout / self . sleep_time ) ) : <EOL> res = condition_cb ( ) <EOL> if res : <EOL> return res <EOL> time . sleep ( self . sleep_time ) <EOL> raise RuntimeError ( "" ) <EOL> def Count ( self , thread_name ) : <EOL> worker_threads = [ thread for thread in threading . enumerate ( ) <EOL> if thread_name in thread . name ] <EOL> return len ( worker_threads ) <EOL> def testThreadCreation ( self ) : <EOL> self . assertEqual ( <EOL> self . Count ( "" ) , self . NUMBER_OF_THREADS ) <EOL> def testStopping ( self ) : <EOL> self . assertEqual ( <EOL> self . Count ( "" ) , self . NUMBER_OF_THREADS ) <EOL> self . test_pool . Stop ( ) <EOL> self . assertEqual ( self . Count ( "" ) , 0 ) <EOL> self . test_pool . Start ( ) <EOL> self . assertEqual ( <EOL> self . Count ( "" ) , self . NUMBER_OF_THREADS ) <EOL> self . test_pool . Stop ( ) <EOL> self . assertEqual ( self . Count ( "" ) , 0 ) <EOL> def testRunTasks ( self ) : <EOL> self . test_pool . Join ( ) <EOL> self . lock = threading . Lock ( ) <EOL> def Insert ( list_obj , element ) : <EOL> with self . lock : <EOL> list_obj . append ( element ) <EOL> test_list = [ ] <EOL> for i in range ( self . NUMBER_OF_TASKS ) : <EOL> self . test_pool . AddTask ( Insert , ( test_list , i ) ) <EOL> self . test_pool . Join ( ) <EOL> test_list . sort ( ) <EOL> self . assertEqual ( range ( self . NUMBER_OF_TASKS ) , test_list ) <EOL> def testRunRaisingTask ( self ) : <EOL> self . lock = threading . Lock ( ) <EOL> def IRaise ( some_obj ) : <EOL> with self . lock : <EOL> some_obj . process ( ) <EOL> self . exception_args = [ ] <EOL> def MockException ( * args ) : <EOL> self . exception_args = args <EOL> with utils . Stubber ( logging , "exception" , MockException ) : <EOL> self . test_pool . AddTask ( IRaise , ( None , ) , "Raising" ) <EOL> self . test_pool . AddTask ( IRaise , ( None , ) , "Raising" ) <EOL> self . test_pool . Join ( ) <EOL> self . assertTrue ( self . exception_args [ 0 ] , <EOL> "" ) <EOL> self . assertTrue ( self . exception_args [ 1 ] , "Raising" ) <EOL> self . assertEqual ( <EOL> stats . STATS . GetMetricValue ( self . test_pool . name + "" ) , <EOL> 2 ) <EOL> def testFailToCreateThread ( self ) : <EOL> self . assertEqual ( len ( self . test_pool ) , self . NUMBER_OF_THREADS ) <EOL> done_event = threading . Event ( ) <EOL> def Block ( done ) : <EOL> done . wait ( ) <EOL> def RaisingStart ( _ ) : <EOL> raise threading . ThreadError ( ) <EOL>
<s> from __future__ import print_function <EOL> from __future__ import unicode_literals <EOL> from __future__ import division <EOL> from __future__ import absolute_import <EOL> from builtins import range <EOL> from future import standard_library <EOL> standard_library . install_aliases ( ) <EOL> import sys <EOL> PYTHON_VERSION = sys . version_info [ : 3 ] <EOL> PY2 = ( PYTHON_VERSION [ 0 ] == 2 ) <EOL> if PY2 : <EOL> if PYTHON_VERSION < ( 2 , 7 , 9 ) : <EOL> raise Exception ( '' ) <EOL> elif PYTHON_VERSION < ( 3 , 4 ) : <EOL> raise Exception ( '' ) <EOL> import hpOneView as hpov <EOL> from pprint import pprint <EOL> def acceptEULA ( con ) : <EOL> con . get_eula_status ( ) <EOL> try : <EOL> if con . get_eula_status ( ) is True : <EOL> print ( '' ) <EOL> con . set_eula ( 'no' ) <EOL> except Exception as e : <EOL> print ( 'EXCEPTION:' ) <EOL> print ( e ) <EOL> def login ( con , credential ) : <EOL> try : <EOL> con . login ( credential ) <EOL> except : <EOL> print ( 'Login failed' ) <EOL> def get_rabbit_kp (
<s> import mptt <EOL> from django . db import models <EOL> from acacia import managers , signals <EOL> class AbstractTopic ( models . Model ) : <EOL> name = models . CharField ( max_length = 50 ) <EOL> parent = models . ForeignKey ( "self" , null = True , blank = True , <EOL> related_name = "children" ) <EOL> objects = managers . TopicManager ( ) <EOL> separator = u"/" <EOL> class Meta : <EOL> abstract = True <EOL> unique_together = [ ( "name" , "parent" ) ] <EOL> def __unicode__ ( self ) : <EOL> return self . full_name ( ) <EOL> def full_name ( self ) : <EOL> if ( not hasattr ( self , "" ) or <EOL> self . parent_id != self . _cached_parent ) : <EOL> if self . parent is not None : <EOL> parents = self . separator . join ( <EOL> self . get_ancestors ( ) . values_list ( "name" , flat = True ) ) <EOL> self . _full_name_cache = u"%s%s%s" % ( parents , self . separator , <EOL> self . name ) <EOL> else : <EOL> self . _full_name_cache = self . name <EOL> self . _cached_parent
<s> from __future__ import unicode_literals <EOL> import json <EOL> from django . http import HttpResponse <EOL> from django . views . generic import FormView <EOL> class TemplateFormView ( FormView ) : <EOL> template_name = 'form.html' <EOL> def heavy_data_1 ( request ) : <EOL> term = request . GET . get ( "term" , "" ) <EOL> numbers = [ 'Zero' , 'One' , 'Two' , 'Three' , 'Four' , 'Five' ] <EOL> numbers = filter ( lambda num : term . lower ( )
<s> from seqdb import SequenceDB , BasicSeqInfoDict <EOL> from annotation import AnnotationDB , TranslationAnnot , TranslationAnnotSlice <EOL> import classutil <EOL> import sequence <EOL> import UserDict <EOL> class SeqTranslator ( sequence . SequenceBase ) : <EOL> def __init__ ( self , db , id , reversePath = None ) : <EOL> self . id = id <EOL> sequence . SequenceBase . __init__ ( self ) <EOL> if reversePath : <EOL> self . orientation = - 1 <EOL> self . start = - len ( self ) <EOL> self . stop = 0 <EOL> self . _reverse = reversePath <EOL> if self . id not in self . db . seqDB : <EOL> raise KeyError ( '' % ( self . id , self . db ) ) <EOL> def __getitem__ ( self , k ) : <EOL> start = k . start <EOL> if start is None : <EOL> start = self . start <EOL> stop = k . stop <EOL> if stop is None : <EOL> stop = self . stop <EOL> annoID = self . _get_anno_id ( start ) <EOL> a = self . db . annodb [ annoID ] <EOL> s = a . sequence <EOL> return a [ ( start - s . start ) / 3 : ( stop - s . start ) / 3 ] <EOL> def absolute_slice ( self , start , stop ) : <EOL> if start < 0 : <EOL> return ( - self ) [ start : stop ] <EOL> else : <EOL> return self [ start : stop ] <EOL> def __len__ ( self ) : <EOL> return self . db . seqInfoDict [ self . id ] . length <EOL> def __neg__ ( self ) : <EOL> try : <EOL> return self . _reverse <EOL> except AttributeError : <EOL> self . _reverse = self . __class__ ( self . db , self . id , <EOL> reversePath = self ) <EOL> return self . _reverse <EOL> def _get_anno_id ( self , start ) : <EOL> if self . orientation > 0 : <EOL> return '%s:%d' % ( self . id , start % 3 ) <EOL> else : <EOL> return '%s:-%d' % ( self . id , ( - start ) % 3 ) <EOL> def iter_frames ( self ) : <EOL> '' <EOL> for frame in ( '0' , '1' , '2' , '-0' , '-1' , '-2' ) : <EOL> yield self . db . annodb [ '%s:%s' % ( self . id , frame ) ] <EOL> def __repr__ ( self ) : <EOL> return 'SeqTranslator(' + sequence . SequenceBase . __repr__ ( self ) + ')' <EOL> class TranslationDB ( SequenceDB ) : <EOL> itemClass = SeqTranslator <EOL> _seqtype = sequence . DNA_SEQTYPE <EOL> def __init__
<s> import unittest <EOL> from nose . tools import assert_equals , assert_raises , assert_true <EOL> from robotide . publish . messages import RideMessage , RideLogMessage , RideLogException <EOL> from robotide . publish . publisher import Publisher <EOL> class RideTestMessage ( RideMessage ) : <EOL> topic = 'My.Topic' <EOL> class RideTestMessageWithAttrs ( RideTestMessage ) : <EOL> data = [ 'foo' , 'bar' ] <EOL> class RideTestMessageWithLongName ( RideTestMessage ) : <EOL> pass <EOL> class TestMessage ( unittest . TestCase ) : <EOL> def test_topic ( self ) : <EOL> assert_equals ( RideMessage ( ) . topic , 'ride' ) <EOL> assert_equals ( RideTestMessage ( ) . topic , 'my.topic' ) <EOL> assert_equals ( RideTestMessageWithLongName ( ) . topic , <EOL> '' ) <EOL> def test_all_attributes_given ( self ) : <EOL> msg = RideTestMessageWithAttrs ( foo = 'bar' , bar = 'quux' ) <EOL> assert_equals ( msg . foo , 'bar' ) <EOL> assert_equals ( msg . bar , 'quux' ) <EOL> def test_missing_mandatory_attribute ( self ) : <EOL> assert_raises ( TypeError , RideTestMessageWithAttrs , foo = 'bar' ) <EOL> def test_missing_many_mandatory_attributes ( self ) : <EOL> assert_raises ( TypeError , RideTestMessageWithAttrs ) <EOL> def test_no_such_attribute_should_fail ( self ) : <EOL> assert_raises ( TypeError , RideTestMessageWithAttrs , foo = '' , bar = '' , <EOL> quux = 'camel' ) <EOL> class TestRideLogMessage ( unittest . TestCase ) : <EOL> def test_log_message ( self ) : <EOL> msg = RideLogMessage ( message = '' , level = 'ERROR' ) <EOL> assert_equals ( msg . message , '' ) <EOL> assert_equals ( msg . level , 'ERROR' ) <EOL> assert_true ( msg . timestamp . startswith ( '20' ) ) <EOL> def test_log_exception ( self ) : <EOL> try : <EOL> 1 / 0 <EOL> except Exception , err : <EOL> msg = RideLogException ( <EOL> message = '' , exception = err , level = 'ERROR' ) <EOL> assert_true
<s> __author__ = "" <EOL> __all__ = [ "Driver" , "load_grammar" ] <EOL> import codecs <EOL> import os <EOL> import logging <EOL> import StringIO <EOL> import sys <EOL> from . import grammar , parse , token , tokenize , pgen <EOL> class Driver ( object ) : <EOL> def __init__ ( self , grammar , convert = None , logger = None ) : <EOL> self . grammar = grammar <EOL> if logger is None : <EOL> logger = logging . getLogger ( ) <EOL> self . logger = logger <EOL> self . convert = convert <EOL> def parse_tokens ( self , tokens , debug = False ) : <EOL> p = parse . Parser ( self . grammar , self . convert ) <EOL> p . setup ( ) <EOL> lineno = 1 <EOL> column = 0 <EOL> type = value = start = end = line_text = None <EOL> prefix = u"" <EOL> for quintuple in tokens : <EOL> type , value , start , end , line_text = quintuple <EOL> if start != ( lineno , column ) : <EOL> assert ( lineno , column ) <= start , ( ( lineno , column ) , start ) <EOL> s_lineno , s_column = start <EOL> if lineno < s_lineno : <EOL> prefix += "\n" * ( s_lineno - lineno ) <EOL> lineno = s_lineno <EOL> column = 0 <EOL> if column < s_column : <EOL> prefix += line_text [ column : s_column ] <EOL> column = s_column <EOL> if type in ( tokenize . COMMENT , tokenize . NL ) : <EOL> prefix += value <EOL> lineno , column = end <EOL> if value . endswith ( "\n" ) : <EOL> lineno += 1 <EOL> column = 0 <EOL> continue <EOL> if type == token . OP : <EOL> type = grammar . opmap [ value ] <EOL> if debug : <EOL> self . logger . debug ( "" , <EOL> token . tok_name [ type ] , value , prefix ) <EOL> if p . addtoken ( type , value , ( prefix , start ) ) : <EOL> if debug : <EOL> self . logger . debug ( "Stop." ) <EOL> break <EOL> prefix = "" <EOL> lineno , column = end <EOL> if value . endswith ( "\n" ) : <EOL> lineno += 1 <EOL> column = 0 <EOL> else : <EOL> raise parse . ParseError ( "" , <EOL> type , value , ( prefix , start ) ) <EOL> return p . rootnode <EOL> def parse_stream_raw ( self , stream , debug = False ) : <EOL> tokens = tokenize . generate_tokens ( stream . readline ) <EOL> return self . parse_tokens ( tokens , debug ) <EOL> def parse_stream ( self , stream , debug = False ) : <EOL> return self . parse_stream_raw ( stream , debug ) <EOL> def parse_file ( self , filename , encoding = None , debug = False ) : <EOL> stream = codecs . open ( filename , "r" , encoding ) <EOL> try : <EOL> return self . parse_stream ( stream , debug ) <EOL> finally : <EOL> stream . close ( ) <EOL> def parse_string ( self , text , debug = False ) : <EOL> tokens = tokenize . generate_tokens ( StringIO . StringIO ( text ) . readline ) <EOL> return self . parse_tokens ( tokens , debug ) <EOL> def load_grammar ( gt = "Grammar.txt" , gp = None , <EOL> save = True , force = False , logger = None ) : <EOL> if logger is None : <EOL> logger = logging . getLogger ( ) <EOL> if gp is None : <EOL> head , tail = os . path . splitext ( gt ) <EOL> if tail == ".txt" : <EOL> tail = "" <EOL> gp = head + tail + "." . join ( map ( str , sys . version_info ) ) + ".pickle" <EOL> if force or not _newer ( gp , gt ) : <EOL> logger . info ( "" , gt ) <EOL> g = pgen . generate_grammar ( gt ) <EOL> if save : <EOL> logger . info ( "" , gp ) <EOL> try : <EOL> g . dump ( gp ) <EOL>
<s> from sure import this <EOL> from unittest import TestCase <EOL> from coinbase import CoinbaseAmount <EOL> from . import account_setup <EOL> from . http_mocking import * <EOL> @ with_http_mocking <EOL> class SellPriceTest1 ( TestCase ) : <EOL> def setUp ( self ) : <EOL> mock_http ( '' , <EOL> self . response_body ) <EOL> def test_sell_price_without_auth ( self ) : <EOL> self . go ( account_setup . without_auth ( ) ) <EOL> def test_sell_price_with_key ( self ) : <EOL> self . go ( account_setup . with_key ( ) ) <EOL> def test_sell_price_with_oauth ( self ) : <EOL> self . go ( account_setup . with_oauth ( ) ) <EOL> def go ( self , account ) : <EOL> this ( account . sell_price ( ) ) . should . equal ( self . expected_price ) <EOL> params = last_request_params ( ) <EOL> params . pop ( 'api_key' , None ) <EOL> this ( params ) . should . equal ( { 'qty' : [ '1' ] } ) <EOL> response_body = <EOL> expected_price = CoinbaseAmount ( '63.31' , 'USD' ) <EOL> @ with_http_mocking <EOL> class SellPriceTest2 ( TestCase
<s> import sys <EOL> from setuptools import setup , find_packages <EOL> install_requires = [ <EOL> 'tornado' , <EOL> 'psutil' , <EOL> 'mock' , <EOL> 'six' , <EOL> ] <EOL> if sys . version_info < ( 3 , 0 ) : <EOL> install_requires . append ( 'ipcalc' ) <EOL> def read_long_description ( filename = "README.md" ) : <EOL> with open ( filename ) as f : <EOL> return f . read ( ) . strip ( ) <EOL> setup ( <EOL> name = "mutornadomon" , <EOL> version =
<s> import pickle <EOL> from nose . tools import eq_ <EOL> from . . import revision <EOL> from ... . datasources import revision_oriented <EOL> from ... . dependencies import solve <EOL> h_headings_ds = revision . datasources . heading_titles_matching ( r"h" ) <EOL> h_headings = revision . heading_titles_matching ( r"h" ) <EOL> lvl_2_headings_ds = revision . datasources . headings_by_level ( 2 ) <EOL> lvl_2_headings = revision . headings_by_level ( 2 ) <EOL> enwiki_wikilinks_ds = revision . datasources . wikilink_titles_matching ( r"^:?en:" ) <EOL> enwiki_wikilinks = revision . wikilink_titles_matching ( r"^:?en:" ) <EOL> wikimedia_external_links_ds = revision . datasources . external_link_urls_matching ( r".*wikimedia.*" ) <EOL> wikimedia_external_links = revision . external_link_urls_matching ( r".*wikimedia.*" ) <EOL> cite_templates_ds = revision . datasources . template_names_matching ( r"^cite" ) <EOL> cite_templates = revision . template_names_matching ( r"^cite" ) <EOL> r_text = revision_oriented . revision . text <EOL> def test_content ( ) : <EOL> cache = { r_text : "" + <EOL> "" + <EOL> "" } <EOL> eq_ ( solve ( revision . datasources . content , cache = cache ) , <EOL> "" + <EOL> " A heading! \n" + <EOL> " the bar!" ) <EOL> eq_ ( solve ( revision . content_chars , cache = cache ) , 41 ) <EOL> eq_ ( pickle . loads ( pickle . dumps ( revision . content_chars ) ) , <EOL> revision . content_chars ) <EOL> def test_headings ( ) : <EOL> cache = { r_text : "" + <EOL> "" + <EOL> "" + <EOL> "" } <EOL> eq_ ( solve ( revision . datasources . heading_titles , cache = cache ) , <EOL> [ "Heading!" , "" ] ) <EOL> eq_ ( solve ( revision . headings , cache = cache ) , 2 ) <EOL> eq_ ( solve ( h_headings , cache = cache ) , 1 ) <EOL> eq_ ( solve ( lvl_2_headings , cache = cache ) , 1 ) <EOL> eq_ ( pickle . loads ( pickle . dumps ( revision . headings ) ) , revision . headings ) <EOL> eq_ ( pickle . loads ( pickle . dumps ( h_headings ) ) , h_headings ) <EOL> eq_ ( pickle . loads ( pickle . dumps ( lvl_2_headings ) ) , lvl_2_headings ) <EOL> def test_wikilinks ( ) : <EOL> cache = { r_text : "" + <EOL> "" + <EOL> "" + <EOL> "" } <EOL> eq_ ( solve ( revision . datasources . wikilink_titles , cache = cache ) , <EOL> [ ":en:some" , "bar" ] ) <EOL> eq_ ( solve ( revision . wikilinks , cache = cache ) , 2 ) <EOL> eq_ ( solve ( enwiki_wikilinks , cache = cache ) , 1 ) <EOL> eq_ ( pickle . loads ( pickle . dumps ( revision . wikilinks ) ) , revision . wikilinks ) <EOL> eq_ ( pickle
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
2
Edit dataset card