Update a label

        Replace 'old_label' by 'new_label'
963934
def update_label(self, old_label, new_label):
        
        logger.info("%s : Updating label ([%s] -> [%s])"
                    % (str(self), old_label.name, new_label.name))
        labels = self.labels
        try:
            labels.remove(old_label)
        except ValueError:
            # this document doesn't have this label
            return

        logger.info("%s : Updating label ([%s] -> [%s])"
                    % (str(self), old_label.name, new_label.name))
        labels.append(new_label)
        with self.fs.open(self.fs.join(self.path, self.LABEL_FILE), 'w') \
                as file_desc:
            for label in labels:
                file_desc.write("%s,%s\n" % (label.name,
                                             label.get_color_str()))
801115
def add_label(self, doc, label, update_index=True):
        
        label = copy.copy(label)
        assert(label in self.labels.values())
        doc.add_label(label)
        if update_index:
            self.upd_doc(doc)
            self.commit()
7371
private function cleanOriginalLabel($label)
    {
        $label = str_replace(LabelFilter::SEPARATOR_RECURSIVE_LABEL, ' - ', $label);
        $label = SafeDecodeLabel::decodeLabelSafe($label);
        return $label;
    }
1014509
def update_labels(self, func):
        
        if not isinstance(self.data, LabelArray):
            raise TypeError(
                'update_labels only supported if data is of type LabelArray.'
            )

        # Map the baseline values.
        self._data = self._data.map(func)

        # Map each of the adjustments.
        for _, row_adjustments in iteritems(self.adjustments):
            for adjustment in row_adjustments:
                adjustment.value = func(adjustment.value)
1306041
def _update_labels(self, label, crop_box, height, width):
        """"""
        xmin = float(crop_box[0]) / width
        ymin = float(crop_box[1]) / height
        w = float(crop_box[2]) / width
        h = float(crop_box[3]) / height
        out = label.copy()
        out[:, (1, 3)] -= xmin
        out[:, (2, 4)] -= ymin
        out[:, (1, 3)] /= w
        out[:, (2, 4)] /= h
        out[:, 1:5] = np.maximum(0, out[:, 1:5])
        out[:, 1:5] = np.minimum(1, out[:, 1:5])
        coverage = self._calculate_areas(out[:, 1:]) * w * h / self._calculate_areas(label[:, 1:])
        valid = np.logical_and(out[:, 3] > out[:, 1], out[:, 4] > out[:, 2])
        valid = np.logical_and(valid, coverage > self.min_eject_coverage)
        valid = np.where(valid)[0]
        if valid.size < 1:
            return None
        out = out[valid, :]
        return out
8584
def _unused_label(self, label):
        """"""
        original = label
        existing = self.labels
        i = 2
        while label in existing:
            label = '{}_{}'.format(original, i)
            i += 1
        return label
1370517
def OnReplace(self, event):
        """"""

        find_string = event.GetFindString()
        flags = self._wxflag2flag(event.GetFlags())
        replace_string = event.GetReplaceString()

        gridpos = list(self.grid.actions.cursor)

        findpos = self.grid.actions.find(gridpos, find_string, flags,
                                         search_result=False)

        if findpos is None:
            statustext = _(u"'{find_string}' not found.")
            statustext = statustext.format(find_string=find_string)

        else:
            with undo.group(_("Replace")):
                self.grid.actions.replace(findpos, find_string, replace_string)
            self.grid.actions.cursor = findpos

            # Update statusbar
            statustext = _(u"Replaced '{find_string}' in cell {key} with "
                           u"{replace_string}.")
            statustext = statustext.format(find_string=find_string,
                                           key=findpos,
                                           replace_string=replace_string)

        post_command_event(self.grid.main_window, self.grid.StatusBarMsg,
                           text=statustext)

        event.Skip()
1243823
def _replace_labels(doc):
    """"""
    lines = doc.splitlines()
    labelstart, labelend = None, None
    foundattributes = False
    for i, line in enumerate(lines):
        stripped = line.strip()
        if stripped == 'Attributes':
            foundattributes = True
        if foundattributes and not labelstart and stripped.startswith('labels_'):
            labelstart = len('\n'.join(lines[:i])) + 1
        if labelstart and not labelend and stripped == '':
            labelend = len('\n'.join(lines[:i + 1]))

    if labelstart is None or labelend is None:
        return doc

    replace = '\n'.join([
        '    labels_ : list of arrays, each of shape [sequence_length, ]',
        '        The label of each point is an integer in [0, n_clusters).',
        '',
    ])
    return doc[:labelstart] + replace + doc[labelend:]
