text:
package info.mornlight.gw2s.android.app;

import android.os.Bundle;
import android.os.Parcelable;
import android.content.Loader;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import butterknife.InjectView;
import info.mornlight.gw2s.android.R;
import info.mornlight.gw2s.android.model.map.*;
import info.mornlight.gw2s.android.ui.LoaderFragment;
import info.mornlight.gw2s.android.ui.ThrowableLoader;
import info.mornlight.gw2s.android.util.ToastUtils;
import org.osmdroid.api.IGeoPoint;
import org.osmdroid.events.MapListener;
import org.osmdroid.events.ScrollEvent;
import org.osmdroid.events.ZoomEvent;
import org.osmdroid.tileprovider.tilesource.ITileSource;
import org.osmdroid.tileprovider.tilesource.XYTileSource;
import org.osmdroid.util.TileSystem;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.ItemizedIconOverlay;
import org.osmdroid.views.overlay.ItemizedOverlay;
import org.osmdroid.views.overlay.OverlayItem;

import java.util.ArrayList;
import java.util.List;

public class MapFragment extends LoaderFragment<ContinentFloor, View> {
    @InjectView(R.id.mapview)
    protected MapView mapview;

    private Continent continent;

    private ItemizedOverlay<OverlayItem> overlay;

    @Override
    protected View onCreateContentView(LayoutInflater inflater, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.map_fragment, null);
    }

    @Override
    public Loader<ContinentFloor> onCreateLoader(int i, Bundle bundle) {
        return new ThrowableLoader<ContinentFloor>(getActivity(), null) {
            @Override
            public ContinentFloor loadData() throws Exception {
                    if(continent == null) return null;

                App app = App.instance();
                return app.getClient().readContinentFloor(Integer.parseInt(continent.getId()), 1);
            }
        };
    }

    @Override
    protected void onLoadSucceed(Loader<ContinentFloor> loader, ContinentFloor data) {
        super.onLoadSucceed(loader, data);

        this.data = data;
        overlay = generateOverlays();
        displayOverlays();
    }

    private ItemizedOverlay<OverlayItem> generateOverlays() {
        if(data == null) return null;

        List<OverlayItem> taskOverlayItems = new ArrayList<OverlayItem>();
        List<OverlayItem> waypointsOverlayItems = new ArrayList<OverlayItem>();
        List<OverlayItem> landmarkOverlayItems = new ArrayList<OverlayItem>();
        List<OverlayItem> vistaOverlayItems = new ArrayList<OverlayItem>();
        List<OverlayItem> skillChallengeOverlayItems = new ArrayList<OverlayItem>();

        for(RegionFloor region : data.getRegions().values()) {
            for(MapFloor map : region.getMaps().values()) {
                for(Task task : map.getTasks()) {
                    OverlayItem overlayItem = new OverlayItem(task.getObjective() + " (" + task.getLevel() + ")", null,
                            TileSystem.PixelXYToLatLong(task.getCoord().getX(), task.getCoord().getY(),
                                    continent.getMaxZoom(), null));
                    overlayItem.setMarker(getResources().getDrawable(R.drawable.marker_task));
                    taskOverlayItems.add(overlayItem);
                }

                for(PointOfInterest poi : map.getPointsOfInterest()) {
                    OverlayItem overlayItem = new OverlayItem(poi.getName(), null,
                            TileSystem.PixelXYToLatLong(poi.getCoord().getX(), poi.getCoord().getY(),
                                    continent.getMaxZoom(), null));

                    if ("waypoint".equals(poi.getType())) {
                        overlayItem.setMarker(getResources()
                                .getDrawable(R.drawable.marker_waypoint));
                        waypointsOverlayItems.add(overlayItem);
                    } else if ("landmark".equals(poi.getType())) {
                        overlayItem.setMarker(getResources()
                                .getDrawable(R.drawable.marker_poi));
                        landmarkOverlayItems.add(overlayItem);
                    } else if ("vista".equals(poi.getType())) {
                        overlayItem.setMarker(getResources()
                                .getDrawable(R.drawable.marker_vista));
                        vistaOverlayItems.add(overlayItem);
                    } else if ("unlock".equals(poi.getType())) {
                        overlayItem.setMarker(getResources()
                                .getDrawable(R.drawable.marker_dungeon));
                        vistaOverlayItems.add(overlayItem);
                    } else {
                        Log.i("MapFragment", "Unsupported POI " + poi.getType());
                    }
                }

                for (SkillChallenge skillChallenge : map.getSkillChallenges()) {
                    OverlayItem overlayItem = new OverlayItem(null, null,
                            TileSystem.PixelXYToLatLong(skillChallenge.getCoord().getX(), skillChallenge.getCoord().getY(),
                                    continent.getMaxZoom(), null));
                    overlayItem.setMarker(getResources()
                            .getDrawable(R.drawable.marker_skillpoint));
                    skillChallengeOverlayItems.add(overlayItem);
                }
            }
        }

        List<OverlayItem> overlayItems = new ArrayList<OverlayItem>();
        overlayItems.addAll(taskOverlayItems);
        overlayItems.addAll(waypointsOverlayItems);
        overlayItems.addAll(landmarkOverlayItems);
        overlayItems.addAll(vistaOverlayItems);
        overlayItems.addAll(skillChallengeOverlayItems);

        ItemizedIconOverlay<OverlayItem> overlay = new ItemizedIconOverlay<OverlayItem>(getActivity(), overlayItems, null) {
            @Override
            protected boolean onTap(int index) {
                showItemInfo(getItem(index).getTitle());
                return true;
            }
        };

        return overlay;
    }

    private void showItemInfo(String info) {
        ToastUtils.show(this.getActivity(), info);
    }

    public void updateView(Continent continent) {
        data = null;
        overlay = null;

        this.continent = continent;
        //https://tiles.guildwars2.com/{continent_id}/{floor}/{zoom}/{x}/{y}.jpg
        ITileSource tileSource = new XYTileSource(continent.getName() + " tiles",
                null, continent.getMinZoom(), continent.getMaxZoom(), 256, ".jpg",
                new String[] { String.format("https://tiles.guildwars2.com/%s/1/", continent.getId()) });

        mapview.setTileSource(tileSource);
        mapview.setMultiTouchControls(true);
        mapview.setUseDataConnection(true);
        mapview.setBuiltInZoomControls(true);
        //mapview.getController().setZoom(2);
        mapview.setMapListener(new MapListener() {
            @Override
            public boolean onScroll(ScrollEvent scrollEvent) {
                return false;
            }

            @Override
            public boolean onZoom(ZoomEvent zoomEvent) {
                displayOverlays();
                return false;
            }
        });
        mapview.getOverlayManager().clear();

        //load the continent floor
        getActivity().getLoaderManager().initLoader(1, null, this);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        //SparseArray<Parcelable> arr = new SparseArray<Parcelable>();
        //mapview.saveHierarchyState(arr);
        //utState.putSparseParcelableArray("mapview", arr);

        outState.putInt("mapview_zoom", mapview.getZoomLevel());
        outState.putParcelable("mapview_center", (Parcelable) mapview.getMapCenter());
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //MapView view = (MapView) getActivity().findViewById(R.id.mapview);
        //if(savedInstanceState != null) {
        //    view.restoreHierarchyState(savedInstanceState.getSparseParcelableArray("mapview"));
        //}
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        if(savedInstanceState != null) {
            mapview.getController().setZoom(savedInstanceState.getInt("mapview_zoom"));
            mapview.getController().setCenter((IGeoPoint) savedInstanceState.getParcelable("mapview_center"));
        } else {
            mapview.getController().setZoom(2);
        }
    }

    private void displayOverlays() {
        if(overlay == null) return;

        try {
            if (mapview.getZoomLevel() >= 4) {
                if (mapview.getOverlayManager().isEmpty()) {
                    mapview.getOverlayManager().add(overlay);
                }
            } else {
                mapview.getOverlayManager().remove(overlay);
            }
        } catch (Exception e) {
            Log.e(getTag(), "Error displaying markers", e);
        }
        mapview.invalidate();
    }
}


text:
<?php namespace Echosign\Options;

class LibDocParticipantInfoSecurityOption {

    protected $messages = [
        'OTHER'        => 'In the future, statuses other than those above may be added to the EchoSign application. For backward compatibility reasons, existing API clients will receive status OTHER. You may need to update your client application to the latest version of the API to receive the new statuses in those cases',
        'KBA'          => 'The participant must pass Knowledge Based Authentication to view and sign the document',
        'WEB_IDENTITY' => 'The participant must provide a web identity to view and sign the document',
        'PASSWORD'     => 'The participant must enter a password to view and sign the document'
    ];

    /**
     * @param $status
     * @throws \InvalidArgumentException
     */
    public function __construct( $status )
    {
        if( ! array_key_exists( $status, $this->messages ) ) {
            throw new \InvalidArgumentException("Invalid status set for ". __CLASS__);
        }

        $this->status = $status;
    }

    public function getMessage()
    {
        return $this->mssages[ $this->status ];
    }

    public function getStatus()
    {
        return $this->status;
    }
}

redpajama_set_name: RedPajamaGithub


text:
//------------------------------------------------------------------------------
//                         COPYRIGHT 2011 GUIDEBEE
//                           ALL RIGHTS RESERVED.
//                     GUIDEBEE CONFIDENTIAL PROPRIETARY
///////////////////////////////////// REVISIONS ////////////////////////////////
// Date       Name                 Tracking #         Description
// ---------  -------------------  ----------         --------------------------
// 22JAN2011  James Shen                 	          Initial Creation
////////////////////////////////////////////////////////////////////////////////
//--------------------------------- PACKAGE ------------------------------------
package com.pstreets.opengl.demo;

//--------------------------------- IMPORTS ------------------------------------
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.ListActivity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;

//[------------------------------ MAIN CLASS ----------------------------------]
//--------------------------------- REVISIONS ----------------------------------
//Date       Name                 Tracking #         Description
//--------   -------------------  -------------      --------------------------
//22JAN2011  James Shen                 	         Initial Creation
////////////////////////////////////////////////////////////////////////////////

public class AndroidOpenGLDemo extends ListActivity {

