idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
24,400 | def _follow_link ( self , value ) : seen_keys = set ( ) while True : link_key = self . _link_for_value ( value ) if not link_key : return value assert link_key not in seen_keys , 'circular symlink reference' seen_keys . add ( link_key ) value = super ( SymlinkDatastore , self ) . get ( link_key ) | Returns given value or if it is a symlink the value it names . | 92 | 16 |
24,401 | def link ( self , source_key , target_key ) : link_value = self . _link_value_for_key ( source_key ) # put straight into the child, to avoid following previous links. self . child_datastore . put ( target_key , link_value ) # exercise the link. ensure there are no cycles. self . get ( target_key ) | Creates a symbolic link key pointing from target_key to source_key | 83 | 15 |
24,402 | def get ( self , key ) : value = super ( SymlinkDatastore , self ) . get ( key ) return self . _follow_link ( value ) | Return the object named by key . Follows links . | 36 | 11 |
24,403 | def put ( self , key , value ) : # if value is a link, don't follow links if self . _link_for_value ( value ) : super ( SymlinkDatastore , self ) . put ( key , value ) return # if `key` points to a symlink, need to follow it. current_value = super ( SymlinkDatastore , self ) . get ( key ) link_key = self . _link_for_value ( current_value ) if link_key : self . put ( link_key , value ) # self.put: could be another link. else : super ( SymlinkDatastore , self ) . put ( key , value ) | Stores the object named by key . Follows links . | 152 | 12 |
24,404 | def query ( self , query ) : results = super ( SymlinkDatastore , self ) . query ( query ) return self . _follow_link_gen ( results ) | Returns objects matching criteria expressed in query . Follows links . | 38 | 12 |
24,405 | def directory ( self , dir_key ) : dir_items = self . get ( dir_key ) if not isinstance ( dir_items , list ) : self . put ( dir_key , [ ] ) | Initializes directory at dir_key . | 45 | 8 |
24,406 | def directoryAdd ( self , dir_key , key ) : key = str ( key ) dir_items = self . get ( dir_key ) or [ ] if key not in dir_items : dir_items . append ( key ) self . put ( dir_key , dir_items ) | Adds directory entry key to directory at dir_key . | 62 | 11 |
24,407 | def directoryRemove ( self , dir_key , key ) : key = str ( key ) dir_items = self . get ( dir_key ) or [ ] if key in dir_items : dir_items = [ k for k in dir_items if k != key ] self . put ( dir_key , dir_items ) | Removes directory entry key from directory at dir_key . | 70 | 12 |
24,408 | def put ( self , key , value ) : super ( DirectoryTreeDatastore , self ) . put ( key , value ) str_key = str ( key ) # ignore root if str_key == '/' : return # retrieve directory, to add entry dir_key = key . parent . instance ( 'directory' ) directory = self . directory ( dir_key ) # ensure key is in directory if str_key not in directory : directory . append ( str_key ) super ( DirectoryTreeDatastore , self ) . put ( dir_key , directory ) | Stores the object value named by key self . DirectoryTreeDatastore stores a directory entry . | 119 | 20 |
24,409 | def delete ( self , key ) : super ( DirectoryTreeDatastore , self ) . delete ( key ) str_key = str ( key ) # ignore root if str_key == '/' : return # retrieve directory, to remove entry dir_key = key . parent . instance ( 'directory' ) directory = self . directory ( dir_key ) # ensure key is not in directory if directory and str_key in directory : directory . remove ( str_key ) if len ( directory ) > 0 : super ( DirectoryTreeDatastore , self ) . put ( dir_key , directory ) else : super ( DirectoryTreeDatastore , self ) . delete ( dir_key ) | Removes the object named by key . DirectoryTreeDatastore removes the directory entry . | 144 | 18 |
24,410 | def directory ( self , key ) : if key . name != 'directory' : key = key . instance ( 'directory' ) return self . get ( key ) or [ ] | Retrieves directory entries for given key . | 37 | 9 |
24,411 | def directory_values_generator ( self , key ) : directory = self . directory ( key ) for key in directory : yield self . get ( Key ( key ) ) | Retrieve directory values for given key . | 36 | 8 |
24,412 | def appendDatastore ( self , store ) : if not isinstance ( store , Datastore ) : raise TypeError ( "stores must be of type %s" % Datastore ) self . _stores . append ( store ) | Appends datastore store to this collection . | 50 | 10 |
24,413 | def insertDatastore ( self , index , store ) : if not isinstance ( store , Datastore ) : raise TypeError ( "stores must be of type %s" % Datastore ) self . _stores . insert ( index , store ) | Inserts datastore store into this collection at index . | 54 | 12 |
24,414 | def get ( self , key ) : value = None for store in self . _stores : value = store . get ( key ) if value is not None : break # add model to lower stores only if value is not None : for store2 in self . _stores : if store == store2 : break store2 . put ( key , value ) return value | Return the object named by key . Checks each datastore in order . | 74 | 15 |
24,415 | def put ( self , key , value ) : for store in self . _stores : store . put ( key , value ) | Stores the object in all underlying datastores . | 26 | 11 |
24,416 | def contains ( self , key ) : for store in self . _stores : if store . contains ( key ) : return True return False | Returns whether the object is in this datastore . | 28 | 11 |
24,417 | def put ( self , key , value ) : self . shardDatastore ( key ) . put ( key , value ) | Stores the object to the corresponding datastore . | 27 | 11 |
24,418 | def shard_query_generator ( self , query ) : shard_query = query . copy ( ) for shard in self . _stores : # yield all items matching within this shard cursor = shard . query ( shard_query ) for item in cursor : yield item # update query with results of first query shard_query . offset = max ( shard_query . offset - cursor . skipped , 0 ) if shard_query . limit : shard_query . limit = max ( shard_query . limit - cursor . returned , 0 ) if shard_query . limit <= 0 : break | A generator that queries each shard in sequence . | 132 | 10 |
24,419 | def monkey_patch_bson ( bson = None ) : if not bson : import bson if not hasattr ( bson , 'loads' ) : bson . loads = lambda bsondoc : bson . BSON ( bsondoc ) . decode ( ) if not hasattr ( bson , 'dumps' ) : bson . dumps = lambda document : bson . BSON . encode ( document ) | Patch bson in pymongo to use loads and dumps interface . | 93 | 14 |
24,420 | def loads ( self , value ) : for serializer in reversed ( self ) : value = serializer . loads ( value ) return value | Returns deserialized value . | 28 | 6 |
24,421 | def dumps ( self , value ) : for serializer in self : value = serializer . dumps ( value ) return value | returns serialized value . | 25 | 6 |
24,422 | def loads ( cls , value ) : if len ( value ) == 1 and cls . sentinel in value : value = value [ cls . sentinel ] return value | Returns mapping type deserialized value . | 37 | 8 |
24,423 | def dumps ( cls , value ) : if not hasattr ( value , '__getitem__' ) or not hasattr ( value , 'iteritems' ) : value = { cls . sentinel : value } return value | returns mapping typed serialized value . | 49 | 8 |
24,424 | def get ( self , key ) : '''''' value = self . child_datastore . get ( key ) return self . deserializedValue ( value ) | Return the object named by key or None if it does not exist . Retrieves the value from the child_datastore and de - serializes it on the way out . | 35 | 37 |
24,425 | def put ( self , key , value ) : value = self . serializedValue ( value ) self . child_datastore . put ( key , value ) | Stores the object value named by key . Serializes values on the way in and stores the serialized data into the child_datastore . | 34 | 30 |
24,426 | def _object_getattr ( obj , field ) : # TODO: consider changing this to raise an exception if no value is found. value = None # check whether this key is an attribute if hasattr ( obj , field ) : value = getattr ( obj , field ) # if not, perhaps it is an item (raw dicts, etc) elif field in obj : value = obj [ field ] # return whatever we've got. return value | Attribute getter for the objects to operate on . | 95 | 10 |
24,427 | def limit_gen ( limit , iterable ) : limit = int ( limit ) assert limit >= 0 , 'negative limit' for item in iterable : if limit <= 0 : break yield item limit -= 1 | A generator that applies a count limit . | 43 | 8 |
24,428 | def offset_gen ( offset , iterable , skip_signal = None ) : offset = int ( offset ) assert offset >= 0 , 'negative offset' for item in iterable : if offset > 0 : offset -= 1 if callable ( skip_signal ) : skip_signal ( item ) else : yield item | A generator that applies an offset skipping offset elements from iterable . If skip_signal is a callable it will be called with every skipped element . | 68 | 31 |
24,429 | def valuePasses ( self , value ) : return self . _conditional_cmp [ self . op ] ( value , self . value ) | Returns whether this value passes this filter | 30 | 7 |
24,430 | def filter ( cls , filters , iterable ) : if isinstance ( filters , Filter ) : filters = [ filters ] for filter in filters : iterable = filter . generator ( iterable ) return iterable | Returns the elements in iterable that pass given filters | 44 | 10 |
24,431 | def multipleOrderComparison ( cls , orders ) : comparers = [ ( o . keyfn , 1 if o . isAscending ( ) else - 1 ) for o in orders ] def cmpfn ( a , b ) : for keyfn , ascOrDesc in comparers : comparison = cmp ( keyfn ( a ) , keyfn ( b ) ) * ascOrDesc if comparison is not 0 : return comparison return 0 return cmpfn | Returns a function that will compare two items according to orders | 97 | 11 |
24,432 | def sorted ( cls , items , orders ) : return sorted ( items , cmp = cls . multipleOrderComparison ( orders ) ) | Returns the elements in items sorted according to orders | 30 | 9 |
24,433 | def order ( self , order ) : order = order if isinstance ( order , Order ) else Order ( order ) # ensure order gets attr values the same way the rest of the query does. order . object_getattr = self . object_getattr self . orders . append ( order ) return self | Adds an Order to this query . | 64 | 7 |
24,434 | def filter ( self , * args ) : if len ( args ) == 1 and isinstance ( args [ 0 ] , Filter ) : filter = args [ 0 ] else : filter = Filter ( * args ) # ensure filter gets attr values the same way the rest of the query does. filter . object_getattr = self . object_getattr self . filters . append ( filter ) return self | Adds a Filter to this query . | 83 | 7 |
24,435 | def copy ( self ) : if self . object_getattr is Query . object_getattr : other = Query ( self . key ) else : other = Query ( self . key , object_getattr = self . object_getattr ) other . limit = self . limit other . offset = self . offset other . offset_key = self . offset_key other . filters = self . filters other . orders = self . orders return other | Returns a copy of this query . | 92 | 7 |
24,436 | def dict ( self ) : d = dict ( ) d [ 'key' ] = str ( self . key ) if self . limit is not None : d [ 'limit' ] = self . limit if self . offset > 0 : d [ 'offset' ] = self . offset if self . offset_key : d [ 'offset_key' ] = str ( self . offset_key ) if len ( self . filters ) > 0 : d [ 'filter' ] = [ [ f . field , f . op , f . value ] for f in self . filters ] if len ( self . orders ) > 0 : d [ 'order' ] = [ str ( o ) for o in self . orders ] return d | Returns a dictionary representing this query . | 152 | 7 |
24,437 | def from_dict ( cls , dictionary ) : query = cls ( Key ( dictionary [ 'key' ] ) ) for key , value in dictionary . items ( ) : if key == 'order' : for order in value : query . order ( order ) elif key == 'filter' : for filter in value : if not isinstance ( filter , Filter ) : filter = Filter ( * filter ) query . filter ( filter ) elif key in [ 'limit' , 'offset' , 'offset_key' ] : setattr ( query , key , value ) return query | Constructs a query from a dictionary . | 122 | 8 |
24,438 | def next ( self ) : # if iteration has not begun, begin it. if not self . _iterator : self . __iter__ ( ) next = self . _iterator . next ( ) if next is not StopIteration : self . _returned_inc ( next ) return next | Iterator next . Build up count of returned elements during iteration . | 60 | 12 |
24,439 | def apply_filter ( self ) : self . _ensure_modification_is_safe ( ) if len ( self . query . filters ) > 0 : self . _iterable = Filter . filter ( self . query . filters , self . _iterable ) | Naively apply query filters . | 56 | 6 |
24,440 | def apply_order ( self ) : self . _ensure_modification_is_safe ( ) if len ( self . query . orders ) > 0 : self . _iterable = Order . sorted ( self . _iterable , self . query . orders ) | Naively apply query orders . | 56 | 6 |
24,441 | def apply_offset ( self ) : self . _ensure_modification_is_safe ( ) if self . query . offset != 0 : self . _iterable = offset_gen ( self . query . offset , self . _iterable , self . _skipped_inc ) | Naively apply query offset . | 61 | 6 |
24,442 | def apply_limit ( self ) : self . _ensure_modification_is_safe ( ) if self . query . limit is not None : self . _iterable = limit_gen ( self . query . limit , self . _iterable ) | Naively apply query limit . | 54 | 6 |
24,443 | def run_transaction ( transactor , callback ) : if isinstance ( transactor , sqlalchemy . engine . Connection ) : return _txn_retry_loop ( transactor , callback ) elif isinstance ( transactor , sqlalchemy . engine . Engine ) : with transactor . connect ( ) as connection : return _txn_retry_loop ( connection , callback ) elif isinstance ( transactor , sqlalchemy . orm . sessionmaker ) : session = transactor ( autocommit = True ) return _txn_retry_loop ( session , callback ) else : raise TypeError ( "don't know how to run a transaction on %s" , type ( transactor ) ) | Run a transaction with retries . | 155 | 7 |
24,444 | def _txn_retry_loop ( conn , callback ) : with conn . begin ( ) : while True : try : with _NestedTransaction ( conn ) : ret = callback ( conn ) return ret except sqlalchemy . exc . DatabaseError as e : if isinstance ( e . orig , psycopg2 . OperationalError ) : if e . orig . pgcode == psycopg2 . errorcodes . SERIALIZATION_FAILURE : continue raise | Inner transaction retry loop . | 101 | 7 |
24,445 | def _get ( self , pos ) : res = None , None if pos is not None : try : res = self [ pos ] , pos except ( IndexError , KeyError ) : pass return res | loads widget at given position ; handling invalid arguments | 42 | 9 |
24,446 | def _next_of_kin ( self , pos ) : candidate = None parent = self . parent_position ( pos ) if parent is not None : candidate = self . next_sibling_position ( parent ) if candidate is None : candidate = self . _next_of_kin ( parent ) return candidate | looks up the next sibling of the closest ancestor with not - None next siblings . | 65 | 17 |
24,447 | def _last_in_direction ( starting_pos , direction ) : cur_pos = None next_pos = starting_pos while next_pos is not None : cur_pos = next_pos next_pos = direction ( cur_pos ) return cur_pos | move in the tree in given direction and return the last position . | 56 | 13 |
24,448 | def depth ( self , pos ) : parent = self . parent_position ( pos ) if parent is None : return 0 else : return self . depth ( parent ) + 1 | determine depth of node at pos | 36 | 8 |
24,449 | def next_position ( self , pos ) : candidate = None if pos is not None : candidate = self . first_child_position ( pos ) if candidate is None : candidate = self . next_sibling_position ( pos ) if candidate is None : candidate = self . _next_of_kin ( pos ) return candidate | returns the next position in depth - first order | 69 | 10 |
24,450 | def prev_position ( self , pos ) : candidate = None if pos is not None : prevsib = self . prev_sibling_position ( pos ) # is None if first if prevsib is not None : candidate = self . last_decendant ( prevsib ) else : parent = self . parent_position ( pos ) if parent is not None : candidate = parent return candidate | returns the previous position in depth - first order | 83 | 10 |
24,451 | def positions ( self , reverse = False ) : def Posgen ( reverse ) : if reverse : lastrootsib = self . last_sibling_position ( self . root ) current = self . last_decendant ( lastrootsib ) while current is not None : yield current current = self . prev_position ( current ) else : current = self . root while current is not None : yield current current = self . next_position ( current ) return Posgen ( reverse ) | returns a generator that walks the positions of this tree in DFO | 99 | 14 |
24,452 | def _get_substructure ( self , treelist , pos ) : subtree = None if len ( pos ) > 1 : subtree = self . _get_substructure ( treelist [ pos [ 0 ] ] [ 1 ] , pos [ 1 : ] ) else : try : subtree = treelist [ pos [ 0 ] ] except ( IndexError , TypeError ) : pass return subtree | recursive helper to look up node - tuple for pos in treelist | 86 | 14 |
24,453 | def _get_node ( self , treelist , pos ) : node = None if pos is not None : subtree = self . _get_substructure ( treelist , pos ) if subtree is not None : node = subtree [ 0 ] return node | look up widget at pos of treelist ; default to None if nonexistent . | 56 | 15 |
24,454 | def _confirm_pos ( self , pos ) : candidate = None if self . _get_node ( self . _treelist , pos ) is not None : candidate = pos return candidate | look up widget for pos and default to None | 40 | 9 |
24,455 | def _list_dir ( self , path ) : try : elements = [ os . path . join ( path , x ) for x in os . listdir ( path ) ] if os . path . isdir ( path ) else [ ] elements . sort ( ) except OSError : elements = None return elements | returns absolute paths for all entries in a directory | 66 | 10 |
24,456 | def _get_siblings ( self , pos ) : parent = self . parent_position ( pos ) siblings = [ pos ] if parent is not None : siblings = self . _list_dir ( parent ) return siblings | lists the parent directory of pos | 46 | 6 |
24,457 | def reorder_view ( self , request ) : model = self . model if not self . has_change_permission ( request ) : raise PermissionDenied if request . method == "POST" : object_pks = request . POST . getlist ( 'neworder[]' ) model . objects . set_orders ( object_pks ) return HttpResponse ( "OK" ) | The reorder admin view for this model . | 84 | 9 |
24,458 | def is_collapsed ( self , pos ) : collapsed = self . _initially_collapsed ( pos ) if pos in self . _divergent_positions : collapsed = not collapsed return collapsed | checks if given position is currently collapsed | 43 | 7 |
24,459 | def _construct_spacer ( self , pos , acc ) : parent = self . _tree . parent_position ( pos ) if parent is not None : grandparent = self . _tree . parent_position ( parent ) if self . _indent > 0 and grandparent is not None : parent_sib = self . _tree . next_sibling_position ( parent ) draw_vbar = parent_sib is not None and self . _arrow_vbar_char is not None space_width = self . _indent - 1 * ( draw_vbar ) - self . _childbar_offset if space_width > 0 : void = urwid . AttrMap ( urwid . SolidFill ( ' ' ) , self . _arrow_att ) acc . insert ( 0 , ( ( space_width , void ) ) ) if draw_vbar : barw = urwid . SolidFill ( self . _arrow_vbar_char ) bar = urwid . AttrMap ( barw , self . _arrow_vbar_att or self . _arrow_att ) acc . insert ( 0 , ( ( 1 , bar ) ) ) return self . _construct_spacer ( parent , acc ) else : return acc | build a spacer that occupies the horizontally indented space between pos s parent and the root node . It will return a list of tuples to be fed into a Columns widget . | 266 | 37 |
24,460 | def _construct_connector ( self , pos ) : # connector symbol, either L or |- shaped. connectorw = None connector = None if self . _tree . next_sibling_position ( pos ) is not None : # |- shaped if self . _arrow_connector_tchar is not None : connectorw = urwid . Text ( self . _arrow_connector_tchar ) else : # L shaped if self . _arrow_connector_lchar is not None : connectorw = urwid . Text ( self . _arrow_connector_lchar ) if connectorw is not None : att = self . _arrow_connector_att or self . _arrow_att connector = urwid . AttrMap ( connectorw , att ) return connector | build widget to be used as connector bit between the vertical bar between siblings and their respective horizontal bars leading to the arrow tip | 167 | 24 |
24,461 | def _construct_first_indent ( self , pos ) : cols = [ ] void = urwid . AttrMap ( urwid . SolidFill ( ' ' ) , self . _arrow_att ) available_width = self . _indent if self . _tree . depth ( pos ) > 0 : connector = self . _construct_connector ( pos ) if connector is not None : width = connector . pack ( ) [ 0 ] if width > available_width : raise NoSpaceError ( ) available_width -= width if self . _tree . next_sibling_position ( pos ) is not None : barw = urwid . SolidFill ( self . _arrow_vbar_char ) below = urwid . AttrMap ( barw , self . _arrow_vbar_att or self . _arrow_att ) else : below = void # pile up connector and bar spacer = urwid . Pile ( [ ( 'pack' , connector ) , below ] ) cols . append ( ( width , spacer ) ) #arrow tip awidth , at = self . _construct_arrow_tip ( pos ) if at is not None : if awidth > available_width : raise NoSpaceError ( ) available_width -= awidth at_spacer = urwid . Pile ( [ ( 'pack' , at ) , void ] ) cols . append ( ( awidth , at_spacer ) ) # bar between connector and arrow tip if available_width > 0 : barw = urwid . SolidFill ( self . _arrow_hbar_char ) bar = urwid . AttrMap ( barw , self . _arrow_hbar_att or self . _arrow_att ) hb_spacer = urwid . Pile ( [ ( 1 , bar ) , void ] ) cols . insert ( 1 , ( available_width , hb_spacer ) ) return cols | build spacer to occupy the first indentation level from pos to the left . This is separate as it adds arrowtip and sibling connector . | 413 | 28 |
24,462 | def collapse_focussed ( self ) : if implementsCollapseAPI ( self . _tree ) : w , focuspos = self . get_focus ( ) self . _tree . collapse ( focuspos ) self . _walker . clear_cache ( ) self . refresh ( ) | Collapse currently focussed position ; works only if the underlying tree allows it . | 59 | 16 |
24,463 | def expand_focussed ( self ) : if implementsCollapseAPI ( self . _tree ) : w , focuspos = self . get_focus ( ) self . _tree . expand ( focuspos ) self . _walker . clear_cache ( ) self . refresh ( ) | Expand currently focussed position ; works only if the underlying tree allows it . | 59 | 16 |
24,464 | def collapse_all ( self ) : if implementsCollapseAPI ( self . _tree ) : self . _tree . collapse_all ( ) self . set_focus ( self . _tree . root ) self . _walker . clear_cache ( ) self . refresh ( ) | Collapse all positions ; works only if the underlying tree allows it . | 58 | 14 |
24,465 | def expand_all ( self ) : if implementsCollapseAPI ( self . _tree ) : self . _tree . expand_all ( ) self . _walker . clear_cache ( ) self . refresh ( ) | Expand all positions ; works only if the underlying tree allows it . | 45 | 14 |
24,466 | def focus_parent ( self ) : w , focuspos = self . get_focus ( ) parent = self . _tree . parent_position ( focuspos ) if parent is not None : self . set_focus ( parent ) | move focus to parent node of currently focussed one | 48 | 10 |
24,467 | def focus_first_child ( self ) : w , focuspos = self . get_focus ( ) child = self . _tree . first_child_position ( focuspos ) if child is not None : self . set_focus ( child ) | move focus to first child of currently focussed one | 52 | 10 |
24,468 | def focus_last_child ( self ) : w , focuspos = self . get_focus ( ) child = self . _tree . last_child_position ( focuspos ) if child is not None : self . set_focus ( child ) | move focus to last child of currently focussed one | 52 | 10 |
24,469 | def focus_next_sibling ( self ) : w , focuspos = self . get_focus ( ) sib = self . _tree . next_sibling_position ( focuspos ) if sib is not None : self . set_focus ( sib ) | move focus to next sibling of currently focussed one | 57 | 10 |
24,470 | def focus_prev_sibling ( self ) : w , focuspos = self . get_focus ( ) sib = self . _tree . prev_sibling_position ( focuspos ) if sib is not None : self . set_focus ( sib ) | move focus to previous sibling of currently focussed one | 57 | 10 |
24,471 | def get_unique_fields ( self ) : for unique_together in self . _meta . unique_together : if 'sort_order' in unique_together : unique_fields = list ( unique_together ) unique_fields . remove ( 'sort_order' ) return [ '%s_id' % f for f in unique_fields ] return [ ] | List field names that are unique_together with sort_order . | 77 | 13 |
24,472 | def _is_sort_order_unique_together_with_something ( self ) : unique_together = self . _meta . unique_together for fields in unique_together : if 'sort_order' in fields and len ( fields ) > 1 : return True return False | Is the sort_order field unique_together with something | 58 | 11 |
24,473 | def _update ( qs ) : try : with transaction . atomic ( ) : qs . update ( sort_order = models . F ( 'sort_order' ) + 1 ) except IntegrityError : for obj in qs . order_by ( '-sort_order' ) : qs . filter ( pk = obj . pk ) . update ( sort_order = models . F ( 'sort_order' ) + 1 ) | Increment the sort_order in a queryset . | 94 | 12 |
24,474 | def save ( self , * args , * * kwargs ) : objects = self . get_filtered_manager ( ) old_pos = getattr ( self , '_original_sort_order' , None ) new_pos = self . sort_order if old_pos is None and self . _unique_togethers_changed ( ) : self . sort_order = None new_pos = None try : with transaction . atomic ( ) : self . _save ( objects , old_pos , new_pos ) except IntegrityError : with transaction . atomic ( ) : old_pos = objects . filter ( pk = self . pk ) . values_list ( 'sort_order' , flat = True ) [ 0 ] self . _save ( objects , old_pos , new_pos ) # Call the "real" save() method. super ( Orderable , self ) . save ( * args , * * kwargs ) | Keep the unique order in sync . | 200 | 7 |
24,475 | def set_orders ( self , object_pks ) : objects_to_sort = self . filter ( pk__in = object_pks ) max_value = self . model . objects . all ( ) . aggregate ( models . Max ( 'sort_order' ) ) [ 'sort_order__max' ] # Call list() on the values right away, so they don't get affected by the # update() later (since values_list() is lazy). orders = list ( objects_to_sort . values_list ( 'sort_order' , flat = True ) ) # Check there are no unrecognised entries in the object_pks list. If so, # throw an error. We only have to check that they're the same length because # orders is built using only entries in object_pks, and all the pks are unique, # so if their lengths are the same, the elements must match up exactly. if len ( orders ) != len ( object_pks ) : pks = set ( objects_to_sort . values_list ( 'pk' , flat = True ) ) message = 'The following object_pks are not in this queryset: {}' . format ( [ pk for pk in object_pks if pk not in pks ] ) raise TypeError ( message ) with transaction . atomic ( ) : objects_to_sort . update ( sort_order = models . F ( 'sort_order' ) + max_value ) for pk , order in zip ( object_pks , orders ) : # Use update() to save a query per item and dodge the insertion sort # code in save(). self . filter ( pk = pk ) . update ( sort_order = order ) # Return the operated-on queryset for convenience. return objects_to_sort | Perform a mass update of sort_orders across the full queryset . Accepts a list object_pks of the intended order for the objects . | 392 | 32 |
24,476 | def order_by_json_path ( self , json_path , language_code = None , order = 'asc' ) : language_code = ( language_code or self . _language_code or self . get_language_key ( language_code ) ) json_path = '{%s,%s}' % ( language_code , json_path ) # Our jsonb field is named `translations`. raw_sql_expression = RawSQL ( "translations#>>%s" , ( json_path , ) ) if order == 'desc' : raw_sql_expression = raw_sql_expression . desc ( ) return self . order_by ( raw_sql_expression ) | Orders a queryset by the value of the specified json_path . | 151 | 16 |
24,477 | def delete ( self , * args , * * kwargs ) : # XXX: circular import from fields import RatingField qs = self . distinct ( ) . values_list ( 'content_type' , 'object_id' ) . order_by ( 'content_type' ) to_update = [ ] for content_type , objects in itertools . groupby ( qs , key = lambda x : x [ 0 ] ) : model_class = ContentType . objects . get ( pk = content_type ) . model_class ( ) if model_class : to_update . extend ( list ( model_class . objects . filter ( pk__in = list ( objects ) [ 0 ] ) ) ) retval = super ( VoteQuerySet , self ) . delete ( * args , * * kwargs ) # TODO: this could be improved for obj in to_update : for field in getattr ( obj , '_djangoratings' , [ ] ) : getattr ( obj , field . name ) . _update ( commit = False ) obj . save ( ) return retval | Handles updating the related votes and score fields attached to the model . | 239 | 14 |
24,478 | def set_pulse_width_range ( self , min_pulse = 750 , max_pulse = 2250 ) : self . _min_duty = int ( ( min_pulse * self . _pwm_out . frequency ) / 1000000 * 0xffff ) max_duty = ( max_pulse * self . _pwm_out . frequency ) / 1000000 * 0xffff self . _duty_range = int ( max_duty - self . _min_duty ) | Change min and max pulse widths . | 108 | 8 |
24,479 | def onestep ( self , * , direction = FORWARD , style = SINGLE ) : # Adjust current steps based on the direction and type of step. step_size = 0 if style == MICROSTEP : step_size = 1 else : half_step = self . _microsteps // 2 full_step = self . _microsteps # Its possible the previous steps were MICROSTEPS so first align with the interleave # pattern. additional_microsteps = self . _current_microstep % half_step if additional_microsteps != 0 : # We set _current_microstep directly because our step size varies depending on the # direction. if direction == FORWARD : self . _current_microstep += half_step - additional_microsteps else : self . _current_microstep -= additional_microsteps step_size = 0 elif style == INTERLEAVE : step_size = half_step current_interleave = self . _current_microstep // half_step if ( ( style == SINGLE and current_interleave % 2 == 1 ) or ( style == DOUBLE and current_interleave % 2 == 0 ) ) : step_size = half_step elif style in ( SINGLE , DOUBLE ) : step_size = full_step if direction == FORWARD : self . _current_microstep += step_size else : self . _current_microstep -= step_size # Now that we know our target microstep we can determine how to energize the four coils. self . _update_coils ( microstepping = style == MICROSTEP ) return self . _current_microstep | Performs one step of a particular style . The actual rotation amount will vary by style . SINGLE and DOUBLE will normal cause a full step rotation . INTERLEAVE will normally do a half step rotation . MICROSTEP will perform the smallest configured step . | 355 | 56 |
24,480 | def merge_records ( env , model_name , record_ids , target_record_id , field_spec = None , method = 'orm' , delete = True , exclude_columns = None ) : if exclude_columns is None : exclude_columns = [ ] if field_spec is None : field_spec = { } if isinstance ( record_ids , list ) : record_ids = tuple ( record_ids ) args0 = ( env , model_name , record_ids , target_record_id ) args = args0 + ( exclude_columns , ) args2 = args0 + ( field_spec , ) if target_record_id in record_ids : raise Exception ( "You can't put the target record in the list or " "records to be merged." ) # Check which records to be merged exist record_ids = env [ model_name ] . browse ( record_ids ) . exists ( ) . ids if not record_ids : return _change_generic ( * args , method = method ) if method == 'orm' : _change_many2one_refs_orm ( * args ) _change_many2many_refs_orm ( * args ) _change_reference_refs_orm ( * args ) _change_translations_orm ( * args ) # TODO: serialized fields with env . norecompute ( ) : _adjust_merged_values_orm ( * args2 ) env [ model_name ] . recompute ( ) if delete : _delete_records_orm ( env , model_name , record_ids , target_record_id ) else : _change_foreign_key_refs ( * args ) _change_reference_refs_sql ( * args ) _change_translations_sql ( * args ) # TODO: Adjust values of the merged records through SQL if delete : _delete_records_sql ( env , model_name , record_ids , target_record_id ) | Merge several records into the target one . | 433 | 9 |
24,481 | def allow_pgcodes ( cr , * codes ) : try : with cr . savepoint ( ) : with core . tools . mute_logger ( 'odoo.sql_db' ) : yield except ( ProgrammingError , IntegrityError ) as error : msg = "Code: {code}. Class: {class_}. Error: {error}." . format ( code = error . pgcode , class_ = errorcodes . lookup ( error . pgcode [ : 2 ] ) , error = errorcodes . lookup ( error . pgcode ) ) if error . pgcode in codes or error . pgcode [ : 2 ] in codes : logger . info ( msg ) else : logger . exception ( msg ) raise | Context manager that will omit specified error codes . | 149 | 9 |
24,482 | def check_values_selection_field ( cr , table_name , field_name , allowed_values ) : res = True cr . execute ( "SELECT %s, count(*) FROM %s GROUP BY %s;" % ( field_name , table_name , field_name ) ) for row in cr . fetchall ( ) : if row [ 0 ] not in allowed_values : logger . error ( "Invalid value '%s' in the table '%s' " "for the field '%s'. (%s rows)." , row [ 0 ] , table_name , field_name , row [ 1 ] ) res = False return res | check if the field selection field_name of the table table_name has only the values allowed_values . If not return False and log an error . If yes return True . | 138 | 36 |
24,483 | def load_data ( cr , module_name , filename , idref = None , mode = 'init' ) : if idref is None : idref = { } logger . info ( '%s: loading %s' % ( module_name , filename ) ) _ , ext = os . path . splitext ( filename ) pathname = os . path . join ( module_name , filename ) fp = tools . file_open ( pathname ) try : if ext == '.csv' : noupdate = True tools . convert_csv_import ( cr , module_name , pathname , fp . read ( ) , idref , mode , noupdate ) elif ext == '.yml' : yaml_import ( cr , module_name , fp , None , idref = idref , mode = mode ) elif mode == 'init_no_create' : for fp2 in _get_existing_records ( cr , fp , module_name ) : tools . convert_xml_import ( cr , module_name , fp2 , idref , mode = 'init' , ) else : tools . convert_xml_import ( cr , module_name , fp , idref , mode = mode ) finally : fp . close ( ) | Load an xml csv or yml data file from your post script . The usual case for this is the occurrence of newly added essential or useful data in the module that is marked with noupdate = 1 and without forcecreate = 1 so that it will not be loaded by the usual upgrade mechanism . Leaving the mode argument to its default init will load the data from your migration script . | 277 | 78 |
24,484 | def _get_existing_records ( cr , fp , module_name ) : def yield_element ( node , path = None ) : if node . tag not in [ 'openerp' , 'odoo' , 'data' ] : if node . tag == 'record' : xmlid = node . attrib [ 'id' ] if '.' not in xmlid : module = module_name else : module , xmlid = xmlid . split ( '.' , 1 ) cr . execute ( 'select id from ir_model_data where module=%s and name=%s' , ( module , xmlid ) ) if not cr . rowcount : return result = StringIO ( etree . tostring ( path , encoding = 'unicode' ) ) result . name = None yield result else : for child in node : for value in yield_element ( child , etree . SubElement ( path , node . tag , node . attrib ) if path else etree . Element ( node . tag , node . attrib ) ) : yield value return yield_element ( etree . parse ( fp ) . getroot ( ) ) | yield file like objects per leaf node in the xml file that exists . This is for not trying to create a record with partial data in case the record was removed in the database . | 246 | 37 |
24,485 | def rename_columns ( cr , column_spec ) : for table in column_spec . keys ( ) : for ( old , new ) in column_spec [ table ] : if new is None : new = get_legacy_name ( old ) logger . info ( "table %s, column %s: renaming to %s" , table , old , new ) cr . execute ( 'ALTER TABLE "%s" RENAME "%s" TO "%s"' % ( table , old , new , ) ) cr . execute ( 'DROP INDEX IF EXISTS "%s_%s_index"' % ( table , old ) ) | Rename table columns . Typically called in the pre script . | 139 | 12 |
24,486 | def rename_tables ( cr , table_spec ) : # Append id sequences to_rename = [ x [ 0 ] for x in table_spec ] for old , new in list ( table_spec ) : if new is None : new = get_legacy_name ( old ) if ( table_exists ( cr , old + '_id_seq' ) and old + '_id_seq' not in to_rename ) : table_spec . append ( ( old + '_id_seq' , new + '_id_seq' ) ) for ( old , new ) in table_spec : if new is None : new = get_legacy_name ( old ) logger . info ( "table %s: renaming to %s" , old , new ) cr . execute ( 'ALTER TABLE "%s" RENAME TO "%s"' % ( old , new , ) ) | Rename tables . Typically called in the pre script . This function also renames the id sequence if it exists and if it is not modified in the same run . | 197 | 33 |
24,487 | def update_workflow_workitems ( cr , pool , ref_spec_actions ) : workflow_workitems = pool [ 'workflow.workitem' ] ir_model_data_model = pool [ 'ir.model.data' ] for ( target_external_id , fallback_external_id ) in ref_spec_actions : target_activity = ir_model_data_model . get_object ( cr , SUPERUSER_ID , target_external_id . split ( "." ) [ 0 ] , target_external_id . split ( "." ) [ 1 ] , ) fallback_activity = ir_model_data_model . get_object ( cr , SUPERUSER_ID , fallback_external_id . split ( "." ) [ 0 ] , fallback_external_id . split ( "." ) [ 1 ] , ) ids = workflow_workitems . search ( cr , SUPERUSER_ID , [ ( 'act_id' , '=' , target_activity . id ) ] ) if ids : logger . info ( "Moving %d items in the removed workflow action (%s) to a " "fallback action (%s): %s" , len ( ids ) , target_activity . name , fallback_activity . name , ids ) workflow_workitems . write ( cr , SUPERUSER_ID , ids , { 'act_id' : fallback_activity . id } ) | Find all the workflow items from the target state to set them to the wanted state . | 311 | 17 |
24,488 | def logged_query ( cr , query , args = None , skip_no_result = False ) : if args is None : args = ( ) args = tuple ( args ) if type ( args ) == list else args try : cr . execute ( query , args ) except ( ProgrammingError , IntegrityError ) : logger . error ( 'Error running %s' % cr . mogrify ( query , args ) ) raise if not skip_no_result or cr . rowcount : logger . debug ( 'Running %s' , query % args ) logger . debug ( '%s rows affected' , cr . rowcount ) return cr . rowcount | Logs query and affected rows at level DEBUG . | 136 | 10 |
24,489 | def update_module_names ( cr , namespec , merge_modules = False ) : for ( old_name , new_name ) in namespec : if merge_modules : # Delete meta entries, that will avoid the entry removal # They will be recreated by the new module anyhow. query = "SELECT id FROM ir_module_module WHERE name = %s" cr . execute ( query , [ old_name ] ) row = cr . fetchone ( ) if row : old_id = row [ 0 ] query = "DELETE FROM ir_model_constraint WHERE module = %s" logged_query ( cr , query , [ old_id ] ) query = "DELETE FROM ir_model_relation WHERE module = %s" logged_query ( cr , query , [ old_id ] ) else : query = "UPDATE ir_module_module SET name = %s WHERE name = %s" logged_query ( cr , query , ( new_name , old_name ) ) query = ( "UPDATE ir_model_data SET name = %s " "WHERE name = %s AND module = 'base' AND " "model='ir.module.module' " ) logged_query ( cr , query , ( "module_%s" % new_name , "module_%s" % old_name ) ) # The subselect allows to avoid duplicated XML-IDs query = ( "UPDATE ir_model_data SET module = %s " "WHERE module = %s AND name NOT IN " "(SELECT name FROM ir_model_data WHERE module = %s)" ) logged_query ( cr , query , ( new_name , old_name , new_name ) ) # Rename the remaining occurrences for let Odoo's update process # to auto-remove related resources query = ( "UPDATE ir_model_data " "SET name = name || '_openupgrade_' || id, " "module = %s " "WHERE module = %s" ) logged_query ( cr , query , ( new_name , old_name ) ) query = ( "UPDATE ir_module_module_dependency SET name = %s " "WHERE name = %s" ) logged_query ( cr , query , ( new_name , old_name ) ) if version_info [ 0 ] > 7 : query = ( "UPDATE ir_translation SET module = %s " "WHERE module = %s" ) logged_query ( cr , query , ( new_name , old_name ) ) if merge_modules : # Conserve old_name's state if new_name is uninstalled logged_query ( cr , "UPDATE ir_module_module m1 SET state=m2.state " "FROM ir_module_module m2 WHERE m1.name=%s AND " "m2.name=%s AND m1.state='uninstalled'" , ( new_name , old_name ) , ) query = "DELETE FROM ir_module_module WHERE name = %s" logged_query ( cr , query , [ old_name ] ) logged_query ( cr , "DELETE FROM ir_model_data WHERE module = 'base' " "AND model='ir.module.module' AND name = %s" , ( 'module_%s' % old_name , ) , ) | Deal with changed module names making all the needed changes on the related tables like XML - IDs translations and so on . | 720 | 23 |
24,490 | def add_ir_model_fields ( cr , columnspec ) : for column in columnspec : query = 'ALTER TABLE ir_model_fields ADD COLUMN %s %s' % ( column ) logged_query ( cr , query , [ ] ) | Typically new columns on ir_model_fields need to be added in a very early stage in the upgrade process of the base module in raw sql as they need to be in place before any model gets initialized . Do not use for fields with additional SQL constraints such as a reference to another table or the cascade constraint but craft your own statement taking them into account . | 56 | 72 |
24,491 | def m2o_to_m2m ( cr , model , table , field , source_field ) : return m2o_to_x2m ( cr , model , table , field , source_field ) | Recreate relations in many2many fields that were formerly many2one fields . Use rename_columns in your pre - migrate script to retain the column s old value then call m2o_to_m2m in your post - migrate script . | 47 | 53 |
24,492 | def message ( cr , module , table , column , message , * args , * * kwargs ) : argslist = list ( args or [ ] ) prefix = ': ' if column : argslist . insert ( 0 , column ) prefix = ', column %s' + prefix if table : argslist . insert ( 0 , table ) prefix = ', table %s' + prefix argslist . insert ( 0 , module ) prefix = 'Module %s' + prefix logger . warn ( prefix + message , * argslist , * * kwargs ) | Log handler for non - critical notifications about the upgrade . To be extended with logging to a table for reporting purposes . | 116 | 23 |
24,493 | def reactivate_workflow_transitions ( cr , transition_conditions ) : for transition_id , condition in transition_conditions . iteritems ( ) : cr . execute ( 'update wkf_transition set condition = %s where id = %s' , ( condition , transition_id ) ) | Reactivate workflow transition previously deactivated by deactivate_workflow_transitions . | 68 | 17 |
24,494 | def convert_field_to_html ( cr , table , field_name , html_field_name ) : if version_info [ 0 ] < 7 : logger . error ( "You cannot use this method in an OpenUpgrade version " "prior to 7.0." ) return cr . execute ( "SELECT id, %(field)s FROM %(table)s WHERE %(field)s IS NOT NULL" % { 'field' : field_name , 'table' : table , } ) for row in cr . fetchall ( ) : logged_query ( cr , "UPDATE %(table)s SET %(field)s = %%s WHERE id = %%s" % { 'field' : html_field_name , 'table' : table , } , ( plaintext2html ( row [ 1 ] ) , row [ 0 ] ) ) | Convert field value to HTML value . | 183 | 8 |
24,495 | def lift_constraints ( cr , table , column ) : cr . execute ( 'select relname, array_agg(conname) from ' '(select t1.relname, c.conname ' 'from pg_constraint c ' 'join pg_attribute a ' 'on c.confrelid=a.attrelid and a.attnum=any(c.conkey) ' 'join pg_class t on t.oid=a.attrelid ' 'join pg_class t1 on t1.oid=c.conrelid ' 'where t.relname=%(table)s and attname=%(column)s ' 'union select t.relname, c.conname ' 'from pg_constraint c ' 'join pg_attribute a ' 'on c.conrelid=a.attrelid and a.attnum=any(c.conkey) ' 'join pg_class t on t.oid=a.attrelid ' 'where relname=%(table)s and attname=%(column)s) in_out ' 'group by relname' , { 'table' : table , 'column' : column , } ) for table , constraints in cr . fetchall ( ) : cr . execute ( 'alter table %s drop constraint %s' , ( AsIs ( table ) , AsIs ( ', drop constraint ' . join ( constraints ) ) ) ) | Lift all constraints on column in table . Typically you use this in a pre - migrate script where you adapt references for many2one fields with changed target objects . If everything went right the constraints will be recreated | 314 | 43 |
24,496 | def savepoint ( cr ) : if hasattr ( cr , 'savepoint' ) : with cr . savepoint ( ) : yield else : name = uuid . uuid1 ( ) . hex cr . execute ( 'SAVEPOINT "%s"' % name ) try : yield cr . execute ( 'RELEASE SAVEPOINT "%s"' % name ) except : cr . execute ( 'ROLLBACK TO SAVEPOINT "%s"' % name ) | return a context manager wrapping postgres savepoints | 98 | 9 |
24,497 | def rename_property ( cr , model , old_name , new_name ) : cr . execute ( "update ir_model_fields f set name=%s " "from ir_model m " "where m.id=f.model_id and m.model=%s and f.name=%s " "returning f.id" , ( new_name , model , old_name ) ) field_ids = tuple ( i for i , in cr . fetchall ( ) ) cr . execute ( "update ir_model_data set name=%s where model='ir.model.fields' and " "res_id in %s" , ( '%s,%s' % ( model , new_name ) , field_ids ) ) cr . execute ( "update ir_property set name=%s where fields_id in %s" , ( new_name , field_ids ) ) | Rename property old_name owned by model to new_name . This should happen in a pre - migration script . | 198 | 24 |
24,498 | def delete_records_safely_by_xml_id ( env , xml_ids ) : for xml_id in xml_ids : logger . debug ( 'Deleting record for XML-ID %s' , xml_id ) try : with env . cr . savepoint ( ) : env . ref ( xml_id ) . exists ( ) . unlink ( ) except Exception as e : logger . error ( 'Error deleting XML-ID %s: %s' , xml_id , repr ( e ) ) | This removes in the safest possible way the records whose XML - IDs are passed as argument . | 112 | 18 |
24,499 | def chunked ( records , single = True ) : if version_info [ 0 ] > 10 : invalidate = records . env . cache . invalidate elif version_info [ 0 ] > 7 : invalidate = records . env . invalidate_all else : raise Exception ( 'Not supported Odoo version for this method.' ) size = core . models . PREFETCH_MAX model = records . _name ids = records . with_context ( prefetch_fields = False ) . ids for i in range ( 0 , len ( ids ) , size ) : invalidate ( ) chunk = records . env [ model ] . browse ( ids [ i : i + size ] ) if single : for record in chunk : yield record continue yield chunk | Memory and performance friendly method to iterate over a potentially large number of records . Yields either a whole chunk or a single record at the time . Don t nest calls to this method . | 161 | 39 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.