si al guardar una linea asociada a un documento bloqueado (lock==True), duplicar el documento en una nueva versión
439021
def save(self, *args, **kwargs):
        if self.pk is None:
            if hasattr(self, 'product'):
                if not self.description:
                    self.description = self.product
                self.price_recommended = self.product.price_base
            elif hasattr(self, 'line_order'):
                if not self.description:
                    self.description = self.line_order.product
                self.price_recommended = self.line_order.price_base

        if hasattr(self, 'tax') and hasattr(self, 'type_tax'):
            self.tax = self.type_tax.tax

        if hasattr(self, 'product'):
            self.tax_label = self.product.product.tax.name
            if self.product.code:
                self.code = self.product.code
            else:
                self.code = self.product.product.code

        
        self.update_total(force_save=False)
        if 'force_save' in kwargs:
            kwargs.pop('force_save')
        return super(GenLineProduct, self).save(*args, **kwargs)
393394
private function manageEditDocumentStoreProperties(&$params, &$dmsLoader, &$manageCategory, &$arrMessages, &$blnShowStart, $documentId)
  {
    $params->loadRootCategory = true; // get complete path to root, for checking inherited access rights
    $params->loadAccessRights = true;
    $params->loadDocuments = false;
    $category = $dmsLoader->loadCategory($manageCategory, $params);
    
    if (!$category->isEditableForCurrentMember())
    {
      $arrMessages['errors'][] = $GLOBALS['TL_LANG']['DMS']['ERR']['manage_document_not_allowed'];
      $blnShowStart = true;
    }
    else
    {
      $document = $dmsLoader->loadDocument($documentId, $params);
      $documentOriginal = clone $document;
      
      // load existing documents for file name
      $params->loadCategory = true; // need the category of existing documents
      $arrDocuments = $dmsLoader->loadDocuments($document->fileName, $document->fileType, $params);
      $params->loadCategory = false;
      
      $existingDocuments = array();
      foreach ($arrDocuments as $existingDocument)
      {
        if ($existingDocument->id != $documentId)
        {
          $existingDocuments[] = $existingDocument;
        }
      }
      
      $documentVersionMajor = $this->Input->post('documentVersionMajor');
      $documentVersionMinor = $this->Input->post('documentVersionMinor');
      $documentVersionPatch = $this->Input->post('documentVersionPatch');
      
      $document->name = $this->Input->post('documentName');
      $document->description = $this->Input->post('documentDescription');
      $document->keywords = $this->Input->post('documentKeywords');
      $document->versionMajor = $documentVersionMajor;
      $document->versionMinor = $documentVersionMinor;
      $document->versionPatch = $documentVersionPatch;
      $document->lasteditMemberId = $this->Member->id;
      $document->lasteditDate = time();
      if ($category->isPublishableForCurrentMember())
      {
        $document->published = (bool) $this->Input->post('documentPublish');
      }
      
      $versionChanged = false;
      if ($documentVersionMajor != $documentOriginal->versionMajor ||
        $documentVersionMinor != $documentOriginal->versionMinor ||
        $documentVersionPatch != $documentOriginal->versionPatch)
      {
        $versionChanged = true;
      }
      
      if (strlen($document->name) == 0)
      {
        $arrMessages['errors'][] = $GLOBALS['TL_LANG']['DMS']['ERR']['edit_no_name_set'];
        $document->name = $documentOriginal->name;
      }
      if ($versionChanged)
      {
        if (strlen($documentVersionMajor) == 0 || !is_numeric($documentVersionMajor) ||
          strlen($documentVersionMinor) == 0 || !is_numeric($documentVersionMinor) ||
          strlen($documentVersionPatch) == 0 || !is_numeric($documentVersionPatch))
        {
          $document->versionMajor = $documentOriginal->versionMajor;
          $document->versionMinor = $documentOriginal->versionMinor;
          $document->versionPatch = $documentOriginal->versionPatch;
          $arrMessages['errors'][] = $GLOBALS['TL_LANG']['DMS']['ERR']['edit_no_version_set'];
        }
        
        foreach ($existingDocuments as $existingDocument)
        {
          // will be true, if one is true (keep true status, if once set)
          if ($existingDocument->versionMajor == $documentVersionMajor &&
            $existingDocument->versionMinor == $documentVersionMinor &&
            $existingDocument->versionPatch == $documentVersionPatch)
          {
            $document->versionMajor = $documentOriginal->versionMajor;
            $document->versionMinor = $documentOriginal->versionMinor;
            $document->versionPatch = $documentOriginal->versionPatch;
            $arrMessages['errors'][] = $GLOBALS['TL_LANG']['DMS']['ERR']['edit_version_already_used'];
          }
        }
      }
      
      // HOOK: verify the edited document from frontend
      if (isset($GLOBALS['TL_HOOKS']['dmsVerifyEditedDocument']) && is_array($GLOBALS['TL_HOOKS']['dmsVerifyEditedDocument']))
      {
        foreach ($GLOBALS['TL_HOOKS']['dmsVerifyEditedDocument'] as $callback)
        {
          $this->import($callback[0]);
          $arrMessages = $this->{$callback[0]}->{$callback[1]}($arrMessages, $existingDocuments, $this->Input);
        }
      }
      
      if (count($arrMessages['errors']) > 0)
      {
        $this->Template = new \FrontendTemplate("mod_dms_mgmt_manage_document_edit");
        $this->Template->setData($this->arrData);
      }
      else
      {
        // HOOK: modify the edited document from frontend
        if (isset($GLOBALS['TL_HOOKS']['dmsModifyEditedDocument']) && is_array($GLOBALS['TL_HOOKS']['dmsModifyEditedDocument']))
        {
          foreach ($GLOBALS['TL_HOOKS']['dmsModifyEditedDocument'] as $callback)
          {
            $this->import($callback[0]);
            $document = $this->{$callback[0]}->{$callback[1]}($document, $this->Input);
          }
        }

        // update document
        $dmsWriter = \DmsWriter::getInstance();
        $document = $dmsWriter->updateDocument($document);
        
        $arrMessages['successes'][] = $GLOBALS['TL_LANG']['DMS']['SUCCESS']['document_successfully_edited'];
        
        // rename the file if the version changed
        if ($versionChanged)
        {
          $filePath = \DmsConfig::getDocumentFilePath($documentOriginal->getFileNameVersioned());
          if (file_exists(TL_ROOT . '/' . $filePath))
          {
            rename($filePath, \DmsConfig::getDocumentFilePath($document->getFileNameVersioned()));
            $arrMessages['successes'][] = $GLOBALS['TL_LANG']['DMS']['SUCCESS']['document_file_successfully_renamed'];
          }
          else
          {
            $arrMessages['errors'][] = $GLOBALS['TL_LANG']['DMS']['ERR']['edit_file_not_exists'];
          }
        }
        
        $this->Template = new \FrontendTemplate("mod_dms_mgmt_manage_document_edit_processed");
        $this->Template->setData($this->arrData);
      }
      
      $this->Template->category = $category;
      $this->Template->document = $document;
      $this->Template->existingDocuments = $existingDocuments;
      
      $blnShowStart = false;
    }
  }
