text:
'use strict';

const fs = require('fs');
const fetch = require('isomorphic-fetch');
const Dropbox = require('dropbox').Dropbox;
const mkdirp = require('mkdirp');
const rimraf = require('rimraf');
const Base = require('./base');

class DropBoxClient extends Base {

  static get config() {
    return {
      dropBoxAccessToken: 'dropboxAccessToken',
      dropBoxPath: 'dropBoxPath',
      workDir: 'workDir',
      imageSize: 'imageSize'
    };
  }

  static init(config) {
    return new DropBoxClient(config);
  }

  constructor(config) {
    super();
    this._configErrors = [];
    if (config) {
      this.apply(this, config, this.config);
    }
    this._pending = 0;
  }

  get configErrors() {
    return this._configErrors;
  }

  get pending() {
    return this._pending;
  }

  cleanup(callbackFn) {
    if (fs.existsSync(this.workDir)) {
      console.log('cleanup\t\t', 'deleting ' + this.workDir + ' directory');
      rimraf(this.workDir + '/*', callbackFn);
    } else {
      callbackFn();
    }
  };

  setup(callbackFn) {
    this.cleanup(() => {
      console.log('setup\t\t', 'creating empty ' + this.workDir + ' directory')
      mkdirp(this.workDir, (err) => {
        if (err) {
          this.emit('error', err);
        } else {
          callbackFn();
        }
      });
    });
  };

  explode(files) {
    console.log('explode\t\t', 'writing individual json files');
    const lastFile = files.length - 1;
    for (var i = 0; i < files.length; i++) {
      new Dropbox({
          fetch: fetch,
          accessToken: this.dropBoxAccessToken
        }).filesGetThumbnail({
          "path": this.dropBoxPath + files[i].name,
          "size": this.imageSize
        })
        .then((response) => {
          const filename = response.name.split('.')[0];
          const writeStream = fs.createWriteStream(this.workDir + '/' + filename + '.json');
          const buff = Buffer.from(response.fileBinary);
          const base64data = buff.toString('base64');
          let json = "{" +
            '"name": "' + response.name + '",' +
            '"image": "' + base64data + '"' +
            "}";
          writeStream.write(json);
          writeStream.end();
          if (!--this._pending) {
            this.emit('complete', {
              status: 'complete'
            });
          }
        })
        .catch((error) => {
          this.emit('error', error);
          return false;
        });
    }
  }

  downloadImages() {
    console.log('download\t', 'connecting to dropbox');
    new Dropbox({
        fetch: fetch,
        accessToken: this.dropBoxAccessToken
      })
      .filesListFolder({
        path: this.dropBoxPath,
      })
      .then((response) => {
        this._pending = response.entries.length;
        if (this.pending) {
          this.explode(response.entries);
        } else {
          this.emit('complete', {
            status: 'complete'
          });
        }
      })
      .catch((error) => {
        this.emit('error', error);
        return false;
      });
  }

  verifyDropBoxAccessToken() {
    const rc = this.dropBoxAccessToken !== '';
    if (!rc) {
      this._configErrors.push('Please provide a valid DropBox Access Token.\n');
    }
    return rc;
  }

  verifyDropBoxPath() {
    const rc = this.dropBoxPath !== '';
    if (!rc) {
      this._configErrors.push('Please provide a valid DropBox Path.\n');
    }
    return rc;
  }

  verifyWorkDir() {
    const rc = this.workDir !== '';
    if (!rc) {
      this._configErrors.push('Please provide a valid working directory.\n');
    }
    return rc;
  }

  verifyImageSize() {
    const rc = this.imageSize !== '';
    if (!rc) {
      this._configErrors.push('Please provide a valid Image size.\n');
    }
    return rc;
  }

  verifyConfig() {
    return this.verifyDropBoxAccessToken() &&
      this.verifyDropBoxPath() &&
      this.verifyWorkDir() &&
      this.verifyImageSize();
  }

  download() {
    if (this.verifyConfig()) {
      this.setup(() => this.downloadImages());
    } else {
      this.emit('error', new Error(this.configErrors.toString()));
    }
  }
}

module.exports = DropBoxClient;


text:
<?php

namespace Redtrine\Structure;

/**
 * Common base structure.
 */
abstract class Base
{
    protected $name;

    protected $key;

    protected $client;

    public function __construct($name)
    {
        $this->setName($name);
        $this->key = $this->name;
    }

    public function setName($name)
    {
        $this->name = $name;
    }

    public function getName()
    {
        return $this->name;
    }

    public function getKey()
    {
        return $this->key;
    }

    public function setClient($client)
    {
        $this->client = $client;
    }

    public function getClient()
    {
        return $this->client;
    }

    /**
     * Remove the structure from the underlying Redis database.
     *
     * @return array The number of keys that were removed.
     */
    public function destroy()
    {
        return $this->getClient()->del($this->getKey());
    }
}

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// clang-format off
// #import 'chrome://os-settings/chromeos/os_settings.js';

// #import {FakeNetworkConfig} from 'chrome://test/chromeos/fake_network_config_mojom.m.js';
// #import {MojoInterfaceProviderImpl} from 'chrome://resources/cr_components/chromeos/network/mojo_interface_provider.m.js';
// #import {OncMojo} from 'chrome://resources/cr_components/chromeos/network/onc_mojo.m.js';
// #import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
// #import {FakeUserActionRecorder} from './fake_user_action_recorder.m.js';
// #import {setUserActionRecorderForTesting} from 'chrome://os-settings/chromeos/os_settings.js';
// clang-format on

suite('InternetConfig', function() {
  /** @type {!InternetConfig|undefined} */
  let internetConfig;

  /** @type {!chromeos.networkConfig.mojom.CrosNetworkConfigRemote|undefined} */
  let mojoApi_;

  /** @type {?chromeos.settings.mojom.UserActionRecorderInterface} */
  let userActionRecorder;

  suiteSetup(function() {
    mojoApi_ = new FakeNetworkConfig();
    network_config.MojoInterfaceProviderImpl.getInstance().remote_ = mojoApi_;
  });

  setup(function() {
    internetConfig = document.createElement('internet-config');
    internetConfig.type = OncMojo.getNetworkTypeString(
        chromeos.networkConfig.mojom.NetworkType.kWiFi);
    document.body.appendChild(internetConfig);
    Polymer.dom.flush();

    userActionRecorder = new settings.FakeUserActionRecorder();
    settings.setUserActionRecorderForTesting(userActionRecorder);
  });

  test('Cancel button closes the dialog', function() {
    internetConfig.open();
    assertTrue(internetConfig.$.dialog.open);

    internetConfig.$$('cr-button.cancel-button').click();
    assertFalse(internetConfig.$.dialog.open);
  });

  test('Connect button click increments settings change count', function() {
    internetConfig.open();
    internetConfig.showConnect = true;
    Polymer.dom.flush();

    const connectBtn = internetConfig.$$('#connectButton');
    connectBtn.disabled = false;
    Polymer.dom.flush();

    assertFalse(connectBtn.disabled);
    assertEquals(userActionRecorder.settingChangeCount, 0);
    internetConfig.$$('cr-button.action-button').click();
    assertEquals(userActionRecorder.settingChangeCount, 1);
  });

  test('Save button click increments settings change count', function() {
    internetConfig.open();
    internetConfig.showConnect = false;
    Polymer.dom.flush();

    const saveBtn = internetConfig.$$('#saveButton');
    saveBtn.disabled = false;
    Polymer.dom.flush();

    assertFalse(saveBtn.disabled);
    assertEquals(userActionRecorder.settingChangeCount, 0);
    internetConfig.$$('cr-button.action-button').click();
    assertEquals(userActionRecorder.settingChangeCount, 1);
  });
});


text:
var r = require('request');
var p = r.post('http://localhost:8000');

process.stdin.pipe(p).pipe(process.stdout);


text:
package org.visallo.core.util;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface VisalloPlugin {
    boolean disabledByDefault() default false;
}


text:
package com.docusign.esign.api;

import javax.ws.rs.core.GenericType;

import com.docusign.esign.client.ApiException;
import com.docusign.esign.client.ApiClient;
import com.docusign.esign.client.Configuration;
import com.docusign.esign.model.*;
import com.docusign.esign.client.Pair;

/**
 * NotaryApi class.
 *
 **/
public class NotaryApi {
  private ApiClient apiClient;

 /**
  * NotaryApi.
  *
  **/
  public NotaryApi() {
    this(Configuration.getDefaultApiClient());
  }

 /**
  * NotaryApi.
  *
  **/
  public NotaryApi(ApiClient apiClient) {
    this.apiClient = apiClient;
  }

 /**
  * getApiClient Method.
  *
  * @return ApiClient
  **/
  public ApiClient getApiClient() {
    return apiClient;
  }

 /**
  * setApiClient Method.
  *
  **/
  public void setApiClient(ApiClient apiClient) {
    this.apiClient = apiClient;
  }

  /**
   * Add a notary to the system.
   *
   * @param notary  (optional)
   * @return Notary
   * @throws ApiException if fails to make API call
   */
  public Notary createNotary(Notary notary) throws ApiException {
    Object localVarPostBody = notary;

    // create path and map variables
    String localVarPath = "/v2.1/current_user/notary";

    // query params
    java.util.List<Pair> localVarQueryParams = new java.util.ArrayList<Pair>();
    java.util.List<Pair> localVarCollectionQueryParams = new java.util.ArrayList<Pair>();
    java.util.Map<String, String> localVarHeaderParams = new java.util.HashMap<String, String>();
    java.util.Map<String, Object> localVarFormParams = new java.util.HashMap<String, Object>();

    final String[] localVarAccepts = {
      "application/json"
    };
    final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);

