PDF copy method
$dataPost is actually having the Document model
$file is having the master file details in pseudo format
776927
public static function copyFile($files, $dataPost, $caller) {

        $manager = $caller->managers()->getDalInstance("Document");
        $manager->setRootDirectory($caller->app()->config()->get(\Puzzlout\Framework\Enums\AppSettingKeys::RootDocumentUpload));
        $manager->setWebDirectory($caller->app()->config()->get(\Puzzlout\Framework\Enums\AppSettingKeys::BaseUrl) . $caller->app()->config()->get(\Puzzlout\Framework\Enums\AppSettingKeys::RootUploadsFolderPath));
        $directory = str_replace("_id", "", $dataPost['itemCategory']);
        $manager->setObjectDirectory($directory);
        if ($dataPost['itemReplace'] === "true") {
            $manager->selectManyByCategoryAndId($dataPost['itemCategory'], $dataPost['itemId']);
        }
        $manager->setFilenamePrefix($dataPost['itemId'] . '_');
        $document = new \Applications\EasyMvc\Models\Dao\Document();
        $document->setDocument_category($dataPost['itemCategory']);
        if (isset($dataPost['title']) && $dataPost['title'] != "") {
            $document->setDocument_title($dataPost['title']);
        } else {
            $document->setDocument_title($files['file']['name']);
        }

        $manager->copyWithFile($document, $files['file']);
    }
175427
private function makePrettyArchivedOnText()
    {
        $dateText = $this->metadata[DataTable::ARCHIVED_DATE_METADATA_NAME];
        $date     = Date::factory($dateText);
        $today    = mktime(0, 0, 0);

        if ($date->getTimestamp() > $today) {
            $elapsedSeconds = time() - $date->getTimestamp();
            $timeAgo        = $this->metricsFormatter->getPrettyTimeFromSeconds($elapsedSeconds);

            return Piwik::translate('CoreHome_ReportGeneratedXAgo', $timeAgo);
        }

        $prettyDate = $date->getLocalized(Date::DATE_FORMAT_SHORT);

        $timezoneAppend = ' (UTC)';
        return Piwik::translate('CoreHome_ReportGeneratedOn', $prettyDate) . $timezoneAppend;
    }
428765
def copy
            saved_doc = @document
            saved_parent = @parent

            @document = @parent = nil # do not process parent object and document in the copy

            # Perform the recursive copy (quite dirty).
            copyobj = Marshal.load(Marshal.dump(self))

            # restore saved values
            @document = saved_doc
            @parent = saved_parent

            copyobj.set_document(saved_doc) if copyobj.indirect?
            copyobj.parent = parent

            copyobj
        end