658312
public function duplicateUnderlyingFile()
    {
        $app = Application::getFacadeApplication();
        $importer = new Importer();
        $cf = $app->make('helper/concrete/file');
        $filesystem = $this->getFile()->getFileStorageLocationObject()->getFileSystemObject();
        $fileName = $this->getFileName();
        do {
            $prefix = $importer->generatePrefix();
            $path = $cf->prefix($prefix, $fileName);
        } while ($filesystem->has($path));
        $fileContents = $this->getFileResource()->read();
        $mimeType = Util::guessMimeType($fileName, $fileContents);
        $filesystem->write(
            $path,
            $fileContents,
            [
                'visibility' => AdapterInterface::VISIBILITY_PUBLIC,
                'mimetype' => $mimeType,
            ]
        );
        $this->updateFile($fileName, $prefix);
    }
643866
private void newLine() {
    numBlocks = 0;
    perms = username = group = path = linkTarget = replication = hardlinkId = "";
    filesize = 0l;
    type = INode.INodeType.REGULAR_INODE.toString();
    inInode = true;
  }
780382
def get_corpus_line(self, item):
        
        t1 = ""
        t2 = ""
        assert item < self.corpus_lines
        if self.on_memory:
            sample = self.sample_to_doc[item]
            t1 = self.all_docs[sample["doc_id"]][sample["line"]]
            t2 = self.all_docs[sample["doc_id"]][sample["line"]+1]
            # used later to avoid random nextSentence from same doc
            self.current_doc = sample["doc_id"]
            return t1, t2
        else:
            if self.line_buffer is None:
                # read first non-empty line of file
                while t1 == "" :
                    t1 = next(self.file).strip()
                    t2 = next(self.file).strip()
            else:
                # use t2 from previous iteration as new t1
                t1 = self.line_buffer
                t2 = next(self.file).strip()
                # skip empty rows that are used for separating documents and keep track of current doc id
                while t2 == "" or t1 == "":
                    t1 = next(self.file).strip()
                    t2 = next(self.file).strip()
                    self.current_doc = self.current_doc+1
            self.line_buffer = t2

        assert t1 != ""
        assert t2 != ""
        return t1, t2