    final String[] localVarContentTypes = {

    };
    final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);

    String[] localVarAuthNames = new String[] { "docusignAccessCode" };

    GenericType<Notary> localVarReturnType = new GenericType<Notary>() {};
    return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType);
      }

  /**
   * Add a notary jurisdiction to the system.
   *
   * @param notaryJurisdiction  (optional)
   * @return NotaryJurisdiction
   * @throws ApiException if fails to make API call
   */
  public NotaryJurisdiction createNotaryJurisdictions(NotaryJurisdiction notaryJurisdiction) throws ApiException {
    Object localVarPostBody = notaryJurisdiction;

    // create path and map variables
    String localVarPath = "/v2.1/current_user/notary/jurisdictions";

    // query params
    java.util.List<Pair> localVarQueryParams = new java.util.ArrayList<Pair>();
    java.util.List<Pair> localVarCollectionQueryParams = new java.util.ArrayList<Pair>();
    java.util.Map<String, String> localVarHeaderParams = new java.util.HashMap<String, String>();
    java.util.Map<String, Object> localVarFormParams = new java.util.HashMap<String, Object>();

    final String[] localVarAccepts = {
      "application/json"
    };
    final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);

    final String[] localVarContentTypes = {

    };
    final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);

    String[] localVarAuthNames = new String[] { "docusignAccessCode" };

    GenericType<NotaryJurisdiction> localVarReturnType = new GenericType<NotaryJurisdiction>() {};
    return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType);
      }

  /**
   * Delete a notary jurisdiction a specified user..
   *
   * @param jurisdictionId  (required)
   * @throws ApiException if fails to make API call
   */
  public void deleteNotaryJurisdiction(String jurisdictionId) throws ApiException {
    Object localVarPostBody = "{}";

    // verify the required parameter 'jurisdictionId' is set
    if (jurisdictionId == null) {
      throw new ApiException(400, "Missing the required parameter 'jurisdictionId' when calling deleteNotaryJurisdiction");
    }

    // create path and map variables
    String localVarPath = "/v2.1/current_user/notary/jurisdictions/{jurisdictionId}"
      .replaceAll("\\{" + "jurisdictionId" + "\\}", apiClient.escapeString(jurisdictionId.toString()));

    // query params
    java.util.List<Pair> localVarQueryParams = new java.util.ArrayList<Pair>();
    java.util.List<Pair> localVarCollectionQueryParams = new java.util.ArrayList<Pair>();
    java.util.Map<String, String> localVarHeaderParams = new java.util.HashMap<String, String>();
    java.util.Map<String, Object> localVarFormParams = new java.util.HashMap<String, Object>();

    final String[] localVarAccepts = {
      "application/json"
    };
    final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);

    final String[] localVarContentTypes = {

    };
    final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);

    String[] localVarAuthNames = new String[] { "docusignAccessCode" };

    apiClient.invokeAPI(localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null);
  }
  /// <summary>
  /// Get notary settings for a user
  /// </summary>

 /**
  * GetNotaryOptions Class.
  *
  **/
  public class GetNotaryOptions
  {
  private String includeJurisdictions = null;

 /**
  * setIncludeJurisdictions method.
  */
  public void setIncludeJurisdictions(String includeJurisdictions) {
    this.includeJurisdictions = includeJurisdictions;
  }

 /**
  * getIncludeJurisdictions method.
  *
  * @return String
  */
  public String getIncludeJurisdictions() {
    return this.includeJurisdictions;
  }
  }

   /**
   * Get notary settings for a user.
   *
   * @return NotaryResult
   */
  public NotaryResult getNotary() throws ApiException {
    return getNotary(null);
  }

  /**
   * Get notary settings for a user.
   *
   * @param options for modifying the method behavior.
   * @return NotaryResult
   * @throws ApiException if fails to make API call
   */
  public NotaryResult getNotary(NotaryApi.GetNotaryOptions options) throws ApiException {
    Object localVarPostBody = "{}";

    // create path and map variables
    String localVarPath = "/v2.1/current_user/notary";

    // query params
    java.util.List<Pair> localVarQueryParams = new java.util.ArrayList<Pair>();
    java.util.List<Pair> localVarCollectionQueryParams = new java.util.ArrayList<Pair>();
    java.util.Map<String, String> localVarHeaderParams = new java.util.HashMap<String, String>();
    java.util.Map<String, Object> localVarFormParams = new java.util.HashMap<String, Object>();

    if (options != null) {
      localVarQueryParams.addAll(apiClient.parameterToPair("include_jurisdictions", options.includeJurisdictions));
    }

    final String[] localVarAccepts = {
      "application/json"
    };
    final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);

    final String[] localVarContentTypes = {

    };
    final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);

    String[] localVarAuthNames = new String[] { "docusignAccessCode" };

    GenericType<NotaryResult> localVarReturnType = new GenericType<NotaryResult>() {};
    return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType);
      }

  /**
   * Get notary a jurisdiction for a user.
   *
   * @param jurisdictionId  (required)
   * @return NotaryJurisdiction
   * @throws ApiException if fails to make API call
   */
  public NotaryJurisdiction getNotaryJurisdiction(String jurisdictionId) throws ApiException {
    Object localVarPostBody = "{}";

    // verify the required parameter 'jurisdictionId' is set
    if (jurisdictionId == null) {
      throw new ApiException(400, "Missing the required parameter 'jurisdictionId' when calling getNotaryJurisdiction");
    }

    // create path and map variables
    String localVarPath = "/v2.1/current_user/notary/jurisdictions/{jurisdictionId}"
      .replaceAll("\\{" + "jurisdictionId" + "\\}", apiClient.escapeString(jurisdictionId.toString()));

    // query params
    java.util.List<Pair> localVarQueryParams = new java.util.ArrayList<Pair>();
    java.util.List<Pair> localVarCollectionQueryParams = new java.util.ArrayList<Pair>();
    java.util.Map<String, String> localVarHeaderParams = new java.util.HashMap<String, String>();
    java.util.Map<String, Object> localVarFormParams = new java.util.HashMap<String, Object>();

    final String[] localVarAccepts = {
      "application/json"
    };
    final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);

    final String[] localVarContentTypes = {

    };
    final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);

    String[] localVarAuthNames = new String[] { "docusignAccessCode" };

    GenericType<NotaryJurisdiction> localVarReturnType = new GenericType<NotaryJurisdiction>() {};
    return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType);
      }

  /**
   * Get notary seal for a jurisdiction.
   *
   * @param jurisdictionId  (required)
   * @throws ApiException if fails to make API call
   */
  public void getNotaryJurisdictionSeal(String jurisdictionId) throws ApiException {
    Object localVarPostBody = "{}";

    // verify the required parameter 'jurisdictionId' is set
    if (jurisdictionId == null) {
      throw new ApiException(400, "Missing the required parameter 'jurisdictionId' when calling getNotaryJurisdictionSeal");
    }

    // create path and map variables
    String localVarPath = "/v2.1/current_user/notary/jurisdictions/{jurisdictionId}/seal"
      .replaceAll("\\{" + "jurisdictionId" + "\\}", apiClient.escapeString(jurisdictionId.toString()));

    // query params
    java.util.List<Pair> localVarQueryParams = new java.util.ArrayList<Pair>();
    java.util.List<Pair> localVarCollectionQueryParams = new java.util.ArrayList<Pair>();
    java.util.Map<String, String> localVarHeaderParams = new java.util.HashMap<String, String>();
    java.util.Map<String, Object> localVarFormParams = new java.util.HashMap<String, Object>();

    final String[] localVarAccepts = {
      "application/json"
    };
    final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);

    final String[] localVarContentTypes = {

    };
    final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);

    String[] localVarAuthNames = new String[] { "docusignAccessCode" };

    apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null);
  }

  /**
   * Get notary jurisdictions for a user.
   *
   * @return NotaryJurisdictionList
   * @throws ApiException if fails to make API call
   */
  public NotaryJurisdictionList getNotaryJurisdictions() throws ApiException {
    Object localVarPostBody = "{}";

    // create path and map variables
    String localVarPath = "/v2.1/current_user/notary/jurisdictions";

    // query params
    java.util.List<Pair> localVarQueryParams = new java.util.ArrayList<Pair>();
    java.util.List<Pair> localVarCollectionQueryParams = new java.util.ArrayList<Pair>();
    java.util.Map<String, String> localVarHeaderParams = new java.util.HashMap<String, String>();
    java.util.Map<String, Object> localVarFormParams = new java.util.HashMap<String, Object>();

    final String[] localVarAccepts = {
      "application/json"
    };
    final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);

    final String[] localVarContentTypes = {

    };
    final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);

    String[] localVarAuthNames = new String[] { "docusignAccessCode" };

    GenericType<NotaryJurisdictionList> localVarReturnType = new GenericType<NotaryJurisdictionList>() {};
    return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType);
      }
  /// <summary>
  /// Get notary jurisdictions for a user
  /// </summary>

 /**
  * ListNotaryJournalsOptions Class.
  *
  **/
  public class ListNotaryJournalsOptions
  {
  private String count = null;
  private String searchText = null;
  private String startPosition = null;

 /**
  * setCount method.
  */
  public void setCount(String count) {
    this.count = count;
  }

 /**
  * getCount method.
  *
  * @return String
  */
  public String getCount() {
    return this.count;
  }

 /**
  * setSearchText method.
  */
  public void setSearchText(String searchText) {
    this.searchText = searchText;
  }

 /**
  * getSearchText method.
  *
  * @return String
  */
  public String getSearchText() {
    return this.searchText;
  }

 /**
  * setStartPosition method.
  */
  public void setStartPosition(String startPosition) {
    this.startPosition = startPosition;
  }

 /**
  * getStartPosition method.
  *
  * @return String
  */
  public String getStartPosition() {
    return this.startPosition;
  }
  }

   /**
   * Get notary jurisdictions for a user.
   *
   * @return NotaryJournalList
   */
  public NotaryJournalList listNotaryJournals() throws ApiException {
    return listNotaryJournals(null);
  }

  /**
   * Get notary jurisdictions for a user.
   *
   * @param options for modifying the method behavior.
   * @return NotaryJournalList
   * @throws ApiException if fails to make API call
   */
  public NotaryJournalList listNotaryJournals(NotaryApi.ListNotaryJournalsOptions options) throws ApiException {
    Object localVarPostBody = "{}";

    // create path and map variables
    String localVarPath = "/v2.1/current_user/notary/journals";

    // query params
    java.util.List<Pair> localVarQueryParams = new java.util.ArrayList<Pair>();
    java.util.List<Pair> localVarCollectionQueryParams = new java.util.ArrayList<Pair>();
    java.util.Map<String, String> localVarHeaderParams = new java.util.HashMap<String, String>();
    java.util.Map<String, Object> localVarFormParams = new java.util.HashMap<String, Object>();

    if (options != null) {
      localVarQueryParams.addAll(apiClient.parameterToPair("count", options.count));
    }if (options != null) {
      localVarQueryParams.addAll(apiClient.parameterToPair("search_text", options.searchText));
    }if (options != null) {
      localVarQueryParams.addAll(apiClient.parameterToPair("start_position", options.startPosition));
    }

    final String[] localVarAccepts = {
      "application/json"
    };
    final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);

    final String[] localVarContentTypes = {

    };
    final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);

    String[] localVarAuthNames = new String[] { "docusignAccessCode" };

    GenericType<NotaryJournalList> localVarReturnType = new GenericType<NotaryJournalList>() {};
    return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType);
      }

  /**
   * Update a notary.
   *
   * @param notary  (optional)
   * @return Notary
   * @throws ApiException if fails to make API call
   */
  public Notary updateNotary(Notary notary) throws ApiException {
    Object localVarPostBody = notary;

    // create path and map variables
    String localVarPath = "/v2.1/current_user/notary";

    // query params
    java.util.List<Pair> localVarQueryParams = new java.util.ArrayList<Pair>();
    java.util.List<Pair> localVarCollectionQueryParams = new java.util.ArrayList<Pair>();
    java.util.Map<String, String> localVarHeaderParams = new java.util.HashMap<String, String>();
    java.util.Map<String, Object> localVarFormParams = new java.util.HashMap<String, Object>();

    final String[] localVarAccepts = {
      "application/json"
    };
    final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);

    final String[] localVarContentTypes = {

    };
    final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);

    String[] localVarAuthNames = new String[] { "docusignAccessCode" };

    GenericType<Notary> localVarReturnType = new GenericType<Notary>() {};
    return apiClient.invokeAPI(localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType);
      }

  /**
   * Update a notary jurisdiction.
   *
   * @param jurisdictionId  (required)
   * @param notaryJurisdiction  (optional)
   * @return NotaryJurisdiction
   * @throws ApiException if fails to make API call
   */
  public NotaryJurisdiction updateNotaryJurisdiction(String jurisdictionId, NotaryJurisdiction notaryJurisdiction) throws ApiException {
    Object localVarPostBody = notaryJurisdiction;

    // verify the required parameter 'jurisdictionId' is set
    if (jurisdictionId == null) {
      throw new ApiException(400, "Missing the required parameter 'jurisdictionId' when calling updateNotaryJurisdiction");
    }

    // create path and map variables
    String localVarPath = "/v2.1/current_user/notary/jurisdictions/{jurisdictionId}"
      .replaceAll("\\{" + "jurisdictionId" + "\\}", apiClient.escapeString(jurisdictionId.toString()));

    // query params
    java.util.List<Pair> localVarQueryParams = new java.util.ArrayList<Pair>();
    java.util.List<Pair> localVarCollectionQueryParams = new java.util.ArrayList<Pair>();
    java.util.Map<String, String> localVarHeaderParams = new java.util.HashMap<String, String>();
    java.util.Map<String, Object> localVarFormParams = new java.util.HashMap<String, Object>();

    final String[] localVarAccepts = {
      "application/json"
    };
    final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);

    final String[] localVarContentTypes = {

    };
    final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);

    String[] localVarAuthNames = new String[] { "docusignAccessCode" };

    GenericType<NotaryJurisdiction> localVarReturnType = new GenericType<NotaryJurisdiction>() {};
    return apiClient.invokeAPI(localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType);
      }
}