	private static final String CategoryName="guidebee.intent.category.opengl.SAMPLE_CODE";
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setListAdapter(new SimpleAdapter(this, getData(),
				android.R.layout.simple_list_item_1, new String[] { "title" },
				new int[] { android.R.id.text1 }));
		getListView().setTextFilterEnabled(true);

	}

	protected List getData() {
		List<Map> myData = new ArrayList<Map>();

		Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
		mainIntent.addCategory(CategoryName);

		PackageManager pm = getPackageManager();
		List<ResolveInfo> list = pm.queryIntentActivities(mainIntent, 0);

		if (null == list)
			return myData;

		String[] prefixPath;

		prefixPath = null;

		int len = list.size();

		Map<String, Boolean> entries = new HashMap<String, Boolean>();

		for (int i = 0; i < len; i++) {
			ResolveInfo info = list.get(i);
			CharSequence labelSeq = info.loadLabel(pm);
			String label = labelSeq != null ? labelSeq.toString()
					: info.activityInfo.name;

			String[] labelPath = label.split("/");

			String nextLabel = prefixPath == null ? labelPath[0]
					: labelPath[prefixPath.length];

			if ((prefixPath != null ? prefixPath.length : 0) == labelPath.length - 1) {
				addItem(myData,
						nextLabel,
						activityIntent(
								info.activityInfo.applicationInfo.packageName,
								info.activityInfo.name));
			} else {
				if (entries.get(nextLabel) == null) {
					addItem(myData, nextLabel, browseIntent(nextLabel));
					entries.put(nextLabel, true);
				}
			}

		}

		Collections.sort(myData, sDisplayNameComparator);

		return myData;
	}

	private final static Comparator<Map> sDisplayNameComparator = new Comparator<Map>() {
		private final Collator collator = Collator.getInstance();

		public int compare(Map map1, Map map2) {
			return collator.compare(map1.get("title"), map2.get("title"));
		}
	};

	protected Intent activityIntent(String pkg, String componentName) {
		Intent result = new Intent();
		result.setClassName(pkg, componentName);
		return result;
	}

	protected Intent browseIntent(String path) {
		Intent result = new Intent();
		result.setClass(this, AndroidOpenGLDemo.class);
		return result;
	}

	protected void addItem(List<Map> data, String name, Intent intent) {
		Map<String, Object> temp = new HashMap<String, Object>();
		temp.put("title", name);
		temp.put("intent", intent);
		data.add(temp);
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		Map map = (Map) l.getItemAtPosition(position);
		Intent intent = (Intent) map.get("intent");
		startActivity(intent);
	}
}


text:
package com.twitter.scalding.jdbc

import org.scalatest.WordSpec

class ExampleMysqlJdbcSource() extends JDBCSource with MysqlDriver {
  override val tableName = TableName("test")
  override val columns: Iterable[ColumnDefinition] = Iterable(
    int("hey"),
    bigint("you"),
    varchar("get"),
    datetime("off"),
    text("of"),
    double("my"),
    smallint("cloud"))
  override def currentConfig = ConnectionSpec(ConnectUrl("how"), UserName("are"), Password("you"))
}

class ExampleVerticaJdbcSource() extends JDBCSource with VerticaJdbcDriver {
  override val tableName = TableName("test")
  override val columns: Iterable[ColumnDefinition] = Iterable(
    int("hey"),
    bigint("you"),
    varchar("get"),
    datetime("off"),
    text("of"),
    double("my"),
    smallint("cloud"))
  override def currentConfig = ConnectionSpec(ConnectUrl("how"), UserName("are"), Password("you"))
}

class JDBCSourceCompileTest extends WordSpec {
  "JDBCSource" should {
    "Pick up correct column definitions for MySQL Driver" in {
      new ExampleMysqlJdbcSource().toSqlCreateString
    }
  }
}


text:
<!DOCTYPE html>

	<title>

            Gough Technology Group Inc. -

    Complete profile - Canadian Company Capabilities - Industries and Business - Industry Canada
  </title>

<meta charset="utf-8" />
<meta name="dcterms.language" title="ISO639-2" content="eng" />
<meta name="dcterms.title" content="" />
<meta name="description" content="" />
<meta name="dcterms.description" content="" />
<meta name="dcterms.type" content="report, data set" />
<meta name="dcterms.subject" content="businesses, industry" />
<meta name="dcterms.subject" content="businesses, industry" />
<meta name="dcterms.issued" title="W3CDTF" content="" />
<meta name="dcterms.modified" title="W3CDTF" content="" />
<meta name="keywords" content="" />

<meta name="dcterms.creator" content="" />
<meta name="author" content="" />
<meta name="dcterms.created" title="W3CDTF" content="" />
<meta name="dcterms.publisher" content="" />
<meta name="dcterms.audience" title="icaudience" content="" />
<meta name="dcterms.spatial" title="ISO3166-1" content="" />
<meta name="dcterms.spatial" title="gcgeonames" content="" />
<meta name="dcterms.format" content="HTML" />
<meta name="dcterms.identifier" title="ICsiteProduct" content="536" />

<meta http-equiv="X-UA-Compatible" content="IE=edge">

<meta content="width=device-width,initial-scale=1" name="viewport">

<meta name = "format-detection" content = "telephone=no">

<meta name="robots" content="noarchive">

<link href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/favicon.ico" rel="icon" type="image/x-icon">
<link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/wet-boew.min.css">

<link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/theme.min.css">

<link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/noscript.min.css" />

<link rel="stylesheet" href="/eic/home.nsf/css/add_WET_4-0_Canada_Apps.css">

  	<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
  	<link href="/app/ccc/srch/css/print.css" media="print" rel="stylesheet" type="text/css" />

<meta property="legalName" content="Department_of_Industry">

Skip to main content

Skip to "About this site"

Language selection

Français

<object type="image/svg+xml" tabindex="-1" data="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/sig-blk-en.svg"></object> Government of Canada

Search and menus

Search and menus

Topics menu

Jobs

Immigration

Travel

Business

Benefits

Health

Taxes

More services

You are here:

Home

Industries and Business

Canadian Company Capabilities

<input id="showMore" type="hidden" value='more'/>
<input id="showLess" type="hidden" value='less'/>

 Company profile - Canadian Company Capabilities

New Search |

<form name="searchForm" method="post" action="/app/ccc/srch/bscSrch.do">

          <input type="hidden" name="lang" value="eng" />
          <input type="hidden" name="profileId" value="" />
          <input type="hidden" name="prtl" value="1" />
          <input type="hidden" name="searchPage" value="%2Fapp%2Fccc%2Fsrch%2FcccBscSrch.do%3Flang%3Deng%26amp%3Bprtl%3D1%26amp%3Btagid%3D"  />

          <input type="hidden" name="V_SEARCH.scopeCategory" value="CCC.Root" />

          <input type="hidden" name="V_SEARCH.depth" value="1" />
          <input type="hidden" name="V_SEARCH.showStricts" value="false" />
          <input id="repeatSearchBtn" class="btn btn-link" type="submit" value="Return to search results" />

  </form>

| Previous Company

| Next Company

      Third-Party Information Liability Disclaimer

Some of the information on this Web page has been provided by external sources. The Government of Canada is not responsible for the accuracy, reliability or currency of the information supplied by external sources. Users wishing to rely upon this information should consult directly with the source of the information. Content provided by external sources is not subject to official languages, privacy and accessibility requirements.

      Gough Technology Group Inc.

Legal/Operating Name:

Gough Technology Group Inc.

http://www.goughtechgroup.com

david@goughtechgroup.com

Mailing Address:

              	<address class="mrgn-bttm-md">

                   5876 Rogers Dr.

                    HALIFAX,

                    Nova Scotia

                  B3H 1G1

                </address>

Location Address:

              	         <address class="mrgn-bttm-md">

                   5876 Rogers Dr.

                    HALIFAX,

                    Nova Scotia

                  B3H 1G1

                         </address>

Tel.:
		      (902) 401-7474

Fax:
		      (902) 422-0666

Logo

Company Profile

            A diversified business development and marketing services firm,

Gough Technology Group Inc. and its substantial network of

partners and associates help technology firms, private & public

sector organizations and governments strategically enter new

markets, generate new business and ensure superior client and

partner relationships.  GTG provides value-added services and

programs in such areas as market & client expansion,

international trade, strategic partnering, relationship-based

matchmaking, account management and technology

commercialization, by operating as an individual resource or as

part of a larger external team of resources.

				Full profile

				Full profile

				Contact information

                David
                Gough

                  Title:

                President

                  Telephone:

                (902) 401-7474

                  Facsimile:

                (902) 422-0666

                    Email:

                  david@goughtechgroup.com

  top of page

				Company description

            Country of Ownership:

              Canada

            Exporting:

              Yes

                Primary Industry (NAICS):

				541619 - Other Management Consulting Services

            Primary Business Activity:

            Services

				Product / Service / Licensing

                              Service Name:

                            Business development services.

                            Gough Technology Group and its associates provide business

development and marketing services and programs to help

technology firms, private & public sector organizations and

governments be more effective and successful in such areas as

market and client expansion, international trade, strategic

partnering and account management, by providing services in the

following areas:

- Canadian and international business development.

- US market entry, especially into the Washington, Boston and

the Valley areas.

- Partner searches and relationship-based executive matchmaking.

- Major & strategic account and alliance management.

- Government relations in Atlantic Canada and Washington, DC.

- Competitive intelligence assessments.

- Technology commercialization assessment and implementation.

- Outgoing and incoming business development programs, trade

missions and market visits.

- Representation of external technology and related service

firms in Atlantic Canada.

- Conference planning and execution.

- Marketing & sales training.

- Financing referrals [Angel or VC] for technology firms.

Our extensive network of contacts in the Atlantic Canadian

technology [ICT, aerospace & defence, biotech, marine] and

business communities allows us to provide rapid and quality

connections to decision makers in the Atlantic marketplace.

              FSC Code:

              9999-Miscellaneous Items (includes only those items of Goods which cannot conceivably be classified in any existing Classes)

  top of page

					Market profile

                        Alliances:

Sales/Marketing

Technology

                          Industry sector market interests:

Information Technology and Telecommunications

Medical/Biotechnology/Chemical

Aerospace

Defence

  top of page

					Third-Party Information Liability Disclaimer

					Some of the information on this Web page has been provided by external sources. The Government of Canada is not responsible for the accuracy, reliability or currency of the information supplied by external sources. Users wishing to rely upon this information should consult directly with the source of the information. Content provided by external sources is not subject to official languages, privacy and accessibility requirements.

				Contacts

				Contact information

                David
                Gough

                  Title:

                President

                  Telephone:

                (902) 401-7474

                  Facsimile:

                (902) 422-0666

                    Email:

                  david@goughtechgroup.com

				Description

				Company description

            Country of Ownership:

              Canada

            Exporting:

              Yes

                Primary Industry (NAICS):

				541619 - Other Management Consulting Services

            Primary Business Activity:

            Services

				Products, services and licensing

				Product / Service / Licensing

                              Service Name:

                            Business development services.

                            Gough Technology Group and its associates provide business

development and marketing services and programs to help

technology firms, private & public sector organizations and

governments be more effective and successful in such areas as

market and client expansion, international trade, strategic

partnering and account management, by providing services in the

following areas:

- Canadian and international business development.

- US market entry, especially into the Washington, Boston and

the Valley areas.

- Partner searches and relationship-based executive matchmaking.

- Major & strategic account and alliance management.

- Government relations in Atlantic Canada and Washington, DC.

- Competitive intelligence assessments.

- Technology commercialization assessment and implementation.

- Outgoing and incoming business development programs, trade

missions and market visits.

- Representation of external technology and related service

firms in Atlantic Canada.

- Conference planning and execution.

- Marketing & sales training.

- Financing referrals [Angel or VC] for technology firms.

Our extensive network of contacts in the Atlantic Canadian

technology [ICT, aerospace & defence, biotech, marine] and

business communities allows us to provide rapid and quality

connections to decision makers in the Atlantic marketplace.

              FSC Code:

              9999-Miscellaneous Items (includes only those items of Goods which cannot conceivably be classified in any existing Classes)

					Market

					Market profile

                        Alliances:

Sales/Marketing

Technology

                          Industry sector market interests:

Information Technology and Telecommunications

Medical/Biotechnology/Chemical

Aerospace

Defence

    Last Update Date 2015-06-24

Date Modified:

      <time>2017-03-02</time>