1233367
private function preIndent()
    {
        $prev = $this->tokens->getId($this->tokens->key() - 1);

        switch ($this->tokens->getId()) {
            case DocLexer::T_AT:
                if ($prev
                    && (DocLexer::T_COLON !== $prev)
                    && (DocLexer::T_COMMA !== $prev)
                    && (DocLexer::T_EQUALS !== $prev)
                    && (DocLexer::T_OPEN_CURLY_BRACES !== $prev)
                    && (DocLexer::T_OPEN_PARENTHESIS !== $prev)) {
                    $this->indent(true);
                }

                break;
            case DocLexer::T_CLOSE_CURLY_BRACES:
                $this->level--;

                if (DocLexer::T_OPEN_CURLY_BRACES !== $prev) {
                    $this->indent();
                }

                break;
            case DocLexer::T_CLOSE_PARENTHESIS:
                $this->level--;

                if (DocLexer::T_OPEN_PARENTHESIS !== $prev) {
                    $this->indent();
                }

                break;
        }
    }
772649
public function getCodigoTransmissao()
    {
        $conta = $this->getConta();
        if (strlen($conta) == 9) {
            $conta = substr($conta, 0, 7);
        }

        return Util::formatCnab('9', $this->getAgencia(), 4)
            . Util::formatCnab('9', substr($this->getCodigoCliente(), 0, 7), 8)
            . Util::formatCnab('9', $conta, 8);
    }
1056677
public function acquireLocks()
    {
        if (! isset($this->locks) && ! is_array($this->locks)) {
            $message = "Il ne semble pas y avoir de verrous définis pour ce process. Arrêt";
            self::getLogger()->err($message);
            self::alertError($message);
            $this->setAlive(false);
            return false;
        }
        foreach ($this->locks as $name => $mode) {
            self::getLogger()->info($this->translate("Trying to acquire the lock ") . $name . " " . $this->translate("in mode") . " : " . ($mode == LOCK_EX ? $this->translate('exclusive') : $this->translate('shared')));
            if (true === $this->lockFile($name, $mode))
                self::getLogger()->info($this->translate("Successfully acquired the lock ") . $name . " " . $this->translate("in mode") . " : " . ($mode == LOCK_EX ? $this->translate('exclusive') : $this->translate('shared')));
            else {
                $message = $this->translate("Unable to acquire the lock ") . $name . " " . $this->translate("in mode") . " : " . ($mode == LOCK_EX ? $this->translate('exclusive') : $this->translate('shared'));
                self::getLogger()->err($message);
                self::alertError($message);
                $this->setAlive(false);
                return false;
            }
        }
        return true;
    }
221823
private function extractDocBlockPartsSource(): void
  {
    // Get the DocBlock for the source.
    $tmp = PHP_EOL;
    foreach ($this->routineSourceCodeLines as $line)
    {
      $n = preg_match('/create\\s+(procedure|function)\\s+([a-zA-Z0-9_]+)/i', $line);
      if ($n) break;

      $tmp .= $line;
      $tmp .= PHP_EOL;
    }

    $phpdoc = new DocBlockReflection($tmp);

    // Get the short description.
    $this->docBlockPartsSource['sort_description'] = $phpdoc->getShortDescription();

    // Get the long description.
    $this->docBlockPartsSource['long_description'] = $phpdoc->getLongDescription();

    // Get the description for each parameter of the stored routine.
    foreach ($phpdoc->getTags() as $key => $tag)
    {
      if ($tag->getName()=='param')
      {
        /* @var $tag ParamTag */
        $this->docBlockPartsSource['parameters'][$key] = ['name'        => $tag->getTypes()[0],
                                                          'description' => $tag->getDescription()];
      }
    }
  }
1134611
public function getCodigoTransmissao()
    {
        return Util::formatCnab('9', $this->getAgencia(), 4)
        . Util::formatCnab('9', '0000', 4)
        . Util::formatCnab('9', $this->getCodigoCliente(), 7);
    }
