idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
234,800 | 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 . ) |
234,801 | 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 |
234,802 | 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 |
234,803 | 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 . |
234,804 | 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... | Parse the date from an ISO - formatted date string or None . |
234,805 | 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 . |
234,806 | 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 . |
234,807 | 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 ( "Onl... | Open a local resource . |
234,808 | 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 . |
234,809 | 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 . |
234,810 | 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 . |
234,811 | def render ( self , view , context = None ) : return self . runtime . render ( self , view , context ) | Render view with this block s runtime and the supplied context |
234,812 | 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 . |
234,813 | 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 . |
234,814 | 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 |
234,815 | 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 . |
234,816 | 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 . |
234,817 | 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 . |
234,818 | 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 . |
234,819 | 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 . |
234,820 | 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 (... | Convert the 2D numpy array gray into a 8 - bit indexed QImage_ with a gray colormap . The first dimension represents the vertical image axis . |
234,821 | def getVariable ( self , name ) : return lock_and_call ( lambda : Variable ( self . _impl . getVariable ( name ) ) , self . _lock ) | Get the variable with the corresponding name . |
234,822 | def getConstraint ( self , name ) : return lock_and_call ( lambda : Constraint ( self . _impl . getConstraint ( name ) ) , self . _lock ) | Get the constraint with the corresponding name . |
234,823 | def getObjective ( self , name ) : return lock_and_call ( lambda : Objective ( self . _impl . getObjective ( name ) ) , self . _lock ) | Get the objective with the corresponding name . |
234,824 | def getSet ( self , name ) : return lock_and_call ( lambda : Set ( self . _impl . getSet ( name ) ) , self . _lock ) | Get the set with the corresponding name . |
234,825 | def getParameter ( self , name ) : return lock_and_call ( lambda : Parameter ( self . _impl . getParameter ( name ) ) , self . _lock ) | Get the parameter with the corresponding name . |
234,826 | 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 . |
234,827 | 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 . |
234,828 | 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 Excep... | Interpret the given AMPL statement asynchronously . |
234,829 | 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 . |
234,830 | 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 ) : lo... | Set an AMPL option to a specified value . |
234,831 | 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 . |
234,832 | 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 . |
234,833 | 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... | Assign the data in the dataframe to the AMPL entities with the names corresponding to the column names . |
234,834 | 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 |
234,835 | 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 . |
234,836 | 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 . s... | Sets a new output handler . |
234,837 | 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 ( except... | Sets a new error handler . |
234,838 | def getVariables ( self ) : variables = lock_and_call ( lambda : self . _impl . getVariables ( ) , self . _lock ) return EntityMap ( variables , Variable ) | Get all the variables declared . |
234,839 | def getConstraints ( self ) : constraints = lock_and_call ( lambda : self . _impl . getConstraints ( ) , self . _lock ) return EntityMap ( constraints , Constraint ) | Get all the constraints declared . |
234,840 | def getObjectives ( self ) : objectives = lock_and_call ( lambda : self . _impl . getObjectives ( ) , self . _lock ) return EntityMap ( objectives , Objective ) | Get all the objectives declared . |
234,841 | def getSets ( self ) : sets = lock_and_call ( lambda : self . _impl . getSets ( ) , self . _lock ) return EntityMap ( sets , Set ) | Get all the sets declared . |
234,842 | def getParameters ( self ) : parameters = lock_and_call ( lambda : self . _impl . getParameters ( ) , self . _lock ) return EntityMap ( parameters , Parameter ) | Get all the parameters declared . |
234,843 | 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 . |
234,844 | 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 . |
234,845 | 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 ( '... | Create a . dat file with the data that has been loaded . |
234,846 | 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 . |
234,847 | 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 . |
234,848 | def _loadSession ( self , filename ) : try : self . eval ( open ( filename ) . read ( ) ) except RuntimeError as e : print ( e ) | Load a recorded session . |
234,849 | 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 . |
234,850 | 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 . |
234,851 | 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 . |
234,852 | 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 . |
234,853 | 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 ) el... | Add a new column with the corresponding header and values to the dataframe . |
234,854 | 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 ) ) se... | Set the values of a column . |
234,855 | 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 . |
234,856 | def getRowByIndex ( self , index ) : assert isinstance ( index , int ) return Row ( self . _impl . getRowByIndex ( index ) ) | Get row by numeric index . |
234,857 | 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 . |
234,858 | 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 . |
234,859 | 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 ( ... | Return a dictionary with the DataFrame data . |
234,860 | 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 . |
234,861 | 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... | Return a pandas DataFrame with the DataFrame data . |
234,862 | 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 ... | Set the value of a single instance of this parameter . |
234,863 | 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 ( m... | Set the tuples in this set . Valid only for non - indexed sets . |
234,864 | 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 . |
234,865 | def warning ( self , amplexception ) : msg = '\t' + str ( amplexception ) . replace ( '\n' , '\n\t' ) print ( 'Warning:\n{:s}' . format ( msg ) ) | Receives notification of a warning . |
234,866 | def register_magics ( store_name = '_ampl_cells' , ampl_object = None ) : from IPython . core . magic import ( Magics , magics_class , cell_magic , line_magic ) @ magics_class class StoreAMPL ( Magics ) : def __init__ ( self , shell = None , ** kwargs ) : Magics . __init__ ( self , shell = shell , ** kwargs ) self . _s... | Register jupyter notebook magics %%ampl and %%ampl_eval . |
234,867 | def fix ( self , value = None ) : if value is None : self . _impl . fix ( ) else : self . _impl . fix ( value ) | Fix all instances of this variable to a value if provided or to their current value otherwise . |
234,868 | def toVName ( name , stripNum = 0 , upper = False ) : if upper : name = name . upper ( ) if stripNum != 0 : name = name [ : - stripNum ] return name . replace ( '_' , '-' ) | Turn a Python name into an iCalendar style name optionally uppercase and with characters stripped off . |
234,869 | def readComponents ( streamOrString , validate = False , transform = True , ignoreUnreadable = False , allowQP = False ) : if isinstance ( streamOrString , basestring ) : stream = six . StringIO ( streamOrString ) else : stream = streamOrString try : stack = Stack ( ) versionLine = None n = 0 for line , n in getLogical... | Generate one Component at a time from a stream . |
234,870 | def readOne ( stream , validate = False , transform = True , ignoreUnreadable = False , allowQP = False ) : return next ( readComponents ( stream , validate , transform , ignoreUnreadable , allowQP ) ) | Return the first component from stream . |
234,871 | def registerBehavior ( behavior , name = None , default = False , id = None ) : if not name : name = behavior . name . upper ( ) if id is None : id = behavior . versionString if name in __behaviorRegistry : if default : __behaviorRegistry [ name ] . insert ( 0 , ( id , behavior ) ) else : __behaviorRegistry [ name ] . ... | Register the given behavior . |
234,872 | def getBehavior ( name , id = None ) : name = name . upper ( ) if name in __behaviorRegistry : if id : for n , behavior in __behaviorRegistry [ name ] : if n == id : return behavior return __behaviorRegistry [ name ] [ 0 ] [ 1 ] return None | Return a matching behavior if it exists or None . |
234,873 | def validate ( self , * args , ** kwds ) : if self . behavior : return self . behavior . validate ( self , * args , ** kwds ) return True | Call the behavior s validate method or return True . |
234,874 | def autoBehavior ( self , cascade = False ) : parentBehavior = self . parentBehavior if parentBehavior is not None : knownChildTup = parentBehavior . knownChildren . get ( self . name , None ) if knownChildTup is not None : behavior = getBehavior ( self . name , knownChildTup [ 2 ] ) if behavior is not None : self . se... | Set behavior if name is in self . parentBehavior . knownChildren . |
234,875 | def setBehavior ( self , behavior , cascade = True ) : self . behavior = behavior if cascade : for obj in self . getChildren ( ) : obj . parentBehavior = behavior obj . autoBehavior ( True ) | Set behavior . If cascade is True autoBehavior all descendants . |
234,876 | def serialize ( self , buf = None , lineLength = 75 , validate = True , behavior = None ) : if not behavior : behavior = self . behavior if behavior : if DEBUG : logger . debug ( "serializing {0!s} with behavior {1!s}" . format ( self . name , behavior ) ) return behavior . serialize ( self , buf , lineLength , validat... | Serialize to buf if it exists otherwise return a string . |
234,877 | def valueRepr ( self ) : v = self . value if self . behavior : v = self . behavior . valueRepr ( self ) return v | Transform the representation of the value according to the behavior if any . |
234,878 | def setProfile ( self , name ) : if self . name or self . useBegin : if self . name == name : return raise VObjectError ( "This component already has a PROFILE or " "uses BEGIN." ) self . name = name . upper ( ) | Assign a PROFILE to this unnamed component . |
234,879 | def add ( self , objOrName , group = None ) : if isinstance ( objOrName , VBase ) : obj = objOrName if self . behavior : obj . parentBehavior = self . behavior obj . autoBehavior ( True ) else : name = objOrName . upper ( ) try : id = self . behavior . knownChildren [ name ] [ 2 ] behavior = getBehavior ( name , id ) i... | Add objOrName to contents set behavior if it can be inferred . |
234,880 | def remove ( self , obj ) : named = self . contents . get ( obj . name . lower ( ) ) if named : try : named . remove ( obj ) if len ( named ) == 0 : del self . contents [ obj . name . lower ( ) ] except ValueError : pass | Remove obj from contents . |
234,881 | def setBehaviorFromVersionLine ( self , versionLine ) : v = getBehavior ( self . name , versionLine . value ) if v : self . setBehavior ( v ) | Set behavior if one matches name versionLine . value . |
234,882 | def transformChildrenToNative ( self ) : for childArray in ( self . contents [ k ] for k in self . sortChildKeys ( ) ) : for child in childArray : child = child . transformToNative ( ) child . transformChildrenToNative ( ) | Recursively replace children with their native representation . |
234,883 | def transformChildrenFromNative ( self , clearBehavior = True ) : for childArray in self . contents . values ( ) : for child in childArray : child = child . transformFromNative ( ) child . transformChildrenFromNative ( clearBehavior ) if clearBehavior : child . behavior = None child . parentBehavior = None | Recursively transform native children to vanilla representations . |
234,884 | def change_tz ( cal , new_timezone , default , utc_only = False , utc_tz = icalendar . utc ) : for vevent in getattr ( cal , 'vevent_list' , [ ] ) : start = getattr ( vevent , 'dtstart' , None ) end = getattr ( vevent , 'dtend' , None ) for node in ( start , end ) : if node : dt = node . value if ( isinstance ( dt , da... | Change the timezone of the specified component . |
234,885 | def defaultSerialize ( obj , buf , lineLength ) : outbuf = buf or six . StringIO ( ) if isinstance ( obj , Component ) : if obj . group is None : groupString = '' else : groupString = obj . group + '.' if obj . useBegin : foldOneLine ( outbuf , "{0}BEGIN:{1}" . format ( groupString , obj . name ) , lineLength ) for chi... | Encode and fold obj and its children write to buf or return a string . |
234,886 | def toUnicode ( s ) : if isinstance ( s , six . binary_type ) : s = s . decode ( 'utf-8' ) return s | Take a string or unicode turn it into unicode decoding as utf - 8 |
234,887 | def numToDigits ( num , places ) : s = str ( num ) if len ( s ) < places : return ( "0" * ( places - len ( s ) ) ) + s elif len ( s ) > places : return s [ len ( s ) - places : ] else : return s | Helper for converting numbers to textual digits . |
234,888 | def timedeltaToString ( delta ) : if delta . days == 0 : sign = 1 else : sign = delta . days / abs ( delta . days ) delta = abs ( delta ) days = delta . days hours = int ( delta . seconds / 3600 ) minutes = int ( ( delta . seconds % 3600 ) / 60 ) seconds = int ( delta . seconds % 60 ) output = '' if sign == - 1 : outpu... | Convert timedelta to an ical DURATION . |
234,889 | def stringToTextValues ( s , listSeparator = ',' , charList = None , strict = False ) : if charList is None : charList = escapableCharList def escapableChar ( c ) : return c in charList def error ( msg ) : if strict : raise ParseError ( msg ) else : logging . error ( msg ) charIterator = enumerate ( s ) state = "read n... | Returns list of strings . |
234,890 | def parseDtstart ( contentline , allowSignatureMismatch = False ) : tzinfo = getTzid ( getattr ( contentline , 'tzid_param' , None ) ) valueParam = getattr ( contentline , 'value_param' , 'DATE-TIME' ) . upper ( ) if valueParam == "DATE" : return stringToDate ( contentline . value ) elif valueParam == "DATE-TIME" : try... | Convert a contentline s value into a date or date - time . |
234,891 | def tzinfo_eq ( tzinfo1 , tzinfo2 , startYear = 2000 , endYear = 2020 ) : if tzinfo1 == tzinfo2 : return True elif tzinfo1 is None or tzinfo2 is None : return False def dt_test ( dt ) : if dt is None : return True return tzinfo1 . utcoffset ( dt ) == tzinfo2 . utcoffset ( dt ) if not dt_test ( datetime . datetime ( sta... | Compare offsets and DST transitions from startYear to endYear . |
234,892 | def registerTzinfo ( obj , tzinfo ) : tzid = obj . pickTzid ( tzinfo ) if tzid and not getTzid ( tzid , False ) : registerTzid ( tzid , tzinfo ) return tzid | Register tzinfo if it s not already registered return its tzid . |
234,893 | def pickTzid ( tzinfo , allowUTC = False ) : if tzinfo is None or ( not allowUTC and tzinfo_eq ( tzinfo , utc ) ) : return None if hasattr ( tzinfo , 'tzid' ) : return toUnicode ( tzinfo . tzid ) if hasattr ( tzinfo , 'zone' ) : return toUnicode ( tzinfo . zone ) elif hasattr ( tzinfo , '_tzid' ) : return toUnicode ( t... | Given a tzinfo class use known APIs to determine TZID or use tzname . |
234,894 | def transformToNative ( obj ) : if not obj . isNative : object . __setattr__ ( obj , '__class__' , RecurringComponent ) obj . isNative = True return obj | Turn a recurring Component into a RecurringComponent . |
234,895 | def generateImplicitParameters ( obj ) : if not hasattr ( obj , 'uid' ) : rand = int ( random . random ( ) * 100000 ) now = datetime . datetime . now ( utc ) now = dateTimeToString ( now ) host = socket . gethostname ( ) obj . add ( ContentLine ( 'UID' , [ ] , "{0} - {1}@{2}" . format ( now , rand , host ) ) ) | Generate a UID if one does not exist . |
234,896 | def transformToNative ( obj ) : if obj . isNative : return obj obj . isNative = True if obj . value == '' : return obj obj . value = obj . value obj . value = parseDtstart ( obj , allowSignatureMismatch = True ) if getattr ( obj , 'value_param' , 'DATE-TIME' ) . upper ( ) == 'DATE-TIME' : if hasattr ( obj , 'tzid_param... | Turn obj . value into a date or datetime . |
234,897 | def transformFromNative ( obj ) : if type ( obj . value ) == datetime . date : obj . isNative = False obj . value_param = 'DATE' obj . value = dateToString ( obj . value ) return obj else : return DateTimeBehavior . transformFromNative ( obj ) | Replace the date or datetime in obj . value with an ISO 8601 string . |
234,898 | def transformFromNative ( obj ) : if obj . value and type ( obj . value [ 0 ] ) == datetime . date : obj . isNative = False obj . value_param = 'DATE' obj . value = ',' . join ( [ dateToString ( val ) for val in obj . value ] ) return obj else : if obj . isNative : obj . isNative = False transformed = [ ] tzid = None f... | Replace the date datetime or period tuples in obj . value with appropriate strings . |
234,899 | def decode ( cls , line ) : if line . encoded : line . value = stringToTextValues ( line . value , listSeparator = cls . listSeparator ) line . encoded = False | Remove backslash escaping from line . value then split on commas . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.