About government

Contact us

Departments and agencies

Public service and military

News

Treaties, laws and regulations

Government-wide reporting

Prime Minister

How government works

Open government

About this site

Social media

Mobile applications

About Canada.ca

Terms and conditions

Privacy

Top of Page

<object type="image/svg+xml" tabindex="-1" role="img" data="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/wmms-blk.svg" aria-label="Symbol of the Government of Canada"></object>


text:
package org.zstack.storage.ceph.primary;

import org.springframework.http.HttpMethod;
import org.zstack.header.query.APIQueryMessage;
import org.zstack.header.query.AutoQuery;
import org.zstack.header.rest.RestRequest;
import org.zstack.header.storage.primary.APIQueryPrimaryStorageReply;

import java.util.Collections;
import java.util.List;

/**
 * Created by frank on 8/6/2015.
 */
@AutoQuery(replyClass = APIQueryPrimaryStorageReply.class, inventoryClass = CephPrimaryStorageInventory.class)
@RestRequest(
        path = "/primary-storage/ceph",
        optionalPaths = {"/primary-storage/ceph/{uuid}"},
        method = HttpMethod.GET,
        responseClass = APIQueryPrimaryStorageReply.class
)
public class APIQueryCephPrimaryStorageMsg extends APIQueryMessage {

    public static List<String> __example__() {
        return Collections.singletonList("uuid=" + uuid());
    }

}


text:
$(document).ready(function(){
	(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
	(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
	m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
	})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

	ga('create', 'UA-47727668-1', 'whoisjack.herokuapp.com');
	ga('send', 'pageview');

	$('.question-form').submit(submitAnswer)
	$('.points-header').tooltip('show')
});

function submitAnswer(event) {
	if($('.answer').attr('type') == "text" && $('.answer').val()) {
    	$('.submit-answer').remove()
	} else if ($('input[name=answer]:checked').val()) {
    	$('.submit-answer').remove()
	}
	event.preventDefault();
	var frm = $('.question-form')

    // Tab problems
    var col_popularity_tab = $('a[href="#college-popularity"]').parent().hasClass('active')
    var std_popularity_tab = $('a[href="#individual-popularity"]').parent().hasClass('active')

	$.ajax({
        type: frm.attr('method'),
        url: '/answer_question/',
        data: frm.serialize(),
        success: function (data) {
        	console.log(data.levelup)
        	if (data.levelup) {
        		console.log('leveledup')
        		console.log(data.levelup)
				$('.question-wrapper').empty();
				$('.question-wrapper').append(data.levelup)
				$('.continue').click(newQuestion);
			}
        	$('.footer-container').append(data.footer);
			$('.next-question').click(newQuestion)
			$('.profile-content').empty();
			$('.profile-content').append(data.profile)
			$("input").prop('disabled', true);
            $('.highscores-panels').empty()
            $('.highscores-panels').append(data.highscores)

            if (col_popularity_tab) {
                $('a[href="#college-popularity"]').tab('show');
            }
            if (std_popularity_tab) {
                $('a[href="#individual-popularity"]').tab('show');
            }
        },
        error: function(data) {
            console.log('bad')
        }
    });
}

function newQuestion() {
    $.ajax({
        method: "post",
        dataType: "json",
        data: "csrfmiddlewaretoken=" + $('input[name="nextcsrf"]').val(),
        url: '/new_question/',
        success: function(data) {
            $('.question-wrapper').empty()
            $('.question-wrapper').append(data.question)
            var frm = $('.question-form');
            frm.submit(submitAnswer);
        }
    });
}
var target_date = new Date('Mar, 3, 2014').getTime();
var countdown = $('#timer');

setInterval(function () {
    // find the amount of "seconds" between now and target
    var current_date = new Date().getTime();
    var seconds_left = (target_date - current_date) / 1000;

    // do some time calculations
    hours = parseInt(seconds_left / 3600);
    seconds_left = seconds_left % 3600;

    minutes = parseInt(seconds_left / 60);
    seconds = parseInt(seconds_left % 60);

    // format countdown string + set tag value
    countdown.html( hours + ' Hours ' + minutes + ' Minutes ' + seconds + ' Seconds ');

}, 1000);


text:
package org.jon.ivmark.graphit.core.graph.node;

import org.junit.Test;

import java.util.Arrays;
import java.util.List;

import static org.junit.Assert.*;

/**
 * @author jon
 *
 */
public class NodeTypesTest {

    @Test
    public void testAddValidNodeTypes() {
        NodeTypes nodeTypes = new NodeTypes();
        nodeTypes.getOrAdd("A");
        nodeTypes.add(new NodeType("B-A"));
        nodeTypes.add("C_1");

        assertEquals(3, nodeTypes.size());

        assertNotNull(nodeTypes.valueOf("A"));
        assertNotNull(nodeTypes.valueOf("B-A"));
        assertNotNull(nodeTypes.valueOf("C_1"));
    }

    @Test
    public void testAddInvalidNodeTypes() {
        NodeTypes nodeTypes = new NodeTypes();
        // TODO: Use parameterized test instead
        List<String> invalid = Arrays.asList("A B", "C:", "$", "");
        for (String invalidName : invalid) {
            boolean exceptionWhenAddingName = false;
            try {
                nodeTypes.add(invalidName);
            } catch (IllegalArgumentException e) {
                exceptionWhenAddingName = true;
            }
            assertTrue(exceptionWhenAddingName);

            boolean exceptionOnGetOrAdd = false;
            try {
                nodeTypes.getOrAdd(invalidName);
            } catch (IllegalArgumentException e) {
                exceptionOnGetOrAdd = true;
            }
            assertTrue(exceptionOnGetOrAdd);

            boolean exceptionWhenAddingType = false;
            try {
                nodeTypes.add(new NodeType(invalidName));
            } catch (IllegalArgumentException e) {
                exceptionWhenAddingType = true;
            }
            assertTrue(exceptionWhenAddingType);
        }
    }

}


text:
#include <proton/selector.h>
#include <proton/error.h>
#include <poll.h>
#include <stdlib.h>
#include <assert.h>
#include "platform.h"
#include "selectable.h"
#include "util.h"

struct pn_selector_t {
  struct pollfd *fds;
  pn_timestamp_t *deadlines;
  size_t capacity;
  pn_list_t *selectables;
  pn_timestamp_t deadline;
  size_t current;
  pn_timestamp_t awoken;
  pn_error_t *error;
};

void pn_selector_initialize(void *obj)
{
  pn_selector_t *selector = (pn_selector_t *) obj;
  selector->fds = NULL;
  selector->deadlines = NULL;
  selector->capacity = 0;
  selector->selectables = pn_list(PN_WEAKREF, 0);
  selector->deadline = 0;
  selector->current = 0;
  selector->awoken = 0;
  selector->error = pn_error();
}

void pn_selector_finalize(void *obj)
{
  pn_selector_t *selector = (pn_selector_t *) obj;
  free(selector->fds);
  free(selector->deadlines);
  pn_free(selector->selectables);
  pn_error_free(selector->error);
}

#define pn_selector_hashcode NULL
#define pn_selector_compare NULL
#define pn_selector_inspect NULL

pn_selector_t *pni_selector(void)
{
  static const pn_class_t clazz = PN_CLASS(pn_selector);
  pn_selector_t *selector = (pn_selector_t *) pn_class_new(&clazz, sizeof(pn_selector_t));
  return selector;
}

void pn_selector_add(pn_selector_t *selector, pn_selectable_t *selectable)
{
  assert(selector);
  assert(selectable);
  assert(pni_selectable_get_index(selectable) < 0);

  if (pni_selectable_get_index(selectable) < 0) {
    pn_list_add(selector->selectables, selectable);
    size_t size = pn_list_size(selector->selectables);

    if (selector->capacity < size) {
      selector->fds = (struct pollfd *) realloc(selector->fds, size*sizeof(struct pollfd));
      selector->deadlines = (pn_timestamp_t *) realloc(selector->deadlines, size*sizeof(pn_timestamp_t));
      selector->capacity = size;
    }

    pni_selectable_set_index(selectable, size - 1);
  }

  pn_selector_update(selector, selectable);
}

void pn_selector_update(pn_selector_t *selector, pn_selectable_t *selectable)
{
  int idx = pni_selectable_get_index(selectable);
  assert(idx >= 0);
  selector->fds[idx].fd = pn_selectable_fd(selectable);
  selector->fds[idx].events = 0;
  selector->fds[idx].revents = 0;
  if (pn_selectable_capacity(selectable) > 0) {
    selector->fds[idx].events |= POLLIN;
  }
  if (pn_selectable_pending(selectable) > 0) {
    selector->fds[idx].events |= POLLOUT;
  }
  selector->deadlines[idx] = pn_selectable_deadline(selectable);
}

void pn_selector_remove(pn_selector_t *selector, pn_selectable_t *selectable)
{
  assert(selector);
  assert(selectable);

  int idx = pni_selectable_get_index(selectable);
  assert(idx >= 0);
  pn_list_del(selector->selectables, idx, 1);
  size_t size = pn_list_size(selector->selectables);
  for (size_t i = idx; i < size; i++) {
    pn_selectable_t *sel = (pn_selectable_t *) pn_list_get(selector->selectables, i);
    pni_selectable_set_index(sel, i);
    selector->fds[i] = selector->fds[i + 1];
  }

  pni_selectable_set_index(selectable, -1);
}

int pn_selector_select(pn_selector_t *selector, int timeout)
{
  assert(selector);

  size_t size = pn_list_size(selector->selectables);

  if (timeout) {
    pn_timestamp_t deadline = 0;
    for (size_t i = 0; i < size; i++) {
      pn_timestamp_t d = selector->deadlines[i];
      if (d)
        deadline = (deadline == 0) ? d : pn_min(deadline, d);
    }

    if (deadline) {
      pn_timestamp_t now = pn_i_now();
      int delta = selector->deadline - now;
      if (delta < 0) {
        timeout = 0;
      } else if (delta < timeout) {
        timeout = delta;
      }
    }
  }

  int result = poll(selector->fds, size, timeout);
  if (result == -1) {
    pn_i_error_from_errno(selector->error, "poll");
  } else {
    selector->current = 0;
    selector->awoken = pn_i_now();
  }

  return pn_error_code(selector->error);
}

pn_selectable_t *pn_selector_next(pn_selector_t *selector, int *events)
{
  pn_list_t *l = selector->selectables;
  size_t size = pn_list_size(l);
  while (selector->current < size) {
    pn_selectable_t *sel = (pn_selectable_t *) pn_list_get(l, selector->current);
    struct pollfd *pfd = &selector->fds[selector->current];
    pn_timestamp_t deadline = selector->deadlines[selector->current];
    int ev = 0;
    if (pfd->revents & POLLIN) {
      ev |= PN_READABLE;
    }
    if (pfd->revents & POLLOUT) {
      ev |= PN_WRITABLE;
    }
    if (deadline && selector->awoken >= deadline) {
      ev |= PN_EXPIRED;
    }
    selector->current++;
    if (ev) {
      *events = ev;
      return sel;
    }
  }
  return NULL;
}

void pn_selector_free(pn_selector_t *selector)
{
  assert(selector);
  pn_free(selector);
}


text:
package org.xbib.io.compress.xz.check;