132362
function save($path_copy = null, $quality = 100)
    {
        if($path_copy)
        {
            $copy = $path_copy;
        }
        else
        {
            $copy = $this->path_image;
        }

        //---Guardar la imagen en el tipo de archivo correcto
        switch($this->type){
            case IMAGETYPE_JPEG:
                imagejpeg($this->image, $copy, $quality);
                break;
            case IMAGETYPE_GIF:
                imagegif($this->image, $copy);
                break;
            case IMAGETYPE_PNG:
                $pngquality = floor(($quality - 10) / 10);
                imagepng($this->image, $copy, $pngquality);
                break;
        }
    }
1091931
function insert() {
		if (isset($this->document['_id']))
			return $this->update();
		if (isset($this->trigger['beforeinsert']) &&
			\Base::instance()->call($this->trigger['beforeinsert'],
				[$this,['_id'=>$this->document['_id']]])===FALSE)
			return $this->document;
		if ($this->legacy) {
			$this->collection->insert($this->document);
			$pkey=['_id'=>$this->document['_id']];
		}
		else {
			$result=$this->collection->insertone($this->document);
			$pkey=['_id'=>$result->getinsertedid()];
		}
		if (isset($this->trigger['afterinsert']))
			\Base::instance()->call($this->trigger['afterinsert'],
				[$this,$pkey]);
		$this->load($pkey);
		return $this->document;
	}
861073
public function unlock($document)
    {
        $qb          = $this->dm->createQueryBuilder($this->class->name);
        $identifier  = $this->uow->getDocumentIdentifier($document);
        $lockMapping = $this->class->lockMetadata;

        $qb->update();
        $qb->setIdentifier($identifier);
        $qb->attr($lockMapping->name)->remove();

        $qb->getQuery()->execute();

        $lockMapping->setValue($document, null);
    }
519697
def embeddedFileGet(self, id):
        """"""
        if self.isClosed or self.isEncrypted:
            raise ValueError("operation illegal for closed / encrypted doc")

        return _fitz.Document_embeddedFileGet(self, id)
314118
def leer(linea, formato, expandir_fechas=False):
    ""
    dic = {}
    comienzo = 1
    for fmt in formato:    
        clave, longitud, tipo = fmt[0:3]
        dec = (len(fmt)>3 and isinstance(fmt[3], int)) and fmt[3] or 2
        valor = linea[comienzo-1:comienzo-1+longitud].strip()
        try:
            if chr(8) in valor or chr(127) in valor or chr(255) in valor:
                valor = None        # nulo
            elif tipo == N:
                if valor:
                    valor = long(valor)
                else:
                    valor = 0
            elif tipo == I:
                if valor:
                    try:
                        if '.' in valor:
                                valor = float(valor)
                        else:
                            valor = valor.strip(" ")
                            if valor[0] == "-":
                                sign = -1
                                valor = valor[1:] 
                            else:
                                sign = +1
                            valor = sign * float(("%%s.%%0%sd" % dec) % (long(valor[:-dec] or '0'), int(valor[-dec:] or '0')))
                    except ValueError:
                        raise ValueError("Campo invalido: %s = '%s'" % (clave, valor))
                else:
                    valor = 0.00
            elif expandir_fechas and clave.lower().startswith("fec") and longitud <= 8:
                if valor:
                    valor = "%s-%s-%s" % (valor[0:4], valor[4:6], valor[6:8])
                else:
                    valor = None
            else:
                valor = valor.decode("ascii","ignore")
            if not valor and clave in dic and len(linea) <= comienzo:
                pass    # ignorar - compatibilidad hacia atrás (cambios tamaño)
            else:
                dic[clave] = valor
            comienzo += longitud
        except Exception, e:
            raise ValueError("Error al leer campo %s pos %s val '%s': %s" % (
                clave, comienzo, valor, str(e)))
    return dic
