/*
Copyright (c) 2009-2020 Roger Light <roger@atchoo.org>

All rights reserved. This program and the accompanying materials
are made available under the terms of the Eclipse Public License v1.0
and Eclipse Distribution License v1.0 which accompany this distribution.

The Eclipse Public License is available at
   http://www.eclipse.org/legal/epl-v10.html
and the Eclipse Distribution License is available at
  http://www.eclipse.org/org/documents/edl-v10.php.

Contributors:
   Roger Light - initial implementation and documentation.
*/

#include "config.h"

#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#ifndef WIN32
#include <unistd.h>
#include <signal.h>
#else
#include <process.h>
#include <winsock2.h>
#define snprintf sprintf_s
#endif

#include <mosquitto.h>
#include <mqtt_protocol.h>
#include "client_shared.h"

struct mosq_config cfg;
bool process_messages = true;
int msg_count = 0;
struct mosquitto *mosq = NULL;
int last_mid = 0;
static int connack_result = 0;

#ifndef WIN32
void my_signal_handler(int signum)
{
	if(signum == SIGALRM || signum == SIGTERM || signum == SIGINT){
		process_messages = false;
		mosquitto_disconnect_v5(mosq, MQTT_RC_DISCONNECT_WITH_WILL_MSG, cfg.disconnect_props);
	}
}
#endif

void print_message(struct mosq_config *cfg, const struct mosquitto_message *message);

void my_publish_callback(struct mosquitto *mosq, void *obj, int mid, int reason_code, const mosquitto_property *properties)
{
	UNUSED(obj);
	UNUSED(reason_code);
	UNUSED(properties);

	if(process_messages == false && (mid == last_mid || last_mid == 0)){
		mosquitto_disconnect_v5(mosq, 0, cfg.disconnect_props);
	}
}

void my_message_callback(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message, const mosquitto_property *properties)
{
	int i;
	bool res;

	UNUSED(obj);
	UNUSED(properties);

	if(process_messages == false) return;

	if(cfg.retained_only && !message->retain && process_messages){
		process_messages = false;
		if(last_mid == 0){
			mosquitto_disconnect_v5(mosq, 0, cfg.disconnect_props);
		}
		return;
	}

	if(message->retain && cfg.no_retain) return;
	if(cfg.filter_outs){
		for(i=0; i<cfg.filter_out_count; i++){
			mosquitto_topic_matches_sub(cfg.filter_outs[i], message->topic, &res);
			if(res) return;
		}
	}

	if(cfg.remove_retained && message->retain){
		mosquitto_publish(mosq, &last_mid, message->topic, 0, NULL, 1, true);
	}

	print_message(&cfg, message);

	if(cfg.msg_count>0){
		msg_count++;
		if(cfg.msg_count == msg_count){
			process_messages = false;
			if(last_mid == 0){
				mosquitto_disconnect_v5(mosq, 0, cfg.disconnect_props);
			}
		}
	}
}

void my_connect_callback(struct mosquitto *mosq, void *obj, int result, int flags, const mosquitto_property *properties)
{
	int i;

	UNUSED(obj);
	UNUSED(flags);
	UNUSED(properties);

	connack_result = result;
	if(!result){
		mosquitto_subscribe_multiple(mosq, NULL, cfg.topic_count, cfg.topics, cfg.qos, cfg.sub_opts, cfg.subscribe_props);

		for(i=0; i<cfg.unsub_topic_count; i++){
			mosquitto_unsubscribe_v5(mosq, NULL, cfg.unsub_topics[i], cfg.unsubscribe_props);
		}
	}else{
		if(result){
			if(cfg.protocol_version == MQTT_PROTOCOL_V5){
				if(result == MQTT_RC_UNSUPPORTED_PROTOCOL_VERSION){
					err_printf(&cfg, "Connection error: %s. Try connecting to an MQTT v5 broker, or use MQTT v3.x mode.\n", mosquitto_reason_string(result));
				}else{
					err_printf(&cfg, "Connection error: %s\n", mosquitto_reason_string(result));
				}
			}else{
				err_printf(&cfg, "Connection error: %s\n", mosquitto_connack_string(result));
			}
		}
		mosquitto_disconnect_v5(mosq, 0, cfg.disconnect_props);
	}
}

void my_subscribe_callback(struct mosquitto *mosq, void *obj, int mid, int qos_count, const int *granted_qos)
{
	int i;

	UNUSED(obj);

	if(cfg.debug){
		if(!cfg.quiet) printf("Subscribed (mid: %d): %d", mid, granted_qos[0]);
		for(i=1; i<qos_count; i++){
			if(!cfg.quiet) printf(", %d", granted_qos[i]);
		}
		if(!cfg.quiet) printf("\n");
	}

	if(cfg.exit_after_sub){
		mosquitto_disconnect_v5(mosq, 0, cfg.disconnect_props);
	}
}

void my_log_callback(struct mosquitto *mosq, void *obj, int level, const char *str)
{
	UNUSED(mosq);
	UNUSED(obj);
	UNUSED(level);

	printf("%s\n", str);
}

void print_usage(void)
{
	int major, minor, revision;

	mosquitto_lib_version(&major, &minor, &revision);
	printf("mosquitto_sub is a simple mqtt client that will subscribe to a set of topics and print all messages it receives.\n");
	printf("mosquitto_sub version %s running on libmosquitto %d.%d.%d.\n\n", VERSION, major, minor, revision);
	printf("Usage: mosquitto_sub {[-h host] [-p port] [-u username] [-P password] -t topic | -L URL [-t topic]}\n");
	printf("                     [-c] [-k keepalive] [-q qos]\n");
	printf("                     [-C msg_count] [-E] [-R] [--retained-only] [--remove-retained] [-T filter_out] [-U topic ...]\n");
	printf("                     [-F format]\n");
#ifndef WIN32
	printf("                     [-W timeout_secs]\n");
#endif
#ifdef WITH_SRV
	printf("                     [-A bind_address] [-S]\n");
#else
	printf("                     [-A bind_address]\n");
#endif
	printf("                     [-i id] [-I id_prefix]\n");
	printf("                     [-d] [-N] [--quiet] [-v]\n");
	printf("                     [--will-topic [--will-payload payload] [--will-qos qos] [--will-retain]]\n");
#ifdef WITH_TLS
	printf("                     [{--cafile file | --capath dir} [--cert file] [--key file]\n");
	printf("                       [--ciphers ciphers] [--insecure]\n");
	printf("                       [--tls-alpn protocol]\n");
	printf("                       [--tls-engine engine] [--keyform keyform] [--tls-engine-kpass-sha1]]\n");
#ifdef FINAL_WITH_TLS_PSK
	printf("                     [--psk hex-key --psk-identity identity [--ciphers ciphers]]\n");
#endif
#endif
#ifdef WITH_SOCKS
	printf("                     [--proxy socks-url]\n");
#endif
	printf("                     [-D command identifier value]\n");
	printf("       mosquitto_sub --help\n\n");
	printf(" -A : bind the outgoing socket to this host/ip address. Use to control which interface\n");
	printf("      the client communicates over.\n");
	printf(" -c : disable 'clean session' (store subscription and pending messages when client disconnects).\n");
	printf(" -C : disconnect and exit after receiving the 'msg_count' messages.\n");
	printf(" -d : enable debug messages.\n");
	printf(" -D : Define MQTT v5 properties. See the documentation for more details.\n");
	printf(" -E : Exit once all subscriptions have been acknowledged by the broker.\n");
	printf(" -F : output format.\n");
	printf(" -h : mqtt host to connect to. Defaults to localhost.\n");
	printf(" -i : id to use for this client. Defaults to mosquitto_sub_ appended with the process id.\n");
	printf(" -I : define the client id as id_prefix appended with the process id. Useful for when the\n");
	printf("      broker is using the clientid_prefixes option.\n");
	printf(" -k : keep alive in seconds for this client. Defaults to 60.\n");
	printf(" -L : specify user, password, hostname, port and topic as a URL in the form:\n");
	printf("      mqtt(s)://[username[:password]@]host[:port]/topic\n");
	printf(" -N : do not add an end of line character when printing the payload.\n");
	printf(" -p : network port to connect to. Defaults to 1883 for plain MQTT and 8883 for MQTT over TLS.\n");
	printf(" -P : provide a password\n");
	printf(" -q : quality of service level to use for the subscription. Defaults to 0.\n");
	printf(" -R : do not print stale messages (those with retain set).\n");
#ifdef WITH_SRV
	printf(" -S : use SRV lookups to determine which host to connect to.\n");
#endif
	printf(" -t : mqtt topic to subscribe to. May be repeated multiple times.\n");
	printf(" -T : topic string to filter out of results. May be repeated.\n");
	printf(" -u : provide a username\n");
	printf(" -U : unsubscribe from a topic. May be repeated.\n");
	printf(" -v : print published messages verbosely.\n");
	printf(" -V : specify the version of the MQTT protocol to use when connecting.\n");
	printf("      Can be mqttv5, mqttv311 or mqttv31. Defaults to mqttv311.\n");
#ifndef WIN32
	printf(" -W : Specifies a timeout in seconds how long to process incoming MQTT messages.\n");
#endif
	printf(" --help : display this message.\n");
	printf(" --quiet : don't print error messages.\n");
	printf(" --retained-only : only handle messages with the retained flag set, and exit when the\n");
	printf("                   first non-retained message is received.\n");
	printf(" --remove-retained : send a message to the server to clear any received retained messages\n");
	printf("                     Use -T to filter out messages you do not want to be cleared.\n");
	printf(" --will-payload : payload for the client Will, which is sent by the broker in case of\n");
	printf("                  unexpected disconnection. If not given and will-topic is set, a zero\n");
	printf("                  length message will be sent.\n");
	printf(" --will-qos : QoS level for the client Will.\n");
	printf(" --will-retain : if given, make the client Will retained.\n");
	printf(" --will-topic : the topic on which to publish the client Will.\n");
#ifdef WITH_TLS
	printf(" --cafile : path to a file containing trusted CA certificates to enable encrypted\n");
	printf("            certificate based communication.\n");
	printf(" --capath : path to a directory containing trusted CA certificates to enable encrypted\n");
	printf("            communication.\n");
	printf(" --cert : client certificate for authentication, if required by server.\n");
	printf(" --key : client private key for authentication, if required by server.\n");
	printf(" --keyform : keyfile type, can be either \"pem\" or \"engine\".\n");
	printf(" --ciphers : openssl compatible list of TLS ciphers to support.\n");
	printf(" --tls-version : TLS protocol version, can be one of tlsv1.3 tlsv1.2 or tlsv1.1.\n");
	printf("                 Defaults to tlsv1.2 if available.\n");
	printf(" --insecure : do not check that the server certificate hostname matches the remote\n");
	printf("              hostname. Using this option means that you cannot be sure that the\n");
	printf("              remote host is the server you wish to connect to and so is insecure.\n");
	printf("              Do not use this option in a production environment.\n");
	printf(" --tls-engine : If set, enables the use of a SSL engine device.\n");
	printf(" --tls-engine-kpass-sha1 : SHA1 of the key password to be used with the selected SSL engine.\n");
#ifdef FINAL_WITH_TLS_PSK
	printf(" --psk : pre-shared-key in hexadecimal (no leading 0x) to enable TLS-PSK mode.\n");
	printf(" --psk-identity : client identity string for TLS-PSK mode.\n");
#endif
#endif
#ifdef WITH_SOCKS
	printf(" --proxy : SOCKS5 proxy URL of the form:\n");
	printf("           socks5h://[username[:password]@]hostname[:port]\n");
	printf("           Only \"none\" and \"username\" authentication is supported.\n");
#endif
	printf("\nSee https://mosquitto.org/ for more information.\n\n");
}