public class None extends Check {
    public None() {
        size = 0;
        name = "None";
    }

    public void update(byte[] buf, int off, int len) {
    }

    public byte[] finish() {
        byte[] empty = new byte[0];
        return empty;
    }
}


text:
#import "ORKRegistrationStep.h"

#import "ORKAnswerFormat_Private.h"

#import "ORKHelpers_Internal.h"

NSString *const ORKRegistrationFormItemIdentifierEmail = @"ORKRegistrationFormItemEmail";
NSString *const ORKRegistrationFormItemIdentifierPassword = @"ORKRegistrationFormItemPassword";
NSString *const ORKRegistrationFormItemIdentifierConfirmPassword = @"ORKRegistrationFormItemConfirmPassword";
NSString *const ORKRegistrationFormItemIdentifierGivenName = @"ORKRegistrationFormItemGivenName";
NSString *const ORKRegistrationFormItemIdentifierFamilyName = @"ORKRegistrationFormItemFamilyName";
NSString *const ORKRegistrationFormItemIdentifierGender = @"ORKRegistrationFormItemGender";
NSString *const ORKRegistrationFormItemIdentifierDOB = @"ORKRegistrationFormItemDOB";

static id ORKFindInArrayByFormItemId(NSArray *array, NSString *formItemIdentifier) {
    return findInArrayByKey(array, @"identifier", formItemIdentifier);
}

static NSArray <ORKFormItem*> *ORKRegistrationFormItems(ORKRegistrationStepOption options) {
    NSMutableArray *formItems = [NSMutableArray new];

    {
        ORKEmailAnswerFormat *answerFormat = [ORKAnswerFormat emailAnswerFormat];

        ORKFormItem *item = [[ORKFormItem alloc] initWithIdentifier:ORKRegistrationFormItemIdentifierEmail
                                                               text:ORKLocalizedString(@"EMAIL_FORM_ITEM_TITLE", nil)
                                                       answerFormat:answerFormat
                                                           optional:NO];
        item.placeholder = ORKLocalizedString(@"EMAIL_FORM_ITEM_PLACEHOLDER", nil);

        [formItems addObject:item];
    }

    ORKFormItem *passwordFormItem;
    {
        ORKTextAnswerFormat *answerFormat = [ORKAnswerFormat textAnswerFormat];
        answerFormat.multipleLines = NO;
        answerFormat.secureTextEntry = YES;
        answerFormat.autocapitalizationType = UITextAutocapitalizationTypeNone;
        answerFormat.autocorrectionType = UITextAutocorrectionTypeNo;
        answerFormat.spellCheckingType = UITextSpellCheckingTypeNo;

        ORKFormItem *item = [[ORKFormItem alloc] initWithIdentifier:ORKRegistrationFormItemIdentifierPassword
                                                               text:ORKLocalizedString(@"PASSWORD_FORM_ITEM_TITLE", nil)
                                                       answerFormat:answerFormat
                                                           optional:NO];
        item.placeholder = ORKLocalizedString(@"PASSWORD_FORM_ITEM_PLACEHOLDER", nil);
        passwordFormItem = item;

        [formItems addObject:item];
    }

    {
        ORKFormItem *item = [passwordFormItem confirmationAnswerFormItemWithIdentifier:ORKRegistrationFormItemIdentifierConfirmPassword
                                                text:ORKLocalizedString(@"CONFIRM_PASSWORD_FORM_ITEM_TITLE", nil)
                                                errorMessage:ORKLocalizedString(@"CONFIRM_PASSWORD_ERROR_MESSAGE", nil)];
        item.placeholder = ORKLocalizedString(@"CONFIRM_PASSWORD_FORM_ITEM_PLACEHOLDER", nil);

        [formItems addObject:item];
    }

    if (options & (ORKRegistrationStepIncludeFamilyName | ORKRegistrationStepIncludeGivenName | ORKRegistrationStepIncludeDOB | ORKRegistrationStepIncludeGender)) {
        ORKFormItem *item = [[ORKFormItem alloc] initWithSectionTitle:ORKLocalizedString(@"ADDITIONAL_INFO_SECTION_TITLE", nil)];

        [formItems addObject:item];
    }

    if (options & ORKRegistrationStepIncludeGivenName) {
        ORKTextAnswerFormat *answerFormat = [ORKAnswerFormat textAnswerFormat];
        answerFormat.multipleLines = NO;

        ORKFormItem *item = [[ORKFormItem alloc] initWithIdentifier:ORKRegistrationFormItemIdentifierGivenName
                                                               text:ORKLocalizedString(@"CONSENT_NAME_GIVEN", nil)
                                                       answerFormat:answerFormat
                                                           optional:NO];
        item.placeholder = ORKLocalizedString(@"GIVEN_NAME_ITEM_PLACEHOLDER", nil);

        [formItems addObject:item];
    }

    if (options & ORKRegistrationStepIncludeFamilyName) {
        ORKTextAnswerFormat *answerFormat = [ORKAnswerFormat textAnswerFormat];
        answerFormat.multipleLines = NO;

        ORKFormItem *item = [[ORKFormItem alloc] initWithIdentifier:ORKRegistrationFormItemIdentifierFamilyName
                                                               text:ORKLocalizedString(@"CONSENT_NAME_FAMILY", nil)
                                                       answerFormat:answerFormat
                                                           optional:NO];
        item.placeholder = ORKLocalizedString(@"FAMILY_NAME_ITEM_PLACEHOLDER", nil);

        [formItems addObject:item];
    }

    // Adjust order of given name and family name form item cells based on current locale.
    if ((options & ORKRegistrationStepIncludeGivenName) && (options & ORKRegistrationStepIncludeFamilyName)) {
        if (ORKCurrentLocalePresentsFamilyNameFirst()) {
            ORKFormItem *givenNameFormItem = ORKFindInArrayByFormItemId(formItems, ORKRegistrationFormItemIdentifierGivenName);
            ORKFormItem *familyNameFormItem = ORKFindInArrayByFormItemId(formItems, ORKRegistrationFormItemIdentifierFamilyName);
            [formItems exchangeObjectAtIndex:[formItems indexOfObject:givenNameFormItem]
                           withObjectAtIndex:[formItems indexOfObject:familyNameFormItem]];
        }
    }

    if (options & ORKRegistrationStepIncludeGender) {
        NSArray *textChoices = @[[ORKTextChoice choiceWithText:ORKLocalizedString(@"GENDER_FEMALE", nil) value:@"female"],
                                 [ORKTextChoice choiceWithText:ORKLocalizedString(@"GENDER_MALE", nil) value:@"male"],
                                 [ORKTextChoice choiceWithText:ORKLocalizedString(@"GENDER_OTHER", nil) value:@"other"]];
        ORKValuePickerAnswerFormat *answerFormat = [ORKAnswerFormat valuePickerAnswerFormatWithTextChoices:textChoices];

        ORKFormItem *item = [[ORKFormItem alloc] initWithIdentifier:ORKRegistrationFormItemIdentifierGender
                                                               text:ORKLocalizedString(@"GENDER_FORM_ITEM_TITLE", nil)
                                                       answerFormat:answerFormat
                                                           optional:NO];
        item.placeholder = ORKLocalizedString(@"GENDER_FORM_ITEM_PLACEHOLDER", nil);

        [formItems addObject:item];
    }

    if (options & ORKRegistrationStepIncludeDOB) {
        // Calculate default date (20 years from now).
        NSDate *defaultDate = [[NSCalendar currentCalendar] dateByAddingUnit:NSCalendarUnitYear
                                                                       value:-20
                                                                      toDate:[NSDate date]
                                                                     options:(NSCalendarOptions)0];

        ORKDateAnswerFormat *answerFormat = [ORKAnswerFormat dateAnswerFormatWithDefaultDate:defaultDate
                                                                                minimumDate:nil
                                                                                maximumDate:[NSDate date]
                                                                                calendar:[NSCalendar currentCalendar]];

        ORKFormItem *item = [[ORKFormItem alloc] initWithIdentifier:ORKRegistrationFormItemIdentifierDOB
                                                               text:ORKLocalizedString(@"DOB_FORM_ITEM_TITLE", nil)
                                                       answerFormat:answerFormat
                                                           optional:NO];
        item.placeholder = ORKLocalizedString(@"DOB_FORM_ITEM_PLACEHOLDER", nil);

        [formItems addObject:item];
    }

    return formItems;
}

@implementation ORKRegistrationStep

- (instancetype)initWithIdentifier:(NSString *)identifier
                             title:(NSString *)title
                              text:(NSString *)text
           passcodeValidationRegex:(NSString *)passcodeValidationRegex
            passcodeInvalidMessage:(NSString *)passcodeInvalidMessage
                           options:(ORKRegistrationStepOption)options {
    self = [super initWithIdentifier:identifier title:title text:text];
    if (self) {
        _options = options;
        self.passcodeValidationRegex = passcodeValidationRegex;
        self.passcodeInvalidMessage = passcodeInvalidMessage;
        self.optional = NO;
    }
    return self;
}

- (instancetype)initWithIdentifier:(NSString *)identifier
                             title:(NSString *)title
                              text:(NSString *)text
                           options:(ORKRegistrationStepOption)options {
    return [self initWithIdentifier:identifier
                              title:title
                               text:text
            passcodeValidationRegex:nil
             passcodeInvalidMessage:nil
                            options:options];
}

- (instancetype)initWithIdentifier:(NSString *)identifier
                             title:(NSString *)title
                              text:(NSString *)text {
    return [self initWithIdentifier:identifier
                              title:title
                               text:text
                            options:ORKRegistrationStepDefault];
}

- (instancetype)initWithIdentifier:(NSString *)identifier {
    return [self initWithIdentifier:identifier
                              title:nil
                               text:nil];
}

- (ORKTextAnswerFormat *)passwordAnswerFormat {
    ORKFormItem *passwordFormItem = ORKFindInArrayByFormItemId(self.formItems, ORKRegistrationFormItemIdentifierPassword);
    ORKTextAnswerFormat *passwordAnswerFormat = (ORKTextAnswerFormat *)passwordFormItem.answerFormat;
    return passwordAnswerFormat;
}

- (NSArray <ORKFormItem *> *)formItems {
    if (![super formItems]) {
        self.formItems = ORKRegistrationFormItems(_options);
    }

    ORKFormItem *dobFormItem = ORKFindInArrayByFormItemId([super formItems], ORKRegistrationFormItemIdentifierDOB);
    ORKDateAnswerFormat *originalAnswerFormat = (ORKDateAnswerFormat *)dobFormItem.answerFormat;
    ORKDateAnswerFormat *modifiedAnswerFormat = [ORKAnswerFormat dateAnswerFormatWithDefaultDate:originalAnswerFormat.defaultDate
                                                                                minimumDate:originalAnswerFormat.minimumDate
                                                                                maximumDate:[NSDate date]
                                                                                calendar:originalAnswerFormat.calendar];

    dobFormItem = [[ORKFormItem alloc] initWithIdentifier:ORKRegistrationFormItemIdentifierDOB
                                                     text:ORKLocalizedString(@"DOB_FORM_ITEM_TITLE", nil)
                                             answerFormat:modifiedAnswerFormat
                                                 optional:NO];
    dobFormItem.placeholder = ORKLocalizedString(@"DOB_FORM_ITEM_PLACEHOLDER", nil);

    return [super formItems];
}