text:
<?xml version="1.0"?>
<workflow-app xmlns="uri:oozie:workflow:0.4" name="test-importer_patent">

    <global>
        <job-tracker>${jobTracker}</job-tracker>
        <name-node>${nameNode}</name-node>
        <configuration>
            <property>
                <name>mapreduce.job.queuename</name>
                <value>${queueName}</value>
            </property>
            <property>
                <name>oozie.launcher.mapred.job.queue.name</name>
                <value>${oozieLauncherQueueName}</value>
            </property>
        </configuration>
    </global>

    <start to="import_patent"/>

    <action name="import_patent">
        <sub-workflow>
            <app-path>${wf:appPath()}/import_patent</app-path>
            <propagate-configuration/>
            <configuration>
                <property>
                    <name>input_tsv</name>
                    <value>${wf:appPath()}/input/patents_epo.tsv</value>
                </property>
                <property>
                    <name>output</name>
                    <value>${workingDir}/output</value>
                </property>
                <property>
                    <name>output_report_root_path</name>
                    <value>${workingDir}/report</value>
                </property>
                <property>
                    <name>output_report_relative_path</name>
                    <value>patent</value>
                </property>
            </configuration>
        </sub-workflow>
        <ok to="consumer"/>
        <error to="fail"/>
    </action>

    <action name="consumer">
        <java>
            <main-class>eu.dnetlib.iis.common.java.ProcessWrapper</main-class>
            <arg>eu.dnetlib.iis.common.java.jsonworkflownodes.TestingConsumer</arg>
            <arg>-C{patent,
                eu.dnetlib.iis.referenceextraction.patent.schemas.ImportedPatent,
                eu/dnetlib/iis/wf/importer/patent/data/output/patents_epo_output.json}
            </arg>
            <arg>-C{report,
                eu.dnetlib.iis.common.schemas.ReportEntry,
                eu/dnetlib/iis/wf/importer/patent/data/output/report.json}
            </arg>
            <arg>-Ipatent=${workingDir}/output</arg>
            <arg>-Ireport=${workingDir}/report/patent</arg>
        </java>
        <ok to="end"/>
        <error to="fail"/>
    </action>

    <kill name="fail">
        <message>Unfortunately, the process failed -- error message:
            [${wf:errorMessage(wf:lastErrorNode())}]
        </message>
    </kill>

    <end name="end"/>
</workflow-app>


text:
package org.apache.arrow.vector;

import io.netty.buffer.ArrowBuf;
import org.apache.arrow.memory.BufferAllocator;
import org.apache.arrow.vector.complex.impl.DecimalReaderImpl;
import org.apache.arrow.vector.complex.reader.FieldReader;
import org.apache.arrow.vector.holders.DecimalHolder;
import org.apache.arrow.vector.holders.NullableDecimalHolder;
import org.apache.arrow.vector.types.Types.MinorType;
import org.apache.arrow.vector.types.pojo.FieldType;
import org.apache.arrow.vector.util.DecimalUtility;
import org.apache.arrow.vector.util.TransferPair;

import java.math.BigDecimal;

/**
 * DecimalVector implements a fixed width vector (16 bytes) of
 * decimal values which could be null. A validity buffer (bit vector) is
 * maintained to track which elements in the vector are null.
 */
public class DecimalVector extends BaseFixedWidthVector {
  public static final byte TYPE_WIDTH = 16;
  private final FieldReader reader;

  private final int precision;
  private final int scale;

  /**
   * Instantiate a DecimalVector. This doesn't allocate any memory for
   * the data in vector.
   * @param name name of the vector
   * @param allocator allocator for memory management.
   */
  public DecimalVector(String name, BufferAllocator allocator,
                               int precision, int scale) {
    this(name, FieldType.nullable(new org.apache.arrow.vector.types.pojo.ArrowType.Decimal(precision, scale)),
            allocator);
  }

  /**
   * Instantiate a DecimalVector. This doesn't allocate any memory for
   * the data in vector.
   * @param name name of the vector
   * @param fieldType type of Field materialized by this vector
   * @param allocator allocator for memory management.
   */
  public DecimalVector(String name, FieldType fieldType, BufferAllocator allocator) {
    super(name, allocator, fieldType, TYPE_WIDTH);
    org.apache.arrow.vector.types.pojo.ArrowType.Decimal arrowType = (org.apache.arrow.vector.types.pojo.ArrowType.Decimal) fieldType.getType();
    reader = new DecimalReaderImpl(DecimalVector.this);
    this.precision = arrowType.getPrecision();
    this.scale = arrowType.getScale();
  }

  /**
   * Get a reader that supports reading values from this vector
   * @return Field Reader for this vector
   */
  @Override
  public FieldReader getReader() {
    return reader;
  }

  /**
   * Get minor type for this vector. The vector holds values belonging
   * to a particular type.
   * @return {@link org.apache.arrow.vector.types.Types.MinorType}
   */
  @Override
  public MinorType getMinorType() {
    return MinorType.DECIMAL;
  }

  /******************************************************************
   *                                                                *
   *          vector value retrieval methods                        *
   *                                                                *
   ******************************************************************/

  /**
   * Get the element at the given index from the vector.
   *
   * @param index   position of element
   * @return element at given index
   */
  public ArrowBuf get(int index) throws IllegalStateException {
    if (isSet(index) == 0) {
      throw new IllegalStateException("Value at index is null");
    }
    return valueBuffer.slice(index * TYPE_WIDTH, TYPE_WIDTH);
  }

  /**
   * Get the element at the given index from the vector and
   * sets the state in holder. If element at given index
   * is null, holder.isSet will be zero.
   *
   * @param index   position of element
   */
  public void get(int index, NullableDecimalHolder holder) {
    if (isSet(index) == 0) {
      holder.isSet = 0;
      return;
    }
    holder.isSet = 1;
    holder.buffer = valueBuffer;
    holder.precision = precision;
    holder.scale = scale;
    holder.start = index * TYPE_WIDTH;
  }

  /**
   * Same as {@link #get(int)}.
   *
   * @param index   position of element
   * @return element at given index
   */
  public BigDecimal getObject(int index) {
    if (isSet(index) == 0) {
      return null;
    } else {
      return DecimalUtility.getBigDecimalFromArrowBuf(valueBuffer, index, scale);
    }
  }

  /**
   * Copy a cell value from a particular index in source vector to a particular
   * position in this vector
   * @param fromIndex position to copy from in source vector
   * @param thisIndex position to copy to in this vector
   * @param from source vector
   */
  public void copyFrom(int fromIndex, int thisIndex, DecimalVector from) {
    BitVectorHelper.setValidityBit(validityBuffer, thisIndex, from.isSet(fromIndex));
    from.valueBuffer.getBytes(fromIndex * TYPE_WIDTH, valueBuffer,
            thisIndex * TYPE_WIDTH, TYPE_WIDTH);
  }

  /**
   * Same as {@link #copyFrom(int, int, DecimalVector)} except that
   * it handles the case when the capacity of the vector needs to be expanded
   * before copy.
   * @param fromIndex position to copy from in source vector
   * @param thisIndex position to copy to in this vector
   * @param from source vector
   */
  public void copyFromSafe(int fromIndex, int thisIndex, DecimalVector from) {
    handleSafe(thisIndex);
    copyFrom(fromIndex, thisIndex, from);
  }

  /**
   * Return scale for the decimal value
   */
  public int getScale() {
    return scale;
  }