int main(int argc, char *argv[])
{
	int rc;
#ifndef WIN32
		struct sigaction sigact;
#endif

	mosquitto_lib_init();

	rc = client_config_load(&cfg, CLIENT_SUB, argc, argv);
	if(rc){
		if(rc == 2){
			/* --help */
			print_usage();
		}else{
			fprintf(stderr, "\nUse 'mosquitto_sub --help' to see usage.\n");
		}
		goto cleanup;
	}

	if(cfg.no_retain && cfg.retained_only){
		fprintf(stderr, "\nError: Combining '-R' and '--retained-only' makes no sense.\n");
		goto cleanup;
	}

	if(client_id_generate(&cfg)){
		goto cleanup;
	}

	mosq = mosquitto_new(cfg.id, cfg.clean_session, &cfg);
	if(!mosq){
		switch(errno){
			case ENOMEM:
				err_printf(&cfg, "Error: Out of memory.\n");
				break;
			case EINVAL:
				err_printf(&cfg, "Error: Invalid id and/or clean_session.\n");
				break;
		}
		goto cleanup;
	}
	if(client_opts_set(mosq, &cfg)){
		goto cleanup;
	}
	if(cfg.debug){
		mosquitto_log_callback_set(mosq, my_log_callback);
	}
	mosquitto_subscribe_callback_set(mosq, my_subscribe_callback);
	mosquitto_connect_v5_callback_set(mosq, my_connect_callback);
	mosquitto_message_v5_callback_set(mosq, my_message_callback);

	rc = client_connect(mosq, &cfg);
	if(rc){
		goto cleanup;
	}

#ifndef WIN32
	sigact.sa_handler = my_signal_handler;
	sigemptyset(&sigact.sa_mask);
	sigact.sa_flags = 0;

	if(sigaction(SIGALRM, &sigact, NULL) == -1){
		perror("sigaction");
		goto cleanup;
	}

	if(sigaction(SIGTERM, &sigact, NULL) == -1){
		perror("sigaction");
		goto cleanup;
	}

	if(sigaction(SIGINT, &sigact, NULL) == -1){
		perror("sigaction");
		goto cleanup;
	}

	if(cfg.timeout){
		alarm(cfg.timeout);
	}
#endif

	rc = mosquitto_loop_forever(mosq, -1, 1);

	mosquitto_destroy(mosq);
	mosquitto_lib_cleanup();

	if(cfg.msg_count>0 && rc == MOSQ_ERR_NO_CONN){
		rc = 0;
	}
	client_config_cleanup(&cfg);
	if(rc){
		err_printf(&cfg, "Error: %s\n", mosquitto_strerror(rc));
	}
	if(connack_result){
		return connack_result;
	}else{
		return rc;
	}

cleanup:
	mosquitto_destroy(mosq);
	mosquitto_lib_cleanup();
	client_config_cleanup(&cfg);
	return 1;
}


.. _pythonroto:

Roto/RotoPaint
==============

This section provides basic and advanced tutorials on manipulating the Roto/RotoPaint node using python.

.. toctree::
    :maxdepth: 1

    roto/getRotoItemsLabel.rst


/* ----------------------------------------------------------------------------

 * GTSAM Copyright 2010, Georgia Tech Research Corporation,
 * Atlanta, Georgia 30332-0415
 * All Rights Reserved
 * Authors: Frank Dellaert, et al. (see THANKS for the full author list)

 * See LICENSE for the license information

 * -------------------------------------------------------------------------- */

/**
 * @file SmartRangeExample_plaza2.cpp
 * @brief A 2D Range SLAM example
 * @date June 20, 2013
 * @author FRank Dellaert
 */

// Both relative poses and recovered trajectory poses will be stored as Pose2 objects
#include <gtsam/geometry/Pose2.h>

// Each variable in the system (poses and landmarks) must be identified with a unique key.
// We can either use simple integer keys (1, 2, 3, ...) or symbols (X1, X2, L1).
// Here we will use Symbols
#include <gtsam/inference/Symbol.h>

// We want to use iSAM2 to solve the range-SLAM problem incrementally
#include <gtsam/nonlinear/ISAM2.h>

// iSAM2 requires as input a set set of new factors to be added stored in a factor graph,
// and initial guesses for any new variables used in the added factors
#include <gtsam/nonlinear/NonlinearFactorGraph.h>
#include <gtsam/nonlinear/Values.h>

// We will use a non-liear solver to batch-inituialize from the first 150 frames
#include <gtsam/nonlinear/LevenbergMarquardtOptimizer.h>

// In GTSAM, measurement functions are represented as 'factors'. Several common factors
// have been provided with the library for solving robotics SLAM problems.
#include <gtsam/slam/BetweenFactor.h>
#include <gtsam/sam/RangeFactor.h>

// To find data files, we can use `findExampleDataFile`, declared here:
#include <gtsam/slam/dataset.h>

// Standard headers, added last, so we know headers above work on their own
#include <fstream>
#include <iostream>

using namespace std;
using namespace gtsam;
namespace NM = gtsam::noiseModel;

// data available at http://www.frc.ri.cmu.edu/projects/emergencyresponse/RangeData/
// Datafile format (from http://www.frc.ri.cmu.edu/projects/emergencyresponse/RangeData/log.html)

// load the odometry
// DR: Odometry Input (delta distance traveled and delta heading change)
//    Time (sec)  Delta Dist. Trav. (m) Delta Heading (rad)
typedef pair<double, Pose2> TimedOdometry;
list<TimedOdometry> readOdometry() {
  list<TimedOdometry> odometryList;
  string drFile = findExampleDataFile("Plaza2_DR.txt");
  ifstream is(drFile);
  if (!is) throw runtime_error("Plaza2_DR.txt file not found");

  while (is) {
    double t, distance_traveled, delta_heading;
    is >> t >> distance_traveled >> delta_heading;
    odometryList.push_back(
        TimedOdometry(t, Pose2(distance_traveled, 0, delta_heading)));
  }
  is.clear(); /* clears the end-of-file and error flags */
  return odometryList;
}

// load the ranges from TD
//    Time (sec)  Sender / Antenna ID Receiver Node ID  Range (m)
typedef boost::tuple<double, size_t, double> RangeTriple;
vector<RangeTriple> readTriples() {
  vector<RangeTriple> triples;
  string tdFile = findExampleDataFile("Plaza2_TD.txt");
  ifstream is(tdFile);
  if (!is) throw runtime_error("Plaza2_TD.txt file not found");

  while (is) {
    double t, sender, receiver, range;
    is >> t >> sender >> receiver >> range;
    triples.push_back(RangeTriple(t, receiver, range));
  }
  is.clear(); /* clears the end-of-file and error flags */
  return triples;
}