1229008
def update_label(self, name, color, new_name=''):
        
        label = self.label(name)
        resp = False
        if label:
            upd = label.update
            resp = upd(new_name, color) if new_name else upd(name, color)
        return resp
825895
function(tpl, data, label) {
    var t = String(tpl),
      s = label || /#\{([^}]*)\}/mg,
      trim = String.trim ||
      function(str) {
          return str.replace(/^\s+|\s+$/g, "")
      }
    return t.replace(s, function(value, name) {
      value = data[trim(name)]
      // only handle `undefined`
      return value === undefined ? "" : value
    })
  }
562903
def edit(self, name, label=None):
        
        if not name:
            return False
        edit_data = {'name': name, 'label': label}
        self._remove_none(edit_data)
        r = self._patch(
            self._api,
            data=json.dumps(edit_data),
            headers=Release.CUSTOM_HEADERS
        )
        successful = self._boolean(r, 200, 404)
        if successful:
            self.__init__(r.json(), self)

        return successful
1010481
def set_label(self, label, lineno, local=False):
        
        ex_label, namespace = Memory.id_name(label)

        if ex_label in self.local_labels[-1].keys():
            result = self.local_labels[-1][ex_label]
            result.lineno = lineno
        else:
            result = self.local_labels[-1][ex_label] = Label(ex_label, lineno, namespace=NAMESPACE)

        if result.local == local:
            warning(lineno, "label '%s' already declared as LOCAL" % label)

        result.local = local

        return result
790657
def update_label(self):
        """"""
        current_file = str(self.selectedFiles()[0])
        if not '.' in current_file.split(os.path.sep)[-1]:
            # add hdf5 extention if none given
            current_file += '.hdf5'
        if os.path.isfile(current_file):
            self.setLabelText(QtGui.QFileDialog.Accept, 'Reload')
        elif os.path.isdir(current_file):
            self.setLabelText(QtGui.QFileDialog.Accept, 'Open')
        else:
            self.setLabelText(QtGui.QFileDialog.Accept, 'Create')
955417
def flip_labels(obj):
    
    def sub(a, b):
        """
        Substitute all keys that start with a to b
        """
        for label in list(obj.keys()):
            if label.startswith(a):
                new_label = b+label[1:]
                obj[new_label] = obj.pop(label)

    sub('x', 'z')
    sub('y', 'x')
    sub('z', 'y')
    return obj
382171
def update(self, data):
        """"""
        if not isinstance(data, list): data = [data] # otherwise no conversion is necessary
        master = Handler.ALL_VERS_DATA
        for record in data:
            #print(record)
            for k,v in iteritems(record): # ensure record contents aretyped appropriately
                try:                record[k] = int(v)
                except ValueError:  record[k] = v
            try: label = record["label"] # verify this record has the required 'label' key
            except KeyError:
                raise ValueError("Must provide a valid label argument.  Given:%s%s"%(\
                    os.linesep, ("%s  "%(os.linesep)).join(
                        ["%15s:%s"%(k,v) for k,v in iteritems(kwargs)]
                    )))
            try:    masterLabel = master[label] # identify the already existing record that matches this to-be-updated record, if any
            except KeyError: # master hasn't been defined yet
                master[label] = record
                self._updated = True # a new record should also be saved
                continue
            for k,v in iteritems(record): # determine whether master needs to be updated
                try:
                    if masterLabel[k] == v:  continue # whether an entry in the record needs to be updated (doesn't match)
                except KeyError:             pass # this condition means that k is a new key, so the record must be updated
                self._updated = True
                try:    master[label].update(record) # index each record by its label
                except KeyError:             break
760137
def update_user_label(self):
        
        self._user_label = _uniqueid_to_uniquetwig(self._bundle, self.unique_label)
        self._set_curly_label()
991430
def update_asset(self, name, label=""):
        
        assert isinstance(name, (str, unicode)), name
        assert isinstance(label, (str, unicode)), label
        post_parameters = {
            "name": name,
            "label": label
        }
        headers, data = self._requester.requestJsonAndCheck(
            "PATCH",
            self.url,
            input=post_parameters
        )
        return GitReleaseAsset(self._requester, headers, data, completed=True)