- (NSString *)passcodeValidationRegex {
    return [self passwordAnswerFormat].validationRegex;
}

- (NSString *)passcodeInvalidMessage {
    return [self passwordAnswerFormat].invalidMessage;
}

- (void)setPasscodeValidationRegex:(NSString *)passcodeValidationRegex {
    [self passwordAnswerFormat].validationRegex = passcodeValidationRegex;
}

- (void)setPasscodeInvalidMessage:(NSString *)passcodeInvalidMessage {
    [self passwordAnswerFormat].invalidMessage = passcodeInvalidMessage;
}

+ (BOOL)supportsSecureCoding {
    return YES;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {

        // The `passcodeValidationRegex` and `passcodeInvalidMessage` properties
        // are transparent properties. The `initWithCoder:` for these properties is
        // defined in the answer format (super).
        ORK_DECODE_INTEGER(aDecoder, options);
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder {
    [super encodeWithCoder:aCoder];

    // The `passcodeValidationRegex` and `passcodeInvalidMessage` properties
    // are transparent properties. The `encodeWithCoder:` for these properties is
    // defined in the answer format (super).
    ORK_ENCODE_INTEGER(aCoder, options);
}

- (instancetype)copyWithZone:(NSZone *)zone {
    ORKRegistrationStep *step = [super copyWithZone:zone];

    // The `passcodeValidationRegex` and `passcodeInvalidMessage` properties
    // are transparent properties. The `copyWithZone:` for these properties is
    // defined in the answer format (super).
    step->_options = self.options;
    return step;
}

- (BOOL)isEqual:(id)object {
    BOOL isParentSame = [super isEqual:object];

    // The `passcodeValidationRegex` and `passcodeInvalidMessage` properties
    // are transparent properties. The `isEqual:` for these properties is
    // defined in the answer format (super).
    __typeof(self) castObject = object;
    return (isParentSame &&
            self.options == castObject.options);
}

@end


text:
	Formularz generowania nowego hasła

	<?= $form; ?>


text:
package ru.job4j.calculator;

/**
 * Class Calculator.
 *
 * @author Anatolii Shalobasov (proboostbiznes@gmail.com)
 * @version 1
 * @since 20.06.2017
 */
public class Calculator {
	/**
     * result.
     */
    private double result;
	/**
     * add.
     * @param first - first number.
	 * @param second - second number.
     */
    public void add(double first, double second) {
        this.result = first + second;
    }
    /**
     * substruct.
     * @param first - first number.
	 * @param second - second number.
     */
	public void substruct(double first, double second) {
        this.result = first - second;
    }
	/**
     * div.
     * @param first - first number.
	 * @param second - second number.
     */
	public void div(double first, double second) {
        this.result = first / second;
    }
	/**
     * multiple.
     * @param first - first number.
	 * @param second - second number.
     */
	public void multiple(double first, double second) {
        this.result = first * second;
    }
	/**
     * getResult.
	 * @return result.
     */
    public double getResult() {
        return this.result;
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>MqttDecoder.Result</title>
<meta name="date" content="2018-01-27">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.dsngroup.broke.protocol

Class MqttDecoder.Result<T>

java.lang.Object

org.dsngroup.broke.protocol.MqttDecoder.Result<T>

Enclosing class:

MqttDecoder

private static final class MqttDecoder.Result<T>
extends java.lang.Object

Field Summary

Fields

Modifier and Type
Field and Description

private int
numberOfBytesConsumed

private T
value

Constructor Summary

Constructors

Constructor and Description

Result(T value,
      int numberOfBytesConsumed)

Method Summary

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

value

private final T value

numberOfBytesConsumed

private final int numberOfBytesConsumed

Constructor Detail

Result

Result(T value,
       int numberOfBytesConsumed)

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
using namespace glm;
using namespace std;
using namespace asdf::util;

namespace asdf
{
	ui_button_t::ui_button_t(vec3 _position, vec3 size, bool togglable)
	    : ui_base_t(_position)
	    , state(up)
	    , togglable(togglable)
	    , toggled(false)
	{
	    upper_bound = position + size / 2.0f;
	    lower_bound = position - size / 2.0f;
	}

	void ui_button_t::update(float dt)
	{
	    ui_base_t::update(dt);
	}

	void ui_button_t::render(vec3 const& _position, mat3 const& _matrix, color_t const& _color)
	{
	    DEFAULT_TRANSFORM_COPYPASTA

	    base_highlight->visible = state == highlighted;
	    base_pressed->  visible = state == down || (toggled && state == up);
	    base_disabled-> visible = state == disabled;

	    base_unpressed->visible = !base_highlight->visible
	                           && !base_pressed->visible
	                           && !base_disabled->visible;

	    //recolor base_pressed for other button states if necessary
	    if(state == down && !base_pressed)
	        base_unpressed->render(position_, matrix_, color_ * BUTTON_PRESSED_COLOR);

	    else if(state == highlighted && !base_highlight)
	        base_unpressed->render(position_, matrix_, color_ * BUTTON_HIGHLIGHT_COLOR);

	    else if(state == disabled && !base_disabled)
	        base_unpressed->render(position_, matrix_, color_ * BUTTON_DISABLED_COLOR);

	    ui_base_t::render(_position, _matrix, _color);

	    base_unpressed->visible = state == up;
	}

	// #define BUTTON_LOG() {}
	#define BUTTON_LOG(event_type) LOG("%s %s  xy:(%f,%f)  upper:(%f,%f) lower(%f,%f)"              \
													, #event_type, inside ? "inside" : "not-inside" \
													, mouse_abspos.x, mouse_abspos.y                \
													, upper_bound.x, upper_bound.y                  \
													, lower_bound.x, lower_bound.y);
	//----

	bool ui_button_t::on_event(SDL_Event* event , glm::vec3 const& _position, glm::mat3 const& _matrix)
	{
	    auto pos = position + _position;

	    vec3 mouse_abspos(event->motion.x, event->motion.y, 0.0f);
	    vec3 mouse_relpos = mouse_abspos - pos;

	    bool inside = contains_point(mouse_relpos);

	    switch (event->type)
	    {
	        case SDL_MOUSEMOTION:
	        {
	            if(inside)
	            {
	                state = (state == down) ? down : highlighted;
	            }
	            else
	            {
	                state = up;
	            }
	            break;
	        };

	        case SDL_MOUSEBUTTONDOWN:
	        {
	            if (inside)
	            {
	            	BUTTON_LOG(mouse_down);
	                // state = toggled ? highlighted : down;
	                state = down;

	                if (on_start_callback)
	                {
	                    on_start_callback(this);
	                    return true;
	                }
	            }
	            break;
	        }
	        case SDL_MOUSEBUTTONUP:
	        {
	            if (inside)
	            {
	            	BUTTON_LOG(mouse_up);

	                toggled = !toggled && togglable;
	                // state = toggled ? down : highlighted;
	                state = highlighted;

	                if (on_end_inside_callback)
	                {
	                    on_end_inside_callback(this);
	                    return true;
	                }
	            } else {
	                // state = toggled ? state : up;
	                state = up;

	                if (on_end_callback)
	                {
	                    on_end_callback(this);
	                    return true;
	                }
	            }
	            break;
	        }
	    }

	    return ui_base_t::on_event(event, _position, _matrix);
	}
}


text:
    Show
    Hide
     completed items

      <orchestra-checklist-item></orchestra-checklist-item>

Add new checklist item


text:
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.camunda.bpm.engine.test.history;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.camunda.bpm.engine.history.HistoricActivityInstance;
import org.camunda.bpm.engine.history.HistoricActivityInstanceQuery;
import org.camunda.bpm.engine.history.HistoricDetail;
import org.camunda.bpm.engine.history.HistoricVariableInstance;
import org.camunda.bpm.engine.history.HistoricVariableInstanceQuery;
import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.camunda.bpm.engine.impl.history.HistoryLevel;
import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity;
import org.camunda.bpm.engine.impl.test.PluggableProcessEngineTestCase;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.engine.task.Task;
import org.camunda.bpm.engine.test.Deployment;

/**
 * @author Roman Smirnov
 *
 */
public class HistoricVariableInstanceScopeTest extends PluggableProcessEngineTestCase {

  @Deployment(resources={"org/camunda/bpm/engine/test/api/oneTaskProcess.bpmn20.xml"})
  public void testSetVariableOnProcessInstanceStart() {
    Map<String, Object> variables = new HashMap<String, Object>();
    variables.put("testVar", "testValue");
    ProcessInstance pi = runtimeService.startProcessInstanceByKey("oneTaskProcess", variables);

    HistoricVariableInstanceQuery query = historyService.createHistoricVariableInstanceQuery();
    assertEquals(1, query.count());

    HistoricVariableInstance variable = query.singleResult();
    assertNotNull(variable);

    // the variable is in the process instance scope
    assertEquals(pi.getId(), variable.getActivityInstanceId());

    taskService.complete(taskService.createTaskQuery().singleResult().getId());
    assertProcessEnded(pi.getId());
  }

  @Deployment(resources={"org/camunda/bpm/engine/test/api/oneTaskProcess.bpmn20.xml"})
  public void testSetVariableLocalOnUserTask() {
    ProcessInstance pi = runtimeService.startProcessInstanceByKey("oneTaskProcess");

    Task task = taskService.createTaskQuery().singleResult();
    assertNotNull(task);

    taskService.setVariableLocal(task.getId(), "testVar", "testValue");
    ExecutionEntity taskExecution = (ExecutionEntity) runtimeService.createExecutionQuery()
        .executionId(task.getExecutionId())
        .singleResult();
    assertNotNull(taskExecution);

    HistoricVariableInstanceQuery query = historyService.createHistoricVariableInstanceQuery();
    assertEquals(1, query.count());

    HistoricVariableInstance variable = query.singleResult();
    assertNotNull(variable);

    // the variable is in the task scope
    assertEquals(taskExecution.getActivityInstanceId(), variable.getActivityInstanceId());

    taskService.complete(task.getId());
    assertProcessEnded(pi.getId());
  }

  @Deployment(resources={"org/camunda/bpm/engine/test/api/oneTaskProcess.bpmn20.xml"})
  public void testSetVariableOnProcessIntanceStartAndSetVariableLocalOnUserTask() {
    Map<String, Object> variables = new HashMap<String, Object>();
    variables.put("testVar", "testValue");
    ProcessInstance pi = runtimeService.startProcessInstanceByKey("oneTaskProcess", variables);

    Task task = taskService.createTaskQuery().singleResult();
    assertNotNull(task);

    taskService.setVariableLocal(task.getId(), "testVar", "anotherTestValue");
    ExecutionEntity taskExecution = (ExecutionEntity) runtimeService.createExecutionQuery().singleResult();
    assertNotNull(taskExecution);

    HistoricVariableInstanceQuery query = historyService.createHistoricVariableInstanceQuery();
    assertEquals(2, query.count());

    List<HistoricVariableInstance> result = query.list();

    HistoricVariableInstance firstVar = result.get(0);
    assertEquals("testVar", firstVar.getVariableName());
    assertEquals("testValue", firstVar.getValue());
    // the variable is in the process instance scope
    assertEquals(pi.getId(), firstVar.getActivityInstanceId());

    HistoricVariableInstance secondVar = result.get(1);
    assertEquals("testVar", secondVar.getVariableName());
    assertEquals("anotherTestValue", secondVar.getValue());
    // the variable is in the task scope
    assertEquals(taskExecution.getActivityInstanceId(), secondVar.getActivityInstanceId());

    taskService.complete(task.getId());
    assertProcessEnded(pi.getId());
  }

  @Deployment(resources={"org/camunda/bpm/engine/test/api/oneSubProcess.bpmn20.xml"})
  public void testSetVariableOnUserTaskInsideSubProcess() {
    ProcessInstance pi = runtimeService.startProcessInstanceByKey("startSimpleSubProcess");

    Task task = taskService.createTaskQuery().singleResult();
    assertNotNull(task);

    taskService.setVariable(task.getId(), "testVar", "testValue");

    HistoricVariableInstanceQuery query = historyService.createHistoricVariableInstanceQuery();
    assertEquals(1, query.count());

    HistoricVariableInstance variable = query.singleResult();
    // the variable is in the process instance scope
    assertEquals(pi.getId(), variable.getActivityInstanceId());

    taskService.complete(task.getId());
    assertProcessEnded(pi.getId());
  }

  @Deployment
  public void testSetVariableOnServiceTaskInsideSubProcess() {
    ProcessInstance pi = runtimeService.startProcessInstanceByKey("process");

    HistoricVariableInstanceQuery query = historyService.createHistoricVariableInstanceQuery();
    assertEquals(1, query.count());

    HistoricVariableInstance variable = query.singleResult();
    // the variable is in the process instance scope
    assertEquals(pi.getId(), variable.getActivityInstanceId());

    assertProcessEnded(pi.getId());
  }

  @Deployment
  public void testSetVariableLocalOnServiceTaskInsideSubProcess() {
    ProcessInstance pi = runtimeService.startProcessInstanceByKey("process");

    HistoricVariableInstanceQuery query = historyService.createHistoricVariableInstanceQuery();
    assertEquals(1, query.count());

    String activityInstanceId = historyService.createHistoricActivityInstanceQuery()
        .activityId("SubProcess_1")
        .singleResult()
        .getId();

    HistoricVariableInstance variable = query.singleResult();
    // the variable is in the sub process scope
    assertEquals(activityInstanceId, variable.getActivityInstanceId());

    assertProcessEnded(pi.getId());
  }

  @Deployment
  public void testSetVariableLocalOnTaskInsideParallelBranch() {
    ProcessInstance pi = runtimeService.startProcessInstanceByKey("process");

    Task task = taskService.createTaskQuery().singleResult();
    assertNotNull(task);

    taskService.setVariableLocal(task.getId(), "testVar", "testValue");
    ExecutionEntity taskExecution = (ExecutionEntity) runtimeService.createExecutionQuery()
        .executionId(task.getExecutionId())
        .singleResult();
    assertNotNull(taskExecution);

    HistoricVariableInstanceQuery query = historyService.createHistoricVariableInstanceQuery();
    assertEquals(1, query.count());

    HistoricVariableInstance variable = query.singleResult();
    // the variable is in the user task scope
    assertEquals(taskExecution.getActivityInstanceId(), variable.getActivityInstanceId());

    taskService.complete(task.getId());

    assertProcessEnded(pi.getId());
  }

  @Deployment(resources={"org/camunda/bpm/engine/test/history/HistoricVariableInstanceScopeTest.testSetVariableLocalOnTaskInsideParallelBranch.bpmn"})
  public void testSetVariableOnTaskInsideParallelBranch() {
    ProcessInstance pi = runtimeService.startProcessInstanceByKey("process");

    Task task = taskService.createTaskQuery().singleResult();
    assertNotNull(task);

    taskService.setVariable(task.getId(), "testVar", "testValue");

    HistoricVariableInstanceQuery query = historyService.createHistoricVariableInstanceQuery();
    assertEquals(1, query.count());

    HistoricVariableInstance variable = query.singleResult();
    // the variable is in the process instance scope
    assertEquals(pi.getId(), variable.getActivityInstanceId());

    taskService.complete(task.getId());

    assertProcessEnded(pi.getId());
  }

  @Deployment
  public void testSetVariableOnServiceTaskInsideParallelBranch() {
    ProcessInstance pi = runtimeService.startProcessInstanceByKey("process");

    HistoricVariableInstanceQuery query = historyService.createHistoricVariableInstanceQuery();
    assertEquals(1, query.count());

    HistoricVariableInstance variable = query.singleResult();
    // the variable is in the process instance scope
    assertEquals(pi.getId(), variable.getActivityInstanceId());

    assertProcessEnded(pi.getId());
  }

  @Deployment
  public void testSetVariableLocalOnServiceTaskInsideParallelBranch() {
    ProcessInstance pi = runtimeService.startProcessInstanceByKey("process");

    HistoricActivityInstance serviceTask = historyService.createHistoricActivityInstanceQuery()
        .activityId("serviceTask1")
        .singleResult();
    assertNotNull(serviceTask);

    HistoricVariableInstanceQuery query = historyService.createHistoricVariableInstanceQuery();
    assertEquals(1, query.count());

    HistoricVariableInstance variable = query.singleResult();
    // the variable is in the service task scope
    assertEquals(serviceTask.getId(), variable.getActivityInstanceId());

    assertProcessEnded(pi.getId());
  }

  @Deployment(resources = {"org/camunda/bpm/engine/test/api/cmmn/oneTaskCase.cmmn"})
  public void testHistoricCaseVariableInstanceQuery() {
    // start case instance with variables
    Map<String, Object> variables = new HashMap<String, Object>();
    variables.put("foo", "bar");
    String caseInstanceId =  caseService.createCaseInstanceByKey("oneTaskCase", variables).getId();

    String caseExecutionId = caseService.createCaseExecutionQuery().activityId("CasePlanModel_1").singleResult().getId();
    String taskExecutionId = caseService.createCaseExecutionQuery().activityId("PI_HumanTask_1").singleResult().getId();

    // set variable on both executions
    caseService.setVariableLocal(caseExecutionId, "case", "execution");
    caseService.setVariableLocal(taskExecutionId, "task", "execution");

    // update variable on both executions
    caseService.setVariableLocal(caseExecutionId, "case", "update");
    caseService.setVariableLocal(taskExecutionId, "task", "update");

    assertEquals(3, historyService.createHistoricVariableInstanceQuery().count());
    assertEquals(3, historyService.createHistoricVariableInstanceQuery().caseInstanceId(caseInstanceId).count());
    assertEquals(3, historyService.createHistoricVariableInstanceQuery().caseExecutionIdIn(caseExecutionId, taskExecutionId).count());
    assertEquals(2, historyService.createHistoricVariableInstanceQuery().caseExecutionIdIn(caseExecutionId).count());
    assertEquals(1, historyService.createHistoricVariableInstanceQuery().caseExecutionIdIn(taskExecutionId).count());

    HistoryLevel historyLevel = processEngineConfiguration.getHistoryLevel();
    if (historyLevel.equals(HistoryLevel.HISTORY_LEVEL_FULL)) {
      assertEquals(5, historyService.createHistoricDetailQuery().count());
      assertEquals(5, historyService.createHistoricDetailQuery().caseInstanceId(caseInstanceId).count());
      assertEquals(3, historyService.createHistoricDetailQuery().caseExecutionId(caseExecutionId).count());
      assertEquals(2, historyService.createHistoricDetailQuery().caseExecutionId(taskExecutionId).count());
    }
  }

  @Deployment
  public void testInputMappings() {
    // given
    String processInstanceId = runtimeService.startProcessInstanceByKey("process").getId();

    HistoricActivityInstanceQuery activityInstanceQuery = historyService
        .createHistoricActivityInstanceQuery()
        .processInstanceId(processInstanceId);

    String theService1Id = activityInstanceQuery.activityId("theService1").singleResult().getId();
    String theService2Id = activityInstanceQuery.activityId("theService2").singleResult().getId();
    String theTaskId = activityInstanceQuery.activityId("theTask").singleResult().getId();

    // when (1)
    HistoricVariableInstance firstVariable = historyService
      .createHistoricVariableInstanceQuery()
      .variableName("firstInputVariable")
      .singleResult();

    // then (1)
    assertEquals(theService1Id, firstVariable.getActivityInstanceId());

    if(processEngineConfiguration.getHistoryLevel().getId() > ProcessEngineConfigurationImpl.HISTORYLEVEL_AUDIT) {
      HistoricDetail firstVariableDetail = historyService
        .createHistoricDetailQuery()
        .variableUpdates()
        .variableInstanceId(firstVariable.getId())
        .singleResult();
      assertEquals(theService1Id, firstVariableDetail.getActivityInstanceId());
    }

    // when (2)
    HistoricVariableInstance secondVariable = historyService
      .createHistoricVariableInstanceQuery()
      .variableName("secondInputVariable")
      .singleResult();

    // then (2)
    assertEquals(theService2Id, secondVariable.getActivityInstanceId());

    if(processEngineConfiguration.getHistoryLevel().getId() > ProcessEngineConfigurationImpl.HISTORYLEVEL_AUDIT) {
      HistoricDetail secondVariableDetail = historyService
        .createHistoricDetailQuery()
        .variableUpdates()
        .variableInstanceId(secondVariable.getId())
        .singleResult();
      assertEquals(theService2Id, secondVariableDetail.getActivityInstanceId());
    }

    // when (3)
    HistoricVariableInstance thirdVariable = historyService
      .createHistoricVariableInstanceQuery()
      .variableName("thirdInputVariable")
      .singleResult();

    // then (3)
    assertEquals(theTaskId, thirdVariable.getActivityInstanceId());

    if(processEngineConfiguration.getHistoryLevel().getId() > ProcessEngineConfigurationImpl.HISTORYLEVEL_AUDIT) {
      HistoricDetail thirdVariableDetail = historyService
        .createHistoricDetailQuery()
        .variableUpdates()
        .variableInstanceId(thirdVariable.getId())
        .singleResult();
      assertEquals(theTaskId, thirdVariableDetail.getActivityInstanceId());
    }
  }
}


text:
<link rel="import" href="bower_components/paper-styles/paper-styles-classes.html">
<link rel="import" href="bower_components/paper-styles/paper-styles.html">

<link rel="import" href="bower_components/web-animations-js/web-animations-next-lite.min.html">

<link rel="import" href="bower_components/iron-flex-layout/iron-flex-layout-classes.html">

<link rel="import" href="bower_components/iron-icons/iron-icons.html">
<link rel="import" href="bower_components/iron-icons/av-icons.html">
<link rel="import" href="bower_components/iron-icons/notification-icons.html">

<link rel="import" href="bower_components/app-layout/app-layout.html">
<link rel="import" href="bower_components/app-layout/app-scroll-effects/app-scroll-effects.html">

<link rel="import" href="bower_components/paper-menu-button/paper-menu-button.html">
<link rel="import" href="bower_components/paper-button/paper-button.html">
<link rel="import" href="bower_components/paper-checkbox/paper-checkbox.html">
<link rel="import" href="bower_components/paper-item/all-imports.html">
<link rel="import" href="bower_components/paper-toggle-button/paper-toggle-button.html">
<link rel="import" href="bower_components/paper-icon-button/paper-icon-button.html">
<link rel="import" href="bower_components/paper-fab/paper-fab.html">
<link rel="import" href="bower_components/paper-listbox/paper-listbox.html">

<link rel="import" href="bower_components/polymerfire/polymerfire.html">

<dom-module id="shared-styles">

    <template>

    </template>
</dom-module>

<custom-style>

</custom-style>


text:
// Copyright (c) 2019-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#ifndef BITCOIN_WALLET_SCRIPTPUBKEYMAN_H
#define BITCOIN_WALLET_SCRIPTPUBKEYMAN_H

#include <psbt.h>
#include <script/signingprovider.h>
#include <script/standard.h>
#include <util/error.h>
#include <util/message.h>
#include <wallet/crypter.h>
#include <wallet/ismine.h>
#include <wallet/walletdb.h>
#include <wallet/walletutil.h>

#include <boost/signals2/signal.hpp>

enum class OutputType;

// Wallet storage things that ScriptPubKeyMans need in order to be able to store things to the wallet database.
// It provides access to things that are part of the entire wallet and not specific to a ScriptPubKeyMan such as
// wallet flags, wallet version, encryption keys, encryption status, and the database itself. This allows a
// ScriptPubKeyMan to have callbacks into CWallet without causing a circular dependency.
// WalletStorage should be the same for all ScriptPubKeyMans of a wallet.
class WalletStorage
{
public:
    virtual ~WalletStorage() = default;
    virtual const std::string GetDisplayName() const = 0;
    virtual WalletDatabase& GetDatabase() = 0;
    virtual bool IsWalletFlagSet(uint64_t) const = 0;
    virtual void UnsetBlankWalletFlag(WalletBatch&) = 0;
    virtual bool CanSupportFeature(enum WalletFeature) const = 0;
    virtual void SetMinVersion(enum WalletFeature, WalletBatch* = nullptr, bool = false) = 0;
    virtual const CKeyingMaterial& GetEncryptionKey() const = 0;
    virtual bool HasEncryptionKeys() const = 0;
    virtual bool IsLocked() const = 0;
};

//! Default for -keypool
static const unsigned int DEFAULT_KEYPOOL_SIZE = 1000;

std::vector<CKeyID> GetAffectedKeys(const CScript& spk, const SigningProvider& provider);

/** A key from a CWallet's keypool
 *
 * The wallet holds one (for pre HD-split wallets) or several keypools. These
 * are sets of keys that have not yet been used to provide addresses or receive
 * change.
 *
 * The Bitcoin Core wallet was originally a collection of unrelated private
 * keys with their associated addresses. If a non-HD wallet generated a
 * key/address, gave that address out and then restored a backup from before
 * that key's generation, then any funds sent to that address would be
 * lost definitively.
 *
 * The keypool was implemented to avoid this scenario (commit: 10384941). The
 * wallet would generate a set of keys (100 by default). When a new public key
 * was required, either to give out as an address or to use in a change output,
 * it would be drawn from the keypool. The keypool would then be topped up to
 * maintain 100 keys. This ensured that as long as the wallet hadn't used more
 * than 100 keys since the previous backup, all funds would be safe, since a
 * restored wallet would be able to scan for all owned addresses.
 *
 * A keypool also allowed encrypted wallets to give out addresses without
 * having to be decrypted to generate a new private key.
 *
 * With the introduction of HD wallets (commit: f1902510), the keypool
 * essentially became an address look-ahead pool. Restoring old backups can no
 * longer definitively lose funds as long as the addresses used were from the
 * wallet's HD seed (since all private keys can be rederived from the seed).
 * However, if many addresses were used since the backup, then the wallet may
 * not know how far ahead in the HD chain to look for its addresses. The
 * keypool is used to implement a 'gap limit'. The keypool maintains a set of
 * keys (by default 1000) ahead of the last used key and scans for the
 * addresses of those keys.  This avoids the risk of not seeing transactions
 * involving the wallet's addresses, or of re-using the same address.
 * In the unlikely case where none of the addresses in the `gap limit` are
 * used on-chain, the look-ahead will not be incremented to keep
 * a constant size and addresses beyond this range will not be detected by an
 * old backup. For this reason, it is not recommended to decrease keypool size
 * lower than default value.
 *
 * The HD-split wallet feature added a second keypool (commit: 02592f4c). There
 * is an external keypool (for addresses to hand out) and an internal keypool
 * (for change addresses).
 *
 * Keypool keys are stored in the wallet/keystore's keymap. The keypool data is
 * stored as sets of indexes in the wallet (setInternalKeyPool,
 * setExternalKeyPool and set_pre_split_keypool), and a map from the key to the
 * index (m_pool_key_to_index). The CKeyPool object is used to
 * serialize/deserialize the pool data to/from the database.
 */
class CKeyPool
{
public:
    //! The time at which the key was generated. Set in AddKeypoolPubKeyWithDB
    int64_t nTime;
    //! The public key
    CPubKey vchPubKey;
    //! Whether this keypool entry is in the internal keypool (for change outputs)
    bool fInternal;
    //! Whether this key was generated for a keypool before the wallet was upgraded to HD-split
    bool m_pre_split;

    CKeyPool();
    CKeyPool(const CPubKey& vchPubKeyIn, bool internalIn);

    ADD_SERIALIZE_METHODS;

    template <typename Stream, typename Operation>
    inline void SerializationOp(Stream& s, Operation ser_action) {
        int nVersion = s.GetVersion();
        if (!(s.GetType() & SER_GETHASH))
            READWRITE(nVersion);
        READWRITE(nTime);
        READWRITE(vchPubKey);
        if (ser_action.ForRead()) {
            try {
                READWRITE(fInternal);
            }
            catch (std::ios_base::failure&) {
                /* flag as external address if we can't read the internal boolean
                   (this will be the case for any wallet before the HD chain split version) */
                fInternal = false;
            }
            try {
                READWRITE(m_pre_split);
            }
            catch (std::ios_base::failure&) {
                /* flag as postsplit address if we can't read the m_pre_split boolean
                   (this will be the case for any wallet that upgrades to HD chain split)*/
                m_pre_split = false;
            }
        }
        else {
            READWRITE(fInternal);
            READWRITE(m_pre_split);
        }
    }
};

/*
 * A class implementing ScriptPubKeyMan manages some (or all) scriptPubKeys used in a wallet.
 * It contains the scripts and keys related to the scriptPubKeys it manages.
 * A ScriptPubKeyMan will be able to give out scriptPubKeys to be used, as well as marking
 * when a scriptPubKey has been used. It also handles when and how to store a scriptPubKey
 * and its related scripts and keys, including encryption.
 */
class ScriptPubKeyMan
{
protected:
    WalletStorage& m_storage;

public:
    ScriptPubKeyMan(WalletStorage& storage) : m_storage(storage) {}
    virtual ~ScriptPubKeyMan() {};
    virtual bool GetNewDestination(const OutputType type, CTxDestination& dest, std::string& error) { return false; }
    virtual isminetype IsMine(const CScript& script) const { return ISMINE_NO; }

    //! Check that the given decryption key is valid for this ScriptPubKeyMan, i.e. it decrypts all of the keys handled by it.
    virtual bool CheckDecryptionKey(const CKeyingMaterial& master_key, bool accept_no_keys = false) { return false; }
    virtual bool Encrypt(const CKeyingMaterial& master_key, WalletBatch* batch) { return false; }

    virtual bool GetReservedDestination(const OutputType type, bool internal, CTxDestination& address, int64_t& index, CKeyPool& keypool) { return false; }
    virtual void KeepDestination(int64_t index, const OutputType& type) {}
    virtual void ReturnDestination(int64_t index, bool internal, const CTxDestination& addr) {}

    /** Fills internal address pool. Use within ScriptPubKeyMan implementations should be used sparingly and only
      * when something from the address pool is removed, excluding GetNewDestination and GetReservedDestination.
      * External wallet code is primarily responsible for topping up prior to fetching new addresses
      */
    virtual bool TopUp(unsigned int size = 0) { return false; }

    //! Mark unused addresses as being used
    virtual void MarkUnusedAddresses(const CScript& script) {}

    /** Sets up the key generation stuff, i.e. generates new HD seeds and sets them as active.
      * Returns false if already setup or setup fails, true if setup is successful
      * Set force=true to make it re-setup if already setup, used for upgrades
      */
    virtual bool SetupGeneration(bool force = false) { return false; }

    /* Returns true if HD is enabled */
    virtual bool IsHDEnabled() const { return false; }

    /* Returns true if the wallet can give out new addresses. This means it has keys in the keypool or can generate new keys */
    virtual bool CanGetAddresses(bool internal = false) const { return false; }

    /** Upgrades the wallet to the specified version */
    virtual bool Upgrade(int prev_version, std::string& error) { return false; }

    virtual bool HavePrivateKeys() const { return false; }

    //! The action to do when the DB needs rewrite
    virtual void RewriteDB() {}

    virtual int64_t GetOldestKeyPoolTime() const { return GetTime(); }

    virtual size_t KeypoolCountExternalKeys() const { return 0; }
    virtual unsigned int GetKeyPoolSize() const { return 0; }

    virtual int64_t GetTimeFirstKey() const { return 0; }

    virtual const CKeyMetadata* GetMetadata(const CTxDestination& dest) const { return nullptr; }

    virtual std::unique_ptr<SigningProvider> GetSolvingProvider(const CScript& script) const { return nullptr; }

    /** Whether this ScriptPubKeyMan can provide a SigningProvider (via GetSolvingProvider) that, combined with
      * sigdata, can produce solving data.
      */
    virtual bool CanProvide(const CScript& script, SignatureData& sigdata) { return false; }

    /** Creates new signatures and adds them to the transaction. Returns whether all inputs were signed */
    virtual bool SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, std::string>& input_errors) const { return false; }
    /** Sign a message with the given script */
    virtual SigningResult SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const { return SigningResult::SIGNING_FAILED; };
    /** Adds script and derivation path information to a PSBT, and optionally signs it. */
    virtual TransactionError FillPSBT(PartiallySignedTransaction& psbt, int sighash_type = 1 /* SIGHASH_ALL */, bool sign = true, bool bip32derivs = false) const { return TransactionError::INVALID_PSBT; }

    virtual uint256 GetID() const { return uint256(); }

    /** Prepends the wallet name in logging output to ease debugging in multi-wallet use cases */
    template<typename... Params>
    void WalletLogPrintf(std::string fmt, Params... parameters) const {
        LogPrintf(("%s " + fmt).c_str(), m_storage.GetDisplayName(), parameters...);
    };

    /** Watch-only address added */
    boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;

    /** Keypool has new keys */
    boost::signals2::signal<void ()> NotifyCanGetAddressesChanged;
};

class LegacyScriptPubKeyMan : public ScriptPubKeyMan, public FillableSigningProvider
{
private:
    //! keeps track of whether Unlock has run a thorough check before
    bool fDecryptionThoroughlyChecked = false;

    using WatchOnlySet = std::set<CScript>;
    using WatchKeyMap = std::map<CKeyID, CPubKey>;

    WalletBatch *encrypted_batch GUARDED_BY(cs_KeyStore) = nullptr;

    using CryptedKeyMap = std::map<CKeyID, std::pair<CPubKey, std::vector<unsigned char>>>;

    CryptedKeyMap mapCryptedKeys GUARDED_BY(cs_KeyStore);
    WatchOnlySet setWatchOnly GUARDED_BY(cs_KeyStore);
    WatchKeyMap mapWatchKeys GUARDED_BY(cs_KeyStore);

    int64_t nTimeFirstKey GUARDED_BY(cs_KeyStore) = 0;

    bool AddKeyPubKeyInner(const CKey& key, const CPubKey &pubkey);
    bool AddCryptedKeyInner(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);

    /**
     * Private version of AddWatchOnly method which does not accept a
     * timestamp, and which will reset the wallet's nTimeFirstKey value to 1 if
     * the watch key did not previously have a timestamp associated with it.
     * Because this is an inherited virtual method, it is accessible despite
     * being marked private, but it is marked private anyway to encourage use
     * of the other AddWatchOnly which accepts a timestamp and sets
     * nTimeFirstKey more intelligently for more efficient rescans.
     */
    bool AddWatchOnly(const CScript& dest) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
    bool AddWatchOnlyWithDB(WalletBatch &batch, const CScript& dest) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
    bool AddWatchOnlyInMem(const CScript &dest);
    //! Adds a watch-only address to the store, and saves it to disk.
    bool AddWatchOnlyWithDB(WalletBatch &batch, const CScript& dest, int64_t create_time) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);

    //! Adds a key to the store, and saves it to disk.
    bool AddKeyPubKeyWithDB(WalletBatch &batch,const CKey& key, const CPubKey &pubkey) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);

    void AddKeypoolPubkeyWithDB(const CPubKey& pubkey, const bool internal, WalletBatch& batch);

    //! Adds a script to the store and saves it to disk
    bool AddCScriptWithDB(WalletBatch& batch, const CScript& script);

    /** Add a KeyOriginInfo to the wallet */
    bool AddKeyOriginWithDB(WalletBatch& batch, const CPubKey& pubkey, const KeyOriginInfo& info);

    /* the HD chain data model (external chain counters) */
    CHDChain hdChain;

    /* HD derive new child key (on internal or external chain) */
    void DeriveNewChildKey(WalletBatch& batch, CKeyMetadata& metadata, CKey& secret, bool internal = false) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);

    std::set<int64_t> setInternalKeyPool GUARDED_BY(cs_KeyStore);
    std::set<int64_t> setExternalKeyPool GUARDED_BY(cs_KeyStore);
    std::set<int64_t> set_pre_split_keypool GUARDED_BY(cs_KeyStore);
    int64_t m_max_keypool_index GUARDED_BY(cs_KeyStore) = 0;
    std::map<CKeyID, int64_t> m_pool_key_to_index;
    // Tracks keypool indexes to CKeyIDs of keys that have been taken out of the keypool but may be returned to it
    std::map<int64_t, CKeyID> m_index_to_reserved_key;

    //! Fetches a key from the keypool
    bool GetKeyFromPool(CPubKey &key, const OutputType type, bool internal = false);

    /**
     * Reserves a key from the keypool and sets nIndex to its index
     *
     * @param[out] nIndex the index of the key in keypool
     * @param[out] keypool the keypool the key was drawn from, which could be the
     *     the pre-split pool if present, or the internal or external pool
     * @param fRequestedInternal true if the caller would like the key drawn
     *     from the internal keypool, false if external is preferred
     *
     * @return true if succeeded, false if failed due to empty keypool
     * @throws std::runtime_error if keypool read failed, key was invalid,
     *     was not found in the wallet, or was misclassified in the internal
     *     or external keypool
     */
    bool ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fRequestedInternal);