// main
int main(int argc, char** argv) {

  // load Plaza1 data
  list<TimedOdometry> odometry = readOdometry();
//  size_t M = odometry.size();

  vector<RangeTriple> triples = readTriples();
  size_t K = triples.size();

  // parameters
  size_t incK = 50; // minimum number of range measurements to process after
  bool robust = false;

  // Set Noise parameters
  Vector priorSigmas = Vector3(0.01, 0.01, 0.01);
  Vector odoSigmas = Vector3(0.05, 0.01, 0.2);
  double sigmaR = 100; // range standard deviation
  const NM::Base::shared_ptr // all same type
  priorNoise = NM::Diagonal::Sigmas(priorSigmas), //prior
  odoNoise = NM::Diagonal::Sigmas(odoSigmas), // odometry
  gaussian = NM::Isotropic::Sigma(1, sigmaR), // non-robust
  tukey = NM::Robust::Create(NM::mEstimator::Tukey::Create(15), gaussian), //robust
  rangeNoise = robust ? tukey : gaussian;

  // Initialize iSAM
  ISAM2 isam;

  // Add prior on first pose
  Pose2 pose0 = Pose2(-34.2086489999201, 45.3007639991120, -2.02108900000000);
  NonlinearFactorGraph newFactors;
  newFactors.addPrior(0, pose0, priorNoise);

  //  initialize points (Gaussian)
  Values initial;
  initial.insert(symbol('L', 1), Point2(-68.9265, 18.3778));
  initial.insert(symbol('L', 6), Point2(-37.5805, 69.2278));
  initial.insert(symbol('L', 0), Point2(-33.6205, 26.9678));
  initial.insert(symbol('L', 5), Point2(1.7095, -5.8122));
  Values landmarkEstimates = initial; // copy landmarks
  initial.insert(0, pose0);

  // set some loop variables
  size_t i = 1; // step counter
  size_t k = 0; // range measurement counter
  Pose2 lastPose = pose0;
  size_t countK = 0;

  // Loop over odometry
  gttic_(iSAM);
  for(const TimedOdometry& timedOdometry: odometry) {
    //--------------------------------- odometry loop -----------------------------------------
    double t;
    Pose2 odometry;
    boost::tie(t, odometry) = timedOdometry;

    // add odometry factor
    newFactors.push_back(
        BetweenFactor<Pose2>(i - 1, i, odometry,
            NM::Diagonal::Sigmas(odoSigmas)));

    // predict pose and add as initial estimate
    Pose2 predictedPose = lastPose.compose(odometry);
    lastPose = predictedPose;
    initial.insert(i, predictedPose);
    landmarkEstimates.insert(i, predictedPose);

    // Check if there are range factors to be added
    while (k < K && t >= boost::get<0>(triples[k])) {
      size_t j = boost::get<1>(triples[k]);
      double range = boost::get<2>(triples[k]);
      RangeFactor<Pose2, Point2> factor(i, symbol('L', j), range, rangeNoise);
      // Throw out obvious outliers based on current landmark estimates
      Vector error = factor.unwhitenedError(landmarkEstimates);
      if (k <= 200 || std::abs(error[0]) < 5)
        newFactors.push_back(factor);
      k = k + 1;
      countK = countK + 1;
    }

    // Check whether to update iSAM 2
    if (countK > incK) {
      gttic_(update);
      isam.update(newFactors, initial);
      gttoc_(update);
      gttic_(calculateEstimate);
      Values result = isam.calculateEstimate();
      gttoc_(calculateEstimate);
      lastPose = result.at<Pose2>(i);
      // update landmark estimates
      landmarkEstimates = Values();
      landmarkEstimates.insert(symbol('L', 1), result.at(symbol('L', 1)));
      landmarkEstimates.insert(symbol('L', 6), result.at(symbol('L', 6)));
      landmarkEstimates.insert(symbol('L', 0), result.at(symbol('L', 0)));
      landmarkEstimates.insert(symbol('L', 5), result.at(symbol('L', 5)));
      newFactors = NonlinearFactorGraph();
      initial = Values();
      countK = 0;
    }
    i += 1;
    //--------------------------------- odometry loop -----------------------------------------
  } // end for
  gttoc_(iSAM);

  // Print timings
  tictoc_print_();

  // Write result to file
  Values result = isam.calculateEstimate();
  ofstream os2("rangeResultLM.txt");
  for(const Values::ConstFiltered<Point2>::KeyValuePair& it: result.filter<Point2>())
    os2 << it.key << "\t" << it.value.x() << "\t" << it.value.y() << "\t1"
        << endl;
  ofstream os("rangeResult.txt");
  for(const Values::ConstFiltered<Pose2>::KeyValuePair& it: result.filter<Pose2>())
    os << it.key << "\t" << it.value.x() << "\t" << it.value.y() << "\t"
        << it.value.theta() << endl;
  exit(0);
}


StartChar: uni0206.sq
Encoding: 1114237 -1 742
Width: 1024
VWidth: 0
Flags: W
HStem: 0 120<256 896> 648 120<256 768> 1160 120<256 896> 1408 21G<108 236 660 788> 1560 120<307.067 588.933>
VStem: 108 128<1408 1495.49> 128 128<120 648 768 1160> 660 128<1408 1495.49>
LayerCount: 5
Back
Fore
SplineSet
128 1280 m 5xfb
 896 1280 l 5
 896 1160 l 5
 256 1160 l 5
 256 768 l 5
 768 768 l 5
 768 648 l 5
 256 648 l 5
 256 120 l 5
 896 120 l 5
 896 0 l 5
 128 0 l 5
 128 1280 l 5xfb
660 1408 m 1
 660 1494 591 1560 448 1560 c 0
 305 1560 236 1494 236 1408 c 1
 108 1408 l 1xfd
 108 1576 260 1680 448 1680 c 0
 636 1680 788 1576 788 1408 c 1
 660 1408 l 1
EndSplineSet
Validated: 1
Layer: 2
Layer: 3
Layer: 4
EndChar


LIBRARY()

SRCS(
    feature.cpp
    binarizations_manager.cpp
    permutation.cpp
    data_utils.cpp
    leaf_path.cpp
)

PEERDIR(
    catboost/cuda/cuda_lib
    catboost/private/libs/ctr_description
    catboost/libs/data
    catboost/private/libs/data_types
    catboost/libs/model
    catboost/libs/helpers
    catboost/private/libs/options
    catboost/private/libs/feature_estimator
)

GENERATE_ENUM_SERIALIZATION(feature.h)

END()


// Copyright 2016 Mark Raasveldt
//
// 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.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;

namespace Tibialyzer {
    public struct SpellTaught {
        public int spellid;
        public int npcid;
        public bool knight;
        public bool druid;
        public bool paladin;
        public bool sorcerer;

        public bool GetVocation(int i) {
            if (i == 0) return knight;
            if (i == 1) return druid;
            if (i == 2) return paladin;
            if (i == 3) return sorcerer;
            throw new Exception("Unsupported index");
        }
    }

    public class Spell : TibiaObject {
        public int id;
        public string name;
        public string words;
        public string element;
        public int cooldown;
        public bool premium;
        public bool promotion;
        public int levelrequired;
        public int goldcost;
        public int manacost;
        public bool knight;
        public bool paladin;
        public bool sorcerer;
        public bool druid;
        public Image image;

        public override Spell AsSpell() { return this; }

        private static Color ManaCostColor = Color.FromArgb(((int)(((byte)(46)))), ((int)(((byte)(180)))), ((int)(((byte)(176)))));

        public List<SpellTaught> teachNPCs = new List<SpellTaught>();
        public override string GetName() { return name; }
        public override Image GetImage() { return image; }
        public override List<string> GetAttributeHeaders() {
            return headers;
        }
        public override List<Attribute> GetAttributes() {
            return new List<Attribute> { new StringAttribute(name, 140), new StringAttribute(words, 100), new StringAttribute(manacost >= 0 ? manacost.ToString() : "-", 50, ManaCostColor), new StringAttribute(levelrequired > 0 ? levelrequired.ToString() : "-", 50) };
        }
        public override string GetCommand() {
            return "spell" + Constants.CommandSymbol + name;
        }
        static List<string> headers = new List<string> { "Name", "Words", "Mana", "Level" };
        static int[] hashes = { headers[0].GetHashCode(), headers[1].GetHashCode(), headers[2].GetHashCode(), headers[3].GetHashCode() };
        public override IComparable GetHeaderValue(int header) {
            if (header == hashes[0]) {
                return name;
            }
            if (header == hashes[1]) {
                return words;
            }
            if (header == hashes[2]) {
                return manacost;
            }
            if (header == hashes[3]) {
                return levelrequired;
            }
            return base.GetHeaderValue(header);
        }
    }
}


pragma solidity 0.4.24;

import "../common/IsContract.sol";
import "../lib/misc/ERCProxy.sol";

contract DelegateProxy is ERCProxy, IsContract {
    uint256 internal constant FWD_GAS_LIMIT = 10000;

    /**
    * @dev Performs a delegatecall and returns whatever the delegatecall returned (entire context execution will return!)
    * @param _dst Destination address to perform the delegatecall
    * @param _calldata Calldata for the delegatecall
    */
    function delegatedFwd(address _dst, bytes _calldata) internal {
        require(isContract(_dst));
        uint256 fwdGasLimit = FWD_GAS_LIMIT;

        assembly {
            let result := delegatecall(sub(gas, fwdGasLimit), _dst, add(_calldata, 0x20), mload(_calldata), 0, 0)
            let size := returndatasize
            let ptr := mload(0x40)
            returndatacopy(ptr, 0, size)

            // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas.
            // if the call returned error data, forward it
            switch result case 0 { revert(ptr, size) }
            default { return(ptr, size) }
        }
    }
}