  /******************************************************************
   *                                                                *
   *          vector value setter methods                           *
   *                                                                *
   ******************************************************************/

  /**
   * Set the element at the given index to the given value.
   *
   * @param index    position of element
   * @param buffer   ArrowBuf containing decimal value.
   */
  public void set(int index, ArrowBuf buffer) {
    BitVectorHelper.setValidityBitToOne(validityBuffer, index);
    valueBuffer.setBytes(index * TYPE_WIDTH, buffer, 0, TYPE_WIDTH);
  }

  /**
   * Set the decimal element at given index to the provided array of bytes.
   * Decimal is now implemented as Little Endian. This API allows the user
   * to pass a decimal value in the form of byte array in BE byte order.
   *
   * Consumers of Arrow code can use this API instead of first swapping
   * the source bytes (doing a write and read) and then finally writing to
   * ArrowBuf of decimal vector.
   *
   * This method takes care of adding the necessary padding if the length
   * of byte array is less then 16 (length of decimal type).
   *
   * @param index position of element
   * @param value array of bytes containing decimal in big endian byte order.
   */
  public void setBigEndian(int index, byte[] value) {
    BitVectorHelper.setValidityBitToOne(validityBuffer, index);
    final int length = value.length;
    int startIndex = index * TYPE_WIDTH;
    if (length == TYPE_WIDTH) {
      for (int i = TYPE_WIDTH - 1; i >= 3; i-=4) {
        valueBuffer.setByte(startIndex, value[i]);
        valueBuffer.setByte(startIndex + 1, value[i-1]);
        valueBuffer.setByte(startIndex + 2, value[i-2]);
        valueBuffer.setByte(startIndex + 3, value[i-3]);
        startIndex += 4;
      }

      return;
    }

    if (length == 0) {
      valueBuffer.setZero(startIndex, TYPE_WIDTH);
      return;
    }

    if (length < 16) {
      for (int i = length - 1; i >= 0; i--) {
        valueBuffer.setByte(startIndex, value[i]);
        startIndex++;
      }

      final byte pad = (byte) (value[0] < 0 ? 0xFF : 0x00);
      final int maxStartIndex = (index + 1) * TYPE_WIDTH;
      while (startIndex < maxStartIndex) {
        valueBuffer.setByte(startIndex, pad);
        startIndex++;
      }

      return;
    }

    throw new IllegalArgumentException("Invalid decimal value length. Valid length in [1 - 16], got " + length);
  }

  /**
   * Set the element at the given index to the given value.
   *
   * @param index    position of element
   * @param start    start index of data in the buffer
   * @param buffer   ArrowBuf containing decimal value.
   */
  public void set(int index, int start, ArrowBuf buffer) {
    BitVectorHelper.setValidityBitToOne(validityBuffer, index);
    valueBuffer.setBytes(index * TYPE_WIDTH, buffer, start, TYPE_WIDTH);
  }

  /**
   * Set the element at the given index to the given value.
   *
   * @param index   position of element
   * @param value   BigDecimal containing decimal value.
   */
  public void set(int index, BigDecimal value) {
    BitVectorHelper.setValidityBitToOne(validityBuffer, index);
    DecimalUtility.checkPrecisionAndScale(value, precision, scale);
    DecimalUtility.writeBigDecimalToArrowBuf(value, valueBuffer, index);
  }

  /**
   * Set the element at the given index to the value set in data holder.
   * If the value in holder is not indicated as set, element in the
   * at the given index will be null.
   *
   * @param index   position of element
   * @param holder  nullable data holder for value of element
   */
  public void set(int index, NullableDecimalHolder holder) throws IllegalArgumentException {
    if (holder.isSet < 0) {
      throw new IllegalArgumentException();
    } else if (holder.isSet > 0) {
      BitVectorHelper.setValidityBitToOne(validityBuffer, index);
      valueBuffer.setBytes(index * TYPE_WIDTH, holder.buffer, holder.start, TYPE_WIDTH);
    } else {
      BitVectorHelper.setValidityBit(validityBuffer, index, 0);
    }
  }

  /**
   * Set the element at the given index to the value set in data holder.
   *
   * @param index   position of element
   * @param holder  data holder for value of element
   */
  public void set(int index, DecimalHolder holder) {
    BitVectorHelper.setValidityBitToOne(validityBuffer, index);
    valueBuffer.setBytes(index * TYPE_WIDTH, holder.buffer, holder.start, TYPE_WIDTH);
  }

  /**
   * Same as {@link #set(int, ArrowBuf)} except that it handles the
   * case when index is greater than or equal to existing
   * value capacity {@link #getValueCapacity()}.
   *
   * @param index   position of element
   * @param buffer  ArrowBuf containing decimal value.
   */
  public void setSafe(int index, ArrowBuf buffer) {
    handleSafe(index);
    set(index, buffer);
  }

  /**
   * Same as {@link #setBigEndian(int, byte[])} except that it handles the
   * case when index is greater than or equal to existing
   * value capacity {@link #getValueCapacity()}.
   */
  public void setBigEndianSafe(int index, byte[] value) {
    handleSafe(index);
    setBigEndian(index, value);
  }

  /**
   * Same as {@link #set(int, int, ArrowBuf)} except that it handles the
   * case when index is greater than or equal to existing
   * value capacity {@link #getValueCapacity()}.
   *
   * @param index    position of element
   * @param start    start index of data in the buffer
   * @param buffer   ArrowBuf containing decimal value.
   */
  public void setSafe(int index, int start, ArrowBuf buffer) {
    handleSafe(index);
    set(index, start, buffer);
  }

  /**
   * Same as {@link #set(int, BigDecimal)} except that it handles the
   * case when index is greater than or equal to existing
   * value capacity {@link #getValueCapacity()}.
   *
   * @param index   position of element
   * @param value   BigDecimal containing decimal value.
   */
  public void setSafe(int index, BigDecimal value) {
    handleSafe(index);
    set(index, value);
  }

  /**
   * Same as {@link #set(int, NullableDecimalHolder)} except that it handles the
   * case when index is greater than or equal to existing
   * value capacity {@link #getValueCapacity()}.
   *
   * @param index   position of element
   * @param holder  nullable data holder for value of element
   */
  public void setSafe(int index, NullableDecimalHolder holder) throws IllegalArgumentException {
    handleSafe(index);
    set(index, holder);
  }

  /**
   * Same as {@link #set(int, DecimalHolder)} except that it handles the
   * case when index is greater than or equal to existing
   * value capacity {@link #getValueCapacity()}.
   *
   * @param index   position of element
   * @param holder  data holder for value of element
   */
  public void setSafe(int index, DecimalHolder holder) {
    handleSafe(index);
    set(index, holder);
  }

  /**
   * Set the element at the given index to null.
   *
   * @param index   position of element
   */
  public void setNull(int index) {
    handleSafe(index);
      /* not really needed to set the bit to 0 as long as
       * the buffer always starts from 0.
       */
    BitVectorHelper.setValidityBit(validityBuffer, index, 0);
  }

  /**
   * Store the given value at a particular position in the vector. isSet indicates
   * whether the value is NULL or not.
   * @param index position of the new value
   * @param isSet 0 for NULL value, 1 otherwise
   * @param start start position of the value in the buffer
   * @param buffer buffer containing the value to be stored in the vector
   */
  public void set(int index, int isSet, int start, ArrowBuf buffer) {
    if (isSet > 0) {
      set(index, start, buffer);
    } else {
      BitVectorHelper.setValidityBit(validityBuffer, index, 0);
    }
  }

  /**
   * Same as {@link #setSafe(int, int, int, ArrowBuf)} except that it handles
   * the case when the position of new value is beyond the current value
   * capacity of the vector.
   * @param index position of the new value
   * @param isSet 0 for NULL value, 1 otherwise
   * @param start start position of the value in the buffer
   * @param buffer buffer containing the value to be stored in the vector
   */
  public void setSafe(int index, int isSet, int start, ArrowBuf buffer) {
    handleSafe(index);
    set(index, isSet, start, buffer);
  }

  /******************************************************************
   *                                                                *
   *                      vector transfer                           *
   *                                                                *
   ******************************************************************/

  /**
   * Construct a TransferPair comprising of this and and a target vector of
   * the same type.
   * @param ref name of the target vector
   * @param allocator allocator for the target vector
   * @return {@link TransferPair}
   */
  @Override
  public TransferPair getTransferPair(String ref, BufferAllocator allocator) {
    return new TransferImpl(ref, allocator);
  }

  /**
   * Construct a TransferPair with a desired target vector of the same type.
   * @param to target vector
   * @return {@link TransferPair}
   */
  @Override
  public TransferPair makeTransferPair(ValueVector to) {
    return new TransferImpl((DecimalVector) to);
  }

  private class TransferImpl implements TransferPair {
    DecimalVector to;

    public TransferImpl(String ref, BufferAllocator allocator) {
      to = new DecimalVector(ref, allocator, DecimalVector.this.precision,
              DecimalVector.this.scale);
    }

    public TransferImpl(DecimalVector to) {
      this.to = to;
    }

    @Override
    public DecimalVector getTo() {
      return to;
    }

    @Override
    public void transfer() {
      transferTo(to);
    }

    @Override
    public void splitAndTransfer(int startIndex, int length) {
      splitAndTransferTo(startIndex, length, to);
    }

    @Override
    public void copyValueSafe(int fromIndex, int toIndex) {
      to.copyFromSafe(fromIndex, toIndex, DecimalVector.this);
    }
  }
}


text:
package com.gavin.ssm.msg.core.rabbitmq;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class WorkTest {

    private static final String QUEUE_NAME = "work_queue";

    private Connection connection;

    @Before
    public void setUp() throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        connection = factory.newConnection();
    }

    @After
    public void tearDown() throws Exception {
        if (connection != null) {
            connection.close();
        }
    }

    @Test
    public void testSend() throws Exception {
        Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        for (int i = 1; i <= 50; i++) {
            String message = "task_" + i;
            channel.basicPublish("", QUEUE_NAME, null, message.getBytes(StandardCharsets.UTF_8));
            System.out.println(" [x] Sent '" + message + "'");
        }
        channel.close();
    }

    @Test
    public void testRecv() throws Exception {
        Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        channel.basicQos(1);
        System.out.println(" [*] Waiting for messages...");
        channel.basicConsume(QUEUE_NAME, false, new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope,
                                       AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message = new String(body, StandardCharsets.UTF_8);
                System.out.println(" [x] Received '" + message + "'");
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        });
        Thread.currentThread().join();
    }

}


