idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
45,900
def lex ( self , text ) : for match in self . regex . finditer ( text ) : name = match . lastgroup yield ( name , match . group ( name ) )
Iterator that tokenizes text and yields up tokens as they are found
45,901
def strftime ( self , dtime , format ) : format = self . STRFTIME_FORMATS . get ( format + "_FORMAT" , format ) if six . PY2 and isinstance ( format , six . text_type ) : format = format . encode ( "utf8" ) timestring = dtime . strftime ( format ) if six . PY2 : timestring = timestring . decode ( "utf8" ) return timestring
Locale - aware strftime with format short - cuts .
45,902
def ugettext ( self ) : if six . PY2 : return self . _translations . ugettext else : return self . _translations . gettext
Dispatch to the appropriate gettext method to handle text objects .
45,903
def ungettext ( self ) : if six . PY2 : return self . _translations . ungettext else : return self . _translations . ngettext
Dispatch to the appropriate ngettext method to handle text objects .
45,904
def load ( self , instance , xblock ) : if djpyfs : return djpyfs . get_filesystem ( scope_key ( instance , xblock ) ) else : raise NotImplementedError ( "djpyfs not available" )
Get the filesystem for the field specified in instance and the xblock in xblock It is locally scoped .
45,905
def emit_completion ( self , completion_percent ) : completion_mode = XBlockCompletionMode . get_mode ( self ) if not self . has_custom_completion or completion_mode != XBlockCompletionMode . COMPLETABLE : raise AttributeError ( "Using `emit_completion` requires `has_custom_completion == True` (was {}) " "and `completion_mode == 'completable'` (was {})" . format ( self . has_custom_completion , completion_mode , ) ) if completion_percent is None or not 0.0 <= completion_percent <= 1.0 : raise ValueError ( "Completion percent must be in [0.0; 1.0] interval, {} given" . format ( completion_percent ) ) self . runtime . publish ( self , 'completion' , { 'completion' : completion_percent } , )
Emits completion event through Completion API .
45,906
def has ( self , block , name ) : try : self . get ( block , name ) return True except KeyError : return False
Return whether or not the field named name has a non - default value for the XBlock block .
45,907
def set_many ( self , block , update_dict ) : for key , value in six . iteritems ( update_dict ) : self . set ( block , key , value )
Update many fields on an XBlock simultaneously .
45,908
def get_response ( self , ** kwargs ) : return Response ( json . dumps ( { "error" : self . message } ) , status_code = self . status_code , content_type = "application/json" , charset = "utf-8" , ** kwargs )
Returns a Response object containing this object s status code and a JSON object containing the key error with the value of this object s error message in the body . Keyword args are passed through to the Response .
45,909
def json_handler ( cls , func ) : @ cls . handler @ functools . wraps ( func ) def wrapper ( self , request , suffix = '' ) : if request . method != "POST" : return JsonHandlerError ( 405 , "Method must be POST" ) . get_response ( allow = [ "POST" ] ) try : request_json = json . loads ( request . body ) except ValueError : return JsonHandlerError ( 400 , "Invalid JSON" ) . get_response ( ) try : response = func ( self , request_json , suffix ) except JsonHandlerError as err : return err . get_response ( ) if isinstance ( response , Response ) : return response else : return Response ( json . dumps ( response ) , content_type = 'application/json' , charset = 'utf8' ) return wrapper
Wrap a handler to consume and produce JSON .
45,910
def handle ( self , handler_name , request , suffix = '' ) : return self . runtime . handle ( self , handler_name , request , suffix )
Handle request with this block s runtime .
45,911
def _combined_services ( cls ) : combined = { } for parent in reversed ( cls . mro ( ) ) : combined . update ( getattr ( parent , "_services_requested" , { } ) ) return combined
A dictionary that collects all _services_requested by all ancestors of this XBlock class .
45,912
def needs ( cls , * service_names ) : def _decorator ( cls_ ) : for service_name in service_names : cls_ . _services_requested [ service_name ] = "need" return cls_ return _decorator
A class decorator to indicate that an XBlock class needs particular services .
45,913
def wants ( cls , * service_names ) : def _decorator ( cls_ ) : for service_name in service_names : cls_ . _services_requested [ service_name ] = "want" return cls_ return _decorator
A class decorator to indicate that an XBlock class wants particular services .
45,914
def get_parent ( self ) : if not self . has_cached_parent : if self . parent is not None : self . _parent_block = self . runtime . get_block ( self . parent ) else : self . _parent_block = None self . _parent_block_id = self . parent return self . _parent_block
Return the parent block of this block or None if there isn t one .
45,915
def get_child ( self , usage_id ) : if usage_id in self . _child_cache : return self . _child_cache [ usage_id ] child_block = self . runtime . get_block ( usage_id , for_parent = self ) self . _child_cache [ usage_id ] = child_block return child_block
Return the child identified by usage_id .
45,916
def get_children ( self , usage_id_filter = None ) : if not self . has_children : return [ ] return [ self . get_child ( usage_id ) for usage_id in self . children if usage_id_filter is None or usage_id_filter ( usage_id ) ]
Return instantiated XBlocks for each of this blocks children .
45,917
def add_children_to_node ( self , node ) : if self . has_children : for child_id in self . children : child = self . runtime . get_block ( child_id ) self . runtime . add_block_as_child_node ( child , node )
Add children to etree . Element node .
45,918
def parse_xml ( cls , node , runtime , keys , id_generator ) : block = runtime . construct_xblock_from_class ( cls , keys ) for child in node : if child . tag is etree . Comment : continue qname = etree . QName ( child ) tag = qname . localname namespace = qname . namespace if namespace == XML_NAMESPACES [ "option" ] : cls . _set_field_if_present ( block , tag , child . text , child . attrib ) else : block . runtime . add_node_as_child ( block , child , id_generator ) for name , value in node . items ( ) : cls . _set_field_if_present ( block , name , value , { } ) if "content" in block . fields and block . fields [ "content" ] . scope == Scope . content : text = node . text if text : text = text . strip ( ) if text : block . content = text return block
Use node to construct a new block .
45,919
def add_xml_to_node ( self , node ) : node . tag = self . xml_element_name ( ) node . set ( 'xblock-family' , self . entry_point ) for field_name , field in self . fields . items ( ) : if field_name in ( 'children' , 'parent' , 'content' ) : continue if field . is_set_on ( self ) or field . force_export : self . _add_field ( node , field_name , field ) text = self . xml_text_content ( ) if text is not None : node . text = text
For exporting set data on node from ourselves .
45,920
def _set_field_if_present ( cls , block , name , value , attrs ) : if name in block . fields : value = ( block . fields [ name ] ) . from_string ( value ) if "none" in attrs and attrs [ "none" ] == "true" : setattr ( block , name , None ) else : setattr ( block , name , value ) else : logging . warning ( "XBlock %s does not contain field %s" , type ( block ) , name )
Sets the field block . name if block have such a field .
45,921
def _add_field ( self , node , field_name , field ) : value = field . to_string ( field . read_from ( self ) ) text_value = "" if value is None else value save_none_as_xml_attr = field . none_to_xml and value is None field_attrs = { "none" : "true" } if save_none_as_xml_attr else { } if save_none_as_xml_attr or field . xml_node : tag = etree . QName ( XML_NAMESPACES [ "option" ] , field_name ) elem = etree . SubElement ( node , tag , field_attrs ) if field . xml_node : elem . text = text_value else : node . set ( field_name , text_value )
Add xml representation of field to node .
45,922
def supports ( cls , * functionalities ) : def _decorator ( view ) : if not hasattr ( view , "_supports" ) : view . _supports = set ( ) for functionality in functionalities : view . _supports . add ( functionality ) return view return _decorator
A view decorator to indicate that an xBlock view has support for the given functionalities .
45,923
def rescore ( self , only_if_higher ) : _ = self . runtime . service ( self , 'i18n' ) . ugettext if not self . allows_rescore ( ) : raise TypeError ( _ ( 'Problem does not support rescoring: {}' ) . format ( self . location ) ) if not self . has_submitted_answer ( ) : raise ValueError ( _ ( 'Cannot rescore unanswered problem: {}' ) . format ( self . location ) ) new_score = self . calculate_score ( ) self . _publish_grade ( new_score , only_if_higher )
Calculate a new raw score and save it to the block . If only_if_higher is True and the score didn t improve keep the existing score .
45,924
def _publish_grade ( self , score , only_if_higher = None ) : grade_dict = { 'value' : score . raw_earned , 'max_value' : score . raw_possible , 'only_if_higher' : only_if_higher , } self . runtime . publish ( self , 'grade' , grade_dict )
Publish a grade to the runtime .
45,925
def scope_key ( instance , xblock ) : scope_key_dict = { } scope_key_dict [ 'name' ] = instance . name if instance . scope . user == UserScope . NONE or instance . scope . user == UserScope . ALL : pass elif instance . scope . user == UserScope . ONE : scope_key_dict [ 'user' ] = six . text_type ( xblock . scope_ids . user_id ) else : raise NotImplementedError ( ) if instance . scope . block == BlockScope . TYPE : scope_key_dict [ 'block' ] = six . text_type ( xblock . scope_ids . block_type ) elif instance . scope . block == BlockScope . USAGE : scope_key_dict [ 'block' ] = six . text_type ( xblock . scope_ids . usage_id ) elif instance . scope . block == BlockScope . DEFINITION : scope_key_dict [ 'block' ] = six . text_type ( xblock . scope_ids . def_id ) elif instance . scope . block == BlockScope . ALL : pass else : raise NotImplementedError ( ) replacements = itertools . product ( "._-" , "._-" ) substitution_list = dict ( six . moves . zip ( "./\\,_ +:-" , ( "" . join ( x ) for x in replacements ) ) ) key_list = [ ] def encode ( char ) : if char . isalnum ( ) : return char elif char in substitution_list : return substitution_list [ char ] else : return "_{}_" . format ( ord ( char ) ) for item in [ 'block' , 'name' , 'user' ] : if item in scope_key_dict : field = scope_key_dict [ item ] if field . startswith ( "." ) or field . startswith ( "_" ) : field = "_" + field field = "" . join ( encode ( char ) for char in field ) else : field = "NONE.NONE" key_list . append ( field ) key = "/" . join ( key_list ) return key
Generate a unique key for a scope that can be used as a filename in a URL or in a KVS .
45,926
def default ( self ) : if self . MUTABLE : return copy . deepcopy ( self . _default ) else : return self . _default
Returns the static value that this defaults to .
45,927
def _set_cached_value ( self , xblock , value ) : if not hasattr ( xblock , '_field_data_cache' ) : xblock . _field_data_cache = { } xblock . _field_data_cache [ self . name ] = value
Store a value in the xblock s cache creating the cache if necessary .
45,928
def _del_cached_value ( self , xblock ) : if hasattr ( xblock , '_field_data_cache' ) and self . name in xblock . _field_data_cache : del xblock . _field_data_cache [ self . name ]
Remove a value from the xblock s cache if the cache exists .
45,929
def _mark_dirty ( self , xblock , value ) : if self not in xblock . _dirty_fields : xblock . _dirty_fields [ self ] = copy . deepcopy ( value )
Set this field to dirty on the xblock .
45,930
def _check_or_enforce_type ( self , value ) : if self . _enable_enforce_type : return self . enforce_type ( value ) try : new_value = self . enforce_type ( value ) except : message = "The value {!r} could not be enforced ({})" . format ( value , traceback . format_exc ( ) . splitlines ( ) [ - 1 ] ) warnings . warn ( message , FailingEnforceTypeWarning , stacklevel = 3 ) else : try : equal = value == new_value except TypeError : equal = False if not equal : message = "The value {!r} would be enforced to {!r}" . format ( value , new_value ) warnings . warn ( message , ModifyingEnforceTypeWarning , stacklevel = 3 ) return value
Depending on whether enforce_type is enabled call self . enforce_type and return the result or call it and trigger a silent warning if the result is different or a Traceback
45,931
def _calculate_unique_id ( self , xblock ) : key = scope_key ( self , xblock ) return hashlib . sha1 ( key . encode ( 'utf-8' ) ) . hexdigest ( )
Provide a default value for fields with default = UNIQUE_ID .
45,932
def _get_default_value_to_cache ( self , xblock ) : try : return self . from_json ( xblock . _field_data . default ( xblock , self . name ) ) except KeyError : if self . _default is UNIQUE_ID : return self . _check_or_enforce_type ( self . _calculate_unique_id ( xblock ) ) else : return self . default
Perform special logic to provide a field s default value for caching .
45,933
def _warn_deprecated_outside_JSONField ( self ) : if not isinstance ( self , JSONField ) and not self . warned : warnings . warn ( "Deprecated. JSONifiable fields should derive from JSONField ({name})" . format ( name = self . name ) , DeprecationWarning , stacklevel = 3 ) self . warned = True
Certain methods will be moved to JSONField .
45,934
def to_string ( self , value ) : self . _warn_deprecated_outside_JSONField ( ) value = json . dumps ( self . to_json ( value ) , indent = 2 , sort_keys = True , separators = ( ',' , ': ' ) , ) return value
Return a JSON serialized string representation of the value .
45,935
def from_string ( self , serialized ) : self . _warn_deprecated_outside_JSONField ( ) value = yaml . safe_load ( serialized ) return self . enforce_type ( value )
Returns a native value from a YAML serialized string representation . Since YAML is a superset of JSON this is the inverse of to_string . )
45,936
def read_json ( self , xblock ) : self . _warn_deprecated_outside_JSONField ( ) return self . to_json ( self . read_from ( xblock ) )
Retrieve the serialized value for this field from the specified xblock
45,937
def is_set_on ( self , xblock ) : return self . _is_dirty ( xblock ) or xblock . _field_data . has ( xblock , self . name )
Return whether this field has a non - default value on the supplied xblock
45,938
def to_string ( self , value ) : if isinstance ( value , six . binary_type ) : value = value . decode ( 'utf-8' ) return self . to_json ( value )
String gets serialized and deserialized without quote marks .
45,939
def from_json ( self , value ) : if value is None : return None if isinstance ( value , six . binary_type ) : value = value . decode ( 'utf-8' ) if isinstance ( value , six . text_type ) : if value == "" : return None try : value = dateutil . parser . parse ( value ) except ( TypeError , ValueError ) : raise ValueError ( "Could not parse {} as a date" . format ( value ) ) if not isinstance ( value , datetime . datetime ) : raise TypeError ( "Value should be loaded from a string, a datetime object or None, not {}" . format ( type ( value ) ) ) if value . tzinfo is not None : return value . astimezone ( pytz . utc ) else : return value . replace ( tzinfo = pytz . utc )
Parse the date from an ISO - formatted date string or None .
45,940
def to_json ( self , value ) : if isinstance ( value , datetime . datetime ) : return value . strftime ( self . DATETIME_FORMAT ) if value is None : return None raise TypeError ( "Value stored must be a datetime object, not {}" . format ( type ( value ) ) )
Serialize the date as an ISO - formatted date string or None .
45,941
def run_script ( pycode ) : if pycode [ 0 ] == "\n" : pycode = pycode [ 1 : ] pycode . rstrip ( ) pycode = textwrap . dedent ( pycode ) globs = { } six . exec_ ( pycode , globs , globs ) return globs
Run the Python in pycode and return a dict of the resulting globals .
45,942
def open_local_resource ( cls , uri ) : if isinstance ( uri , six . binary_type ) : uri = uri . decode ( 'utf-8' ) if cls . resources_dir is None : raise DisallowedFileError ( "This XBlock is not configured to serve local resources" ) if not uri . startswith ( cls . public_dir + '/' ) : raise DisallowedFileError ( "Only files from %r/ are allowed: %r" % ( cls . public_dir , uri ) ) if "/." in uri : raise DisallowedFileError ( "Only safe file names are allowed: %r" % uri ) return pkg_resources . resource_stream ( cls . __module__ , os . path . join ( cls . resources_dir , uri ) )
Open a local resource .
45,943
def _class_tags ( cls ) : class_tags = set ( ) for base in cls . mro ( ) [ 1 : ] : class_tags . update ( getattr ( base , '_class_tags' , set ( ) ) ) return class_tags
Collect the tags from all base classes .
45,944
def tag ( tags ) : def dec ( cls ) : cls . _class_tags . update ( tags . replace ( "," , " " ) . split ( ) ) return cls return dec
Returns a function that adds the words in tags as class tags to this class .
45,945
def load_tagged_classes ( cls , tag , fail_silently = True ) : for name , class_ in cls . load_classes ( fail_silently ) : if tag in class_ . _class_tags : yield name , class_
Produce a sequence of all XBlock classes tagged with tag .
45,946
def render ( self , view , context = None ) : return self . runtime . render ( self , view , context )
Render view with this block s runtime and the supplied context
45,947
def add_xml_to_node ( self , node ) : super ( XBlock , self ) . add_xml_to_node ( node ) self . add_children_to_node ( node )
For exporting set data on etree . Element node .
45,948
def aside_for ( cls , view_name ) : def _decorator ( func ) : if not hasattr ( func , '_aside_for' ) : func . _aside_for = [ ] func . _aside_for . append ( view_name ) return func return _decorator
A decorator to indicate a function is the aside view for the given view_name .
45,949
def aside_view_declaration ( self , view_name ) : if view_name in self . _combined_asides : return getattr ( self , self . _combined_asides [ view_name ] ) else : return None
Find and return a function object if one is an aside_view for the given view_name
45,950
def needs_serialization ( self ) : return any ( field . is_set_on ( self ) for field in six . itervalues ( self . fields ) )
Return True if the aside has any data to serialize to XML .
45,951
def add ( self , message ) : if not isinstance ( message , ValidationMessage ) : raise TypeError ( "Argument must of type ValidationMessage" ) self . messages . append ( message )
Add a new validation message to this instance .
45,952
def add_messages ( self , validation ) : if not isinstance ( validation , Validation ) : raise TypeError ( "Argument must be of type Validation" ) self . messages . extend ( validation . messages )
Adds all the messages in the specified Validation object to this instance s messages array .
45,953
def to_json ( self ) : return { "xblock_id" : six . text_type ( self . xblock_id ) , "messages" : [ message . to_json ( ) for message in self . messages ] , "empty" : self . empty }
Convert to a json - serializable representation .
45,954
def recarray_view ( qimage ) : raw = _qimage_or_filename_view ( qimage ) if raw . itemsize != 4 : raise ValueError ( "For rgb_view, the image must have 32 bit pixel size (use RGB32, ARGB32, or ARGB32_Premultiplied)" ) return raw . view ( bgra_dtype , _np . recarray )
Returns recarray_ view of a given 32 - bit color QImage_ s memory .
45,955
def gray2qimage ( gray , normalize = False ) : if _np . ndim ( gray ) != 2 : raise ValueError ( "gray2QImage can only convert 2D arrays" + " (try using array2qimage)" if _np . ndim ( gray ) == 3 else "" ) h , w = gray . shape result = _qt . QImage ( w , h , _qt . QImage . Format_Indexed8 ) if not _np . ma . is_masked ( gray ) : for i in range ( 256 ) : result . setColor ( i , _qt . qRgb ( i , i , i ) ) _qimageview ( result ) [ : ] = _normalize255 ( gray , normalize ) else : result . setColor ( 0 , _qt . qRgb ( 0 , 0 , 0 ) ) for i in range ( 2 , 256 ) : result . setColor ( i - 1 , _qt . qRgb ( i , i , i ) ) _qimageview ( result ) [ : ] = _normalize255 ( gray , normalize , clip = ( 1 , 255 ) ) - 1 result . setColor ( 255 , 0 ) _qimageview ( result ) [ gray . mask ] = 255 return result
Convert the 2D numpy array gray into a 8 - bit indexed QImage_ with a gray colormap . The first dimension represents the vertical image axis .
45,956
def getVariable ( self , name ) : return lock_and_call ( lambda : Variable ( self . _impl . getVariable ( name ) ) , self . _lock )
Get the variable with the corresponding name .
45,957
def getConstraint ( self , name ) : return lock_and_call ( lambda : Constraint ( self . _impl . getConstraint ( name ) ) , self . _lock )
Get the constraint with the corresponding name .
45,958
def getObjective ( self , name ) : return lock_and_call ( lambda : Objective ( self . _impl . getObjective ( name ) ) , self . _lock )
Get the objective with the corresponding name .
45,959
def getSet ( self , name ) : return lock_and_call ( lambda : Set ( self . _impl . getSet ( name ) ) , self . _lock )
Get the set with the corresponding name .
45,960
def getParameter ( self , name ) : return lock_and_call ( lambda : Parameter ( self . _impl . getParameter ( name ) ) , self . _lock )
Get the parameter with the corresponding name .
45,961
def eval ( self , amplstatements , ** kwargs ) : if self . _langext is not None : amplstatements = self . _langext . translate ( amplstatements , ** kwargs ) lock_and_call ( lambda : self . _impl . eval ( amplstatements ) , self . _lock ) self . _errorhandler_wrapper . check ( )
Parses AMPL code and evaluates it as a possibly empty sequence of AMPL declarations and statements .
45,962
def isBusy ( self ) : if self . _lock . acquire ( False ) : self . _lock . release ( ) return False else : return True
Returns true if the underlying engine is doing an async operation .
45,963
def evalAsync ( self , amplstatements , callback , ** kwargs ) : if self . _langext is not None : amplstatements = self . _langext . translate ( amplstatements , ** kwargs ) def async_call ( ) : self . _lock . acquire ( ) try : self . _impl . eval ( amplstatements ) self . _errorhandler_wrapper . check ( ) except Exception : self . _lock . release ( ) raise else : self . _lock . release ( ) callback . run ( ) Thread ( target = async_call ) . start ( )
Interpret the given AMPL statement asynchronously .
45,964
def solveAsync ( self , callback ) : def async_call ( ) : self . _lock . acquire ( ) try : self . _impl . solve ( ) except Exception : self . _lock . release ( ) raise else : self . _lock . release ( ) callback . run ( ) Thread ( target = async_call ) . start ( )
Solve the current model asynchronously .
45,965
def setOption ( self , name , value ) : if isinstance ( value , bool ) : lock_and_call ( lambda : self . _impl . setBoolOption ( name , value ) , self . _lock ) elif isinstance ( value , int ) : lock_and_call ( lambda : self . _impl . setIntOption ( name , value ) , self . _lock ) elif isinstance ( value , float ) : lock_and_call ( lambda : self . _impl . setDblOption ( name , value ) , self . _lock ) elif isinstance ( value , basestring ) : lock_and_call ( lambda : self . _impl . setOption ( name , value ) , self . _lock ) else : raise TypeError
Set an AMPL option to a specified value .
45,966
def getOption ( self , name ) : try : value = lock_and_call ( lambda : self . _impl . getOption ( name ) . value ( ) , self . _lock ) except RuntimeError : return None else : try : return int ( value ) except ValueError : try : return float ( value ) except ValueError : return value
Get the current value of the specified option . If the option does not exist returns None .
45,967
def getValue ( self , scalarExpression ) : return lock_and_call ( lambda : Utils . castVariant ( self . _impl . getValue ( scalarExpression ) ) , self . _lock )
Get a scalar value from the underlying AMPL interpreter as a double or a string .
45,968
def setData ( self , data , setName = None ) : if not isinstance ( data , DataFrame ) : if pd is not None and isinstance ( data , pd . DataFrame ) : data = DataFrame . fromPandas ( data ) if setName is None : lock_and_call ( lambda : self . _impl . setData ( data . _impl ) , self . _lock ) else : lock_and_call ( lambda : self . _impl . setData ( data . _impl , setName ) , self . _lock )
Assign the data in the dataframe to the AMPL entities with the names corresponding to the column names .
45,969
def writeTable ( self , tableName ) : lock_and_call ( lambda : self . _impl . writeTable ( tableName ) , self . _lock )
Write the table corresponding to the specified name equivalent to the AMPL statement
45,970
def display ( self , * amplExpressions ) : exprs = list ( map ( str , amplExpressions ) ) lock_and_call ( lambda : self . _impl . displayLst ( exprs , len ( exprs ) ) , self . _lock )
Writes on the current OutputHandler the outcome of the AMPL statement .
45,971
def setOutputHandler ( self , outputhandler ) : class OutputHandlerInternal ( amplpython . OutputHandler ) : def output ( self , kind , msg ) : outputhandler . output ( kind , msg ) self . _outputhandler = outputhandler self . _outputhandler_internal = OutputHandlerInternal ( ) lock_and_call ( lambda : self . _impl . setOutputHandler ( self . _outputhandler_internal ) , self . _lock )
Sets a new output handler .
45,972
def setErrorHandler ( self , errorhandler ) : class ErrorHandlerWrapper ( ErrorHandler ) : def __init__ ( self , errorhandler ) : self . errorhandler = errorhandler self . last_exception = None def error ( self , exception ) : if isinstance ( exception , amplpython . AMPLException ) : exception = AMPLException ( exception ) try : self . errorhandler . error ( exception ) except Exception as e : self . last_exception = e def warning ( self , exception ) : if isinstance ( exception , amplpython . AMPLException ) : exception = AMPLException ( exception ) try : self . errorhandler . warning ( exception ) except Exception as e : self . last_exception = e def check ( self ) : if self . last_exception is not None : e , self . last_exception = self . last_exception , None raise e errorhandler_wrapper = ErrorHandlerWrapper ( errorhandler ) class InnerErrorHandler ( amplpython . ErrorHandler ) : def error ( self , exception ) : errorhandler_wrapper . error ( exception ) def warning ( self , exception ) : errorhandler_wrapper . warning ( exception ) self . _errorhandler = errorhandler self . _errorhandler_inner = InnerErrorHandler ( ) self . _errorhandler_wrapper = errorhandler_wrapper lock_and_call ( lambda : self . _impl . setErrorHandler ( self . _errorhandler_inner ) , self . _lock )
Sets a new error handler .
45,973
def getVariables ( self ) : variables = lock_and_call ( lambda : self . _impl . getVariables ( ) , self . _lock ) return EntityMap ( variables , Variable )
Get all the variables declared .
45,974
def getConstraints ( self ) : constraints = lock_and_call ( lambda : self . _impl . getConstraints ( ) , self . _lock ) return EntityMap ( constraints , Constraint )
Get all the constraints declared .
45,975
def getObjectives ( self ) : objectives = lock_and_call ( lambda : self . _impl . getObjectives ( ) , self . _lock ) return EntityMap ( objectives , Objective )
Get all the objectives declared .
45,976
def getSets ( self ) : sets = lock_and_call ( lambda : self . _impl . getSets ( ) , self . _lock ) return EntityMap ( sets , Set )
Get all the sets declared .
45,977
def getParameters ( self ) : parameters = lock_and_call ( lambda : self . _impl . getParameters ( ) , self . _lock ) return EntityMap ( parameters , Parameter )
Get all the parameters declared .
45,978
def getCurrentObjective ( self ) : name = self . _impl . getCurrentObjectiveName ( ) if name == '' : return None else : return self . getObjective ( name )
Get the the current objective . Returns None if no objective is set .
45,979
def _obj ( self ) : class Objectives ( object ) : def __getitem__ ( _self , name ) : return self . getObjective ( name ) def __iter__ ( _self ) : return self . getObjectives ( ) return Objectives ( )
Get an objective .
45,980
def exportData ( self , datfile ) : def ampl_set ( name , values ) : def format_entry ( e ) : return repr ( e ) . replace ( ' ' , '' ) return 'set {0} := {1};' . format ( name , ',' . join ( format_entry ( e ) for e in values ) ) def ampl_param ( name , values ) : def format_entry ( k , v ) : k = repr ( k ) . strip ( '()' ) . replace ( ' ' , '' ) if v == inf : v = "Infinity" elif v == - inf : v = "-Infinity" else : v = repr ( v ) . strip ( '()' ) . replace ( ' ' , '' ) return '[{0}]{1}' . format ( k , v ) return 'param {0} := {1};' . format ( name , '' . join ( format_entry ( k , v ) for k , v in values . items ( ) ) ) with open ( datfile , 'w' ) as f : for name , entity in self . getSets ( ) : values = entity . getValues ( ) . toList ( ) print ( ampl_set ( name , values ) , file = f ) for name , entity in self . getParameters ( ) : if entity . isScalar ( ) : print ( 'param {} := {};' . format ( name , entity . value ( ) ) , file = f ) else : values = entity . getValues ( ) . toDict ( ) print ( ampl_param ( name , values ) , file = f )
Create a . dat file with the data that has been loaded .
45,981
def importGurobiSolution ( self , grbmodel ) : self . eval ( '' . join ( 'let {} := {};' . format ( var . VarName , var . X ) for var in grbmodel . getVars ( ) if '$' not in var . VarName ) )
Import the solution from a gurobipy . Model object .
45,982
def _startRecording ( self , filename ) : self . setOption ( '_log_file_name' , filename ) self . setOption ( '_log_input_only' , True ) self . setOption ( '_log' , True )
Start recording the session to a file for debug purposes .
45,983
def _loadSession ( self , filename ) : try : self . eval ( open ( filename ) . read ( ) ) except RuntimeError as e : print ( e )
Load a recorded session .
45,984
def ls_dir ( base_dir ) : return [ os . path . join ( dirpath . replace ( base_dir , '' , 1 ) , f ) for ( dirpath , dirnames , files ) in os . walk ( base_dir ) for f in files ]
List files recursively .
45,985
def get ( self , * index ) : assert self . wrapFunction is not None if len ( index ) == 1 and isinstance ( index [ 0 ] , ( tuple , list ) ) : index = index [ 0 ] if len ( index ) == 0 : return self . wrapFunction ( self . _impl . get ( ) ) else : return self . wrapFunction ( self . _impl . get ( Tuple ( index ) . _impl ) )
Get the instance with the specified index .
45,986
def find ( self , * index ) : assert self . wrapFunction is not None if len ( index ) == 1 and isinstance ( index [ 0 ] , ( tuple , list ) ) : index = index [ 0 ] it = self . _impl . find ( Tuple ( index ) . _impl ) if it == self . _impl . end ( ) : return None else : return self . wrapFunction ( it )
Searches the current entity for an instance with the specified index .
45,987
def addRow ( self , * value ) : if len ( value ) == 1 and isinstance ( value [ 0 ] , ( tuple , list ) ) : value = value [ 0 ] assert len ( value ) == self . getNumCols ( ) self . _impl . addRow ( Tuple ( value ) . _impl )
Add a row to the DataFrame . The size of the tuple must be equal to the total number of columns in the dataframe .
45,988
def addColumn ( self , header , values = [ ] ) : if len ( values ) == 0 : self . _impl . addColumn ( header ) else : assert len ( values ) == self . getNumRows ( ) if any ( isinstance ( value , basestring ) for value in values ) : values = list ( map ( str , values ) ) self . _impl . addColumnStr ( header , values ) elif all ( isinstance ( value , Real ) for value in values ) : values = list ( map ( float , values ) ) self . _impl . addColumnDbl ( header , values ) else : raise NotImplementedError
Add a new column with the corresponding header and values to the dataframe .
45,989
def setColumn ( self , header , values ) : if any ( isinstance ( value , basestring ) for value in values ) : values = list ( map ( str , values ) ) self . _impl . setColumnStr ( header , values , len ( values ) ) elif all ( isinstance ( value , Real ) for value in values ) : values = list ( map ( float , values ) ) self . _impl . setColumnDbl ( header , values , len ( values ) ) else : print ( values ) raise NotImplementedError
Set the values of a column .
45,990
def getRow ( self , key ) : return Row ( self . _impl . getRow ( Tuple ( key ) . _impl ) )
Get a row by value of the indexing columns . If the index is not specified gets the only row of a dataframe with no indexing columns .
45,991
def getRowByIndex ( self , index ) : assert isinstance ( index , int ) return Row ( self . _impl . getRowByIndex ( index ) )
Get row by numeric index .
45,992
def getHeaders ( self ) : headers = self . _impl . getHeaders ( ) return tuple ( headers . getIndex ( i ) for i in range ( self . _impl . getNumCols ( ) ) )
Get the headers of this DataFrame .
45,993
def setValues ( self , values ) : ncols = self . getNumCols ( ) nindices = self . getNumIndices ( ) for key , value in values . items ( ) : key = Utils . convToList ( key ) assert len ( key ) == nindices value = Utils . convToList ( value ) assert len ( value ) == ncols - nindices self . addRow ( key + value )
Set the values of a DataFrame from a dictionary .
45,994
def toDict ( self ) : d = { } nindices = self . getNumIndices ( ) for i in range ( self . getNumRows ( ) ) : row = list ( self . getRowByIndex ( i ) ) if nindices > 1 : key = tuple ( row [ : nindices ] ) elif nindices == 1 : key = row [ 0 ] else : key = None if len ( row ) - nindices == 0 : d [ key ] = None elif len ( row ) - nindices == 1 : d [ key ] = row [ nindices ] else : d [ key ] = tuple ( row [ nindices : ] ) return d
Return a dictionary with the DataFrame data .
45,995
def toList ( self ) : if self . getNumCols ( ) > 1 : return [ tuple ( self . getRowByIndex ( i ) ) for i in range ( self . getNumRows ( ) ) ] else : return [ self . getRowByIndex ( i ) [ 0 ] for i in range ( self . getNumRows ( ) ) ]
Return a list with the DataFrame data .
45,996
def toPandas ( self ) : assert pd is not None nindices = self . getNumIndices ( ) headers = self . getHeaders ( ) columns = { header : list ( self . getColumn ( header ) ) for header in headers [ nindices : ] } index = zip ( * [ list ( self . getColumn ( header ) ) for header in headers [ : nindices ] ] ) index = [ key if len ( key ) > 1 else key [ 0 ] for key in index ] if index == [ ] : return pd . DataFrame ( columns , index = None ) else : return pd . DataFrame ( columns , index = index )
Return a pandas DataFrame with the DataFrame data .
45,997
def set ( self , * args ) : assert len ( args ) in ( 1 , 2 ) if len ( args ) == 1 : value = args [ 0 ] self . _impl . set ( value ) else : index , value = args if isinstance ( value , Real ) : self . _impl . setTplDbl ( Tuple ( index ) . _impl , value ) elif isinstance ( value , basestring ) : self . _impl . setTplStr ( Tuple ( index ) . _impl , value ) else : raise TypeError
Set the value of a single instance of this parameter .
45,998
def setValues ( self , values ) : if isinstance ( values , ( list , set ) ) : if any ( isinstance ( value , basestring ) for value in values ) : values = list ( map ( str , values ) ) self . _impl . setValuesStr ( values , len ( values ) ) elif all ( isinstance ( value , Real ) for value in values ) : values = list ( map ( float , values ) ) self . _impl . setValuesDbl ( values , len ( values ) ) elif all ( isinstance ( value , tuple ) for value in values ) : self . _impl . setValues ( Utils . toTupleArray ( values ) , len ( values ) ) else : raise TypeError else : if np is not None and isinstance ( values , np . ndarray ) : self . setValues ( DataFrame . fromNumpy ( values ) . toList ( ) ) return Entity . setValues ( self , values )
Set the tuples in this set . Valid only for non - indexed sets .
45,999
def error ( self , amplexception ) : msg = '\t' + str ( amplexception ) . replace ( '\n' , '\n\t' ) print ( 'Error:\n{:s}' . format ( msg ) ) raise amplexception
Receives notification of an error .