0x00	0x0000
0x01	0x0001
0x02	0x0002
0x03	0x0003
0x04	0x0004
0x05	0x0005
0x06	0x0006
0x07	0x0007
0x08	0x0008
0x09	0x0009
0x0A	0x000A
0x0B	0x000B
0x0C	0x000C
0x0D	0x000D
0x0E	0x000E
0x0F	0x000F
0x10	0x0010
0x11	0x0011
0x12	0x0012
0x13	0x0013
0x14	0x0014
0x15	0x0015
0x16	0x0016
0x17	0x0017
0x18	0x0018
0x19	0x0019
0x1A	0x001A
0x1B	0x001B
0x1C	0x001C
0x1D	0x001D
0x1E	0x001E
0x1F	0x001F
0x20	0x0020
0x21	0x0021
0x22	0x0022
0x23	0x0023
0x24	0x0024
0x25	0x0025
0x26	0x0026
0x27	0x0027
0x28	0x0028
0x29	0x0029
0x2A	0x002A
0x2B	0x002B
0x2C	0x002C
0x2D	0x002D
0x2E	0x002E
0x2F	0x002F
0x30	0x0030
0x31	0x0031
0x32	0x0032
0x33	0x0033
0x34	0x0034
0x35	0x0035
0x36	0x0036
0x37	0x0037
0x38	0x0038
0x39	0x0039
0x3A	0x003A
0x3B	0x003B
0x3C	0x003C
0x3D	0x003D
0x3E	0x003E
0x3F	0x003F
0x40	0x0040
0x41	0x0041
0x42	0x0042
0x43	0x0043
0x44	0x0044
0x45	0x0045
0x46	0x0046
0x47	0x0047
0x48	0x0048
0x49	0x0049
0x4A	0x004A
0x4B	0x004B
0x4C	0x004C
0x4D	0x004D
0x4E	0x004E
0x4F	0x004F
0x50	0x0050
0x51	0x0051
0x52	0x0052
0x53	0x0053
0x54	0x0054
0x55	0x0055
0x56	0x0056
0x57	0x0057
0x58	0x0058
0x59	0x0059
0x5A	0x005A
0x5B	0x005B
0x5C	0x005C
0x5D	0x005D
0x5E	0x005E
0x5F	0x005F
0x60	0x0060
0x61	0x0061
0x62	0x0062
0x63	0x0063
0x64	0x0064
0x65	0x0065
0x66	0x0066
0x67	0x0067
0x68	0x0068
0x69	0x0069
0x6A	0x006A
0x6B	0x006B
0x6C	0x006C
0x6D	0x006D
0x6E	0x006E
0x6F	0x006F
0x70	0x0070
0x71	0x0071
0x72	0x0072
0x73	0x0073
0x74	0x0074
0x75	0x0075
0x76	0x0076
0x77	0x0077
0x78	0x0078
0x79	0x0079
0x7A	0x007A
0x7B	0x007B
0x7C	0x007C
0x7D	0x007D
0x7E	0x007E
0x7F	0x007F
0x80	0x00C7
0x81	0x00FC
0x82	0x00E9
0x83	0x00E2
0x84	0x00E4
0x85	0x00E0
0x86	0x00E5
0x87	0x00E7
0x88	0x00EA
0x89	0x00EB
0x8A	0x00E8
0x8B	0x00EF
0x8C	0x00EE
0x8D	0x00EC
0x8E	0x00C4
0x8F	0x00C5
0x90	0x00C9
0x91	0x00E6
0x92	0x00C6
0x93	0x00F4
0x94	0x00F6
0x95	0x00F2
0x96	0x00FB
0x97	0x00F9
0x98	0x00FF
0x99	0x00D6
0x9A	0x00DC
0x9B	0x00F8
0x9C	0x00A3
0x9D	0x00D8
0x9E	0x20A7
0x9F	0x0192
0xA0	0x00E1
0xA1	0x00ED
0xA2	0x00F3
0xA3	0x00FA
0xA4	0x00F1
0xA5	0x00D1
0xA6	0x00AA
0xA7	0x00BA
0xA8	0x00BF
0xA9	0x2310
0xAA	0x00AC
0xAB	0x00BD
0xAC	0x00BC
0xAD	0x00A1
0xAE	0x00AB
0xAF	0x00A4
0xB0	0x2591
0xB1	0x2592
0xB2	0x2593
0xB3	0x2502
0xB4	0x2524
0xB5	0x2561
0xB6	0x2562
0xB7	0x2556
0xB8	0x2555
0xB9	0x2563
0xBA	0x2551
0xBB	0x2557
0xBC	0x255D
0xBD	0x255C
0xBE	0x255B
0xBF	0x2510
0xC0	0x2514
0xC1	0x2534
0xC2	0x252C
0xC3	0x251C
0xC4	0x2500
0xC5	0x253C
0xC6	0x255E
0xC7	0x255F
0xC8	0x255A
0xC9	0x2554
0xCA	0x2569
0xCB	0x2566
0xCC	0x2560
0xCD	0x2550
0xCE	0x256C
0xCF	0x2567
0xD0	0x2568
0xD1	0x2564
0xD2	0x2565
0xD3	0x2559
0xD4	0x2558
0xD5	0x2552
0xD6	0x2553
0xD7	0x256B
0xD8	0x256A
0xD9	0x2518
0xDA	0x250C
0xDB	0x2588
0xDC	0x2584
0xDD	0x258C
0xDE	0x2590
0xDF	0x2580
0xE0	0x03B1
0xE1	0x00DF
0xE2	0x0393
0xE3	0x03C0
0xE4	0x03A3
0xE5	0x03C3
0xE6	0x00B5
0xE7	0x03C4
0xE8	0x03A6
0xE9	0x0398
0xEA	0x03A9
0xEB	0x03B4
0xEC	0x221E
0xED	0x03C6
0xEE	0x03B5
0xEF	0x2229
0xF0	0x2261
0xF1	0x00B1
0xF2	0x2265
0xF3	0x2264
0xF4	0x2320
0xF5	0x2321
0xF6	0x00F7
0xF7	0x2248
0xF8	0x00B0
0xF9	0x2219
0xFA	0x00B7
0xFB	0x221A
0xFC	0x207F
0xFD	0x00B2
0xFE	0x25A0
0xFF	0x00A0


/**
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0.
 */

#include <aws/directconnect/model/AllocatePublicVirtualInterfaceResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>

#include <utility>

using namespace Aws::DirectConnect::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;

AllocatePublicVirtualInterfaceResult::AllocatePublicVirtualInterfaceResult() :
    m_vlan(0),
    m_asn(0),
    m_amazonSideAsn(0),
    m_addressFamily(AddressFamily::NOT_SET),
    m_virtualInterfaceState(VirtualInterfaceState::NOT_SET),
    m_mtu(0),
    m_jumboFrameCapable(false)
{
}

AllocatePublicVirtualInterfaceResult::AllocatePublicVirtualInterfaceResult(const Aws::AmazonWebServiceResult<JsonValue>& result) :
    m_vlan(0),
    m_asn(0),
    m_amazonSideAsn(0),
    m_addressFamily(AddressFamily::NOT_SET),
    m_virtualInterfaceState(VirtualInterfaceState::NOT_SET),
    m_mtu(0),
    m_jumboFrameCapable(false)
{
  *this = result;
}

AllocatePublicVirtualInterfaceResult& AllocatePublicVirtualInterfaceResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  JsonView jsonValue = result.GetPayload().View();
  if(jsonValue.ValueExists("ownerAccount"))
  {
    m_ownerAccount = jsonValue.GetString("ownerAccount");

  }

  if(jsonValue.ValueExists("virtualInterfaceId"))
  {
    m_virtualInterfaceId = jsonValue.GetString("virtualInterfaceId");

  }

  if(jsonValue.ValueExists("location"))
  {
    m_location = jsonValue.GetString("location");

  }

  if(jsonValue.ValueExists("connectionId"))
  {
    m_connectionId = jsonValue.GetString("connectionId");

  }

  if(jsonValue.ValueExists("virtualInterfaceType"))
  {
    m_virtualInterfaceType = jsonValue.GetString("virtualInterfaceType");

  }

  if(jsonValue.ValueExists("virtualInterfaceName"))
  {
    m_virtualInterfaceName = jsonValue.GetString("virtualInterfaceName");

  }

  if(jsonValue.ValueExists("vlan"))
  {
    m_vlan = jsonValue.GetInteger("vlan");

  }

  if(jsonValue.ValueExists("asn"))
  {
    m_asn = jsonValue.GetInteger("asn");

  }

  if(jsonValue.ValueExists("amazonSideAsn"))
  {
    m_amazonSideAsn = jsonValue.GetInt64("amazonSideAsn");

  }

  if(jsonValue.ValueExists("authKey"))
  {
    m_authKey = jsonValue.GetString("authKey");

  }

  if(jsonValue.ValueExists("amazonAddress"))
  {
    m_amazonAddress = jsonValue.GetString("amazonAddress");

  }

  if(jsonValue.ValueExists("customerAddress"))
  {
    m_customerAddress = jsonValue.GetString("customerAddress");

  }

  if(jsonValue.ValueExists("addressFamily"))
  {
    m_addressFamily = AddressFamilyMapper::GetAddressFamilyForName(jsonValue.GetString("addressFamily"));

  }

  if(jsonValue.ValueExists("virtualInterfaceState"))
  {
    m_virtualInterfaceState = VirtualInterfaceStateMapper::GetVirtualInterfaceStateForName(jsonValue.GetString("virtualInterfaceState"));

  }

  if(jsonValue.ValueExists("customerRouterConfig"))
  {
    m_customerRouterConfig = jsonValue.GetString("customerRouterConfig");

  }

  if(jsonValue.ValueExists("mtu"))
  {
    m_mtu = jsonValue.GetInteger("mtu");

  }

  if(jsonValue.ValueExists("jumboFrameCapable"))
  {
    m_jumboFrameCapable = jsonValue.GetBool("jumboFrameCapable");

  }

  if(jsonValue.ValueExists("virtualGatewayId"))
  {
    m_virtualGatewayId = jsonValue.GetString("virtualGatewayId");

  }

  if(jsonValue.ValueExists("directConnectGatewayId"))
  {
    m_directConnectGatewayId = jsonValue.GetString("directConnectGatewayId");

  }

  if(jsonValue.ValueExists("routeFilterPrefixes"))
  {
    Array<JsonView> routeFilterPrefixesJsonList = jsonValue.GetArray("routeFilterPrefixes");
    for(unsigned routeFilterPrefixesIndex = 0; routeFilterPrefixesIndex < routeFilterPrefixesJsonList.GetLength(); ++routeFilterPrefixesIndex)
    {
      m_routeFilterPrefixes.push_back(routeFilterPrefixesJsonList[routeFilterPrefixesIndex].AsObject());
    }
  }

  if(jsonValue.ValueExists("bgpPeers"))
  {
    Array<JsonView> bgpPeersJsonList = jsonValue.GetArray("bgpPeers");
    for(unsigned bgpPeersIndex = 0; bgpPeersIndex < bgpPeersJsonList.GetLength(); ++bgpPeersIndex)
    {
      m_bgpPeers.push_back(bgpPeersJsonList[bgpPeersIndex].AsObject());
    }
  }

  if(jsonValue.ValueExists("region"))
  {
    m_region = jsonValue.GetString("region");

  }

  if(jsonValue.ValueExists("awsDeviceV2"))
  {
    m_awsDeviceV2 = jsonValue.GetString("awsDeviceV2");

  }

  if(jsonValue.ValueExists("tags"))
  {
    Array<JsonView> tagsJsonList = jsonValue.GetArray("tags");
    for(unsigned tagsIndex = 0; tagsIndex < tagsJsonList.GetLength(); ++tagsIndex)
    {
      m_tags.push_back(tagsJsonList[tagsIndex].AsObject());
    }
  }

  return *this;
}