text:
<?php

namespace UthandoBlog\Service;

use UthandoBlog\Form\PostForm;
use UthandoBlog\Hydrator\PostHydrator;
use UthandoBlog\InputFilter\PostInputFilter;
use UthandoBlog\Model\TagModel;
use UthandoBlog\Options\BlogOptions;
use UthandoCommon\Service\AbstractRelationalMapperService;
use UthandoBlog\Mapper\PostMapper;
use UthandoBlog\Model\PostModel;
use UthandoUser\Service\UserService;
use Zend\Db\Sql\Where;
use Zend\EventManager\Event;

/**
 * Class Post
 *
 * @package UthandoBlog\Service
 * @method PostMapper getMapper($mapperClass = null, array $options = [])
 */
class PostService extends AbstractRelationalMapperService
{
    protected $form         = PostForm::class;
    protected $hydrator     = PostHydrator::class;
    protected $inputFilter  = PostInputFilter::class;
    protected $mapper       = PostMapper::class;
    protected $model        = PostModel::class;

    protected $autoPost = false;

    /**
     * @var array
     */
    protected $referenceMap = [
        'category' => [
            'refCol' => 'categoryId',
            'service' => CategoryService::class,
        ],
        'tags' => [
            'refCol' => 'postId',
            'service' => TagService::class,
            'getMethod' => 'getTagsByPostId'
        ],
        'user' => [
            'refCol' => 'userId',
            'service' => UserService::class,
        ],
    ];

    protected $tags = [
        'blog-post',
    ];

    /**
     * Attach events
     */
    public function attachEvents()
    {
        $this->getEventManager()->attach([
            'pre.form'
        ], [$this, 'setTagsArray']);

        $this->getEventManager()->attach([
            'pre.add', 'pre.edit'
        ], [$this, 'setValidation']);

        $this->getEventManager()->attach([
            'post.add', 'post.edit'
        ], [$this, 'saveTags']);

        $this->getEventManager()->attach([
            'post.edit'
        ], [$this, 'autoPostEdit']);

        $this->getEventManager()->attach([
            'post.add',
        ], [$this, 'autoPostAdd']);
    }

    public function setTagsArray(Event $e)
    {
        $model = $e->getParam('model');

        if (!$model instanceof PostModel) {
            return;
        }

        $tags = $model->getTags();

        $tagsArray = [];

        foreach ($tags as $tag) {
            if ($tag instanceof TagModel) {
                $tagsArray[] = $tag->getTagId();
            } else {
                $tagsArray[] = $tag;
            }
        }

        $model->setTags($tagsArray);
    }

    /**
     * @param Event $e
     */
    public function setValidation(Event $e)
    {
        $form = $e->getParam('form');
        $model = $e->getParam('model', new PostModel());
        $post = $e->getParam('post');

        if ($model instanceof PostModel) {
            $model->setDateModified();
        }

        if (!$post['slug']) {
            $post['slug'] = $post['title'];
        }

        if (PostModel::STATUS_PUBLISHED == $post['status'] && PostModel::STATUS_DRAFT == $model->getStatus()) {
            $post['dateCreated'] = '';
            $this->autoPost = true;
            $model->setDateCreated();
        }

        /* @var \UthandoBlog\InputFilter\PostInputFilter $inputFilter */
        $inputFilter = $form->getInputFilter();
        $inputFilter->addSlugNoRecordExists($model->getSlug());

        /* @var \UthandoBlog\Options\BlogOptions $options */
        $options = $this->getServiceLocator()
            ->getServiceLocator()->get(BlogOptions::class);

        $hydrator = $form->getHydrator();
        /* @var DateTime $dateTimeStrategy */
        $dateTimeStrategy = $hydrator->getStrategy('dateCreated');
        $dateTimeStrategy->setHydrateFormat($options->getDateFormat());
        $dateTimeStrategy = $hydrator->getStrategy('dateModified');
        $dateTimeStrategy->setHydrateFormat($options->getDateFormat());

        $form->setValidationGroup([
            'postId', 'userId', 'title', 'slug',
            'content', 'description', 'categoryId',
            'tags', 'image', 'lead', 'layout', 'status',
            'dateCreated', 'enableComments',
        ]);

        $form->setData($post);

        $e->setParam('post', $post);
    }

    public function autoPostAdd(Event $e)
    {
        $id         = $e->getParam('saved');
        $model      = $this->getById($id);

        $this->autoPost($model);
    }

    public function autoPostEdit(Event $e)
    {
        $model      = $e->getParam('model');

        $this->autoPost($model);
    }

    public function autoPost(PostModel $model)
    {
        if (PostModel::STATUS_PUBLISHED === $model->getStatus() && true === $this->autoPost) {

            /* @var $options BlogOptions */
            $options = $this->getService(BlogOptions::class);

            $viewManager = $this->getServiceLocator()
                ->get('ViewHelperManager');

            $url = $viewManager->get('Url');
            $scheme = $viewManager->get('ServerUrl');

            $url = $url('blog', [
                'post-item'    => $model->getSlug(),
            ]);

            $string = sprintf('%s %s', $model->getTitle(), $scheme($url));

            $argv   = compact('string');
            $argv   = $this->prepareEventArguments($argv);

            foreach ($options->getAutoPost() as $event) {
                $this->getEventManager()->trigger($event, $this, $argv);
            }
        }
    }

    public function saveTags(Event $e)
    {
        $model      = $e->getParam('model', new PostModel());
        $post       = $e->getParam('post');
        $saved      = $e->getParam('saved');
        $tags       = $post['tags'];

        /* @var TagService $tagService */
        $tagService = $this->getRelatedService('tags');
        $mapper     = $tagService->getMapper();
        $id         = $model->getPostId() ?? $saved;

        $currentTags = $tagService->getTagsByPostId($id);
        $keptTags = [];

        /* @var TagModel $tag */
        foreach ($currentTags as $tag) {
            if (!in_array($tag->getTagId(), $tags)) {
                $where = new Where();
                $where->equalTo('tagId', $tag->getTagId())
                    ->and->equalTo('postId', $id);
                $mapper->delete($where, 'blogPostTag');
            } else {
                $keptTags[] = $tag->getTagId();
            }
        }

        $tags = array_diff($tags, $keptTags);

        foreach ($tags as $tag) {
            $mapper->insert([
                'tagId' => $tag,
                'postId' => $id
            ], 'blogPostTag');
        }
    }

    /**
     * @param int $id
     * @param null $col
     * @return array|mixed|\UthandoCommon\Model\ModelInterface
     */
    public function getById($id, $col = null)
    {
        $model = parent::getById($id, $col);
        $this->populate($model, true);

        return $model;
    }

    public function searchPosts($post, $sort)
    {
        $searches = [];
        $type = [];

        foreach ($post as $key => $value) {
            switch ($key) {
                case 'tag':
                case 'category':
                case 'archive':
                    if (!$value || (is_array($value) && !array_filter($value))) continue;
                    $type = [$key, $value];
                    break;
                default:
                    $searches[] = [
                        'searchString' => $value,
                        'columns' => explode('-', $key),
                    ];
                    break;
            }
        }

        $models = $this->getMapper()->searchPosts($searches, $sort, $type);

        foreach ($models as $model) {
            $this->populate($model, true);
        }

        return $models;
    }

    /**
     * @param $slug
     * @return PostModel|null
     */
    public function getBySlug($slug)
    {
        $slug = (string) $slug;
        $mapper = $this->getMapper();
        $model = $mapper->getBySlug($slug);

        if ($model) {
            $this->populate($model, true);
        }

        return $model;
    }

    /**
     * @param PostModel $postModel
     */
    public function addPageHit(PostModel $postModel)
    {
        $pageHits = $postModel->getHits();
        $pageHits++;
        $postModel->setHits($pageHits);
        $this->save($postModel);
    }

    /**
     * @param int $limit
     * @return \Zend\Db\ResultSet\HydratingResultSet|\Zend\Db\ResultSet\ResultSet|\Zend\Paginator\Paginator
     */
    public function getPopularPosts(int $limit)
    {
        $mapper = $this->getMapper();
        $models = $mapper->getPostsByHits($limit);

        return $models;
    }

    /**
     * @param int $limit
     * @return \Zend\Db\ResultSet\HydratingResultSet|\Zend\Db\ResultSet\ResultSet|\Zend\Paginator\Paginator
     */
    public function getRecentPosts(int $limit)
    {
        $mapper = $this->getMapper();
        $models = $mapper->getPostsByDate($limit);

        return $models;

    }

    public function getArchiveList()
    {
        $mapper = $this->getMapper();
        $archiveList = $mapper->getArchiveList();

        return $archiveList;
    }
}


text:
/**
 * Created by felix on 14-11-5.
 */
angular.module('lovev.level1',[])
    .constant('level1Constant',{
        //放置一些常量
    })
    .config(['$routeProvider', function($routeProvider) {
        $routeProvider.when('/level1', {
            templateUrl: 'level1/level1.html',
            controller: 'level1Ctrl'
        });
    }])
    .controller('level1Ctrl',[function(){

    }])
;


text:
package com.mayinews.mv.utils;

import android.content.Context;

/**
 * dp和px转换工具类
 */
public class DensityUtil {
    /**
     * 将px值转换为dip或dp值,保证尺寸大小不变
     *
     *
     *
     *            (DisplayMetrics类中属性density)
     * @return
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 将dip或dp值转换为px值,保证尺寸大小不变
     *
     *
     *
     *            (DisplayMetrics类中属性density)
     * @return
     */
    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    /**
     * 将px值转换为sp值,保证文字大小不变
     *
     *
     *
     *            (DisplayMetrics类中属性scaledDensity)
     * @return
     */
    public static int px2sp(Context context, float pxValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    /**
     * 将sp值转换为px值,保证文字大小不变
     *
     *
     *
     *            (DisplayMetrics类中属性scaledDensity)
     * @return
     */
    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }
}


text:
    {% if include.page.image %}

    {% endif %}

{{ include.page.title }}

{{ include.page.date }}

{{ include.page.summary }}

      {% for label in include.page.labels %}

{{ label }}

      {% endfor %}

      {% if page.projecturl %}
        Leia Mais
      {% else %}
        Leia Mais
      {% endif %}