public:
    using ScriptPubKeyMan::ScriptPubKeyMan;

    bool GetNewDestination(const OutputType type, CTxDestination& dest, std::string& error) override;
    isminetype IsMine(const CScript& script) const override;

    bool CheckDecryptionKey(const CKeyingMaterial& master_key, bool accept_no_keys = false) override;
    bool Encrypt(const CKeyingMaterial& master_key, WalletBatch* batch) override;

    bool GetReservedDestination(const OutputType type, bool internal, CTxDestination& address, int64_t& index, CKeyPool& keypool) override;
    void KeepDestination(int64_t index, const OutputType& type) override;
    void ReturnDestination(int64_t index, bool internal, const CTxDestination&) override;

    bool TopUp(unsigned int size = 0) override;

    void MarkUnusedAddresses(const CScript& script) override;

    //! Upgrade stored CKeyMetadata objects to store key origin info as KeyOriginInfo
    void UpgradeKeyMetadata();

    bool IsHDEnabled() const override;

    bool SetupGeneration(bool force = false) override;

    bool Upgrade(int prev_version, std::string& error) override;

    bool HavePrivateKeys() const override;

    void RewriteDB() override;

    int64_t GetOldestKeyPoolTime() const override;
    size_t KeypoolCountExternalKeys() const override;
    unsigned int GetKeyPoolSize() const override;

    int64_t GetTimeFirstKey() const override;

    const CKeyMetadata* GetMetadata(const CTxDestination& dest) const override;

    bool CanGetAddresses(bool internal = false) const override;

    std::unique_ptr<SigningProvider> GetSolvingProvider(const CScript& script) const override;

    bool CanProvide(const CScript& script, SignatureData& sigdata) override;

    bool SignTransaction(CMutableTransaction& tx, const std::map<COutPoint, Coin>& coins, int sighash, std::map<int, std::string>& input_errors) const override;
    SigningResult SignMessage(const std::string& message, const PKHash& pkhash, std::string& str_sig) const override;
    TransactionError FillPSBT(PartiallySignedTransaction& psbt, int sighash_type = 1 /* SIGHASH_ALL */, bool sign = true, bool bip32derivs = false) const override;

    uint256 GetID() const override;

    // Map from Key ID to key metadata.
    std::map<CKeyID, CKeyMetadata> mapKeyMetadata GUARDED_BY(cs_KeyStore);

    // Map from Script ID to key metadata (for watch-only keys).
    std::map<CScriptID, CKeyMetadata> m_script_metadata GUARDED_BY(cs_KeyStore);

    //! Adds a key to the store, and saves it to disk.
    bool AddKeyPubKey(const CKey& key, const CPubKey &pubkey) override;
    //! Adds a key to the store, without saving it to disk (used by LoadWallet)
    bool LoadKey(const CKey& key, const CPubKey &pubkey);
    //! Adds an encrypted key to the store, and saves it to disk.
    bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
    //! Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
    bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
    void UpdateTimeFirstKey(int64_t nCreateTime) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
    //! Adds a CScript to the store
    bool LoadCScript(const CScript& redeemScript);
    //! Load metadata (used by LoadWallet)
    void LoadKeyMetadata(const CKeyID& keyID, const CKeyMetadata &metadata);
    void LoadScriptMetadata(const CScriptID& script_id, const CKeyMetadata &metadata);
    //! Generate a new key
    CPubKey GenerateNewKey(WalletBatch& batch, bool internal = false) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);

    /* Set the HD chain model (chain child index counters) */
    void SetHDChain(const CHDChain& chain, bool memonly);
    const CHDChain& GetHDChain() const { return hdChain; }

    //! Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
    bool LoadWatchOnly(const CScript &dest);
    //! Returns whether the watch-only script is in the wallet
    bool HaveWatchOnly(const CScript &dest) const;
    //! Returns whether there are any watch-only things in the wallet
    bool HaveWatchOnly() const;
    //! Remove a watch only script from the keystore
    bool RemoveWatchOnly(const CScript &dest);
    bool AddWatchOnly(const CScript& dest, int64_t nCreateTime) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);

    //! Fetches a pubkey from mapWatchKeys if it exists there
    bool GetWatchPubKey(const CKeyID &address, CPubKey &pubkey_out) const;

    /* SigningProvider overrides */
    bool HaveKey(const CKeyID &address) const override;
    bool GetKey(const CKeyID &address, CKey& keyOut) const override;
    bool GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const override;
    bool AddCScript(const CScript& redeemScript) override;
    bool GetKeyOrigin(const CKeyID& keyid, KeyOriginInfo& info) const override;

    //! Load a keypool entry
    void LoadKeyPool(int64_t nIndex, const CKeyPool &keypool);
    bool NewKeyPool();
    void MarkPreSplitKeys() EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);

    bool ImportScripts(const std::set<CScript> scripts, int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
    bool ImportPrivKeys(const std::map<CKeyID, CKey>& privkey_map, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
    bool ImportPubKeys(const std::vector<CKeyID>& ordered_pubkeys, const std::map<CKeyID, CPubKey>& pubkey_map, const std::map<CKeyID, std::pair<CPubKey, KeyOriginInfo>>& key_origins, const bool add_keypool, const bool internal, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
    bool ImportScriptPubKeys(const std::set<CScript>& script_pub_keys, const bool have_solving_data, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);

    /* Returns true if the wallet can generate new keys */
    bool CanGenerateKeys() const;

    /* Generates a new HD seed (will not be activated) */
    CPubKey GenerateNewSeed();

    /* Derives a new HD seed (will not be activated) */
    CPubKey DeriveNewSeed(const CKey& key);

    /* Set the current HD seed (will reset the chain child index counters)
       Sets the seed's version based on the current wallet version (so the
       caller must ensure the current wallet version is correct before calling
       this function). */
    void SetHDSeed(const CPubKey& key);

    /**
     * Explicitly make the wallet learn the related scripts for outputs to the
     * given key. This is purely to make the wallet file compatible with older
     * software, as FillableSigningProvider automatically does this implicitly for all
     * keys now.
     */
    void LearnRelatedScripts(const CPubKey& key, OutputType);

    /**
     * Same as LearnRelatedScripts, but when the OutputType is not known (and could
     * be anything).
     */
    void LearnAllRelatedScripts(const CPubKey& key);

    /**
     * Marks all keys in the keypool up to and including reserve_key as used.
     */
    void MarkReserveKeysAsUsed(int64_t keypool_id) EXCLUSIVE_LOCKS_REQUIRED(cs_KeyStore);
    const std::map<CKeyID, int64_t>& GetAllReserveKeys() const { return m_pool_key_to_index; }

    std::set<CKeyID> GetKeys() const override;
};

/** Wraps a LegacyScriptPubKeyMan so that it can be returned in a new unique_ptr. Does not provide privkeys */
class LegacySigningProvider : public SigningProvider
{
private:
    const LegacyScriptPubKeyMan& m_spk_man;
public:
    LegacySigningProvider(const LegacyScriptPubKeyMan& spk_man) : m_spk_man(spk_man) {}

    bool GetCScript(const CScriptID &scriptid, CScript& script) const override { return m_spk_man.GetCScript(scriptid, script); }
    bool HaveCScript(const CScriptID &scriptid) const override { return m_spk_man.HaveCScript(scriptid); }
    bool GetPubKey(const CKeyID &address, CPubKey& pubkey) const override { return m_spk_man.GetPubKey(address, pubkey); }
    bool GetKey(const CKeyID &address, CKey& key) const override { return false; }
    bool HaveKey(const CKeyID &address) const override { return false; }
    bool GetKeyOrigin(const CKeyID& keyid, KeyOriginInfo& info) const override { return m_spk_man.GetKeyOrigin(keyid, info); }
};

#endif // BITCOIN_WALLET_SCRIPTPUBKEYMAN_H