/* ----------------------------------------------------------------------------

 * GTSAM Copyright 2010, Georgia Tech Research Corporation,
 * Atlanta, Georgia 30332-0415
 * All Rights Reserved
 * Authors: Frank Dellaert, et al. (see THANKS for the full author list)

 * See LICENSE for the license information

 * -------------------------------------------------------------------------- */

/**
 * @file concepts.h
 *
 * @brief Concept-checking macros for geometric objects
 * Each macro instantiates a concept check structure, which
 * includes a static function that will fail to compile
 * if the concept does not pass. Functions are made static
 * to ensure they get instantiated.
 *
 * @date Oct 6, 2011
 * @author Alex Cunningham
 */

#pragma once

#include <gtsam/base/Matrix.h>
#include <boost/optional.hpp>

namespace gtsam {

/**
 * Pose Concept
 * A must contain a translation and a rotation, with
 * each structure accessable directly and a type provided
 * for each.
 */
template<class POSE>
class PoseConcept {
public:
  typedef typename POSE::Translation Translation;
  typedef typename POSE::Rotation Rotation;

private:
  static Rotation checkRotationMemberAccess(const POSE& p) {
    return p.rotation();
  }

  static Translation checkTranslationMemberAccess(const POSE& p) {
    return p.translation();
  }

  static std::pair<size_t, size_t> checkTranslationInterval() {
    return POSE::translationInterval();
  }

  static std::pair<size_t, size_t> checkRotationInterval() {
    return POSE::rotationInterval();
  }
};

} // \namespace gtsam

/**
 * Macros to use geometry concepts:
 *  - _INST macro: instantiates a struct: use in unit tests, but not in headers.
 *  - _TYPE macro: use in generic structures to validate the template arguments.
 *
 * NOTE: intentionally not in the gtsam namespace to avoid namespace complications
 * when using with objects not inside gtsam namespace.
 */

/** Pose Concept macros */
#define GTSAM_CONCEPT_POSE_INST(T) template class gtsam::PoseConcept<T>;
#define GTSAM_CONCEPT_POSE_TYPE(T) typedef gtsam::PoseConcept<T> _gtsam_PoseConcept##T;


<?php

/**
 * This file is part of the Carbon package.
 *
 * (c) Brian Nesbitt <brian@nesbot.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

/**
 * Authors:
 * - Chitwanix OS Development    info@chitwanix.com
 */
return array_replace_recursive(require __DIR__.'/en.php', [
    'formats' => [
        'L' => 'dddd DD MMM YYYY',
    ],
    'months' => ['जनवरी', 'फ़रवरी', 'मार्च', 'अप्रेल', 'मई', 'जून', 'जुलाई', 'अगस्त', 'सितम्बर', 'अक्टूबर', 'नवम्बर', 'दिसम्बर'],
    'months_short' => ['जनवरी', 'फ़रवरी', 'मार्च', 'अप्रेल', 'मई', 'जून', 'जुलाई', 'अगस्त', 'सितम्बर', 'अक्टूबर', 'नवम्बर', 'दिसम्बर'],
    'weekdays' => ['आइतबार', 'सोमबार', 'मंगलबार', 'बुधबार', 'बिहिबार', 'शुक्रबार', 'शनिबार'],
    'weekdays_short' => ['आइत', 'सोम', 'मंगल', 'बुध', 'बिहि', 'शुक्र', 'शनि'],
    'weekdays_min' => ['आइत', 'सोम', 'मंगल', 'बुध', 'बिहि', 'शुक्र', 'शनि'],
    'day_of_first_week_of_year' => 1,
    'meridiem' => ['पूर्वाह्न', 'अपराह्न'],
]);


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>BuildMachineOSBuild</key>
	<string>17E190a</string>
	<key>CFBundleDevelopmentRegion</key>
	<string>en</string>
	<key>CFBundleExecutable</key>
	<string>IntelGraphicsFixup</string>
	<key>CFBundleIdentifier</key>
	<string>as.lvs1974.IntelGraphicsFixup</string>
	<key>CFBundleInfoDictionaryVersion</key>
	<string>6.0</string>
	<key>CFBundleName</key>
	<string>IntelGraphicsFixup</string>
	<key>CFBundlePackageType</key>
	<string>KEXT</string>
	<key>CFBundleShortVersionString</key>
	<string>1.2.7</string>
	<key>CFBundleSignature</key>
	<string>????</string>
	<key>CFBundleSupportedPlatforms</key>
	<array>
		<string>MacOSX</string>
	</array>
	<key>CFBundleVersion</key>
	<string>1.2.7</string>
	<key>DTCompiler</key>
	<string>com.apple.compilers.llvm.clang.1_0</string>
	<key>DTPlatformBuild</key>
	<string>9C40b</string>
	<key>DTPlatformVersion</key>
	<string>GM</string>
	<key>DTSDKBuild</key>
	<string>17C76</string>
	<key>DTSDKName</key>
	<string>macosx10.13</string>
	<key>DTXcode</key>
	<string>0920</string>
	<key>DTXcodeBuild</key>
	<string>9C40b</string>
	<key>IOKitPersonalities</key>
	<dict>
		<key>as.lvs1974.IntelGraphicsAudio</key>
		<dict>
			<key>CFBundleIdentifier</key>
			<string>as.lvs1974.IntelGraphicsFixup</string>
			<key>IOClass</key>
			<string>IntelGraphicsAudio</string>
			<key>IOMatchCategory</key>
			<string>IOService</string>
			<key>IOPCIClassMatch</key>
			<string>0x04030000&0xffff0000</string>
			<key>IOPCIMatch</key>
			<string>0x00008086&0x0000ffff</string>
			<key>IOProbeScore</key>
			<integer>60000</integer>
			<key>IOProviderClass</key>
			<string>IOPCIDevice</string>
		</dict>
		<key>as.lvs1974.IntelGraphicsFixup</key>
		<dict>
			<key>CFBundleIdentifier</key>
			<string>as.lvs1974.IntelGraphicsFixup</string>
			<key>IOClass</key>
			<string>IntelGraphicsFixup</string>
			<key>IOMatchCategory</key>
			<string>IntelGraphicsFixup</string>
			<key>IOProviderClass</key>
			<string>IOResources</string>
			<key>IOResourceMatch</key>
			<string>IOKit</string>
		</dict>
	</dict>
	<key>NSHumanReadableCopyright</key>
	<string>Copyright © 2018 lvs1974. All rights reserved.</string>
	<key>OSBundleCompatibleVersion</key>
	<string>1.0</string>
	<key>OSBundleLibraries</key>
	<dict>
		<key>as.vit9696.Lilu</key>
		<string>1.2.0</string>
		<key>com.apple.iokit.IOPCIFamily</key>
		<string>1.0.0b1</string>
		<key>com.apple.kpi.bsd</key>
		<string>12.0.0</string>
		<key>com.apple.kpi.dsep</key>
		<string>12.0.0</string>
		<key>com.apple.kpi.iokit</key>
		<string>12.0.0</string>
		<key>com.apple.kpi.libkern</key>
		<string>12.0.0</string>
		<key>com.apple.kpi.mach</key>
		<string>12.0.0</string>
		<key>com.apple.kpi.unsupported</key>
		<string>12.0.0</string>
	</dict>
	<key>OSBundleRequired</key>
	<string>Root</string>