text:
<?xml version="1.0" encoding="UTF-8"?>
<sem:triples xmlns:sem="http://marklogic.com/semantics">
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/genealogy</sem:subject>
    <sem:predicate>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</sem:predicate>
    <sem:object datatype="sem:iri">http://www.w3.org/2004/02/skos/core#Concept</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/genealogy</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate>
    <sem:object xml:lang="eng" datatype="xsd:string">Genealogy</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/genealogy</sem:subject>
    <sem:predicate>http://www.lds.org/core#weight</sem:predicate>
    <sem:object datatype="xsd:integer">2</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/genealogy</sem:subject>
    <sem:predicate>http://www.lds.org/core#partOfSpeech</sem:predicate>
    <sem:object xml:lang="eng" datatype="xsd:string">noun</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/genealogy</sem:subject>
    <sem:predicate>http://www.lds.org/core#entityType</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/Topic</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/genealogy</sem:subject>
    <sem:predicate>http://www.lds.org/core#instanceOf</sem:predicate>
    <sem:object datatype="xsd:anyURI">http://www.lds.org/scriptures/triple-index/genealogy?lang=eng</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/genealogy</sem:subject>
    <sem:predicate>http://www.lds.org/core#instanceOf</sem:predicate>
    <sem:object datatype="xsd:anyURI">http://www.lds.org/study/topics/genealogy?lang=eng</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/genealogy</sem:subject>
    <sem:predicate>http://www.lds.org/core#instanceOf</sem:predicate>
    <sem:object datatype="xsd:anyURI">http://www.lds.org/scriptures/gs/genealogy</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/genealogy</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#definition</sem:predicate>
    <sem:object xml:lang="eng" datatype="xsd:string">A record tracing the line of descent in a family. Where priesthood offices or certain blessings were restricted to a particular family, genealogies in the scriptures were very important (; ; ; ; ; ; ; ; ). In the restored Church today, members of the Church continue to trace their family lines of descent, in part to properly identify deceased ancestors so they can perform saving ordinances in their ancestors' behalf. These ordinances are valid for those deceased persons who accept the gospel of Jesus Christ in the spirit world ().</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/genealogy</sem:subject>
    <sem:predicate>http://www.lds.org/core#instanceOf</sem:predicate>
    <sem:object datatype="xsd:anyURI">http://www.lds.org/scriptures/bd/genealogy?lang=eng</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/genealogy</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#related</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept/gs/baptism</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/genealogy</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#related</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept/gs/book-of-remembrance</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/genealogy</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#related</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept/gs/family</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/genealogy</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#related</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept/gs/salvation</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/genealogy</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#related</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept/gs/salvation-for-the-dead</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/genealogy</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#inScheme</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept-scheme/guide-to-the-scriptures</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/genealogy</sem:subject>
    <sem:predicate>http://www.lds.org/core#relCount</sem:predicate>
    <sem:object datatype="xsd:integer">5</sem:object>
  </sem:triple>
</sem:triples>


text:
//
//  MBBarcodeRecognizer.h
//  MicroblinkDev
//
//  Created by Jura Skrlec on 28/11/2017.
//

#import <Foundation/Foundation.h>

#import "MBMicroblinkDefines.h"
#import "MBRecognizer.h"
#import "MBBarcodeRecognizerResult.h"
#import "MBMicroblinkInitialization.h"

NS_ASSUME_NONNULL_BEGIN

/**
 * MBBBarcodeRecognizer is used for scanning most of 1D barcode formats, and 2D format
 * such as Aztec, DataMatrix and QR code
 */
MB_CLASS_AVAILABLE_IOS(8.0) MB_FINAL
@interface MBBBarcodeRecognizer : MBBRecognizer<NSCopying>

MB_INIT

/**
 * Barcode recognizer results
 */
@property (nonatomic, strong, readonly) MBBBarcodeRecognizerResult *result;

/**
 * Set this to YES to scan Aztec 2D barcodes
 *
 * Default: NO
 */
@property (nonatomic, assign) BOOL scanAztecCode;

/**
 * Set this to YES to scan Code 128 1D barcodes
 *
 * Default: NO
 */
@property (nonatomic, assign) BOOL scanCode128;

/**
 * Set this to YES to scan Code 39 1D barcodes
 *
 * Default: NO
 */
@property (nonatomic, assign) BOOL scanCode39;

/**
 * Set this to YES to scan DataMatrix 2D barcodes
 *
 * Default: NO
 */
@property (nonatomic, assign) BOOL scanDataMatrix;

/**
 * Set this to YES to scan EAN 13 barcodes
 *
 * Default: NO
 */
@property (nonatomic, assign) BOOL scanEan13;

/**
 * Set this to YES to scan EAN8 barcodes
 *
 * Default: NO
 */
@property (nonatomic, assign) BOOL scanEan8;

/**
 * Set this to YES to scan ITF barcodes
 *
 * Default: NO
 */
@property (nonatomic, assign) BOOL scanItf;

/**
 * Set this to YES to scan QR barcodes
 *
 * Default: NO
 */
@property (nonatomic, assign) BOOL scanQrCode;

/**
 * Set this to YES to scan UPCA barcodes
 *
 * Default: NO
 */
@property (nonatomic, assign) BOOL scanUpca;

/**
 * Set this to YES to scan UPCE barcodes
 *
 * Default: NO
 */
@property (nonatomic, assign) BOOL scanUpce;

/**
 * Set this to YES to scan Pdf417 barcodes
 *
 * Default: NO
 */
@property (nonatomic, assign) BOOL scanPdf417;

/**
 * Set this to YES to allow slower, but better image processing.
 *
 * Default: YES
 */
@property (nonatomic, assign) BOOL slowerThoroughScan;

/**
* Allow enabling the autodetection of image scale when scanning barcodes.
* If set to true, prior reading barcode, image scale will be
* corrected. This enabled correct reading of barcodes on high
* resolution images but slows down the recognition process.
*
* NOTE: This setting is applied only for Code39 and Code128 barcode scanning.
*
 * Default: YES
*/
@property (nonatomic, assign) BOOL autoScaleDetection;

/**
* Enable reading code39 barcode contents as extended data. For more information about code39
* extended data (a.k.a. full ASCII mode), see https://en.wikipedia.org/wiki/Code_39#Full_ASCII_Code_39
*
* Default: NO
*/
@property (nonatomic, assign) BOOL readCode39AsExtendedData;

/**
 * Set this to YES to allow scanning barcodes with inverted intensities
 * (i.e. white barcodes on black background)
 *
 * NOTE: this options doubles the frame processing time
 *
 * Default: NO
 */
@property (nonatomic, assign) BOOL scanInverse;

/**
 * Set this to YES to scan even barcode not compliant with standards
 * For example, malformed PDF417 barcodes which were incorrectly encoded
 *
 * Use only if necessary because it slows down the recognition process
 *
 * Default: YES
 */
@property (nonatomic, assign) BOOL scanUncertain;

/**
 * Set this to YES to scan barcodes which don't have quiet zone (white area) around it
 *
 * Use only if necessary because it slows down the recognition process
 *
 * Default: NO
 */
@property (nonatomic, assign) BOOL nullQuietZoneAllowed;

@end

NS_ASSUME_NONNULL_END


text:
(*

category:      Test
synopsis:      Two reactions with four species in one
compartment using an assignmentRule with a functionDefinition to vary one species.
componentTags: Compartment, Species, Reaction, Parameter, FunctionDefinition, AssignmentRule
testTags:      Amount, InitialValueReassigned
testType:      TimeCourse
levels:        2.1, 2.2, 2.3, 2.4, 3.1
generatedBy:   Numeric

The model contains one compartment called "compartment".  There are four
species named S1, S2, S3 and S4 and three parameters named k1, k2 and p1.
The model contains two reactions defined as:

[{width:30em,margin: 1em auto}|  *Reaction*  |  *Rate*  |
| S1 + S2 -> S3 | $k1 * S1 * S2 * compartment$  |
| S3 -> S1 + S2 | $k2 * S3 * compartment$  |]

The model contains one rule:

[{width:30em,margin: 1em auto}|  *Type*  |  *Variable*  |  *Formula*  |
 | Assignment                           | S4           | $multiply(p1, S2)$  |]

The model contains one FunctionDefinition defined as:

[{width:30em,margin: 1em auto}|  *Id*  |  *Arguments*  |  *Formula*  |
 | multiply | x, y | $x * y$ |]

Note that in this case the initial value of the species S4 is not explicitly
declared and must be calculated by the AssignmentRule.

The initial conditions are as follows:

[{width:30em,margin: 1em auto}|       |*Value*          |*Units*  |
|Initial amount of S1                |$1.0 \x 10^-4$ |mole                      |
|Initial amount of S2                |$2.0 \x 10^-4$ |mole                      |
|Initial amount of S3                |$1.5 \x 10^-4$ |mole                      |
|Initial amount of S4                |$   undeclared$ |mole                      |
|Value of parameter k1               |$0.75 \x 10^4$ |litre mole^-1^ second^-1^ |
|Value of parameter k2               |$0.25 \x 10^-2$ |second^-1^ |
|Value of parameter p1               |$         0.75$ |dimensionless |
|Volume of compartment "compartment" |$            1$ |litre                     |]

The species values are given as amounts of substance to make it easier to
use the model in a discrete stochastic simulator, but (as per usual SBML
principles) their symbols represent their values in concentration units
where they appear in expressions.

*)

newcase[ "00079" ];

addFunction[ multiply, arguments -> {x, y}, math -> x * y];
addCompartment[ compartment, size -> 1];
addSpecies[ S1, initialAmount -> 1.0 10^-4];
addSpecies[ S2, initialAmount -> 2.0 10^-4];
addSpecies[ S3, initialAmount -> 1.5 10^-4];
addSpecies[ S4 ];
addParameter[ k1, value -> .75 10^4];
addParameter[ k2, value -> .25 10^-2];
addParameter[ p1, value -> 0.75];
addRule[ type->AssignmentRule, variable -> S4, math ->multiply[p1,S2]];
addReaction[ S1 + S2 -> S3, reversible -> False,
	     kineticLaw -> k1 * S1 * S2 * compartment ];
addReaction[ S3 -> S1 + S2, reversible -> False,
	     kineticLaw -> k2 * S3 * compartment ];

makemodel[]


text: <!DOCTYPE html>


text:
/
#include "experimental/doxmresource.h"
#include "pstatresource.h"
#include "resourcemanager.h"
#if defined(WITH_CLOUD) && defined(SECURED)
#include "cloud/cloudresource.h"
#endif
#define TAG "OIC_SRM_DOS"