981697
function pongEasyFormSetData( divId, data ) {
	log( "Pong-EaysForm",  'set data hook: '+divId );
	var def = moduleConfig[ divId ];
	if ( def.dataDocSubPath == null ) {
		// table is the root of the doc
		log( "Pong-EaysForm",  'no tbl.dataDocSubPath' );
		// TODO add update code
		//alert( "Update form with dataDocSubPath..." );
		pongEasyFormUpdFieldsDta( divId, moduleConfig[ divId ], data ); 
	} else {
		log( "Pong-EaysForm",  'tbl.dataDocSubPath='+def.dataDocSubPath );
		// table is somewhere in the DOM tree
		var pathToken = def.dataDocSubPath.split('.');
		log( "Pong-EaysForm",  'pathToken[0] ' + pathToken[0] );
		var subdata = data[ pathToken[0] ];
		for ( i = 1; i < pathToken.length; i++ ) {
			log( "Pong-EaysForm", 'pathToken['+i+'] ' + pathToken[i] );	
			subdata = subdata[ pathToken[i] ];
		}
		log( "Pong-EaysForm", ' subdata = ' + JSON.stringify( subdata ) );
		//poList[ divId ].pongListData = subdata;
		// TODO add update code
		//alert( "Update form w/o dataDocSubPath..." );
		pongEasyFormUpdFieldsDta( divId, moduleConfig[ divId ], subdata ); 
	}
}
44222
function upsertDocumentController(req, res) {
                    var modelName = req.params.modelName,
                        id = req.params.documentId,
                        user = req.admin_user,
                        data = _.extend({}, req.body, req.files),
                        modelConfig = registry.models[modelName],
                        form;

                    polymorphGetDocument(modelConfig.model, modelConfig.is_single, id).then(
                        function createTheForm(document) {
                            var action = document ? 'update' : 'create';
                            var docType = document && document._doc.__t;
                            if (docType) modelConfig = registry.models[docType];
                            var FormType = modelConfig.options.form;
                            if (!user.hasPermissions(modelConfig.modelName, action)) throw new Error('unauthorized');
                            form = new FormType(modelConfig.options, modelConfig.model, document, data);
                            return form.save();
                        }
                    ).then(
                        function (document) {
                            modelConfig.options.post(document);
                            return form;
                        },
                        function (err) {
                            err.modelConfig = modelConfig;
                            err.form = form;
                            if (!form) throw err;

                            form.errors = form.errors || {};
                            if (err.name == 'ValidationError') {
                                form.errors = _.merge(form.errors, err.errors);
                            } else if (err.name === 'MongoError' && err.code == 11000) {
                                form.errors.exception = err;
                                err.name = "Duplicate";
                                var msg = '{' + err.err.split('$').pop().split('{').pop();
                                var ObjectID = /ObjectId\(\'(\w+)\'\)/.exec(msg);
                                err.fields = '\n<br />';
                                err.fields += (ObjectID.length == 2) ? '<a href="' + ObjectID[1] + '" target="_blank">Click to open duplicate document</a>' :
                                    msg;
                            } else {
                                form.errors.exception = err;
                            }
                            if (_.isEmpty(form.errors)) return form;
                            throw err;
                        }
                    ).then(
                        function (form) {
                            res._debug_form = form;
                            var response = form.instance.toJSON();
                            response.id = response.id || form.instance._id;
                            response.label = response.label || form.instance.name || form.instance.title || form.instance.toString();
                            return response;
                        }
                    ).then(
                        function (response) {
                            res.json(200, response);
                        },
                        function (err) {
                            err.form = res._debug_form;
                            res.json(422, err);
                        }
                    ).end();
                }
1155491
function copyReadmeFiles() {

    const resolvedSrcReadmePaths = path.resolve(rootDir, srcReadmePaths);

    dryRun ? console.log(`In ${destDir}, this script would...`) : console.log(`In ${destDir}...`);

    fs.readdir('packages', (err, files) => {
        totalDocsCount = files.length;
    });

    createDirectory(destDir);
    glob(resolvedSrcReadmePaths, {realpath:true}, function(error, srcFiles) {
        
        srcFiles.forEach((srcReadmePath) => {    
            createDestReadme(srcReadmePath);
            const srcDirPath = path.dirname(srcReadmePath);
            const lastSrcDir = srcDirPath.split(path.sep).pop();
            sidebarEntries.push(`en/packages/${lastSrcDir}/index`);
        });

        console.log(chalk.green(`${updatedDocsCount} of ${totalDocsCount} package readme.md files updated`));
        updateSidebar();
       
    });

}
903803
private void publishFileSet(CopyEntity.DatasetAndPartition datasetAndPartition,
      Collection<WorkUnitState> datasetWorkUnitStates) throws IOException {
    Map<String, String> additionalMetadata = Maps.newHashMap();

    Preconditions.checkArgument(!datasetWorkUnitStates.isEmpty(),
        "publishFileSet received an empty collection work units. This is an error in code.");

    CopyableDatasetMetadata metadata = CopyableDatasetMetadata
        .deserialize(datasetWorkUnitStates.iterator().next().getProp(CopySource.SERIALIZED_COPYABLE_DATASET));
    Path datasetWriterOutputPath = new Path(this.writerOutputDir, datasetAndPartition.identifier());

    log.info("Merging all split work units.");
    DistcpFileSplitter.mergeAllSplitWorkUnits(this.fs, datasetWorkUnitStates);

    log.info(String.format("[%s] Publishing fileSet from %s for dataset %s", datasetAndPartition.identifier(),
        datasetWriterOutputPath, metadata.getDatasetURN()));

    List<CommitStep> prePublish = getCommitSequence(datasetWorkUnitStates, PrePublishStep.class);
    List<CommitStep> postPublish = getCommitSequence(datasetWorkUnitStates, PostPublishStep.class);
    log.info(String.format("[%s] Found %d prePublish steps and %d postPublish steps.", datasetAndPartition.identifier(),
        prePublish.size(), postPublish.size()));

    executeCommitSequence(prePublish);
    if (hasCopyableFiles(datasetWorkUnitStates)) {
      // Targets are always absolute, so we start moving from root (will skip any existing directories).
      HadoopUtils.renameRecursively(this.fs, datasetWriterOutputPath, new Path("/"));
    } else {
      log.info(String.format("[%s] No copyable files in dataset. Proceeding to postpublish steps.", datasetAndPartition.identifier()));
    }
    executeCommitSequence(postPublish);

    this.fs.delete(datasetWriterOutputPath, true);

    long datasetOriginTimestamp = Long.MAX_VALUE;
    long datasetUpstreamTimestamp = Long.MAX_VALUE;
    Optional<String> fileSetRoot = Optional.<String>absent();

    for (WorkUnitState wus : datasetWorkUnitStates) {
      if (wus.getWorkingState() == WorkingState.SUCCESSFUL) {
        wus.setWorkingState(WorkUnitState.WorkingState.COMMITTED);
      }
      CopyEntity copyEntity = CopySource.deserializeCopyEntity(wus);
      if (copyEntity instanceof CopyableFile) {
        CopyableFile copyableFile = (CopyableFile) copyEntity;
        DataFileVersionStrategy srcVS = this.srcDataFileVersionStrategy;
        DataFileVersionStrategy dstVS = this.dstDataFileVersionStrategy;

        // Prefer to use copyableFile's specific version strategy
        if (copyableFile.getDataFileVersionStrategy() != null) {
          Config versionStrategyConfig = ConfigFactory.parseMap(ImmutableMap.of(
              DataFileVersionStrategy.DATA_FILE_VERSION_STRATEGY_KEY, copyableFile.getDataFileVersionStrategy()));
          srcVS = DataFileVersionStrategy.instantiateDataFileVersionStrategy(this.srcFs, versionStrategyConfig);
          dstVS = DataFileVersionStrategy.instantiateDataFileVersionStrategy(this.fs, versionStrategyConfig);
        }

        if (copyableFile.getPreserve().preserve(PreserveAttributes.Option.VERSION)
            && dstVS.hasCharacteristic(DataFileVersionStrategy.Characteristic.SETTABLE)) {
          dstVS.setVersion(copyableFile.getDestination(),
              srcVS.getVersion(copyableFile.getOrigin().getPath()));
        }

        if (wus.getWorkingState() == WorkingState.COMMITTED) {
          CopyEventSubmitterHelper.submitSuccessfulFilePublish(this.eventSubmitter, copyableFile, wus);
          // Dataset Output path is injected in each copyableFile.
          // This can be optimized by having a dataset level equivalent class for copyable entities
          // and storing dataset related information, e.g. dataset output path, there.

          // Currently datasetOutputPath is only present for hive datasets.
          if (!fileSetRoot.isPresent() && copyableFile.getDatasetOutputPath() != null) {
            fileSetRoot = Optional.of(copyableFile.getDatasetOutputPath());
          }
          if (lineageInfo.isPresent()) {
            lineageInfo.get().putDestination(copyableFile.getDestinationData(), 0, wus);
          }
        }
        if (datasetOriginTimestamp > copyableFile.getOriginTimestamp()) {
          datasetOriginTimestamp = copyableFile.getOriginTimestamp();
        }
        if (datasetUpstreamTimestamp > copyableFile.getUpstreamTimestamp()) {
          datasetUpstreamTimestamp = copyableFile.getUpstreamTimestamp();
        }
      }
    }

    // if there are no valid values for datasetOriginTimestamp and datasetUpstreamTimestamp, use
    // something more readable
    if (Long.MAX_VALUE == datasetOriginTimestamp) {
      datasetOriginTimestamp = 0;
    }
    if (Long.MAX_VALUE == datasetUpstreamTimestamp) {
      datasetUpstreamTimestamp = 0;
    }

    additionalMetadata.put(SlaEventKeys.SOURCE_URI, this.state.getProp(SlaEventKeys.SOURCE_URI));
    additionalMetadata.put(SlaEventKeys.DESTINATION_URI, this.state.getProp(SlaEventKeys.DESTINATION_URI));
    additionalMetadata.put(SlaEventKeys.DATASET_OUTPUT_PATH, fileSetRoot.or("Unknown"));
    CopyEventSubmitterHelper.submitSuccessfulDatasetPublish(this.eventSubmitter, datasetAndPartition,
        Long.toString(datasetOriginTimestamp), Long.toString(datasetUpstreamTimestamp), additionalMetadata);
    }
892584
function Document(db, raw) 
{
  var self = this, raw;
  if (raw===undefined) raw = { };
  if (typeof(raw)==="string") raw = deserialize(raw);
  
  Object.defineProperty(this, "save", { value: function(cb) {
    return db.save(self, cb);
  }, writable: false  });

  Object.defineProperty(this, "remove", { value: function(cb) {
    if (! self._id) return cb(); // TODO maybe emit error
    return db.remove({ _id: self._id }, { }, cb);
  }, writable: false  });

  Object.defineProperty(this, "update", { value: function(modifier, cb) {
    if (self._id === undefined) self._id = db.createNewId();
    return db.update({ _id: self._id }, modifier, { upsert: true }, cb);
  }, writable: false  });

  Object.defineProperty(this, "copy", { value: function(strict) { 
    return deepCopy(self, strict);
  }, writable: false });

  Object.defineProperty(this, "serialize", { value: function(strict) {
    return serialize(self);
  }, writable: false });

  // Special methods
  for (var method in db._methods) Object.defineProperty(this, method, { value: db._methods[method], writable: false });

  // Persist to LevelUP
  Object.defineProperty(this, "_persist", { value: function(cb, quiet) {
    if (!quiet) db.emit("save", self);
    db.store.put(self._id, self.serialize(), function(err) {
      cb(err || null, err ? undefined : self);  
    });
  } });

  _.extend(this, raw.constructor.modelName ? deepCopy(raw) : raw); // Clone it deeply if it's schema-constructed
  schemas.construct(this, db.schema);
  db.emit("construct", self);
}
48488
protected function refreshFromCopied()
    {
        // Skip if copied record isn't available
        $source = $this->CopyContentFrom();
        if (!$source || !$source->exists()) {
            return;
        }

        // We also want to copy certain, but only if we're copying the source page for the first
        // time. After this point, the user is free to customise these for the virtual page themselves.
        if ($this->isChanged('CopyContentFromID', 2) && $this->CopyContentFromID) {
            foreach (self::config()->get('initially_copied_fields') as $fieldName) {
                $this->$fieldName = $source->$fieldName;
            }
        }

        // Copy fields to the original record in case the class type changes
        foreach ($this->getVirtualFields() as $virtualField) {
            $this->$virtualField = $source->$virtualField;
        }
    }
71281
def encode_multipart_formdata(self, fields, files, baseName, verbose=False):
        
        BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$'
        CRLF = '\r\n'
        content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
        if verbose is True:
            print(('Encoding ' + baseName + ' for upload...'))
        fin = self._open(files, 'rb')
        fout = self._open(files + '.b64', 'wb')
        fout.write(bytearray('--' + BOUNDARY + CRLF, 'utf-8'))
        fout.write(bytearray('Content-Disposition: form-data'
                             '; name="file"; filename="' + baseName + '"' + CRLF, "utf-8"))
        fout.write(bytearray('Content-Type: application/octet-stream' + CRLF,
                             'utf-8'))
        fout.write(bytearray(CRLF, 'utf-8'))
        shutil.copyfileobj(fin, fout)
        fout.write(bytearray(CRLF, 'utf-8'))
        fout.write(bytearray('--' + BOUNDARY + '--' + CRLF, 'utf-8'))
        fout.write(bytearray(CRLF, 'utf-8'))
        fout.close()
        fin.close()
        return content_type
1106938
@Transactional
  @PostMapping(value = "/{entityTypeId}", headers = "Content-Type=multipart/form-data")
  public void createFromFormPostMultiPart(
      @PathVariable("entityTypeId") String entityTypeId,
      MultipartHttpServletRequest request,
      HttpServletResponse response) {
    Map<String, Object> paramMap = new HashMap<>();
    for (String param : request.getParameterMap().keySet()) {
      String[] values = request.getParameterValues(param);
      String value = values != null ? StringUtils.join(values, ',') : null;
      if (StringUtils.isNotBlank(value)) {
        paramMap.put(param, value);
      }
    }

    // add files to param map
    for (Entry<String, List<MultipartFile>> entry : request.getMultiFileMap().entrySet()) {
      String param = entry.getKey();
      List<MultipartFile> files = entry.getValue();
      if (files != null && files.size() > 1) {
        throw new IllegalArgumentException("Multiple file input not supported");
      }
      paramMap.put(param, files != null && !files.isEmpty() ? files.get(0) : null);
    }
    createInternal(entityTypeId, paramMap, response);
  }
642357
function dp_duplicate_page( $new_post_id, $old_post_object )
	{
		// only for acf
		if( $old_post_object->post_type != "acf" )
		{
			return;
		}
		
		
		// update keys
		$metas = get_post_custom( $new_post_id );


		if( $metas )
		{
			foreach( $metas as $field_key => $field )
			{
				if( strpos($field_key, 'field_') !== false )
				{
					$field = $field[0];
					$field = maybe_unserialize( $field );
					$field = maybe_unserialize( $field ); // just to be sure!
					
					// delete old field
					delete_post_meta($new_post_id, $field_key);


					// set new keys (recursive for sub fields)
					$this->create_new_field_keys( $field );


					// save it!
					update_post_meta($new_post_id, $field['key'], $field);
					
				}
				// if( strpos($field_key, 'field_') !== false )
			}
			// foreach( $metas as $field_key => $field )
		}
		// if( $metas )
	
	}
673942
def setup_output_document(input_doc, tmp_input_doc, metadata_info,
                                                    copy_document_catalog=True):
    """"""
    # NOTE: Inserting pages from a PdfFileReader into multiple PdfFileWriters
    # seems to cause problems (writer can hang on write), so only one is used.
    # This is why the tmp_input_doc file was created earlier, to get copies of
    # the page objects which are independent of those in input_doc.  An ugly
    # hack for a nasty bug to track down.

    # NOTE: You can get the _root_object attribute (dict for the document
    # catalog) from the output document after calling cloneReaderDocumentRoot
    # or else you can just directly get it from the input_doc.trailer dict, as
    # below (which is from the code for cloneReaderDocumentRoot), but you
    # CANNOT set the full _root_object to be the _root_object attribute for the
    # actual output_doc or else only blank pages show up in acroread (whether
    # or not there is any attempt to explicitly copy the pages over).  The same
    # is true for using cloneDocumentFromReader (which just calls
    # cloneReaderDocumentRoot followed by appendPagesFromReader).  At least the
    # '/Pages' key and value in _root_object cause problems, so they are
    # skipped in the partial copy.  Probably a bug in PyPDF2.  See the original
    # code for the routines on the github pages below.
    #
    # https://github.com/mstamy2/PyPDF2/blob/master/PyPDF2/pdf.py
    # https://github.com/mstamy2/PyPDF2/blob/master/PyPDF2/generic.py
    #
    # Files still can change zoom mode on clicking outline links, but that is
    # an Adobe implementation problem, and happens even in the uncropped files:
    # https://superuser.com/questions/278302/

    output_doc = PdfFileWriter()

    def root_objects_not_indirect(input_doc, root_object):
        """This can expand some of the `IndirectObject` objects in  a root object to
        see the actual values.  Currently only used for debugging.  May mess up the
        input doc and require a temporary one."""
        if isinstance(root_object, dict):
            return {root_objects_not_indirect(input_doc, key):
                    root_objects_not_indirect(input_doc, value) for
                                                  key, value in root_object.items()}
        elif isinstance(root_object, list):
            return [root_objects_not_indirect(input_doc, item) for item in root_object]
        elif isinstance(root_object, IndirectObject):
            return input_doc.getObject(root_object)
        else:
            return root_object

    doc_cat_whitelist = args.docCatWhitelist.split()
    if "ALL" in doc_cat_whitelist:
        doc_cat_whitelist = ["ALL"]

    doc_cat_blacklist = args.docCatBlacklist.split()
    if "ALL" in doc_cat_blacklist:
        doc_cat_blacklist = ["ALL"]

    # Partially copy over document catalog data from input_doc to output_doc.
    if not copy_document_catalog or (
            not doc_cat_whitelist and doc_cat_blacklist == ["ALL"]):
        # Check this first, to completely skip the possibly problematic code getting
        # document catalog items when possible.  Does not print a skipped list, though.
        if args.verbose:
            print("\nNot copying any document catalog items to the cropped document.")
    else:
        try:
            root_object = input_doc.trailer["/Root"]

            copied_items = []
            skipped_items = []
            for key, value in root_object.items():
                # Some possible keys can be:
                #
                # /Type -- required, must have value /Catalog
                # /Pages -- required, indirect ref to page tree; skip, will change
                # /PageMode -- set to /UseNone, /UseOutlines, /UseThumbs, /Fullscreen,
                #              /UseOC, or /UseAttachments, with /UseNone default.
                # /OpenAction -- action to take when document is opened, like zooming
                # /PageLayout -- set to /SinglePage, /OneColumn, /TwoColumnLeft,
                #                /TwoColumnRight, /TwoPageLeft, /TwoPageRight
                # /Names -- a name dictionary to avoid having to use object numbers
                # /Outlines -- indirect ref to document outline, i.e., bookmarks
                # /Dests -- a dict of destinations in the PDF
                # /ViewerPreferences -- a viewer preferences dict
                # /MetaData -- XMP metadata, as opposed to other metadata
                # /PageLabels -- alternate numbering for pages, only affect PDF viewers
                if key == "/Pages":
                    skipped_items.append(key)
                    continue
                if doc_cat_whitelist != ["ALL"] and key not in doc_cat_whitelist:
                    if doc_cat_blacklist == ["ALL"] or key in doc_cat_blacklist:
                        skipped_items.append(key)
                        continue
                copied_items.append(key)
                output_doc._root_object[NameObject(key)] = value

            if args.verbose:
                print("\nCopied these items from the document catalog:\n   ", end="")
                print(*copied_items)
                print("Skipped copy of these items from the document catalog:\n   ", end="")
                print(*skipped_items)

        except (KeyboardInterrupt, EOFError):
            raise
        except: # Just catch any errors here; don't know which might be raised.
            # On exception just warn and get a new PdfFileWriter object, to be safe.
            print("\nWarning: The document catalog data could not be copied to the"
                  "\nnew, cropped document.  Try fixing the PDF document using"
                  "\n'--gsFix' if you have Ghostscript installed.", file=sys.stderr)
            output_doc = PdfFileWriter()

    #output_doc.appendPagesFromReader(input_doc) # Works, but wait and test more.
    for page in [input_doc.getPage(i) for i in range(input_doc.getNumPages())]:
        output_doc.addPage(page)

    tmp_output_doc = PdfFileWriter()
    #tmp_output_doc.appendPagesFromReader(tmp_input_doc)  # Works, but test more.
    for page in [tmp_input_doc.getPage(i) for i in range(tmp_input_doc.getNumPages())]:
        tmp_output_doc.addPage(page)

    ##
    ## Copy the metadata from input_doc to output_doc, modifying the Producer string
    ## if this program didn't already set it.  Get bool for whether this program
    ## cropped the document already.
    ##

    already_cropped_by_this_program = set_cropped_metadata(input_doc, output_doc,
                                                           metadata_info)
    return output_doc, tmp_output_doc, already_cropped_by_this_program
508568
protected function validateRef(&$document_data, &$data, array $data_pointer, array $parent_data_pointer, ISchema $document, stdClass $schema, ValidationResult $bag): bool
    {
        $ref = $schema->{'$ref'};

        // $vars
        if ($this->varsSupport) {
            $ref = URI::parseTemplate($ref, $this->getVars($document_data, $data_pointer, $schema));
        }

        $map_used = $this->mapSupport && property_exists($schema, Schema::MAP_PROP);

        // $map
        if ($map_used) {
            unset($data);
            $data = $this->deepClone($schema->{Schema::MAP_PROP});
            $this->resolveVars($data,$document_data, $data_pointer);

            unset($document_data);
            $document_data = &$data;

            if ($data_pointer) {
                $parent_data_pointer = array_merge($parent_data_pointer, $data_pointer);
                $data_pointer = [];
            }
        }

        // Check if is relative json pointer
        if ($relative = JsonPointer::parseRelativePointer($ref, true)) {
            if (!JsonPointer::isEscapedPointer($ref)) {
                throw new InvalidJsonPointerException($ref);
            }

            $schema = JsonPointer::getDataByRelativePointer(
                $document->resolve(),
                $relative,
                $schema->{Schema::PATH_PROP} ?? [],
                $this
            );
            if ($schema === $this) {
                throw new InvalidJsonPointerException($ref);
            }

            return $this->validateSchema($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema, $bag);
        }

        // Check if is a json pointer relative to this document
        if (isset($ref[0]) && $ref[0] === '#') {
            $pointer = substr($ref, 1);
            if (JsonPointer::isPointer($pointer)) {
                if (!JsonPointer::isEscapedPointer($pointer)) {
                    throw new InvalidJsonPointerException($pointer);
                }
                $schema = JsonPointer::getDataByPointer($document->resolve(), $pointer, $this);
                if ($schema === $this) {
                    throw new InvalidJsonPointerException($pointer);
                }

                return $this->validateSchema($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema, $bag);
            }
            unset($pointer);
        }

        // Merge uris
        $ref = URI::merge($ref, $schema->{Schema::BASE_ID_PROP} ?? '', true);

        list($base_ref, $fragment) = explode('#', $ref, 2);

        if (JsonPointer::isPointer($fragment)) {
            if (!JsonPointer::isEscapedPointer($fragment)) {
                throw new InvalidJsonPointerException($fragment);
            }

            // try to resolve locally
            $schema = $document->resolve($base_ref . '#');

            if ($schema === null) {
                if (!$this->loader) {
                    throw new SchemaNotFoundException($base_ref);
                }
                // use loader
                $document = $this->loader->loadSchema($base_ref);
                if (!($document instanceof ISchema)) {
                    throw new SchemaNotFoundException($base_ref);
                }

                if ($fragment === '' || $fragment === '/') {
                    $schema = $document->resolve();
                } else {
                    $schema = JsonPointer::getDataByPointer($document->resolve(), $fragment, $this);
                    if ($schema === $this) {
                        throw new InvalidJsonPointerException($fragment);
                    }
                }

                if (!$map_used) {
                    unset($document_data);
                    $document_data = &$data;
                    if ($data_pointer) {
                        $parent_data_pointer = array_merge($parent_data_pointer, $data_pointer);
                        $data_pointer = [];
                    }
                }
            } else {
                if ($fragment !== '' && $fragment !== '/') {
                    $schema = JsonPointer::getDataByPointer($schema, $fragment, $this);
                    if ($schema === $this) {
                        throw new InvalidJsonPointerException($fragment);
                    }
                }
            }

            return $this->validateSchema($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema, $bag);
        }

        // Not a json pointer
        $schema = $document->resolve($ref);
        if ($schema !== null) {
            return $this->validateSchema($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema, $bag);
        }

        if (!$this->loader) {
            throw new SchemaNotFoundException($base_ref);
        }
        // use loader
        $document = $this->loader->loadSchema($base_ref);
        if (!($document instanceof ISchema)) {
            throw new SchemaNotFoundException($base_ref);
        }

        $schema = $document->resolve($ref);

        if (!$map_used) {
            unset($document_data);
            $document_data = &$data;
            if ($data_pointer) {
                $parent_data_pointer = array_merge($parent_data_pointer, $data_pointer);
                $data_pointer = [];
            }
        }

        return $this->validateSchema($document_data, $data, $data_pointer, $parent_data_pointer, $document, $schema, $bag);
    }
97967
public function getRequestFormDataKey()
    {
        $post = array_keys($_POST);
        $file = array_keys($_FILES);

        if (!is_array($post)) {
            $post = array();
        }

        if (!is_array($file)) {
            $file = array();
        }

        return $post + $file;
    }
821270
def pdf_copy(input: str, output: str, pages: [int], yes_to_all=False):
    
    if not os.path.isfile(input):
        print("Error. The file '%s' does not exist." % input)
        return

    if os.path.isfile(output) and not yes_to_all and not overwrite_dlg(output):
        return

    with open(input, "rb") as inputfile:
        reader = PdfFileReader(inputfile)
        outputfile = open(output, "wb")
        writer = PdfFileWriter()
        if pages is None:
            pages = range(len(reader.pages))
        else:
            pages = parse_rangearg(pages, len(reader.pages))
        for pagenr in sorted(pages):
            page = reader.getPage(pagenr)
            writer.addPage(page)
            writer.write(outputfile)
        outputfile.close()
1374143
private void processResourceData() throws IOException
   {
      FieldMap fieldMap = new FieldMap12(m_file.getProjectProperties(), m_file.getCustomFields());
      fieldMap.createResourceFieldMap(m_projectProps);

      FieldMap enterpriseCustomFieldMap = new FieldMap12(m_file.getProjectProperties(), m_file.getCustomFields());
      enterpriseCustomFieldMap.createEnterpriseCustomFieldMap(m_projectProps, ResourceField.class);

      DirectoryEntry rscDir = (DirectoryEntry) m_projectDir.getEntry("TBkndRsc");
      VarMeta rscVarMeta = new VarMeta12(new DocumentInputStream(((DocumentEntry) rscDir.getEntry("VarMeta"))));
      Var2Data rscVarData = new Var2Data(rscVarMeta, new DocumentInputStream(((DocumentEntry) rscDir.getEntry("Var2Data"))));
      FixedMeta rscFixedMeta = new FixedMeta(new DocumentInputStream(((DocumentEntry) rscDir.getEntry("FixedMeta"))), 37);
      FixedData rscFixedData = new FixedData(rscFixedMeta, m_inputStreamFactory.getInstance(rscDir, "FixedData"));
      FixedMeta rscFixed2Meta = new FixedMeta(new DocumentInputStream(((DocumentEntry) rscDir.getEntry("Fixed2Meta"))), 49);
      FixedData rscFixed2Data = new FixedData(rscFixed2Meta, m_inputStreamFactory.getInstance(rscDir, "Fixed2Data"));
      Props12 props = new Props12(m_inputStreamFactory.getInstance(rscDir, "Props"));
      //System.out.println(rscVarMeta);
      //System.out.println(rscVarData);
      //System.out.println(rscFixedMeta);
      //System.out.println(rscFixedData);
      //System.out.println(rscFixed2Meta);
      //System.out.println(rscFixed2Data);
      //System.out.println(props);

      // Process aliases
      new CustomFieldAliasReader(m_file.getCustomFields(), props.getByteArray(RESOURCE_FIELD_NAME_ALIASES)).process();

      TreeMap<Integer, Integer> resourceMap = createResourceMap(fieldMap, rscFixedMeta, rscFixedData);
      Integer[] uniqueid = rscVarMeta.getUniqueIdentifierArray();
      Integer id;
      Integer offset;
      byte[] data;
      byte[] metaData;
      Resource resource;

      String notes;

      for (int loop = 0; loop < uniqueid.length; loop++)
      {
         id = uniqueid[loop];
         offset = resourceMap.get(id);
         if (offset == null)
         {
            continue;
         }

         data = rscFixedData.getByteArrayValue(offset.intValue());
         byte[] metaData2 = rscFixed2Meta.getByteArrayValue(offset.intValue());
         byte[] data2 = rscFixed2Data.getByteArrayValue(offset.intValue());
         //metaData = rscFixedMeta.getByteArrayValue(offset.intValue());
         //MPPUtility.dataDump(data, true, true, true, true, true, true, true);
         //MPPUtility.dataDump(metaData, true, true, true, true, true, true, true);
         //MPPUtility.varDataDump(rscVarData, id, true, true, true, true, true, true);

         resource = m_file.addResource();

         resource.disableEvents();
         fieldMap.populateContainer(ResourceField.class, resource, id, new byte[][]
         {
            data,
            data2
         }, rscVarData);

         enterpriseCustomFieldMap.populateContainer(ResourceField.class, resource, id, null, rscVarData);

         resource.enableEvents();

         resource.setBudget((metaData2[8] & 0x20) != 0);

         resource.setGUID(MPPUtility.getGUID(data2, 0));

         processHyperlinkData(resource, rscVarData.getByteArray(id, fieldMap.getVarDataKey(ResourceField.HYPERLINK_DATA)));

         resource.setID(Integer.valueOf(MPPUtility.getInt(data, 4)));

         resource.setOutlineCode1(m_outlineCodeVarData.getUnicodeString(Integer.valueOf(rscVarData.getInt(id, 2, fieldMap.getVarDataKey(ResourceField.OUTLINE_CODE1_INDEX))), OUTLINECODE_DATA));
         resource.setOutlineCode2(m_outlineCodeVarData.getUnicodeString(Integer.valueOf(rscVarData.getInt(id, 2, fieldMap.getVarDataKey(ResourceField.OUTLINE_CODE2_INDEX))), OUTLINECODE_DATA));
         resource.setOutlineCode3(m_outlineCodeVarData.getUnicodeString(Integer.valueOf(rscVarData.getInt(id, 2, fieldMap.getVarDataKey(ResourceField.OUTLINE_CODE3_INDEX))), OUTLINECODE_DATA));
         resource.setOutlineCode4(m_outlineCodeVarData.getUnicodeString(Integer.valueOf(rscVarData.getInt(id, 2, fieldMap.getVarDataKey(ResourceField.OUTLINE_CODE4_INDEX))), OUTLINECODE_DATA));
         resource.setOutlineCode5(m_outlineCodeVarData.getUnicodeString(Integer.valueOf(rscVarData.getInt(id, 2, fieldMap.getVarDataKey(ResourceField.OUTLINE_CODE5_INDEX))), OUTLINECODE_DATA));
         resource.setOutlineCode6(m_outlineCodeVarData.getUnicodeString(Integer.valueOf(rscVarData.getInt(id, 2, fieldMap.getVarDataKey(ResourceField.OUTLINE_CODE6_INDEX))), OUTLINECODE_DATA));
         resource.setOutlineCode7(m_outlineCodeVarData.getUnicodeString(Integer.valueOf(rscVarData.getInt(id, 2, fieldMap.getVarDataKey(ResourceField.OUTLINE_CODE7_INDEX))), OUTLINECODE_DATA));
         resource.setOutlineCode8(m_outlineCodeVarData.getUnicodeString(Integer.valueOf(rscVarData.getInt(id, 2, fieldMap.getVarDataKey(ResourceField.OUTLINE_CODE8_INDEX))), OUTLINECODE_DATA));
         resource.setOutlineCode9(m_outlineCodeVarData.getUnicodeString(Integer.valueOf(rscVarData.getInt(id, 2, fieldMap.getVarDataKey(ResourceField.OUTLINE_CODE9_INDEX))), OUTLINECODE_DATA));
         resource.setOutlineCode10(m_outlineCodeVarData.getUnicodeString(Integer.valueOf(rscVarData.getInt(id, 2, fieldMap.getVarDataKey(ResourceField.OUTLINE_CODE10_INDEX))), OUTLINECODE_DATA));

         resource.setUniqueID(id);

         metaData = rscFixedMeta.getByteArrayValue(offset.intValue());
         resource.setFlag(1, (metaData[28] & 0x40) != 0);
         resource.setFlag(2, (metaData[28] & 0x80) != 0);
         resource.setFlag(3, (metaData[29] & 0x01) != 0);
         resource.setFlag(4, (metaData[29] & 0x02) != 0);
         resource.setFlag(5, (metaData[29] & 0x04) != 0);
         resource.setFlag(6, (metaData[29] & 0x08) != 0);
         resource.setFlag(7, (metaData[29] & 0x10) != 0);
         resource.setFlag(8, (metaData[29] & 0x20) != 0);
         resource.setFlag(9, (metaData[29] & 0x40) != 0);
         resource.setFlag(10, (metaData[28] & 0x20) != 0);
         resource.setFlag(11, (metaData[29] & 0x80) != 0);
         resource.setFlag(12, (metaData[30] & 0x01) != 0);
         resource.setFlag(13, (metaData[30] & 0x02) != 0);
         resource.setFlag(14, (metaData[30] & 0x04) != 0);
         resource.setFlag(15, (metaData[30] & 0x08) != 0);
         resource.setFlag(16, (metaData[30] & 0x10) != 0);
         resource.setFlag(17, (metaData[30] & 0x20) != 0);
         resource.setFlag(18, (metaData[30] & 0x40) != 0);
         resource.setFlag(19, (metaData[30] & 0x80) != 0);
         resource.setFlag(20, (metaData[31] & 0x01) != 0);

         notes = resource.getNotes();
         if (m_reader.getPreserveNoteFormatting() == false)
         {
            notes = RtfHelper.strip(notes);
         }
         resource.setNotes(notes);

         //
         // Configure the resource calendar
         //
         resource.setResourceCalendar(m_resourceMap.get(id));

         //
         // Process any enterprise columns
         //
         processResourceEnterpriseColumns(resource, metaData2);

         //
         // Process cost rate tables
         //
         CostRateTableFactory crt = new CostRateTableFactory();
         crt.process(resource, 0, rscVarData.getByteArray(id, fieldMap.getVarDataKey(ResourceField.COST_RATE_A)));
         crt.process(resource, 1, rscVarData.getByteArray(id, fieldMap.getVarDataKey(ResourceField.COST_RATE_B)));
         crt.process(resource, 2, rscVarData.getByteArray(id, fieldMap.getVarDataKey(ResourceField.COST_RATE_C)));
         crt.process(resource, 3, rscVarData.getByteArray(id, fieldMap.getVarDataKey(ResourceField.COST_RATE_D)));
         crt.process(resource, 4, rscVarData.getByteArray(id, fieldMap.getVarDataKey(ResourceField.COST_RATE_E)));

         //
         // Process availability table
         //
         AvailabilityFactory af = new AvailabilityFactory();
         af.process(resource.getAvailability(), rscVarData.getByteArray(id, fieldMap.getVarDataKey(ResourceField.AVAILABILITY_DATA)));

         //
         // Process resource type
         //
         if ((metaData[9] & 0x02) != 0)
         {
            resource.setType(ResourceType.WORK);
         }
         else
         {
            if ((metaData2[8] & 0x10) != 0)
            {
               resource.setType(ResourceType.COST);
            }
            else
            {
               resource.setType(ResourceType.MATERIAL);
            }
         }

         m_eventManager.fireResourceReadEvent(resource);
      }
   }