</dict>
</plist>


// AFNetworkReachabilityManager.h
//
// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#import <Foundation/Foundation.h>
#import <SystemConfiguration/SystemConfiguration.h>

#import <netinet/in.h>
#import <netinet6/in6.h>
#import <arpa/inet.h>
#import <ifaddrs.h>
#import <netdb.h>

typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) {
    AFNetworkReachabilityStatusUnknown          = -1,
    AFNetworkReachabilityStatusNotReachable     = 0,
    AFNetworkReachabilityStatusReachableViaWWAN = 1,
    AFNetworkReachabilityStatusReachableViaWiFi = 2,
};

/**
 `AFNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces.

 Reachability can be used to determine background information about why a network operation failed, or to trigger a network operation retrying when a connection is established. It should not be used to prevent a user from initiating a network request, as it's possible that an initial request may be required to establish reachability.

 See Apple's Reachability Sample Code (https://developer.apple.com/library/ios/samplecode/reachability/)

 @warning Instances of `AFNetworkReachabilityManager` must be started with `-startMonitoring` before reachability status can be determined.
 */
@interface AFNetworkReachabilityManager : NSObject

/**
 The current network reachability status.
 */
@property (readonly, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus;

/**
 Whether or not the network is currently reachable.
 */
@property (readonly, nonatomic, assign, getter = isReachable) BOOL reachable;

/**
 Whether or not the network is currently reachable via WWAN.
 */
@property (readonly, nonatomic, assign, getter = isReachableViaWWAN) BOOL reachableViaWWAN;

/**
 Whether or not the network is currently reachable via WiFi.
 */
@property (readonly, nonatomic, assign, getter = isReachableViaWiFi) BOOL reachableViaWiFi;

///---------------------
/// @name Initialization
///---------------------

/**
 Returns the shared network reachability manager.
 */
+ (instancetype)sharedManager;

/**
 Creates and returns a network reachability manager for the specified domain.

 @param domain The domain used to evaluate network reachability.

 @return An initialized network reachability manager, actively monitoring the specified domain.
 */
+ (instancetype)managerForDomain:(NSString *)domain;

/**
 Creates and returns a network reachability manager for the socket address.

 @param address The socket address used to evaluate network reachability.

 @return An initialized network reachability manager, actively monitoring the specified socket address.
 */
+ (instancetype)managerForAddress:(const struct sockaddr_in *)address;

/**
 Initializes an instance of a network reachability manager from the specified reachability object.

 @param reachability The reachability object to monitor.

 @return An initialized network reachability manager, actively monitoring the specified reachability.
 */
- (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability;

///--------------------------------------------------
/// @name Starting & Stopping Reachability Monitoring
///--------------------------------------------------

/**
 Starts monitoring for changes in network reachability status.
 */
- (void)startMonitoring;

/**
 Stops monitoring for changes in network reachability status.
 */
- (void)stopMonitoring;

///-------------------------------------------------
/// @name Getting Localized Reachability Description
///-------------------------------------------------

/**
 Returns a localized string representation of the current network reachability status.
 */
- (NSString *)localizedNetworkReachabilityStatusString;

///---------------------------------------------------
/// @name Setting Network Reachability Change Callback
///---------------------------------------------------

/**
 Sets a callback to be executed when the network availability of the `baseURL` host changes.

 @param block A block object to be executed when the network availability of the `baseURL` host changes.. This block has no return value and takes a single argument which represents the various reachability states from the device to the `baseURL`.
 */
- (void)setReachabilityStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block;

@end

///----------------
/// @name Constants
///----------------

/**
 ## Network Reachability

 The following constants are provided by `AFNetworkReachabilityManager` as possible network reachability statuses.

 enum {
 AFNetworkReachabilityStatusUnknown,
 AFNetworkReachabilityStatusNotReachable,
 AFNetworkReachabilityStatusReachableViaWWAN,
 AFNetworkReachabilityStatusReachableViaWiFi,
 }

 `AFNetworkReachabilityStatusUnknown`
 The `baseURL` host reachability is not known.

 `AFNetworkReachabilityStatusNotReachable`
 The `baseURL` host cannot be reached.

 `AFNetworkReachabilityStatusReachableViaWWAN`
 The `baseURL` host can be reached via a cellular connection, such as EDGE or GPRS.

 `AFNetworkReachabilityStatusReachableViaWiFi`
 The `baseURL` host can be reached via a Wi-Fi connection.

 ### Keys for Notification UserInfo Dictionary

 Strings that are used as keys in a `userInfo` dictionary in a network reachability status change notification.

 `AFNetworkingReachabilityNotificationStatusItem`
 A key in the userInfo dictionary in a `AFNetworkingReachabilityDidChangeNotification` notification.
 The corresponding value is an `NSNumber` object representing the `AFNetworkReachabilityStatus` value for the current reachability status.
 */

///--------------------
/// @name Notifications
///--------------------

/**
 Posted when network reachability changes.
 This notification assigns no notification object. The `userInfo` dictionary contains an `NSNumber` object under the `AFNetworkingReachabilityNotificationStatusItem` key, representing the `AFNetworkReachabilityStatus` value for the current network reachability.

 @warning In order for network reachability to be monitored, include the `SystemConfiguration` framework in the active target's "Link Binary With Library" build phase, and add `#import <SystemConfiguration/SystemConfiguration.h>` to the header prefix of the project (`Prefix.pch`).
 */
extern NSString * const AFNetworkingReachabilityDidChangeNotification;
extern NSString * const AFNetworkingReachabilityNotificationStatusItem;

///--------------------
/// @name Functions
///--------------------

/**
 Returns a localized string representation of an `AFNetworkReachabilityStatus` value.
 */
extern NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status);


.\" **************************************************************************
.\" *                                  _   _ ____  _
.\" *  Project                     ___| | | |  _ \| |
.\" *                             / __| | | | |_) | |
.\" *                            | (__| |_| |  _ <| |___
.\" *                             \___|\___/|_| \_\_____|
.\" *
.\" * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
.\" *
.\" * This software is licensed as described in the file COPYING, which
.\" * you should have received as part of this distribution. The terms
.\" * are also available at https://curl.haxx.se/docs/copyright.html.
.\" *
.\" * You may opt to use, copy, modify, merge, publish, distribute and/or sell
.\" * copies of the Software, and permit persons to whom the Software is
.\" * furnished to do so, under the terms of the COPYING file.
.\" *
.\" * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
.\" * KIND, either express or implied.
.\" *
.\" **************************************************************************
.\"
.TH CURLOPT_PRE_PROXY 3 "May 15, 2017" "libcurl 7.56.1" "curl_easy_setopt options"

.SH NAME
CURLOPT_PRE_PROXY \- set pre-proxy to use
.SH SYNOPSIS
#include <curl/curl.h>

CURLcode curl_easy_setopt(CURL *handle, CURLOPT_PRE_PROXY, char *preproxy);
.SH DESCRIPTION
Set the \fIpreproxy\fP to use for the upcoming request. The parameter
should be a char * to a zero terminated string holding the host name or dotted
numerical IP address. A numerical IPv6 address must be written within
[brackets].

To specify port number in this string, append :[port] to the end of the host
name. The proxy's port number may optionally be specified with the separate
option \fICURLOPT_PROXYPORT(3)\fP. If not specified, libcurl will default to
using port 1080 for proxies.

A pre proxy is a SOCKS proxy that curl connects to before it connects to the
HTTP(S) proxy specified in the \fICURLOPT_PROXY\fP option. The pre proxy can
only be a SOCKS proxy.

The pre proxy string should be prefixed with [scheme]:// to specify which kind
of socks is used. Use socks4://, socks4a://, socks5:// or socks5h:// (the last
one to enable socks5 and asking the proxy to do the resolving, also known as
\fICURLPROXY_SOCKS5_HOSTNAME\fP type) to request the specific SOCKS version to
be used. Otherwise SOCKS4 is used as default.

Setting the pre proxy string to "" (an empty string) will explicitly disable
the use of a pre proxy.

The application does not have to keep the string around after setting this
option.
.SH DEFAULT
Default is NULL, meaning no pre proxy is used.

When you set a host name to use, do not assume that there's any particular
single port number used widely for proxies. Specify it!
.SH PROTOCOLS
All except file://. Note that some protocols don't do very well over proxy.
.SH EXAMPLE
.nf
CURL *curl = curl_easy_init();
if(curl) {
  curl_easy_setopt(curl, CURLOPT_URL, "http://example.com/file.txt");
  curl_easy_setopt(curl, CURLOPT_PREPROXY, "socks4://socks-proxy:1080");
  curl_easy_setopt(curl, CURLOPT_PROXY, "http://proxy:80");
  curl_easy_perform(curl);
}
.fi
.SH AVAILABILITY
Added in 7.52.0
.SH RETURN VALUE
Returns CURLE_OK if proxies are supported, CURLE_UNKNOWN_OPTION if not, or
CURLE_OUT_OF_MEMORY if there was insufficient heap space.
.SH "SEE ALSO"
.BR CURLOPT_PROXY "(3), " CURLOPT_HTTPPROXYTUNNEL "(3), "


/* -*- Mode: js; js-indent-level: 2; -*- */
/*
 * Copyright 2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE or:
 * http://opensource.org/licenses/BSD-3-Clause
 */

var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');

/**
 * Encode an integer in the range of 0 to 63 to a single base 64 digit.
 */
exports.encode = function (number) {
  if (0 <= number && number < intToCharMap.length) {
    return intToCharMap[number];
  }
  throw new TypeError("Must be between 0 and 63: " + number);
};