/**
 * @return true if changing from oldState to newState is valid transition.
 */
static bool IsValidStateTransition(OicSecDeviceOnboardingState_t oldState,
    OicSecDeviceOnboardingState_t newState)
{
    bool ret = false;

    switch (newState)
    {
        case DOS_RESET:
        ret = true;
        break;

        case DOS_RFNOP:
        if (DOS_RFPRO == oldState)
        {
            ret = true;
        }
        break;

        case DOS_RFOTM:
        if (DOS_RESET == oldState)
        {
            ret = true;
        }
        break;

        case DOS_RFPRO:
        if (DOS_RFNOP == oldState
            || DOS_RFOTM == oldState
            || DOS_SRESET == oldState)
        {
            ret = true;
        }
        break;

        case DOS_SRESET:
        if (DOS_RFNOP == oldState
            || DOS_RFPRO == oldState)
        {
            ret = true;
        }
        break;
        case DOS_STATE_COUNT:
        // The DOS_STATE_COUNT should never be passed into this function
        assert(false);
        break;
    }

    OIC_LOG_V(INFO, TAG, "%s: returning %s.", __func__, ret?"true":"false");
    return ret;
}

/**
 * @return true if Device meets requirements to enter RFNOP DOS.
 */
static bool IsReadyToEnterRFNOP(void)
{
    bool ret = false;
    bool tempBool = false;

    // Note: pstat.dos.p asserted by DoStateChange(), so not checked here.

    // Verify doxm.owned == TRUE.
    VERIFY_TRUE_OR_EXIT(TAG, IsDoxmOwned(), WARNING);

    // Verify doxm.devowneruuid != nil UUID.
    VERIFY_TRUE_OR_EXIT(TAG, !IsDoxmDevowneruuidTheNilUuid(), WARNING);

    // Verify doxm.deviceuuid != nil UUID.
    VERIFY_TRUE_OR_EXIT(TAG, !IsDoxmDeviceuuidTheNilUuid(), WARNING);

    // Verify oxmsel was the actual OTM used (no-op: CTT will verify this during
    // certification testing, as it requires OBT cooperation to verify).

    // Verify pstat.isop == false (Server sets isop on entry)
    VERIFY_SUCCESS(TAG, OC_STACK_OK == GetPstatIsop(&tempBool), ERROR);
    VERIFY_TRUE_OR_EXIT(TAG, !tempBool, WARNING);

    // Verify implemented SVRs with rowneruuid Property have non-Nil rowneruuid
    VERIFY_TRUE_OR_EXIT(TAG, !IsAclRowneruuidTheNilUuid(), WARNING);

    VERIFY_TRUE_OR_EXIT(TAG, !IsCredRowneruuidTheNilUuid(), WARNING);

    VERIFY_TRUE_OR_EXIT(TAG, !IsDoxmRowneruuidTheNilUuid(), WARNING);

    VERIFY_TRUE_OR_EXIT(TAG, !IsPstatRowneruuidTheNilUuid(), WARNING);

    // Verify each rowneruuid, devowneruuid has a corresponding /cred entry
    // TODO [IOT-2023]

    ret = true;

exit:
    OIC_LOG_V(DEBUG, TAG, "%s: returning %s.", __func__, ret?"true":"false");
    return ret;
}

/**
 * @return true if Device meets requirements to enter RFOTM DOS.
 */
static bool IsReadyToEnterRFOTM(void)
{
    bool ret = false;

    // Note: pstat.dos.p asserted by DoStateChange(), so not checked here.

    // Verify doxm.owned == FALSE.
    VERIFY_TRUE_OR_EXIT(TAG, !IsDoxmOwned(), WARNING);

    // Verify doxm.devowneruuid == nil UUID.
    VERIFY_TRUE_OR_EXIT(TAG, IsDoxmDevowneruuidTheNilUuid(), WARNING);

    // Check and log whether doxm.deviceuuid == nil UUID ("may" reqt not "shall")
    if(!IsDoxmDeviceuuidTheNilUuid())
    {
        OIC_LOG_V(INFO, TAG, "%s: doxm.deviceuuid != Nil UUID... allowed but noted.", __func__);
    }

    ret = true;

exit:
    OIC_LOG_V(DEBUG, TAG, "%s: returning %s.", __func__, ret?"true":"false");
    return ret;
}

/**
 * @return true if Device meets requirements to enter RFPRO DOS.
 */
static bool IsReadyToEnterRFPRO(void)
{
    bool ret = false;

    // Note: pstat.dos.p asserted by DoStateChange(), so not checked here.

    // Verify doxm.owned == TRUE.
    VERIFY_TRUE_OR_EXIT(TAG, IsDoxmOwned(), WARNING);

    // Verify doxm.devowneruuid != nil UUID.
    VERIFY_TRUE_OR_EXIT(TAG, !IsDoxmDevowneruuidTheNilUuid(), WARNING);

    // Verify doxm.deviceuuid != nil UUID.
    VERIFY_TRUE_OR_EXIT(TAG, !IsDoxmDeviceuuidTheNilUuid(), WARNING);

    // doxm.sct and doxm.oxmsel retain previous values (checked by CTT)

    // Verify implemented SVRs with rowneruuid Property have non-Nil rowneruuid
    VERIFY_TRUE_OR_EXIT(TAG, !IsAclRowneruuidTheNilUuid(), WARNING);

    VERIFY_TRUE_OR_EXIT(TAG, !IsCredRowneruuidTheNilUuid(), WARNING);

    VERIFY_TRUE_OR_EXIT(TAG, !IsDoxmRowneruuidTheNilUuid(), WARNING);

    VERIFY_TRUE_OR_EXIT(TAG, !IsPstatRowneruuidTheNilUuid(), WARNING);

    // Verify each rowneruuid, devowneruuid has a corresponding /cred entry
    // TODO [IOT-2023]

    ret = true;

exit:
    OIC_LOG_V(DEBUG, TAG, "%s: returning %s.", __func__, ret?"true":"false");
    return ret;
}

/**
 * @return true if Device meets requirements to set pstat.dos.s = SRESET.
 */
static bool IsReadyToEnterSRESET(void)
{
    bool ret = false;

    // Note: pstat.dos.p set by DoStateChange(), so not checked here.

    // TODO [IOT-2023]: sanity check SVRs (optional)

    // Verify doxm.owned == TRUE.
    VERIFY_TRUE_OR_EXIT(TAG, IsDoxmOwned(), WARNING);

    // Verify doxm.devowneruuid != nil UUID.
    VERIFY_TRUE_OR_EXIT(TAG, !IsDoxmDevowneruuidTheNilUuid(), WARNING);

    // Verify doxm.deviceuuid != nil UUID.
    VERIFY_TRUE_OR_EXIT(TAG, !IsDoxmDeviceuuidTheNilUuid(), WARNING);

    // doxm.sct and doxm.oxmsel retain previous values (checked by CTT)

    ret = true;

exit:
    OIC_LOG_V(DEBUG, TAG, "%s: returning %s.", __func__, ret?"true":"false");
    return ret;
}

/**
 * Generic ops performed on entering most states, coalesced to avoid repeat code.
 */
static bool EnterStateGeneric(bool isop,
                              bool cmReset,
                              bool cmTakeOwner,
                              bool tmReset,
                              bool tmTakeOwner,
                              OicSecDeviceOnboardingState_t state)
{
    bool ret = false;
    OicSecDpm_t cm = 0;
    OicSecDpm_t tm = 0;

    VERIFY_SUCCESS(TAG, OC_STACK_OK == GetPstatCm(&cm), ERROR);
    VERIFY_SUCCESS(TAG, OC_STACK_OK == GetPstatTm(&tm), ERROR);

    // Set pstat.isop
    VERIFY_SUCCESS(TAG, OC_STACK_OK == SetPstatIsop(isop), ERROR);

    // Set pstat.cm
    if (cmReset)
    {
        cm |= RESET; // set RESET bit
    }
    else
    {
        cm &= ~RESET; // clear RESET bit
    }
    if (cmTakeOwner)
    {
        cm |= TAKE_OWNER; // set TAKE_OWNER bit
    }
    else
    {
        cm &= ~TAKE_OWNER; // clear TAKE_OWNER bit
    }
    VERIFY_SUCCESS(TAG, OC_STACK_OK == SetPstatCm(cm), ERROR);

    // Set pstat.tm
    if (tmReset)
    {
        tm |= RESET; // set RESET bit
    }
    else
    {
        tm &= ~RESET; // clear RESET bit
    }
    if (tmTakeOwner)
    {
        tm |= TAKE_OWNER; // set TAKE_OWNER bit
    }
    else
    {
        tm &= ~TAKE_OWNER; // clear TAKE_OWNER bit
    }
    VERIFY_SUCCESS(TAG, OC_STACK_OK == SetPstatTm(tm), ERROR);

    // Set pstat.dos.s
    VERIFY_SUCCESS(TAG, OC_STACK_OK == SetPstatDosS(state), ERROR);

    ret = true;

exit:
    OIC_LOG_V(DEBUG, TAG, "%s: returning %s.", __func__, ret?"true":"false");
    return ret;
}

/**
 * Enter RFNOP state and set all Server-controlled SVR Property values.
 */
static bool EnterRFNOP(void)
{
    bool ret = false;

    // Set pstat.isop = TRUE
    // Unset pstat.cm RESET and TAKE_OWNER bits
    // Unset pstat.tm RESET and TAKE_OWNER bits
    // Set pstat.dos to RFNOP
    ret = EnterStateGeneric(true, false, false, false, false, DOS_RFNOP);

    OIC_LOG_V(DEBUG, TAG, "%s: returning %s.", __func__, ret?"true":"false");
    return ret;
}

/**
 * Enter RFOTM state and set all Server-controlled SVR Property values.
 */
static bool EnterRFOTM(void)
{
    bool ret = false;

    // Set pstat.isop = FALSE
    // Unset pstat.cm RESET bit, and set TAKE_OWNER bit
    // Unset pstat.tm RESET and TAKE_OWNER bits
    // Set pstat.dos to RFOTM
    ret = EnterStateGeneric(false, false, true, false, false, DOS_RFOTM);

    OIC_LOG_V(DEBUG, TAG, "%s: returning %s.", __func__, ret?"true":"false");
    return ret;
}

/**
 * Enter RFPRO state and set all Server-controlled SVR Property values.
 */