170312
function initCompleteTransaction($amount, $buyOrder, $sessionId, $cardExpirationDate, $cvv, $cardNumber) {

        try {

            $wsCompleteInitTransactionInput = new wsCompleteInitTransactionInput();
            $completeCardDetail = new completeCardDetail();
            $wsCompleteTransactionDetail = new wsCompleteTransactionDetail();

            /** (Obligatorio) Indica el tipo de transacción, su valor debe ser siempre TR_COMPLETA_WS */
            $wsCompleteInitTransactionInput->transactionType = 'TR_COMPLETA_WS';
            $wsCompleteInitTransactionInput->sessionId = $sessionId;

            $wsCompleteTransactionDetail->amount = $amount;
            $wsCompleteTransactionDetail->buyOrder = $buyOrder;
            $wsCompleteTransactionDetail->commerceCode = $this->config->getCommerceCode();

            $completeCardDetail->cardExpirationDate = $cardExpirationDate;
            $completeCardDetail->cvv = $cvv;
            $completeCardDetail->cardNumber = $cardNumber;

            /** (Obligatorio) Objeto del tipo wsTransactionDetail que contiene información asociada a la tarjeta de crédito */
            $wsCompleteInitTransactionInput->cardDetail = $completeCardDetail; // cardDetails

            /** (Obligatorio) Lista de objetos del tipo wsTransactionDetail, el cual contiene datos de la transacción. Máxima cantidad de repeticiones es de 1 para este tipo de transacción */
            $wsCompleteInitTransactionInput->transactionDetails = $wsCompleteTransactionDetail; // wsTransactionDetail

            $initCompleteTransactionResponse = $this->_initCompleteTransaction(
                    array("wsCompleteInitTransactionInput" => $wsCompleteInitTransactionInput)
            );

            $xmlResponse = $this->soapClient->__getLastResponse();
            $soapValidation = new SoapValidation($xmlResponse, $this->config->getWebpayCert());
            $validationResult = $soapValidation->getValidationResult();

            if ($validationResult === TRUE) {

                $wsCompleteInitTransactionOutput = $initCompleteTransactionResponse->return;
                return $wsCompleteInitTransactionOutput;
            } else {

                $error["error"] = "Error validando conexi&oacute;n a Webpay (Verificar que la informaci&oacute;n del certificado sea correcta)";
                $error["detail"] = "No se pudo completar la conexi&oacute;n con Webpay";
            }
        } catch (Exception $e) {

            $error["error"] = "Error conectando a Webpay (Verificar que la informaci&oacute;n del certificado sea correcta)";

            $replaceArray = array('<!--' => '', '-->' => '');
            $error["detail"] = str_replace(array_keys($replaceArray), array_values($replaceArray), $e->getMessage());
        }

        return $error;
    }
1241153
def verifica(ver_list, res_dict, difs):
    ""
    for k, v in ver_list.items():
        # normalizo a float para poder comparar numericamente:
        if isinstance(v, (Decimal, int, long)):
            v = float(v)
        if isinstance(res_dict.get(k), (Decimal, int, long)):
            res_dict[k] = float(res_dict[k])
        if isinstance(v, list):
            # verifico que ambas listas tengan la misma cantidad de elementos:
            if v and not k in res_dict and v:
                difs.append("falta tag %s: %s %s" % (k, repr(v), repr(res_dict.get(k))))
            elif len(res_dict.get(k, []))!=len(v or []):
                difs.append("tag %s len !=: %s %s" % (k, repr(v), repr(res_dict.get(k))))
            else:
                # ordeno las listas para poder compararlas si vienen mezcladas
                rl = sorted(res_dict.get(k, []))
                # comparo los elementos uno a uno:
                for i, vl in enumerate(sorted(v)):
                    verifica(vl, rl[i], difs)
        elif isinstance(v, dict):
            # comparo recursivamente los elementos:
            verifica(v, res_dict.get(k, {}), difs)
        elif res_dict.get(k) is None or v is None:
            # alguno de los dos es nulo, verifico si ambos lo son o faltan
            if v=="":
                v = None
            r = res_dict.get(k)
            if r=="":
                r = None
            if not (r is None and v is None):
                difs.append("%s: nil %s!=%s" % (k, repr(v), repr(r)))
        elif type(res_dict.get(k)) == type(v):
            # tipos iguales, los comparo directamente
            if res_dict.get(k) != v:
                difs.append("%s: %s!=%s" % (k, repr(v), repr(res_dict.get(k))))
        elif isinstance(v, float) or isinstance(res_dict.get(k), float):
            # comparar numericamente
            if float(res_dict.get(k)) != float(v):
                difs.append("%s: %s!=%s" % (k, repr(v), repr(res_dict.get(k))))
        elif unicode(res_dict.get(k)) != unicode(v):
            # tipos diferentes, comparo la representación  
            difs.append("%s: str %s!=%s" % (k, repr(v), repr(res_dict.get(k))))
        else:
            pass