/**
 * Decode a single base 64 character code digit to an integer. Returns -1 on
 * failure.
 */
exports.decode = function (charCode) {
  var bigA = 65;     // 'A'
  var bigZ = 90;     // 'Z'

  var littleA = 97;  // 'a'
  var littleZ = 122; // 'z'

  var zero = 48;     // '0'
  var nine = 57;     // '9'

  var plus = 43;     // '+'
  var slash = 47;    // '/'

  var littleOffset = 26;
  var numberOffset = 52;

  // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
  if (bigA <= charCode && charCode <= bigZ) {
    return (charCode - bigA);
  }

  // 26 - 51: abcdefghijklmnopqrstuvwxyz
  if (littleA <= charCode && charCode <= littleZ) {
    return (charCode - littleA + littleOffset);
  }

  // 52 - 61: 0123456789
  if (zero <= charCode && charCode <= nine) {
    return (charCode - zero + numberOffset);
  }

  // 62: +
  if (charCode == plus) {
    return 62;
  }

  // 63: /
  if (charCode == slash) {
    return 63;
  }

  // Invalid base64 digit.
  return -1;
};


-- Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
-- SPDX-License-Identifier: Apache-2.0

module DA.Daml.LF.ScenarioServiceClient
  ( Options(..)
  , ScenarioServiceConfig(..)
  , defaultScenarioServiceConfig
  , readScenarioServiceConfig
  , LowLevel.TimeoutSeconds
  , LowLevel.findServerJar
  , Handle
  , withScenarioService
  , withScenarioService'
  , Context(..)
  , LowLevel.SkipValidation(..)
  , LowLevel.ContextId
  , getNewCtx
  , deleteCtx
  , gcCtxs
  , runScenario
  , runScript
  , LowLevel.BackendError(..)
  , LowLevel.Error(..)
  , LowLevel.ScenarioResult(..)
  , Hash
  , encodeModule
  ) where

import Control.Concurrent.Extra
import Control.DeepSeq
import Control.Exception
import Control.Monad.Except
import qualified Data.ByteString as BS
import Data.Hashable
import Data.IORef
import qualified Data.Map.Strict as MS
import Data.Maybe
import qualified Data.Set as S
import qualified Data.Text as T
import System.Directory

import DA.Daml.Options.Types (EnableScenarioService(..))
import DA.Daml.Project.Config
import DA.Daml.Project.Consts
import DA.Daml.Project.Types

import qualified DA.Daml.LF.Ast as LF
import qualified DA.Daml.LF.ScenarioServiceClient.LowLevel as LowLevel

import qualified DA.Service.Logger as Logger

data Options = Options
  { optServerJar :: FilePath
  , optScenarioServiceConfig :: ScenarioServiceConfig
  , optMaxConcurrency :: Int
  -- This controls the number of parallel gRPC requests
  , optLogInfo :: String -> IO ()
  , optLogError :: String -> IO ()
  }

toLowLevelOpts :: LF.Version -> Options -> LowLevel.Options
toLowLevelOpts optDamlLfVersion Options{..} =
    LowLevel.Options{..}
    where
        optRequestTimeout = fromMaybe 60 $ cnfGrpcTimeout optScenarioServiceConfig
        optGrpcMaxMessageSize = cnfGrpcMaxMessageSize optScenarioServiceConfig
        optJvmOptions = cnfJvmOptions optScenarioServiceConfig

data Handle = Handle
  { hLowLevelHandle :: LowLevel.Handle
  , hOptions :: Options
  , hConcurrencySem :: QSemN
  -- ^ Limits the number of concurrent gRPC requests (not just scenario executions).
  , hContextLock :: Lock
  -- ^ Used to make updating and cloning a context via getNewCtx atomic.
  , hLoadedPackages :: IORef (S.Set LF.PackageId)
  , hLoadedModules :: IORef (MS.Map Hash (LF.ModuleName, BS.ByteString))
  , hContextId :: IORef LowLevel.ContextId
  -- ^ The root context id, this is mutable so that rather than mutating the context
  -- we can clone it and update the clone which allows us to safely interrupt a context update.
  }

withSem :: QSemN -> IO a -> IO a
withSem sem = bracket_ (waitQSemN sem 1) (signalQSemN sem 1)

withScenarioService :: LF.Version -> Logger.Handle IO -> ScenarioServiceConfig -> (Handle -> IO a) -> IO a
withScenarioService ver loggerH scenarioConfig f = do
  hOptions <- getOptions
  LowLevel.withScenarioService (toLowLevelOpts ver hOptions) $ \hLowLevelHandle ->
      bracket
         (either (\err -> fail $ "Failed to start scenario service: " <> show err) pure =<< LowLevel.newCtx hLowLevelHandle)
         (LowLevel.deleteCtx hLowLevelHandle) $ \rootCtxId -> do
             hLoadedPackages <- liftIO $ newIORef S.empty
             hLoadedModules <- liftIO $ newIORef MS.empty
             hConcurrencySem <- liftIO $ newQSemN (optMaxConcurrency hOptions)
             hContextLock <- liftIO newLock
             hContextId <- liftIO $ newIORef rootCtxId
             f Handle {..} `finally`
                 -- Wait for gRPC requests to exit, otherwise gRPC gets very unhappy.
                 liftIO (waitQSemN hConcurrencySem $ optMaxConcurrency hOptions)
  where getOptions = do
            serverJar <- LowLevel.findServerJar
            let ssLogHandle = Logger.tagHandle loggerH "ScenarioService"
            let wrapLog f = f ssLogHandle . T.pack
            pure Options
                { optMaxConcurrency = 5
                , optServerJar = serverJar
                , optScenarioServiceConfig = scenarioConfig
                , optLogInfo = wrapLog Logger.logInfo
                , optLogError = wrapLog Logger.logError
                }

withScenarioService'
    :: EnableScenarioService
    -> LF.Version
    -> Logger.Handle IO
    -> ScenarioServiceConfig
    -> (Maybe Handle -> IO a)
    -> IO a
withScenarioService' (EnableScenarioService enable) ver loggerH conf f
    | enable = withScenarioService ver loggerH conf (f . Just)
    | otherwise = f Nothing

data ScenarioServiceConfig = ScenarioServiceConfig
    { cnfGrpcMaxMessageSize :: Maybe Int -- In bytes
    , cnfGrpcTimeout :: Maybe LowLevel.TimeoutSeconds
    , cnfJvmOptions :: [String]
    } deriving Show

defaultScenarioServiceConfig :: ScenarioServiceConfig
defaultScenarioServiceConfig = ScenarioServiceConfig
    { cnfGrpcMaxMessageSize = Nothing
    , cnfGrpcTimeout = Nothing
    , cnfJvmOptions = []
    }

readScenarioServiceConfig :: IO ScenarioServiceConfig
readScenarioServiceConfig = do
    exists <- doesFileExist projectConfigName
    if exists
        then do
            project <- readProjectConfig $ ProjectPath "."
            either throwIO pure $ parseScenarioServiceConfig project
        else pure defaultScenarioServiceConfig

parseScenarioServiceConfig :: ProjectConfig -> Either ConfigError ScenarioServiceConfig
parseScenarioServiceConfig conf = do
    cnfGrpcMaxMessageSize <- queryProjectConfig ["scenario-service", "grpc-max-message-size"] conf
    cnfGrpcTimeout <- queryProjectConfig ["scenario-service", "grpc-timeout"] conf
    cnfJvmOptions <- fromMaybe [] <$> queryProjectConfig ["scenario-service", "jvm-options"] conf
    pure ScenarioServiceConfig {..}

data Context = Context
  { ctxModules :: MS.Map Hash (LF.ModuleName, BS.ByteString)
  , ctxPackages :: [(LF.PackageId, BS.ByteString)]
  , ctxSkipValidation :: LowLevel.SkipValidation
  }

getNewCtx :: Handle -> Context -> IO (Either LowLevel.BackendError LowLevel.ContextId)
getNewCtx Handle{..} Context{..} = withLock hContextLock $ withSem hConcurrencySem $ do
  loadedPackages <- readIORef hLoadedPackages
  loadedModules <- readIORef hLoadedModules
  let
    loadPackages = filter (\(pId, _) -> not (pId `S.member` loadedPackages)) ctxPackages
    unloadPackages = loadedPackages S.\\ newLoadedPackages
    newLoadedPackages = S.fromList (map fst ctxPackages)

    loadModules = ctxModules MS.\\ loadedModules
    unloadModules =
      S.fromList (map fst $ MS.elems loadedModules) S.\\
      S.fromList (map fst $ MS.elems ctxModules)

    ctxUpdate = LowLevel.ContextUpdate
      (MS.elems loadModules)
      (S.toList unloadModules)
      loadPackages
      (S.toList unloadPackages)
      ctxSkipValidation
  rootCtxId <- readIORef hContextId
  runExceptT $ do
      clonedRootCtxId <- ExceptT $ LowLevel.cloneCtx hLowLevelHandle rootCtxId
      () <- ExceptT $ LowLevel.updateCtx hLowLevelHandle clonedRootCtxId ctxUpdate
      -- Update successful, now atomically update our local state and the root context id.
      -- If we get interrupted before this stage, the new context will just be garbage collected.
      liftIO $ mask_ $ do
          writeIORef hLoadedPackages newLoadedPackages
          writeIORef hLoadedModules ctxModules
          writeIORef hContextId clonedRootCtxId
      -- clone again so that the returned context is independent of the root context
      ExceptT $ LowLevel.cloneCtx hLowLevelHandle clonedRootCtxId