static bool EnterRFPRO(void)
{
    bool ret = false;

    // Set pstat.isop = FALSE
    // Unset pstat.cm RESET and TAKE_OWNER bits
    // Unset pstat.tm RESET and TAKE_OWNER bits
    // Set pstat.dos to RFPRO
    ret = EnterStateGeneric(false, false, false, false, false, DOS_RFPRO);

    OIC_LOG_V(DEBUG, TAG, "%s: returning %s.", __func__, ret?"true":"false");
    return ret;
}

/**
 * Enter RESET state and set all Server-controlled SVR Property values.
 */
static bool EnterRESET(void)
{
    bool ret = false;
    OicSecDpm_t dpmZero = 0;
#if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
    // Enable Anon DH cipher suite if appropriate
    bool isAnonEnabled = false;
#endif // __WITH_DTLS__ or __WITH_TLS__
    // Restore Mfr Defaults
    // "Mfr Defaults" is defined by manufacturer.  It could be "failsafe"
    // SVRs (e.g. the hard-coded SVRs in IoTivity) or it could be a backup
    // copy of the initally-provisioned SVRs (e.g. the ResetSecureResourceInPS
    // function in IoTivity).
    // TODO [IOT-2633]:
    VERIFY_SUCCESS(TAG, OC_STACK_OK == ResetSecureResources(), ERROR);

    // Set doxm.deviceuuid = Mfr Default (handled above)
    // Set doxm.sct = Mfr Default ("")
    // Set doxm.oxmsel = Mfr Default ("")
    // Set pstat.om = Mfr Default ("")
    // Set pstat.sm = Mfr Default ("")
    // Assert acl2, amacl, sacl, cred arrays = mfr defaults ("")

    // Set doxm.owned = FALSE
    VERIFY_SUCCESS(TAG, OC_STACK_OK == SetDoxmIsOwned(false), ERROR);

    // Set doxm.devowneruuid = Nil UUID
    VERIFY_SUCCESS(TAG, OC_STACK_OK == SetDoxmDevOwnerId(&THE_NIL_UUID), ERROR);

    // Set acl, doxm, cred and pstat rowneruuids = Nil UUID
    VERIFY_SUCCESS(TAG, OC_STACK_OK == SetAclRownerId(&THE_NIL_UUID), ERROR);
    VERIFY_SUCCESS(TAG, OC_STACK_OK == SetCredRownerId(&THE_NIL_UUID), ERROR);
    VERIFY_SUCCESS(TAG, OC_STACK_OK == SetDoxmRownerId(&THE_NIL_UUID), ERROR);
    VERIFY_SUCCESS(TAG, OC_STACK_OK == SetPstatRownerId(&THE_NIL_UUID), ERROR);

    // clear all bits in cm and tm before setting the 2 lsbs
    VERIFY_SUCCESS(TAG, OC_STACK_OK == SetPstatCm(dpmZero), ERROR);
    VERIFY_SUCCESS(TAG, OC_STACK_OK == SetPstatTm(dpmZero), ERROR);

    // Set pstat.isop = FALSE
    // Set pstat.cm RESET, and unset TAKE_OWNER
    // Unset pstat.tm RESET, and set TAKE_OWNER
    // Set pstat.dos.s to RESET
    VERIFY_SUCCESS(TAG,
        EnterStateGeneric(false, true, false, false, true, DOS_RESET),
        ERROR);

#if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
    VERIFY_SUCCESS(TAG,
        OC_STACK_OK == EnableAnonCipherSuiteIfUnOwnedAndJustWorksSelected(&isAnonEnabled),
        ERROR);
    OIC_LOG_V(INFO, TAG, "%s: Anon Ciphersuite %sENABLED.", __func__,
        isAnonEnabled ? "" : "NOT ");
#endif // __WITH_DTLS__ or __WITH_TLS__

#if defined(WITH_CLOUD) && defined(SECURED)
    ResetClouds();
#endif

    ret = true;

exit:
    OIC_LOG_V(DEBUG, TAG, "%s: returning %s.", __func__, ret?"true":"false");
    return ret;
}

/**
 * Enter SRESET state and set all Server-controlled SVR Property values.
 */
static bool EnterSRESET(void)
{
    bool ret = false;

    // Set pstat.isop = FALSE
    // Set pstat.cm RESET, and unset TAKE_OWNER
    // Unset pstat.tm RESET, and unset TAKE_OWNER
    // Set pstat.dos.s to RESET
    VERIFY_SUCCESS(TAG,
        EnterStateGeneric(false, true, false, false, false, DOS_SRESET),
        ERROR);

    ret = true;

exit:
    OIC_LOG_V(DEBUG, TAG, "%s: returning %s.", __func__, ret?"true":"false");
    return ret;
}

/**
 * Set pstat.dos.p (pending) to true, then verify device is ready to perform
 * the state change.  If so, perform the state change.  Finally, set
 * pstat.dos.p (pending) to false.
 * @return  OC_STACK_OK if successful change to newState
 *          OC_STACK_FORBIDDEN_REQ if state change preconditions not met
 *          OC_STACK_INTERNAL_SERVER_ERROR if SVRs left in potentially unstable state
 */
static OCStackResult DoStateChange(OicSecDeviceOnboardingState_t newState)
{
    OCStackResult ret = OC_STACK_INTERNAL_SERVER_ERROR;

    switch (newState)
    {
        case DOS_RESET:
        // No preconditions other than setting dos.p = true, which is done above
        if (EnterRESET())
        {
            // if RESET succeeds, immediately enter RFOTM
            if (IsReadyToEnterRFOTM())
            {
                if (EnterRFOTM())
                {
                    ret = OC_STACK_OK;
                }
                else
                {
                    ret = OC_STACK_INTERNAL_SERVER_ERROR;
                }
            }
            else
            {
                ret = OC_STACK_FORBIDDEN_REQ;
            }
        }
        else
        {
            ret = OC_STACK_INTERNAL_SERVER_ERROR;
        }
        break;

        case DOS_RFNOP:
        if (IsReadyToEnterRFNOP())
        {
            if (EnterRFNOP())
            {
                ret = OC_STACK_OK;
            }
            else
            {
                ret = OC_STACK_INTERNAL_SERVER_ERROR;
            }
        }
        else
        {
            ret = OC_STACK_FORBIDDEN_REQ;
        }
        break;

        case DOS_RFOTM:
        if (IsReadyToEnterRFOTM())
        {
            if (EnterRFOTM())
            {
                ret = OC_STACK_OK;
            }
            else
            {
                ret = OC_STACK_INTERNAL_SERVER_ERROR;
            }
        }
        else
        {
            ret = OC_STACK_FORBIDDEN_REQ;
        }
        break;

        case DOS_RFPRO:
        if (IsReadyToEnterRFPRO())
        {
            if (EnterRFPRO())
            {
                ret = OC_STACK_OK;
            }
            else
            {
                ret = OC_STACK_INTERNAL_SERVER_ERROR;
            }
        }
        else
        {
            ret = OC_STACK_FORBIDDEN_REQ;
        }
        break;

        case DOS_SRESET:
        if (IsReadyToEnterSRESET())
        {
            if (EnterSRESET())
            {
                ret = OC_STACK_OK;
            }
            else
            {
                ret = OC_STACK_INTERNAL_SERVER_ERROR;
            }
        }
        else
        {
            ret = OC_STACK_FORBIDDEN_REQ;
        }
        break;
        case DOS_STATE_COUNT:
        // The DOS_STATE_COUNT should never be passed into this function
        assert(false);
        break;
    }

    OIC_LOG_V(DEBUG, TAG, "%s: returning %d.", __func__, ret);
    return ret;
}

OCStackResult GetDos(OicSecDostype_t *dos)
{
    if (dos)
    {
        VERIFY_SUCCESS(TAG, OC_STACK_OK == GetPstatDosS(&(dos->state)), ERROR);
        VERIFY_SUCCESS(TAG, OC_STACK_OK == GetPstatDosP(&(dos->pending)), ERROR);
        return OC_STACK_OK;
    }
exit:
    return OC_STACK_ERROR;
}

OCStackResult SetDosState(const OicSecDeviceOnboardingState_t desiredState)
{
    OIC_LOG_V(INFO, TAG, "%s called for state %d.", __func__, desiredState);

    OCStackResult ret = OC_STACK_ERROR;
    bool pending = false;

    VERIFY_SUCCESS(TAG, OC_STACK_OK == GetPstatDosP(&pending), ERROR);

    if (!pending)
    {

        VERIFY_SUCCESS(TAG, OC_STACK_OK == SetPstatDosP(true), ERROR);

        OicSecDeviceOnboardingState_t oldState = DOS_RESET;
        VERIFY_SUCCESS(TAG, OC_STACK_OK == GetPstatDosS(&oldState), ERROR);
        if (IsValidStateTransition(oldState, desiredState))
        {
            OCStackResult stateChangeResult = DoStateChange(desiredState);
            switch (stateChangeResult)
            {
                case OC_STACK_OK:
                OIC_LOG_V(INFO, TAG, "%s: DOS state changed SUCCESSFULLY from %d to %d.",
                    __func__, oldState, desiredState);
                ret = OC_STACK_OK;
                break;

                case OC_STACK_FORBIDDEN_REQ:
                OIC_LOG_V(WARNING, TAG, "%s: DOS state change change from %d to %d NOT ALLOWED.",
                    __func__, oldState, desiredState);
                ret = OC_STACK_FORBIDDEN_REQ;
                break;

                case OC_STACK_INTERNAL_SERVER_ERROR:
                default:
                OIC_LOG_V(ERROR, TAG, "%s: DOS state change change from %d to %d FAILED."
                    " Internal error - SVRs may be in bad state.",
                    __func__, oldState, desiredState);
                ret = OC_STACK_INTERNAL_SERVER_ERROR;
                break;
            }
        }
        else
        {
            OIC_LOG_V(INFO, TAG, "%s: Invalid transition; cannot go from %d to %d.", \
                __func__, oldState, desiredState);
            ret = OC_STACK_FORBIDDEN_REQ;
        }

        VERIFY_SUCCESS(TAG, OC_STACK_OK == SetPstatDosP(false), ERROR);

    }
    else
    {
        OIC_LOG_V(WARNING, TAG, "%s: cannot set pstat->dos.s, change \
            already pending.", __func__);
        ret = OC_STACK_FORBIDDEN_REQ;
    }

    // TODO [IOT-2023] if OC_STACK_OK, update all SVRs in Persistent Storage?

    return ret;

exit:
    return OC_STACK_INTERNAL_SERVER_ERROR;
}