deleteCtx :: Handle -> LowLevel.ContextId -> IO (Either LowLevel.BackendError ())
deleteCtx Handle{..} ctxId = withSem hConcurrencySem $
  LowLevel.deleteCtx hLowLevelHandle ctxId

gcCtxs :: Handle -> [LowLevel.ContextId] -> IO (Either LowLevel.BackendError ())
gcCtxs Handle{..} ctxIds = withLock hContextLock $ withSem hConcurrencySem $ do
    rootCtxId <- readIORef hContextId
    -- We never want to GC the root context so we always add that
    -- explicitly. Adding it twice is harmless so we do not check
    -- if it is already present.
    LowLevel.gcCtxs hLowLevelHandle (rootCtxId : ctxIds)

encodeModule :: LF.Version -> LF.Module -> (Hash, BS.ByteString)
encodeModule v m = (Hash $ hash m', m')
  where m' = LowLevel.encodeScenarioModule v m

runScenario :: Handle -> LowLevel.ContextId -> LF.ValueRef -> IO (Either LowLevel.Error LowLevel.ScenarioResult)
runScenario h ctxId name = run (\h -> LowLevel.runScenario h ctxId name) h

runScript :: Handle -> LowLevel.ContextId -> LF.ValueRef -> IO (Either LowLevel.Error LowLevel.ScenarioResult)
runScript h ctxId name = run (\h -> LowLevel.runScript h ctxId name) h

run :: (LowLevel.Handle -> IO (Either LowLevel.Error r)) -> Handle -> IO (Either LowLevel.Error r)
run f Handle{..} = do
  resVar <- newEmptyMVar
  -- When a scenario/script execution is aborted, we would like to be able to return
  -- immediately. However, we cannot cancel the actual execution of the scenario/script.
  -- Therefore, we launch run the synchronous execution request in a separate thread
  -- that takes care of managing the semaphore. This thread keeps running
  -- even if `runScenario` was aborted (we cannot abort the FFI calls anyway)
  -- and ensures that we track the actual number of running executions rather
  -- than the number of calls to `run` that have not been canceled.
  _ <- mask $ \restore -> do
      -- Rather than using a bracket in the new thread
      -- we can be a bit more clever and don’t even
      -- launch the new thread until we acquire the
      -- semaphore.
      waitQSemN hConcurrencySem 1
      _ <- forkIO $ do
        r <- try $ restore $ f hLowLevelHandle
        case r of
            Left ex -> putMVar resVar (Left $ LowLevel.ExceptionError ex)
            Right r -> putMVar resVar r
        signalQSemN hConcurrencySem 1
      pure ()
  takeMVar resVar

newtype Hash = Hash Int deriving (Eq, Ord, NFData, Show)

instance Semigroup Hash where
    Hash a <> Hash b = Hash $ hash (a,b)

instance Monoid Hash where
    mempty = Hash 0
    mappend = (<>)


html{
    width: 100%;
    /*overflow: hidden;*/
}
body{
  -webkit-user-select:initial;
  background-color: #f2f2f2;
  width: 100%;
  /*overflow: hidden;*/
}
h1 {
    font-size: 40px;
    color: #000;
    padding-top: 20px;
    text-align: center;
}
.index-wrap h1{
    font-size: 40px;
    color: #34C0F5;
    padding-top: 0;
    height: 64px;
    -webkit-background-size: 100% auto;
            background-size: 100% auto;
    margin-bottom: 10px;
}
.index-wrap h2{
    font-size: 12px;
    color: #bbb;
    line-height: 1.2;
}
.index-wrap{
    width: 100%;
    overflow-x: hidden;
}
.index-wrap .header{
    background-color: #F7F7F7;
    height: 135px;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-box-align: center;
    -webkit-box-pack: center;
}
.index-wrap .footer{
    height: 55px;
    display: -webkit-box;
    -webkit-box-align: center;
    -webkit-box-pack: center;
    background-color: #F7F7F7;
}
.logo{
    width: 53px;
    height: 15px;
    background: url(../img/isux.png) no-repeat;
    -webkit-background-size: 100% auto;
            background-size: 100% auto;
}
.index-wrap table{
    width: 100%;
    overflow: hidden;
}
.demo-block td{
    width: 33.33%;
    /*padding-top: 33.33%;*/
    position: relative;
}
.demo-block td>div{
    padding: 23px 0 23px 0;
}
.demo-block td>div:active{
    background: #e4e4e4;
}
.demo-block .tit{
    text-align: center;
    color: #000;
    font-size: 16px;
    line-height: 1.6;
}
.demo-block .sub-tit{
    text-align: center;
    color: #777;
    font-size: 14px;
    line-height: 1.2;
}
.demo-block .icon{
    width: 46px;
    height: 46px;
    margin: 0 auto;
    /*margin-bottom: 5px;*/
}
.icon-actionsheet{
    background: url(../img/actionsheet.png) no-repeat;
    -webkit-background-size: 100% auto;
            background-size: 100% auto;
}
.icon-article{
    background: url(../img/article.png) no-repeat;
    -webkit-background-size: 100% auto;
            background-size: 100% auto;
}
.icon-button{
    background: url(../img/button.png) no-repeat;
    -webkit-background-size: 100% auto;
            background-size: 100% auto;
}
.icon-cell{
    background: url(../img/cell.png) no-repeat;
    -webkit-background-size: 100% auto;
            background-size: 100% auto;
}
.icon-dialog{
    background: url(../img/dialog.png) no-repeat;
    -webkit-background-size: 100% auto;
            background-size: 100% auto;
}
.icon-icons{
    background: url(../img/icons.png) no-repeat;
    -webkit-background-size: 100% auto;
            background-size: 100% auto;
}
.icon-msg{
    background: url(../img/msg.png) no-repeat;
    -webkit-background-size: 100% auto;
            background-size: 100% auto;
}
.icon-panel{
    background: url(../img/panel.png) no-repeat;
    -webkit-background-size: 100% auto;
            background-size: 100% auto;
}
.icon-progress{
    background: url(../img/progress.png) no-repeat;
    -webkit-background-size: 100% auto;
            background-size: 100% auto;
}
.icon-searchbar{
    background: url(../img/searchbar.png) no-repeat;
    -webkit-background-size: 100% auto;
            background-size: 100% auto;
}
.icon-tab{
    background: url(../img/tab.png) no-repeat;
    -webkit-background-size: 100% auto;
            background-size: 100% auto;
}
.icon-toast{
    background: url(../img/toast.png) no-repeat;
    -webkit-background-size: 100% auto;
            background-size: 100% auto;
}
.icon-more{
    background: url(../img/more.png) no-repeat;
    -webkit-background-size: 100% auto;
            background-size: 100% auto;
}
.icon-grid{
    background: url(../img/grid.png) no-repeat;
    -webkit-background-size: 100% auto;
            background-size: 100% auto;
}
.icon-form{
    background: url(../img/form.png) no-repeat;
    -webkit-background-size: 100% auto;
            background-size: 100% auto;
}
.title{
    /*text-align: center;*/
}

h1{
  width: 100%;
  text-align: center;
  font-size: 40px;
}
.ui-header h1 {
    padding-top: 0;
}
.ui-btn+.ui-btn {
    margin-left: 10px;
}
.demo-desc{
    padding: 10px;
    font-size: 16px;
    color: #7CAE23;
}
.demo-block{
    position: relative;
}
.demo-block .ui-header,
.demo-block .ui-footer{
    position: absolute;
}
.ui-tab-nav{
}
.ui-tab-content{
    padding: 10px;
}
.demo-block > .ui-list,.demo-block >.ui-form{margin-bottom: 20px;}
.content h3{
    padding: 0 15px;
    line-height: 44px;
    font-size: 15px;
}
.border-list{
    background-color: #fff;
}
.border-list li{
    width: 100px;
    margin: 10px auto;
    -webkit-box-pack: center;
    text-align: center;
}
.ui-btn-group-bottom{bottom: 56px;}
.ui-table{
    line-height: 40px;
    text-align: center;
    background-color: #fff;
}
.ui-scroller {width:auto;height:300px;margin:20px;padding:10px;overflow:hidden;}
.ui-scroller li {margin-bottom:10px;}
.ui-notice{
    top: 0;
    z-index: -1;
    height: 400px;
}
.icon-lists li{
  float:left;
  height: 100px;
  width: 103px;
  text-align: center;

}
.icon-lists li i{
    font-size: 32px;
    line-height: 44px;
}
.icon-lists .ui-icon,.icon-lists [class^="ui-icon-"]{
  margin: 10px 0;
  color: #000;
}
.code,.fontclass{
    font-size: 12px;
}
.ui-col{
    padding: 5px;
    background: #777;
    text-align: center;
    -webkit-box-sizing: border-box;
            box-sizing: border-box;
    border: 1px solid #ddd;
}
.ui-flex{
    border: 1px solid #ddd;
    min-height: 80px;
    margin-bottom: 10px;
}
.ui-flex-ver{
    border: 1px solid #ddd;
    min-height: 80px;
    margin-bottom: 10px;
}
.ui-row-flex-ver{
    border: 1px solid #ddd;
    min-height: 100px;
}
.test-img {
    width: 50px;
    height: 50px;
    background: #777;
}

/*
  新增按钮居中问题
*/

/*增加背景色*/
.color-black{
  background-color: #000;
  .demo-desc {
      color: #fff;
  }
}