text:
<?xml version="1.0" encoding="utf-8"?><!--
  ~ 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.
  -->

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <PreferenceCategory android:title="@string/pref_user_profile">
        <EditTextPreference
            android:title="@string/pref_client_id"
            android:defaultValue=""
            android:key="pref_client_id" />
        <EditTextPreference
            android:title="@string/pref_bind_device"
            android:defaultValue=""
            android:key="pref_bind_device" />
        <EditTextPreference
            android:title="@string/pref_server_address"
            android:defaultValue=""
            android:key="pref_server_address" />
    </PreferenceCategory>
    <PreferenceCategory android:title="@string/pref_message_profile">
        <CheckBoxPreference
            android:key="pref_cmd_need_correct"
            android:title="@string/pref_cmd_need_correct"
            android:defaultValue="true" />
        <CheckBoxPreference
            android:key="pref_speech_cmd_need_confirm"
            android:title="@string/pref_speech_cmd_need_confirm"
            android:defaultValue="true" />
        <CheckBoxPreference
            android:key="pref_auto_add_begin_and_end"
            android:title="@string/pref_auto_add_begin_and_end"
            android:defaultValue="false" />
        <EditTextPreference
            android:title="@string/pref_message_begin"
            android:key="pref_message_begin"
            android:enabled="false" />
        <EditTextPreference
            android:title="@string/pref_message_end"
            android:key="pref_message_end"
            android:enabled="false" />
    </PreferenceCategory>
    <PreferenceCategory android:title="@string/pref_network_profile">
        <Preference
            android:title="@string/pref_load_auto_item"
            android:key="load_auto_item" />
        <Preference
            android:title="@string/pref_local_ip_item"
            android:key="local_ip_item" />
        <CheckBoxPreference
            android:key="pref_enable_local_msg"
            android:title="@string/pref_enable_local_msg"
            android:defaultValue="false" />
        <EditTextPreference
            android:title="@string/pref_local_ssid"
            android:defaultValue=""
            android:key="pref_local_ssid" />
        <EditTextPreference
            android:title="@string/pref_local_msg_server_address"
            android:defaultValue=""
            android:key="pref_local_msg_server_address" />
        <EditTextPreference
            android:title="@string/pref_local_msg_subscribe_address"
            android:defaultValue=""
            android:key="pref_local_msg_subscribe_address" />
    </PreferenceCategory>
    <PreferenceCategory android:title="@string/pref_others_profile">
        <CheckBoxPreference
            android:key="pref_loc_me_enable"
            android:title="@string/pref_loc_me_enable"
            android:summary="@string/pref_loc_me_enable_sum"
            android:defaultValue="true" />
        <CheckBoxPreference
            android:key="pref_load_img_wifi"
            android:title="@string/pref_load_img_wifi"
            android:summary="@string/pref_load_img_wifi_sum"
            android:defaultValue="false" />
        <CheckBoxPreference
            android:key="pref_save_power_mode"
            android:title="@string/pref_save_power_mode"
            android:summary="@string/pref_save_power_mode_sum"
            android:defaultValue="false" />
        <CheckBoxPreference
            android:key="pref_auto_connect_sco"
            android:title="@string/pref_auto_connect_sco"
            android:summary="@string/pref_auto_connect_sco_sum"
            android:defaultValue="true" />
        <CheckBoxPreference
            android:key="pref_volume_key_control_speech"
            android:title="@string/pref_volume_key_control_speech"
            android:summary="@string/pref_sum_volume_key_control_speech"
            android:defaultValue="true" />
        <!--<Preference-->
        <!--android:title="@string/pref_homescreen_shortcut"-->
        <!--android:key="homescreen_shortcut" />-->
        <!--<Preference-->
        <!--android:title="@string/pref_clean_cmd_history"-->
        <!--android:key="clean_cmd_history" />-->
    </PreferenceCategory>
</PreferenceScreen>


text:
using System;
using System.Collections;

namespace HarshPoint.Provisioning.Implementation
{
    partial class ResolveBuilder<TResult, TContext>
    {
        void IResolveBuilderElement<TContext>.ElementInitializeContext(TContext context)
        {
            if (context == null)
            {
                throw Logger.Fatal.ArgumentNull(nameof(context));
            }

            InitializeContext(context);
        }

        Object IResolveBuilderElement<TContext>.ElementInitialize(TContext context)
        {
            if (context == null)
            {
                throw Logger.Fatal.ArgumentNull(nameof(context));
            }

            var cached = context.Cache?.TryGetValue(this);

            if (cached != null)
            {
                InitializeCached(context, cached);

                return new CachedResult()
                {
                    Values = cached
                };
            }

            return Initialize(context);
        }

        IEnumerable IResolveBuilderElement<TContext>.ElementToEnumerable(TContext context, Object state)
        {
            if (context == null)
            {
                throw Logger.Fatal.ArgumentNull(nameof(context));
            }

            var cached = (state as CachedResult);

            if (cached != null)
            {
                return cached.Values;
            }

            var result = ToEnumerable(state, context);
            context.Cache?.SetValue(this, result);
            return result;
        }

        protected virtual void InitializeContext(TContext context)
        {
        }

        protected virtual Object Initialize(TContext context) => null;

        protected virtual void InitializeCached(
            TContext context,
            IEnumerable enumerable
        )
        {
        }

        protected abstract IEnumerable ToEnumerable(Object state, TContext context);

        private sealed class CachedResult
        {
            public IEnumerable Values { get; set; }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
typedef NS_ENUM(NSInteger, ProjectsType)
{
    ProjectsTypeAll = 0,
    ProjectsTypeCreated,
    ProjectsTypeJoined,
    ProjectsTypeWatched,
    ProjectsTypeStared,
    ProjectsTypeToChoose,
    ProjectsTypeTaProject,
    ProjectsTypeTaStared,
    ProjectsTypeTaWatched,
    ProjectsTypeAllPublic,
};

@interface Projects : NSObject
@property (strong, nonatomic) User *curUser;
@property (assign, nonatomic) ProjectsType type;
//请求
@property (readwrite, nonatomic, strong) NSNumber *page, *pageSize;
@property (assign, nonatomic) BOOL canLoadMore, willLoadMore, isLoading;
//解析
@property (readwrite, nonatomic, strong) NSNumber *totalPage, *totalRow;
@property (readwrite, nonatomic, strong) NSMutableArray *list;
@property (strong, nonatomic, readonly) NSArray *pinList, *noPinList;
@property (readwrite, nonatomic, strong) NSDictionary *propertyArrayMap;

+ (Projects *)projectsWithType:(ProjectsType)type andUser:(User *)user;
- (NSDictionary *)toParams;
- (NSString *)toPath;
- (void)configWithProjects:(Projects *)responsePros;

@end


text:
package com.tacitknowledge.slowlight.proxyserver.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;

import java.util.concurrent.TimeUnit;

/**
 * This task is used to split given channel message into data fragments and will send them a separate messages to the next handlers.
 *
 * @author Alexandr Donciu (adonciu@tacitknowledge.com)
 */
public class WriteDataFragmentsTask implements Runnable
{
    private ChannelHandlerContext ctx;
    private ByteBuf msg;
    private ChannelPromise promise;

    private int maxDataSize;
    private long delay;

    private WriteDataFragmentsTask thisTask;

    public WriteDataFragmentsTask(final ChannelHandlerContext ctx,
                                   final ByteBuf msg,
                                   final ChannelPromise promise,
                                   final int maxDataSize,
                                   final long delay)
    {
        this.ctx = ctx;
        this.msg = msg;
        this.promise = promise;

        this.maxDataSize = maxDataSize;
        this.delay = delay;

        this.thisTask = this;
    }

    @Override
    public void run()
    {
        if (msg.isReadable())
        {
            ctx.writeAndFlush(readDataFragment(msg)).addListener(new WriteDataListener());
        }
    }

    private ByteBuf readDataFragment(final ByteBuf readChannelBuffer)
    {
        final int readableBytes = readChannelBuffer.readableBytes();
        final int bytesToRead = maxDataSize == 0 || readableBytes < maxDataSize ? readableBytes : maxDataSize;

        final ByteBuf writeChannelBuffer = Unpooled.buffer(bytesToRead);
        readChannelBuffer.readBytes(writeChannelBuffer, bytesToRead);

        return writeChannelBuffer;
    }

    /**
     * Listener class to schedule next write data fragment task.
     */
    protected class WriteDataListener implements ChannelFutureListener
    {
        @Override
        public void operationComplete(final ChannelFuture future) throws Exception
        {
            if (future.isSuccess())
            {
                if (msg.readableBytes() > 0)
                {
                    ctx.executor().schedule(thisTask, delay, TimeUnit.MILLISECONDS);
                }
                else
                {
                    promise.setSuccess();
                }
            }
            else
            {
                future.channel().close();
            }
        }
    }
}


text:
package org.apache.spark.sql.kafka010

import java.io.{File, IOException}
import java.lang.{Integer => JInt}
import java.net.{InetAddress, InetSocketAddress}
import java.nio.charset.StandardCharsets
import java.util.{Collections, Map => JMap, Properties, UUID}
import java.util.concurrent.TimeUnit
import javax.security.auth.login.Configuration

import scala.collection.JavaConverters._
import scala.util.Random

import com.google.common.io.Files
import kafka.api.Request
import kafka.server.{KafkaConfig, KafkaServer}
import kafka.server.checkpoints.OffsetCheckpointFile
import kafka.utils.ZkUtils
import org.apache.hadoop.minikdc.MiniKdc
import org.apache.hadoop.security.UserGroupInformation
import org.apache.kafka.clients.CommonClientConfigs
import org.apache.kafka.clients.admin.{AdminClient, CreatePartitionsOptions, ListConsumerGroupsResult, NewPartitions, NewTopic}
import org.apache.kafka.clients.consumer.KafkaConsumer
import org.apache.kafka.clients.producer._
import org.apache.kafka.common.TopicPartition
import org.apache.kafka.common.config.SaslConfigs
import org.apache.kafka.common.header.Header
import org.apache.kafka.common.header.internals.RecordHeader
import org.apache.kafka.common.network.ListenerName
import org.apache.kafka.common.security.auth.SecurityProtocol.{PLAINTEXT, SASL_PLAINTEXT}
import org.apache.kafka.common.serialization.{StringDeserializer, StringSerializer}
import org.apache.zookeeper.server.{NIOServerCnxnFactory, ZooKeeperServer}
import org.apache.zookeeper.server.auth.SASLAuthenticationProvider
import org.scalatest.concurrent.Eventually._
import org.scalatest.time.SpanSugar._

import org.apache.spark.{SparkConf, SparkException}
import org.apache.spark.internal.Logging
import org.apache.spark.kafka010.KafkaTokenUtil
import org.apache.spark.util.{ShutdownHookManager, Utils}

/**
 * This is a helper class for Kafka test suites. This has the functionality to set up
 * and tear down local Kafka servers, and to push data using Kafka producers.
 *
 * The reason to put Kafka test utility class in src is to test Python related Kafka APIs.
 */
class KafkaTestUtils(
    withBrokerProps: Map[String, Object] = Map.empty,
    secure: Boolean = false) extends Logging {

  private val JAVA_AUTH_CONFIG = "java.security.auth.login.config"

  private val localCanonicalHostName = InetAddress.getLoopbackAddress().getCanonicalHostName()
  logInfo(s"Local host name is $localCanonicalHostName")

  private var kdc: MiniKdc = _

  // Zookeeper related configurations
  private val zkHost = localCanonicalHostName
  private var zkPort: Int = 0
  private val zkConnectionTimeout = 60000
  private val zkSessionTimeout = 10000

  private var zookeeper: EmbeddedZookeeper = _
  private var zkUtils: ZkUtils = _

  // Kafka broker related configurations
  private val brokerHost = localCanonicalHostName
  private var brokerPort = 0
  private var brokerConf: KafkaConfig = _

  private val brokerServiceName = "kafka"
  private val clientUser = s"client/$localCanonicalHostName"
  private var clientKeytabFile: File = _

  // Kafka broker server
  private var server: KafkaServer = _
  private var adminClient: AdminClient = _

  // Kafka producer
  private var producer: Producer[String, String] = _

  // Flag to test whether the system is correctly started
  private var kdcReady = false
  private var zkReady = false
  private var brokerReady = false
  private var leakDetector: AnyRef = null

  def zkAddress: String = {
    assert(zkReady, "Zookeeper not setup yet or already torn down, cannot get zookeeper address")
    s"$zkHost:$zkPort"
  }

  def brokerAddress: String = {
    assert(brokerReady, "Kafka not setup yet or already torn down, cannot get broker address")
    s"$brokerHost:$brokerPort"
  }

  def zookeeperClient: ZkUtils = {
    assert(zkReady, "Zookeeper not setup yet or already torn down, cannot get zookeeper client")
    Option(zkUtils).getOrElse(
      throw new IllegalStateException("Zookeeper client is not yet initialized"))
  }

  def clientPrincipal: String = {
    assert(kdcReady, "KDC should be set up beforehand")
    clientUser + "@" + kdc.getRealm()
  }

  def clientKeytab: String = {
    assert(kdcReady, "KDC should be set up beforehand")
    clientKeytabFile.getAbsolutePath()
  }

  private def setUpMiniKdc(): Unit = {
    val kdcDir = Utils.createTempDir()
    val kdcConf = MiniKdc.createConf()
    kdc = new MiniKdc(kdcConf, kdcDir)
    kdc.start()
    kdcReady = true
  }

  private def createKeytabsAndJaasConfigFile(): String = {
    assert(kdcReady, "KDC should be set up beforehand")
    val baseDir = Utils.createTempDir()

    val zkServerUser = s"zookeeper/$localCanonicalHostName"
    val zkServerKeytabFile = new File(baseDir, "zookeeper.keytab")
    kdc.createPrincipal(zkServerKeytabFile, zkServerUser)
    logDebug(s"Created keytab file: ${zkServerKeytabFile.getAbsolutePath()}")

    val zkClientUser = s"zkclient/$localCanonicalHostName"
    val zkClientKeytabFile = new File(baseDir, "zkclient.keytab")
    kdc.createPrincipal(zkClientKeytabFile, zkClientUser)
    logDebug(s"Created keytab file: ${zkClientKeytabFile.getAbsolutePath()}")

    val kafkaServerUser = s"kafka/$localCanonicalHostName"
    val kafkaServerKeytabFile = new File(baseDir, "kafka.keytab")
    kdc.createPrincipal(kafkaServerKeytabFile, kafkaServerUser)
    logDebug(s"Created keytab file: ${kafkaServerKeytabFile.getAbsolutePath()}")

    clientKeytabFile = new File(baseDir, "client.keytab")
    kdc.createPrincipal(clientKeytabFile, clientUser)
    logDebug(s"Created keytab file: ${clientKeytabFile.getAbsolutePath()}")

    val file = new File(baseDir, "jaas.conf");
    val realm = kdc.getRealm()
    val content =
      s"""
      |Server {
      |  ${KafkaTokenUtil.getKrb5LoginModuleName} required
      |  useKeyTab=true
      |  storeKey=true
      |  useTicketCache=false
      |  keyTab="${zkServerKeytabFile.getAbsolutePath()}"
      |  principal="$zkServerUser@$realm";
      |};
      |
      |Client {
      |  ${KafkaTokenUtil.getKrb5LoginModuleName} required
      |  useKeyTab=true
      |  storeKey=true
      |  useTicketCache=false
      |  keyTab="${zkClientKeytabFile.getAbsolutePath()}"
      |  principal="$zkClientUser@$realm";
      |};
      |
      |KafkaServer {
      |  ${KafkaTokenUtil.getKrb5LoginModuleName} required
      |  serviceName="$brokerServiceName"
      |  useKeyTab=true
      |  storeKey=true
      |  keyTab="${kafkaServerKeytabFile.getAbsolutePath()}"
      |  principal="$kafkaServerUser@$realm";
      |};
      """.stripMargin.trim
    Files.write(content, file, StandardCharsets.UTF_8)
    logDebug(s"Created JAAS file: ${file.getPath}")
    logDebug(s"JAAS file content: $content")
    file.getAbsolutePath()
  }

  // Set up the Embedded Zookeeper server and get the proper Zookeeper port
  private def setupEmbeddedZookeeper(): Unit = {
    // Zookeeper server startup
    zookeeper = new EmbeddedZookeeper(s"$zkHost:$zkPort")
    // Get the actual zookeeper binding port
    zkPort = zookeeper.actualPort
    zkUtils = ZkUtils(s"$zkHost:$zkPort", zkSessionTimeout, zkConnectionTimeout, false)
    zkReady = true
  }

  // Set up the Embedded Kafka server
  private def setupEmbeddedKafkaServer(): Unit = {
    assert(zkReady, "Zookeeper should be set up beforehand")

    val protocolName = if (!secure) PLAINTEXT.name else SASL_PLAINTEXT.name

    // Kafka broker startup
    Utils.startServiceOnPort(brokerPort, port => {
      brokerPort = port
      brokerConf = new KafkaConfig(brokerConfiguration, doLog = false)
      server = new KafkaServer(brokerConf)
      server.startup()
      brokerPort = server.boundPort(new ListenerName(protocolName))
      (server, brokerPort)
    }, new SparkConf(), "KafkaBroker")

    adminClient = AdminClient.create(adminClientConfiguration)
    brokerReady = true
  }

  /** setup the whole embedded servers, including Zookeeper and Kafka brokers */
  def setup(): Unit = {
    // Set up a KafkaTestUtils leak detector so that we can see where the leak KafkaTestUtils is
    // created.
    val exception = new SparkException("It was created at: ")
    leakDetector = ShutdownHookManager.addShutdownHook { () =>
      logError("Found a leak KafkaTestUtils.", exception)
    }

    if (secure) {
      setUpMiniKdc()
      val jaasConfigFile = createKeytabsAndJaasConfigFile()
      System.setProperty(JAVA_AUTH_CONFIG, jaasConfigFile)
      Configuration.getConfiguration.refresh()
    } else {
      System.clearProperty(JAVA_AUTH_CONFIG)
    }
    setupEmbeddedZookeeper()
    setupEmbeddedKafkaServer()
    eventually(timeout(1.minute)) {
      assert(zkUtils.getAllBrokersInCluster().nonEmpty, "Broker was not up in 60 seconds")
    }
  }

  /** Teardown the whole servers, including Kafka broker and Zookeeper */
  def teardown(): Unit = {
    if (leakDetector != null) {
      ShutdownHookManager.removeShutdownHook(leakDetector)
    }
    brokerReady = false
    zkReady = false

    if (producer != null) {
      producer.close()
      producer = null
    }

    if (adminClient != null) {
      adminClient.close()
    }

    if (server != null) {
      server.shutdown()
      server.awaitShutdown()
      server = null
    }

    // On Windows, `logDirs` is left open even after Kafka server above is completely shut down
    // in some cases. It leads to test failures on Windows if the directory deletion failure
    // throws an exception.
    brokerConf.logDirs.foreach { f =>
      try {
        Utils.deleteRecursively(new File(f))
      } catch {
        case e: IOException if Utils.isWindows =>
          logWarning(e.getMessage)
      }
    }

    if (zkUtils != null) {
      zkUtils.close()
      zkUtils = null
    }

    if (zookeeper != null) {
      zookeeper.shutdown()
      zookeeper = null
    }

    System.clearProperty(JAVA_AUTH_CONFIG)
    Configuration.getConfiguration.refresh()
    if (kdc != null) {
      kdc.stop()
    }
    UserGroupInformation.reset()
  }

  /** Create a Kafka topic and wait until it is propagated to the whole cluster */
  def createTopic(topic: String, partitions: Int, overwrite: Boolean = false): Unit = {
    var created = false
    while (!created) {
      try {
        val newTopic = new NewTopic(topic, partitions, 1)
        adminClient.createTopics(Collections.singleton(newTopic))
        created = true
      } catch {
        // Workaround fact that TopicExistsException is in kafka.common in 0.10.0 and
        // org.apache.kafka.common.errors in 0.10.1 (!)
        case e: Exception if (e.getClass.getSimpleName == "TopicExistsException") && overwrite =>
          deleteTopic(topic)
      }
    }
    // wait until metadata is propagated
    (0 until partitions).foreach { p =>
      waitUntilMetadataIsPropagated(topic, p)
    }
  }

  def getAllTopicsAndPartitionSize(): Seq[(String, Int)] = {
    zkUtils.getPartitionsForTopics(zkUtils.getAllTopics()).mapValues(_.size).toSeq
  }

  /** Create a Kafka topic and wait until it is propagated to the whole cluster */
  def createTopic(topic: String): Unit = {
    createTopic(topic, 1)
  }

  /** Delete a Kafka topic and wait until it is propagated to the whole cluster */
  def deleteTopic(topic: String): Unit = {
    val partitions = zkUtils.getPartitionsForTopics(Seq(topic))(topic).size
    adminClient.deleteTopics(Collections.singleton(topic))
    verifyTopicDeletionWithRetries(zkUtils, topic, partitions, List(this.server))
  }

  /** Add new partitions to a Kafka topic */
  def addPartitions(topic: String, partitions: Int): Unit = {
    adminClient.createPartitions(
      Map(topic -> NewPartitions.increaseTo(partitions)).asJava,
      new CreatePartitionsOptions)
    // wait until metadata is propagated
    (0 until partitions).foreach { p =>
      waitUntilMetadataIsPropagated(topic, p)
    }
  }

  def sendMessages(topic: String, msgs: Array[String]): Seq[(String, RecordMetadata)] = {
    sendMessages(topic, msgs, None)
  }

  def sendMessages(
      topic: String,
      msgs: Array[String],
      part: Option[Int]): Seq[(String, RecordMetadata)] = {
    val records = msgs.map { msg =>
      val builder = new RecordBuilder(topic, msg)
      part.foreach { p => builder.partition(p) }
      builder.build()
    }
    sendMessages(records)
  }

  def sendMessage(msg: ProducerRecord[String, String]): Seq[(String, RecordMetadata)] = {
    sendMessages(Array(msg))
  }

  def sendMessages(msgs: Seq[ProducerRecord[String, String]]): Seq[(String, RecordMetadata)] = {
    producer = new KafkaProducer[String, String](producerConfiguration)
    val offsets = try {
      msgs.map { msg =>
        val metadata = producer.send(msg).get(10, TimeUnit.SECONDS)
        logInfo(s"\tSent ($msg) to partition ${metadata.partition}, offset ${metadata.offset}")
        (msg.value(), metadata)
      }
    } finally {
      if (producer != null) {
        producer.close()
        producer = null
      }
    }
    offsets
  }

  def cleanupLogs(): Unit = {
    server.logManager.cleanupLogs()
  }

  def getEarliestOffsets(topics: Set[String]): Map[TopicPartition, Long] = {
    val kc = new KafkaConsumer[String, String](consumerConfiguration)
    logInfo("Created consumer to get earliest offsets")
    kc.subscribe(topics.asJavaCollection)
    kc.poll(0)
    val partitions = kc.assignment()
    kc.pause(partitions)
    kc.seekToBeginning(partitions)
    val offsets = partitions.asScala.map(p => p -> kc.position(p)).toMap
    kc.close()
    logInfo("Closed consumer to get earliest offsets")
    offsets
  }

  def getLatestOffsets(topics: Set[String]): Map[TopicPartition, Long] = {
    val kc = new KafkaConsumer[String, String](consumerConfiguration)
    logInfo("Created consumer to get latest offsets")
    kc.subscribe(topics.asJavaCollection)
    kc.poll(0)
    val partitions = kc.assignment()
    kc.pause(partitions)
    kc.seekToEnd(partitions)
    val offsets = partitions.asScala.map(p => p -> kc.position(p)).toMap
    kc.close()
    logInfo("Closed consumer to get latest offsets")
    offsets
  }

  def listConsumerGroups(): ListConsumerGroupsResult = {
    adminClient.listConsumerGroups()
  }

  protected def brokerConfiguration: Properties = {
    val props = new Properties()
    props.put("broker.id", "0")
    props.put("host.name", "127.0.0.1")
    props.put("advertised.host.name", "127.0.0.1")
    props.put("port", brokerPort.toString)
    props.put("log.dir", Utils.createTempDir().getAbsolutePath)
    props.put("zookeeper.connect", zkAddress)
    props.put("zookeeper.connection.timeout.ms", "60000")
    props.put("log.flush.interval.messages", "1")
    props.put("replica.socket.timeout.ms", "1500")
    props.put("delete.topic.enable", "true")
    props.put("group.initial.rebalance.delay.ms", "10")

    // Change the following settings as we have only 1 broker
    props.put("offsets.topic.num.partitions", "1")
    props.put("offsets.topic.replication.factor", "1")
    props.put("transaction.state.log.replication.factor", "1")
    props.put("transaction.state.log.min.isr", "1")

    if (secure) {
      props.put("listeners", "SASL_PLAINTEXT://127.0.0.1:0")
      props.put("advertised.listeners", "SASL_PLAINTEXT://127.0.0.1:0")
      props.put("inter.broker.listener.name", "SASL_PLAINTEXT")
      props.put("delegation.token.master.key", UUID.randomUUID().toString)
      props.put("sasl.enabled.mechanisms", "GSSAPI,SCRAM-SHA-512")
    }

    // Can not use properties.putAll(propsMap.asJava) in scala-2.12
    // See https://github.com/scala/bug/issues/10418
    withBrokerProps.foreach { case (k, v) => props.put(k, v) }
    props
  }

  private def adminClientConfiguration: Properties = {
    val props = new Properties()
    props.put(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, s"$brokerHost:$brokerPort")
    setAuthenticationConfigIfNeeded(props)
    props
  }

  private def producerConfiguration: Properties = {
    val props = new Properties()
    props.put("bootstrap.servers", brokerAddress)
    props.put("value.serializer", classOf[StringSerializer].getName)
    props.put("key.serializer", classOf[StringSerializer].getName)
    // wait for all in-sync replicas to ack sends
    props.put("acks", "all")
    setAuthenticationConfigIfNeeded(props)
    props
  }

  /** Call `f` with a `KafkaProducer` that has initialized transactions. */
  def withTranscationalProducer(f: KafkaProducer[String, String] => Unit): Unit = {
    val props = producerConfiguration
    props.put("transactional.id", UUID.randomUUID().toString)
    val producer = new KafkaProducer[String, String](props)
    try {
      producer.initTransactions()
      f(producer)
    } finally {
      producer.close()
    }
  }

  private def consumerConfiguration: Properties = {
    val props = new Properties()
    props.put("bootstrap.servers", brokerAddress)
    props.put("group.id", "group-KafkaTestUtils-" + Random.nextInt)
    props.put("value.deserializer", classOf[StringDeserializer].getName)
    props.put("key.deserializer", classOf[StringDeserializer].getName)
    props.put("enable.auto.commit", "false")
    setAuthenticationConfigIfNeeded(props)
    props
  }

  private def setAuthenticationConfigIfNeeded(props: Properties): Unit = {
    if (secure) {
      val jaasParams = KafkaTokenUtil.getKeytabJaasParams(
        clientKeytabFile.getAbsolutePath, clientPrincipal, brokerServiceName)
      props.put(SaslConfigs.SASL_JAAS_CONFIG, jaasParams)
      props.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, SASL_PLAINTEXT.name)
    }
  }

  /** Verify topic is deleted in all places, e.g, brokers, zookeeper. */
  private def verifyTopicDeletion(
      topic: String,
      numPartitions: Int,
      servers: Seq[KafkaServer]): Unit = {
    val topicAndPartitions = (0 until numPartitions).map(new TopicPartition(topic, _))

    import ZkUtils._
    // wait until admin path for delete topic is deleted, signaling completion of topic deletion
    assert(
      !zkUtils.pathExists(getDeleteTopicPath(topic)),
      s"${getDeleteTopicPath(topic)} still exists")
    assert(!zkUtils.pathExists(getTopicPath(topic)), s"${getTopicPath(topic)} still exists")
    // ensure that the topic-partition has been deleted from all brokers' replica managers
    assert(servers.forall(server => topicAndPartitions.forall(tp =>
      server.replicaManager.getPartition(tp) == None)),
      s"topic $topic still exists in the replica manager")
    // ensure that logs from all replicas are deleted if delete topic is marked successful
    assert(servers.forall(server => topicAndPartitions.forall(tp =>
      server.getLogManager().getLog(tp).isEmpty)),
      s"topic $topic still exists in log mananger")
    // ensure that topic is removed from all cleaner offsets
    assert(servers.forall(server => topicAndPartitions.forall { tp =>
      val checkpoints = server.getLogManager().liveLogDirs.map { logDir =>
        new OffsetCheckpointFile(new File(logDir, "cleaner-offset-checkpoint")).read()
      }
      checkpoints.forall(checkpointsPerLogDir => !checkpointsPerLogDir.contains(tp))
    }), s"checkpoint for topic $topic still exists")
    // ensure the topic is gone
    assert(
      !zkUtils.getAllTopics().contains(topic),
      s"topic $topic still exists on zookeeper")
  }

  /** Verify topic is deleted. Retry to delete the topic if not. */
  private def verifyTopicDeletionWithRetries(
      zkUtils: ZkUtils,
      topic: String,
      numPartitions: Int,
      servers: Seq[KafkaServer]) {
    eventually(timeout(1.minute), interval(200.milliseconds)) {
      try {
        verifyTopicDeletion(topic, numPartitions, servers)
      } catch {
        case e: Throwable =>
          // As pushing messages into Kafka updates Zookeeper asynchronously, there is a small
          // chance that a topic will be recreated after deletion due to the asynchronous update.
          // Hence, delete the topic and retry.
          adminClient.deleteTopics(Collections.singleton(topic))
          throw e
      }
    }
  }

  private def waitUntilMetadataIsPropagated(topic: String, partition: Int): Unit = {
    def isPropagated = server.dataPlaneRequestProcessor.metadataCache
        .getPartitionInfo(topic, partition) match {
      case Some(partitionState) =>
        zkUtils.getLeaderForPartition(topic, partition).isDefined &&
          Request.isValidBrokerId(partitionState.basePartitionState.leader) &&
          !partitionState.basePartitionState.replicas.isEmpty

      case _ =>
        false
    }
    eventually(timeout(1.minute)) {
      assert(isPropagated, s"Partition [$topic, $partition] metadata not propagated after timeout")
    }
  }

  /**
   * Wait until the latest offset of the given `TopicPartition` is not less than `offset`.
   */
  def waitUntilOffsetAppears(topicPartition: TopicPartition, offset: Long): Unit = {
    eventually(timeout(1.minute)) {
      val currentOffset = getLatestOffsets(Set(topicPartition.topic)).get(topicPartition)
      assert(currentOffset.nonEmpty && currentOffset.get >= offset)
    }
  }

  private class EmbeddedZookeeper(val zkConnect: String) {
    private val ZOOKEEPER_AUTH_PROVIDER = "zookeeper.authProvider.1"

    val snapshotDir = Utils.createTempDir()
    val logDir = Utils.createTempDir()

    if (secure) {
      System.setProperty(ZOOKEEPER_AUTH_PROVIDER, classOf[SASLAuthenticationProvider].getName)
    } else {
      System.clearProperty(ZOOKEEPER_AUTH_PROVIDER)
    }
    val zookeeper = new ZooKeeperServer(snapshotDir, logDir, 500)
    val (ip, port) = {
      val splits = zkConnect.split(":")
      (splits(0), splits(1).toInt)
    }
    val factory = new NIOServerCnxnFactory()
    factory.configure(new InetSocketAddress(ip, port), 16)
    factory.startup(zookeeper)

    val actualPort = factory.getLocalPort

    def shutdown() {
      factory.shutdown()
      // The directories are not closed even if the ZooKeeper server is shut down.
      // Please see ZOOKEEPER-1844, which is fixed in 3.4.6+. It leads to test failures
      // on Windows if the directory deletion failure throws an exception.
      try {
        Utils.deleteRecursively(snapshotDir)
      } catch {
        case e: IOException if Utils.isWindows =>
          logWarning(e.getMessage)
      }
      try {
        Utils.deleteRecursively(logDir)
      } catch {
        case e: IOException if Utils.isWindows =>
          logWarning(e.getMessage)
      }
      System.clearProperty(ZOOKEEPER_AUTH_PROVIDER)
    }
  }
}


text:
import { BaseComponent } from '../base/Base';
export class CheckBoxComponent extends BaseComponent {
  elementInfo() {
    let info = super.elementInfo();
    info.type = 'input';
    info.changeEvent = 'click';
    info.attr.type = this.component.inputType;
    info.attr.class = '';
    if (this.component.name) {
      info.attr.name = 'data[' + this.component.name + ']';
    }
    info.attr.value = this.component.value ? this.component.value : 0;
    return info;
  }

  build() {
    if (!this.component.input) {
      return;
    }
    this.createElement();
    this.input = this.createInput(this.element);
    this.createLabel(this.element, this.input);
    if (!this.label) {
      this.addInput(this.input, this.element);
    }
    if (this.options.readOnly) {
      this.disabled = true;
    }
  }

  createElement() {
    let className = this.className;
    if (this.component.label) {
      className += ' checkbox';
    }
    this.element = this.ce('element', 'div', {
      id: this.id,
      class: className
    });
  }

  createLabel(container, input) {
    if (!this.component.label) {
      return null;
    }
    this.label = this.ce('label', 'label', {
      class: 'control-label'
    });

    // Create the SPAN around the textNode for better style hooks
    this.labelSpan = this.ce('labelSpan', 'span');

    if (this.info.attr.id) {
      this.label.setAttribute('for', this.info.attr.id);
    }
    this.addInput(input, this.label);
    if (!this.options.inputsOnly) {
      // DMS

      //this.labelSpan.appendChild(this.text(this.component.label));
      //this.label.appendChild(this.labelSpan);

      var labelElement = document.createElement('div');
      labelElement.innerHTML = this.component.label;
      this.label.appendChild(labelElement);
    }
    container.appendChild(this.label);
  }

  createInput(container) {
    if (!this.component.input) {
      return;
    }
    let input = this.ce('input', this.info.type, this.info.attr);
    this.errorContainer = container;
    return input;
  }

  addInputEventListener(input) {
    this.addEventListener(input, this.info.changeEvent, () => {
      // If this input has a "name", then its other input elements are elsewhere on
      // the form. To get the correct submission object, we need to refresh the whole
      // data object.
      if (this.component.name) {
        this.emit('refreshData');
      }
      else {
        this.updateValue();
      }
    });
  }

  getValueAt(index) {
    return !!this.inputs[index].checked;
  }

  setValue(value, noUpdate, noValidate) {
    this.value = value;
    if (!this.input) {
      return;
    }
    if (value === 'on') {
      this.input.value = 1;
      this.input.checked = 1;
    }
    else if (value === 'off') {
      this.input.value = 0;
      this.input.checked = 0;
    }
    else if (value) {
      this.input.value = 1;
      this.input.checked = 1;
    }
    else {
      this.input.value = 0;
      this.input.checked = 0;
    }
    if (!noUpdate) {
      this.updateValue(noValidate);
    }
  }
}


text:
use 5.010;
use strict;
use warnings;

package App::mymeta_requires;
# ABSTRACT: Extract module requirements from MYMETA files
our $VERSION = '0.005'; # VERSION

# Dependencies
use autodie 2.00;
use Class::Load qw/try_load_class/;
use CPAN::Meta;
use Log::Dispatchouli;
use Getopt::Lucid ':all';
use Object::Tiny qw/opt logger/;
use CPAN::Meta::Requirements;

my $opt_spec = [
  Param("file|f"),
  Switch("verbose|v"),
  Switch("help|h"),
  Switch("runtime|r")->default(1),
  Switch("configure|c")->default(1),
  Switch("build|b")->default(1),
  Switch("test|t")->default(1),
  Switch("develop|d")->default(0),
  Switch("recommends")->default(1),
  Switch("suggests")->default(1),
];

sub new {
  my $class = shift;
  my $self = bless {}, $class;
  $self->{opt} = Getopt::Lucid->getopt($opt_spec);
  $self->{logger} = Log::Dispatchouli->new({
      ident => 'mymeta-requires',
      to_stderr => 1,
      debug => $self->opt->get_verbose,
      log_pid => 0,
  });
  return $self;
}

sub run {
  my $self = shift;
  $self = $self->new unless ref $self;

  if ( $self->opt->get_help ) {
    require File::Basename;
    require Pod::Usage;
    my $file = File::Basename::basename($0);
    Pod::Usage::pod2usage();
  }

  my $mymeta = $self->load_mymeta
    or $self->logger->log_fatal("Could not load a MYMETA file");
  my $prereqs = $self->merge_prereqs( $mymeta->effective_prereqs );
  my @missing = $self->find_missing( $prereqs );
  say for sort @missing;
  return 0;
}

sub load_mymeta {
  my $self = shift;
  my @candidates = $self->opt->get_file
    ? ($self->opt->get_file)
    : qw/MYMETA.json MYMETA.yml META.json META.yml/;
  for my $f ( @candidates ) {
    next unless -r $f;
    my $mymeta = eval { CPAN::Meta->load_file($f) }
      or $self->logger->log_debug("Error loading '$f': $@");
    if ( $mymeta ) {
      $self->logger->log_debug("Got MYMETA from '$f'");
      return $mymeta;
    }
  }
  return;
}

sub merge_prereqs {
  my ($self, $prereqs) = @_;
  my $merged = CPAN::Meta::Requirements->new;
  for my $phase (qw(configure runtime build test develop)) {
    my $get_p = "get_$phase";
    next unless $self->opt->$get_p;
    # Always get 'requires'
    $merged->add_requirements( $prereqs->requirements_for( $phase, 'requires' ) );
    # Maybe get other types
    for my $extra( qw/recommends suggests/ ) {
      my $get_x = "get_$extra";
      next unless $self->opt->$get_x;
      $merged->add_requirements( $prereqs->requirements_for( $phase, $extra ) );
    }
  }
  return $merged;
}

sub find_missing {
  my ($self, $prereqs) = @_;
  my @missing;
  for my $mod ( $prereqs->required_modules ) {
    next if $mod eq 'perl';
    if ( try_load_class($mod) ) {
      push @missing, $mod unless $prereqs->accepts_module($mod, $mod->VERSION);
    }
    else {
      push @missing, $mod;
    }
  }
  return @missing;
}

1;

# vim: ts=2 sts=2 sw=2 et:

__END__

=pod

=encoding utf-8

=head1 NAME

App::mymeta_requires - Extract module requirements from MYMETA files

=head1 VERSION

version 0.005

=head1 SYNOPSIS

   use App::mymeta_requires;
   exit App::mymeta_requires->run;

=head1 DESCRIPTION

This module contains the guts of the LE<lt>mymeta_requiresE<gt> program.  See
that program for command line usage information.

=for Pod::Coverage find_missing
load_mymeta
logger
merge_prereqs
new
opt
run

=for :stopwords cpan testmatrix url annocpan anno bugtracker rt cpants kwalitee diff irc mailto metadata placeholders metacpan

=head1 SUPPORT

=head2 Bugs / Feature Requests

Please report any bugs or feature requests through the issue tracker
at L<https://github.com/dagolden/app-mymeta_requires/issues>.
You will be notified automatically of any progress on your issue.

=head2 Source Code

This is open source software.  The code repository is available for
public review and contribution under the terms of the license.

L<https://github.com/dagolden/app-mymeta_requires>

  git clone git://github.com/dagolden/app-mymeta_requires.git

=head1 AUTHOR

David Golden <dagolden@cpan.org>

=head1 COPYRIGHT AND LICENSE

This software is Copyright (c) 2011 by David Golden.

This is free software, licensed under:

  The Apache License, Version 2.0, January 2004

=cut


text:
extern void DrawLaraL4();

#endif


text:
// Copyright (c) "Neo4j"
// Neo4j Sweden AB [http://neo4j.com]
//
// This file is part of Neo4j.
//
// 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.
namespace Neo4j.Driver
{
    /// <summary>
    /// Representation for notifications found when executing a query.
    ///
    /// A notification can be visualized in a client pinpointing problems or other information about the query.
    /// </summary>
    public interface INotification
    {
        /// <summary>
        ///Gets a notification code for the discovered issue.
        /// </summary>
        string Code { get; }

        /// <summary>
        ///Gets a short summary of the notification.
        /// </summary>
        string Title { get; }

        /// <summary>
        ///Gets a longer description of the notification.
        /// </summary>
        string Description { get; }

        /// <summary>
        ///Gets the position in the query where this notification points to.
        ///Not all notifications have a unique position to point to and in that case the position would be set to all 0s.
        /// </summary>
        IInputPosition Position { get; }

        /// <summary>
        /// Gets The severity level of the notification.
        /// </summary>
        string Severity { get; }
    }

}


text:
Find the location for an address.

![Find address sample](find-address.png)

## Use case

A user can input a raw address into your app's search bar and zoom to the address location.

## How to use the sample

For simplicity, the sample comes loaded with a set of suggested addresses. Choose an address from the suggestions or submit your own address to show its location on the map in a callout. Tap the pin to display the address on the map.

## How it works

1. Create an `AGSLocatorTask` using the URL to a locator service.
2. Create an instance of `AGSGeocodeParameters` and specify the `AGSGeocodeParameters.resultAttributeNames`.
3. Pass the `AGSGeocodeParameters` into `AGSLocatorTask.geocode(withSearchText:parameters:completion:)` and get the matching results from the `AGSGeocodeResult`.
4. Create an `AGSGraphic` with the geocode result's location and store the geocode result's attributes in the graphic's attributes.
5. Show the graphic in an `AGSGraphicsOverlay`.

## Relevant API

* AGSGeocodeParameters
* AGSGeocodeResult
* AGSLocatorTask

## Additional information

This sample uses the World Geocoding Service. For more information, see [Geocoding service](https://developers.arcgis.com/documentation/mapping-apis-and-services/search/services/geocoding-service/) from *ArcGIS for Developers*.

## Tags

address, geocode, locator, search


text:
tags: java
layout: post
title: "JIRA 2.4 released"
---

JIRA, our favorite issue tracking system, has come out with 2.4. Lots of cool changes here, although the Jelly changes are like shipping a highly sharpened chainsaw with every download :-)


text:
import React from "react";
import rcSlider from "rc-slider";
import moment from "moment-timezone";
import defaults from "lodash.defaults";
import clamp from "lodash.clamp";
import humanizeDuration from "humanize-duration";

class timeSlider extends React.Component {
  constructor() {
    super();
    this.state = {};
    this.selectTime = this.selectTime.bind(this);
    this.handleAfterChange = this.handleAfterChange.bind(this);
    this.toggleAnimating = this.toggleAnimating.bind(this);
    this.changeAnimationRate = this.changeAnimationRate.bind(this);
    this.halveSpeed = this.halveSpeed.bind(this);
    this.doubleSpeed = this.doubleSpeed.bind(this);
    this.doAnimationFrame = this.doAnimationFrame.bind(this);
  }

  componentWillMount() {
    setInterval(this.doAnimationFrame, 100);
  }

  doAnimationFrame() {
    var mapOptions = this.props.mapOptions;
    if (mapOptions.isAnimating) {
      var time = mapOptions.time;
      var animationSpeed = mapOptions.animationFrameMinutes
        ? mapOptions.animationFrameMinutes
        : ((mapOptions.latestTime - mapOptions.earliestTime) / 1000 / 60) *
          0.01;
      time.add(animationSpeed, "minute");
      if (time.isAfter(mapOptions.latestTime)) {
        time = mapOptions.earliestTime;
      }
      mapOptions.animationFrameMinutes = animationSpeed;
      this.selectTime(+time);
      this.props.updateMapOptions({ mapOptions });
    }
  }

  selectTime(time) {
    this.props.selectTime({
      time: moment.utc(time),
      ignore: !this.props.mapOptions.isAnimating
    });
  }

  handleAfterChange(time) {
    this.props.selectTime({ time: moment.utc(time), ignore: false });
  }

  toggleAnimating() {
    var mapOptions = this.props.mapOptions;
    if (mapOptions.earliestTime && mapOptions.latestTime) {
      mapOptions.isAnimating = !mapOptions.isAnimating;
    }
    this.props.updateMapOptions({ mapOptions });
  }

  changeAnimationRate(options) {
    defaults(options, { rate: 1 });
    var mapOptions = this.props.mapOptions;
    if (mapOptions.animationFrameMinutes === undefined) {
      mapOptions.animationFrameMinutes = 30;
    }
    var maxRate =
      ((mapOptions.latestTime - mapOptions.earliestTime) / 1000 / 60) * 0.33;
    mapOptions.animationFrameMinutes = clamp(
      mapOptions.animationFrameMinutes * options.rate,
      1,
      maxRate
    );
    this.props.updateMapOptions({ mapOptions });
  }

  halveSpeed() {
    this.changeAnimationRate({ rate: 0.5 });
  }

  doubleSpeed() {
    this.changeAnimationRate({ rate: 2 });
  }

  render() {
    var mapOptions = this.props.mapOptions;
    var times = mapOptions.times;
    var earliestTime = mapOptions.earliestTime;
    if (!earliestTime) earliestTime = 1;
    var latestTime = mapOptions.latestTime;
    if (!latestTime) latestTime = 1;
    var marks = mapOptions.marks;

    return React.createElement(
      "div",
      { className: "timeSlider" },
      React.createElement(
        "div",
        {},
        React.createElement(
          "div",
          { className: "animationControl" },
          !mapOptions.isAnimating &&
            React.createElement("div", {
              onClick: this.toggleAnimating,
              className: "glyphicon glyphicon-play"
            }),
          mapOptions.isAnimating &&
            React.createElement("div", {
              onClick: this.toggleAnimating,
              className: "glyphicon glyphicon-pause"
            }),
          React.createElement("div", {
            onClick: this.halveSpeed,
            className: "speed-button glyphicon glyphicon-minus-sign"
          }),
          React.createElement("div", {
            onClick: this.doubleSpeed,
            className: "speed-button glyphicon glyphicon-plus-sign"
          })
        ),
        React.createElement(
          "div",
          { className: "reactSliderContainer" },
          React.createElement(rcSlider, {
            included: false,
            min: +earliestTime,
            // max: +latestTime + (+latestTime - +earliestTime) * 0.05,
            max: +latestTime,
            value: mapOptions.time,
            step: null,
            marks: marks,
            tipFormatter: (tip, index) => {
              var t = moment
                .duration(moment(tip).diff(moment()))
                .asMilliseconds();
              var args = {
                conjunction: " and ",
                largest: Math.abs(t) > 3600000 ? 2 : 1,
                serialComma: false
              };
              return t > -60000 && t < 60000
                ? "now"
                : t < 0
                  ? humanizeDuration(t, args) + " ago"
                  : "in " + humanizeDuration(t, args);
            },
            // step: null, // NOTE null step makes intermediate positions impossible, but disables tip fomatting. https://github.com/react-component/slider/issues/174
            onChange: this.selectTime,
            onAfterChange: this.handleAfterChange
          })
        )
      ),
      React.createElement(
        "div",
        { className: "displayDate" },
        mapOptions.displayTime
          .local()
          .format("ddd MMM DD YYYY \u2014 hh:mm A") +
          " " +
          moment.tz(moment.tz.guess()).format("z")
      )
    );
  }
}

export default timeSlider;


text:
package event

import (
	"encoding/json"
	"github.com/ServiceComb/service-center/pkg/util"
	pb "github.com/ServiceComb/service-center/server/core/proto"
	"github.com/ServiceComb/service-center/server/core/registry/store"
	nf "github.com/ServiceComb/service-center/server/service/notification"
	serviceUtil "github.com/ServiceComb/service-center/server/service/util"
	"golang.org/x/net/context"
	"strings"
	apt "github.com/ServiceComb/service-center/server/core"
)

type InstanceEventHandler struct {
}

func (h *InstanceEventHandler) Type() store.StoreType {
	return store.INSTANCE
}

func (h *InstanceEventHandler) OnEvent(evt *store.KvEvent) {
	kv := evt.KV
	action := evt.Action
	providerId, providerInstanceId, tenantProject, data := pb.GetInfoFromInstKV(kv)
	if data == nil {
		util.Logger().Errorf(nil,
			"unmarshal provider service instance file failed, instance %s/%s [%s] event, data is nil",
			providerId, providerInstanceId, action)
		return
	}
	if action == pb.EVT_DELETE {
		spilted := strings.Split(tenantProject, "/")
		if len(spilted) == 2 && apt.IsDefaultDomain(tenantProject) {
			domainName := spilted[0]
			projectName := spilted[1]
			ctx := context.TODO()
			ctx = context.WithValue(ctx, "tenant", domainName)
			ctx = context.WithValue(ctx, "project", projectName)
			serviceUtil.RemandInstanceQuota(ctx)
		}
	}

	if nf.GetNotifyService().Closed() {
		util.Logger().Warnf(nil, "caught instance %s/%s [%s] event, but notify service is closed",
			providerId, providerInstanceId, action)
		return
	}
	util.Logger().Infof("caught instance %s/%s [%s] event", providerId, providerInstanceId, action)

	var instance pb.MicroServiceInstance
	err := json.Unmarshal(data, &instance)
	if err != nil {
		util.Logger().Errorf(err, "unmarshal provider service instance %s/%s file failed",
			providerId, providerInstanceId)
		return
	}
	// 查询服务版本信息
	ms, err := serviceUtil.GetServiceInCache(context.Background(), tenantProject, providerId)
	if ms == nil {
		util.Logger().Errorf(err, "get provider service %s/%s id in cache failed",
			providerId, providerInstanceId)
		return
	}

	// 查询所有consumer
	consumerIds, _, err := serviceUtil.GetConsumerIds(context.Background(), tenantProject, ms)
	if err != nil {
		util.Logger().Errorf(err, "query service %s consumers failed", providerId)
		return
	}

	nf.PublishInstanceEvent(tenantProject, action, &pb.MicroServiceKey{
		AppId:       ms.AppId,
		ServiceName: ms.ServiceName,
		Version:     ms.Version,
	}, &instance, evt.Revision, consumerIds)
}

func NewInstanceEventHandler() *InstanceEventHandler {
	return &InstanceEventHandler{}
}


text:
using System;

namespace Pierpont
{
    public class DividendRequest
    {
        public DateTime StartDate { get; private set; }
        public decimal Principal { get; private set; }

        public DividendRequest(DateTime startDate, decimal principal)
        {
            StartDate = startDate;
            Principal = principal;
        }
    }
}


text:
#subscribe-email input {
	width: 95%;
}

.comment-subscription-form {
	margin-bottom: 1em;
}

.comment-subscription-form .subscribe-label {
	display: inline !important;
}

/*
Text meant only for screen readers.
Provides support for themes that do not bundle this CSS yet.
@see https://make.wordpress.org/accessibility/2015/02/09/hiding-text-for-screen-readers-with-wordpress-core/
***********************************/
.screen-reader-text {
	border: 0;
	clip: rect(1px, 1px, 1px, 1px);
	clip-path: inset(50%);
	height: 1px;
	margin: -1px;
	overflow: hidden;
	padding: 0;
	position: absolute ! important;
	width: 1px;
	word-wrap: normal ! important;
}


text:
namespace AldursLab.WurmApi.PersistentObjects
{
    interface IPersistentCollectionsLibrary
    {
        IPersistentCollection GetCollection(string collectionId);
        IPersistentCollection DefaultCollection { get; }
    }
}


text:
var path = require('path')
  , fs = require('fs')
  , should = require('should')
  , testFile = path.resolve("..", "testFile.txt");

fs.stat(testFile, function(err) {

  var next = function() {
    fs.writeFile(testFile, "Hello World", function(err) {
      setTimeout(function() {
        var evenness = '';

        var next2 = function() {
          fs.appendFile(testFile, "!", function(err) {
            fs.appendFile(testFile, " " + evenness, function(err) {
              fs.readFile(testFile, function(err, data) {
                data = data.toString();
                data.should.equal("Hello World! " + evenness);
                fs.unlink(testFile, function(err) {
                  console.log("Done!");
                });
              });
            });
          });
        };

        if (Date.now() % 2 === 0) {
          evenness = 'Time was even, doing nothing! ';
          next2();
        } else {
          evenness = 'Time was odd, need to wait a ms...';
          setTimeout(next2, 1);
        }
      }, 500);
    });
  };

  if (err) {
    // file doesn't exist
    next();
  } else {
    fs.unlink(testFile, function(err) {
      next();
    });
  }

});


text:
import ToastComponent, { ToastOptions } from '../components/toast';
import { asyncFor } from 'then-utils';

class ToastManager {
  toasts: ToastComponent[];
  queue: ToastComponent[];
  maxAtOnce = 3;
  //inRender = false;
  //renderQueue: Array<() => void> = [];
  constructor() {
    this.toasts = [];
    this.queue = [];
  }
  add(toast: ToastComponent, milliseconds: number | boolean = toast.timeout): Promise<void> {
    toast.timeout = milliseconds;
    if (this.toasts.length === this.maxAtOnce) {
      if (this.queue.indexOf(toast) !== -1) return Promise.resolve();
      this.queue.push(toast);
      return Promise.resolve();
    }
    if (this.queue.indexOf(toast) !== -1) this.queue.splice(this.queue.indexOf(toast), 1);

    let t = null;
    /*const rerenderFunc = () => {
      if (this.inRender) return new Promise((resolve, reject) => this.renderQueue.push(() => rerenderFunc().then(resolve)));
      if (this.toasts.indexOf(toast) === -1) return;
      const i = this.toasts.indexOf(toast);
      if (!this.toasts[i + 1]) return;
      this.inRender = true;
      const toast2 = this.toasts[i + 1];
      return toast2.offset(10, (() => {
        const style = window.getComputedStyle(toast.elm);
        const parsed = parseFloat(style.bottom);
        const height = parseFloat(style.height);
        return toast2.bottom - (parsed + height + 10);
      })()).then(() => {
        this.inRender = false;
        if (this.renderQueue[0]) this.renderQueue[0]();
      });
    };
    toast.on('rerender', rerenderFunc);*/
    toast.once('hidden', () => {
      //toast.removeListener('rerender', rerenderFunc);
      if (t) clearTimeout(t);
      Promise.resolve(/*rerenderFunc()*/).then(() => this.toasts.splice(this.toasts.indexOf(toast), 1)).then(() => toast.disown()).then(() => {
        if (this.toasts.length === 0 && this.queue[0]) {
          return asyncFor(this.maxAtOnce, (i) => {
            const item = this.queue[0];
            if (!item) return Promise.resolve();
            return this.add(item);
          });
        }
      });
    });

    return toast.offset(10, (() => {
      if (this.toasts.length === 0) return 10;
      const t = this.toasts[this.toasts.length - 1];
      const style = window.getComputedStyle(t.elm);
      const parsed = parseFloat(style.bottom);
      const height = parseFloat(style.height);
      //if (t.elm.classList.contains('shown')) return parsed + height;
      return parsed + height + 10;
    })()).then(() => Promise.resolve(toast.appendTo(document.body))).then(() => {
      const style = window.getComputedStyle(toast.elm);
      return asyncFor(style.transitionProperty.split(','), (i, prop) => {
        style.getPropertyValue(prop.trim()); // force render
        return Promise.resolve();
      });
    }).then(() => this.toasts.push(toast)).then(() => toast.show()).then(() => {
      if (milliseconds !== false) t = setTimeout(() => toast.hide(), milliseconds);
    });
  }
  onetime(opts: ToastOptions): Promise<void> {
    return new Promise((resolve, reject) => {
      const t = new ToastComponent(opts);
      t.once('ready', () => {
        this.add(t).then(() => resolve()).catch(reject);
      });
    });
  }
}

const def = new ToastManager();
export default def; // ToastManager is a singleton
(<object>window).toastManager = def; // Debugging


text:
package io.cattle.platform.core.constants;

public class InstanceConstants {

    public static final String TYPE = "instance";
    public static final String TYPE_CONTAINER = "container";

    public static final String FIELD_AGENT_INSTANCE = "agentInstance";
    public static final String FIELD_COUNT = "count";
    public static final String FIELD_CREDENTIAL_IDS = "credentialIds";
    public static final String FIELD_ENVIRONMENT = "environment";
    public static final String FIELD_IMAGE_UUID = "imageUuid";
    public static final String FIELD_IMAGE_ID = "imageId";
    public static final String FIELD_INSTANCE_LINKS = "instanceLinks";
    public static final String FIELD_INSTANCE_TRIGGERED_STOP = "instanceTriggeredStop";
    public static final String FIELD_PUBLIC_IP_ADDRESS_POOL_ID = "publicIpAddressPoolId";
    public static final String FIELD_NETWORK_IDS = "networkIds";
    public static final String FIELD_PORTS = "ports";
    public static final String FIELD_PRIMARY_IP_ADDRESS = "primaryIpAddress";
    public static final String FIELD_PRIMARY_ASSOCIATED_IP_ADDRESS = "primaryAssociatedIpAddress";
    public static final String FIELD_PRIVILEGED = "privileged";
    public static final String FIELD_REQUESTED_HOST_ID = "requestedHostId";
    public static final String FIELD_VALID_HOST_IDS = "validHostIds";
    public static final String FIELD_SUBNET_IDS = "subnetIds";
    public static final String FIELD_START_ON_CREATE = "startOnCreate";
    public static final String FIELD_VCPU = "vcpu";
    public static final String FIELD_VNET_IDS = "vnetIds";
    public static final String FIELD_VOLUME_OFFERING_IDS = "volumeOfferingIds";

    public static final String REMOVE_OPTION = "remove";
    public static final String DEALLOCATE_OPTION = "deallocateFromHost";

    public static final String PROCESS_START = "instance.start";
    public static final String PROCESS_STOP = "instance.stop";
    public static final String PROCESS_RESTART = "instance.restart";

    public static final String KIND_CONTAINER = "container";
    public static final String KIND_VIRTUAL_MACHINE = "virtualMachine";

    public static final String STATE_RUNNING = "running";
    public static final String STATE_STOPPED = "stopped";

    public static final String ON_STOP_STOP = "stop";
    public static final String ON_STOP_RESTART = "restart";
    public static final String ON_STOP_REMOVE = "remove";

}


text:
package tmpl

var _ = T.MustParse(`{{ template "header" . }}

Dataset: {{.Page.dataset.Name}}

Dataset is associated with {{ .Page.dataset.Dimensions }} directly measured
 genes, {{ .Page.dataset.GeneSigs }} gene signatures,
 {{ .Page.dataset.Samples }} sample signatures, and
 {{.Page.dataset.Genesets }} genesets.

Search

    Signature

    Text

<form method="GET" action="/dataset/{{.Page.dataset.Id}}/search/signature">

  <textarea name="up-regulated" class="form-control" rows="3"
      placeholder="up-regulated dimensions (whitespace separated)"></textarea>

  <textarea name="down-regulated" class="form-control" rows="3"
      placeholder="down-regulated dimensions (whitespace separated)"></textarea>

    filters:
    <input type="text" name="filters" class="form-control" id="filters" />

      <input type="radio" name="direct" value="yes"
          autocomplete="off" checked> Direct measurement

      <input type="radio" name="direct" value="no"
          autocomplete="off"> Signature combination

  <button type="submit" class="btn btn-primary">Search</button>

</form>

<form method="GET" action="/dataset/{{.Page.dataset.Id}}/search/keyword">

  <input type="text" name="keyword" class="form-control" />

  <button type="submit" class="btn btn-primary">Search</button>

</form>

  {{.Page.page_urls.Render}}

{{ $Page := .Page }}

Samples

    {{ range .Page.samples }}

{{.Name}}

    {{ end }}

Gene signatures

    {{ range .Page.genesigs }}

{{.Name}}

    {{ end }}

Gene sets

    {{ range .Page.genesets }}

{{.Name}}

    {{ end }}

{{ template "footer" . }}`)


text:
import * as ts from "typescript";
import { Fix, RuleFailure } from "../rule/rule";
export declare class WalkContext<T = undefined> {
    readonly sourceFile: ts.SourceFile;
    readonly ruleName: string;
    readonly options: T;
    readonly failures: RuleFailure[];
    constructor(sourceFile: ts.SourceFile, ruleName: string, options: T);
    /** Add a failure with any arbitrary span. Prefer `addFailureAtNode` if possible. */
    addFailureAt(start: number, width: number, failure: string, fix?: Fix): void;
    addFailure(start: number, end: number, failure: string, fix?: Fix): void;
    /** Add a failure using a node's span. */
    addFailureAtNode(node: ts.Node, failure: string, fix?: Fix): void;
}


text:
#pragma once
#include "tinyxml.h"
#include "OgitorsPrerequisites.h"
#include "OgitorsClipboardManager.h"
#include "OgitorsRoot.h"
#include "OgitorsSystem.h"
#include "BaseEditor.h"
#include "MultiSelEditor.h"

using namespace Ogitors;

template<> OgitorsClipboardManager* Singleton<OgitorsClipboardManager>::ms_Singleton = 0;
unsigned int OgitorsClipboardManager::mClipboardMaxSize = 10;

//----------------------------------------------------------------------------------
OgitorsClipboardManager::OgitorsClipboardManager()
{
}
//----------------------------------------------------------------------------------
OgitorsClipboardManager::~OgitorsClipboardManager()
{
    unsigned int i;

    for(i = 0;i < mBuffer.size();i++)
        OGRE_DELETE mBuffer[i];

    mBuffer.clear();

    ObjectTemplateMap::iterator it = mGeneralTemplates.begin();
    while(it != mGeneralTemplates.end())
    {
        for(i = 0;i < it->second.size();i++)
        {
            OGRE_DELETE it->second[i].mCustomProperties;
        }
        it++;
    }

    mGeneralTemplates.clear();

    it = mProjectTemplates.begin();
    while(it != mProjectTemplates.end())
    {
        for(i = 0;i < it->second.size();i++)
        {
            OGRE_DELETE it->second[i].mCustomProperties;
        }
        it++;
    }

    mProjectTemplates.clear();
}
//----------------------------------------------------------------------------------
void OgitorsClipboardManager::copy(CBaseEditor* object)
{
    assert(object != 0 && "The object to copy must not be null");

    if((mBuffer.size() + 1) > mClipboardMaxSize)
    {
        int count = (mBuffer.size() + 1) - mClipboardMaxSize;
        for(int i = 0;i < count;i++)
            OGRE_DELETE mBuffer[i];

        mBuffer.erase(mBuffer.begin(), mBuffer.begin() + (mBuffer.size() - mClipboardMaxSize + 1));
    }

    ObjectCopyData *data = OGRE_NEW ObjectCopyData;
    data->mObjectName = object->getName();
    data->mObjectTypeName = object->getTypeName();
    object->getPropertyMap(data->mProperties);
    data->mProperties.erase(data->mProperties.find("object_id"));
    object->getCustomProperties()->cloneSet(data->mCustomProperties);

    mBuffer.push_back(data);
}
//----------------------------------------------------------------------------------
CBaseEditor *OgitorsClipboardManager::paste(CBaseEditor *parent, int index)
{
    ObjectCopyData *data = 0;

    assert(index < (int)mBuffer.size());

    if(index == -1)
        data = mBuffer[mBuffer.size() - 1];
    else
        data = mBuffer[index];

    CBaseEditor* object = OgitorsRoot::getSingletonPtr()->FindObject(data->mObjectName);

    OgitorsPropertyValueMap properties = data->mProperties;
    if(object)
    {
        Ogre::String newname = data->mObjectName + "Copy";
        newname += OgitorsRoot::getSingletonPtr()->CreateUniqueID(newname, "", 0);
        properties["name"].val = Ogre::Any(newname);
    }

    object = OgitorsRoot::getSingletonPtr()->CreateEditorObject(parent, data->mObjectTypeName, properties, true, false);
    if(!object)
        return 0;

    object->getCustomProperties()->initFromSet(data->mCustomProperties);
    object->load();
    OgitorsRoot::getSingletonPtr()->GetSelection()->setSelection(object);

    return object;
}
//----------------------------------------------------------------------------------
bool OgitorsClipboardManager::copyToTemplate(CBaseEditor *object, const Ogre::String& templatename, bool isGeneralScope)
{
    if(templatename.empty())
        return false;

    Ogre::String filename;
    if(isGeneralScope)
        filename = OgitorsSystem::getSingletonPtr()->getProjectsDirectory() + "/Templates/";
    else
        filename = OgitorsRoot::getSingletonPtr()->GetProjectOptions()->ProjectDir + "/Templates/";

    filename = OgitorsUtils::QualifyPath(filename);
    OgitorsSystem::getSingletonPtr()->MakeDirectory(filename);
    filename += "/" + templatename + ".otl";

    std::ofstream outfile(filename.c_str());
    outfile << "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
    outfile << "<TEMPLATES>\n";
    outfile << "  <OBJECTTEMPLATE name=\"";
    outfile << templatename.c_str();
    outfile << "\">\n";
    outfile << OgitorsUtils::GetObjectSaveStringV2(object, 4, false, false).c_str();
    outfile << "  </OBJECTTEMPLATE>\n";
    outfile << "</TEMPLATES>\n";

    outfile.close();

    ObjectTemplateMap::iterator rit;
    if(isGeneralScope)
        rit = mGeneralTemplates.insert(ObjectTemplateMap::value_type(templatename, ObjectTemplate())).first;
    else
        rit = mProjectTemplates.insert(ObjectTemplateMap::value_type(templatename, ObjectTemplate())).first;

    rit->second.push_back(ObjectTemplateData());
    object->getPropertyMap(rit->second[0].mObjectProperties);
    rit->second[0].mObjectProperties.erase(rit->second[0].mObjectProperties.find("object_id"));
    OgitorsCustomPropertySet *tmpset = OGRE_NEW OgitorsCustomPropertySet();
    object->getCustomProperties()->cloneSet(*tmpset);
    rit->second[0].mCustomProperties = tmpset;
    rit->second[0].mTypeName = object->getTypeName();

    return true;
}
//----------------------------------------------------------------------------------
bool OgitorsClipboardManager::copyToTemplateWithChildren(CBaseEditor *object, const Ogre::String& templatename, bool isGeneralScope)
{
    if(templatename.empty())
        return false;

    Ogre::String filename;
    if(isGeneralScope)
        filename = OgitorsSystem::getSingletonPtr()->getProjectsDirectory() + "/Templates/";
    else
        filename = OgitorsRoot::getSingletonPtr()->GetProjectOptions()->ProjectDir + "/Templates/";

    filename = OgitorsUtils::QualifyPath(filename);
    OgitorsSystem::getSingletonPtr()->MakeDirectory(filename);
    filename += "/" + templatename + ".otl";

    std::ofstream outfile(filename.c_str());
    outfile << "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
    outfile << "<TEMPLATES>\n";
    outfile << "  <OBJECTTEMPLATE name=\"";
    outfile << templatename.c_str();
    outfile << "\">\n";
    Ogre::StringVector list;
    object->getNameList(list);
    outfile << OgitorsUtils::GetObjectSaveStringV2(object, 4, false, false).c_str();

    ObjectTemplateMap::iterator rit;
    if(isGeneralScope)
        rit = mGeneralTemplates.insert(ObjectTemplateMap::value_type(templatename, ObjectTemplate())).first;
    else
        rit = mProjectTemplates.insert(ObjectTemplateMap::value_type(templatename, ObjectTemplate())).first;

    rit->second.push_back(ObjectTemplateData());
    object->getPropertyMap(rit->second[0].mObjectProperties);
    rit->second[0].mObjectProperties.erase(rit->second[0].mObjectProperties.find("object_id"));
    OgitorsCustomPropertySet *tmpset = OGRE_NEW OgitorsCustomPropertySet();
    object->getCustomProperties()->cloneSet(*tmpset);
    rit->second[0].mCustomProperties = tmpset;
    rit->second[0].mTypeName = object->getTypeName();

    for(unsigned int i = 1;i < list.size();i++)
    {
        CBaseEditor *item = OgitorsRoot::getSingletonPtr()->FindObject(list[i]);
        if(item != 0)
        {
            outfile << OgitorsUtils::GetObjectSaveStringV2(item, 4, false, true).c_str();

            rit->second.push_back(ObjectTemplateData());
            int itempos = rit->second.size() - 1;
            item->getPropertyMap(rit->second[itempos].mObjectProperties);
            rit->second[itempos].mObjectProperties.erase(rit->second[itempos].mObjectProperties.find("object_id"));
            OgitorsPropertyValue parentnodevalue;
            parentnodevalue.propType = PROP_STRING;
            parentnodevalue.val = Ogre::Any(item->getParent()->getName());
            rit->second[itempos].mObjectProperties.insert(OgitorsPropertyValueMap::value_type("parentnode", parentnodevalue));
            OgitorsCustomPropertySet *tmpset = OGRE_NEW OgitorsCustomPropertySet();
            item->getCustomProperties()->cloneSet(*tmpset);
            rit->second[itempos].mCustomProperties = tmpset;
            rit->second[itempos].mTypeName = item->getTypeName();
        }
    }

    outfile << "  </OBJECTTEMPLATE>\n";
    outfile << "</TEMPLATES>\n";

    outfile.close();
    return true;
}
//----------------------------------------------------------------------------------
bool OgitorsClipboardManager::copyToTemplateMulti(CMultiSelEditor *object, const Ogre::String& templatename, bool isGeneralScope)
{
    if(templatename.empty())
        return false;

    NameObjectPairList list = object->getSelection();
    NameObjectPairList::iterator oit = list.begin();

    if(oit == list.end())
        return false;

    Ogre::String filename;
    if(isGeneralScope)
        filename = OgitorsSystem::getSingletonPtr()->getProjectsDirectory() + "/Templates/";
    else
        filename = OgitorsRoot::getSingletonPtr()->GetProjectOptions()->ProjectDir + "/Templates/";

    filename = OgitorsUtils::QualifyPath(filename);
    OgitorsSystem::getSingletonPtr()->MakeDirectory(filename);
    filename += "/" + templatename + ".otl";

    std::ofstream outfile(filename.c_str());
    outfile << "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
    outfile << "<TEMPLATES>\n";
    outfile << "  <OBJECTTEMPLATE name=\"";
    outfile << templatename.c_str();
    outfile << "\">\n";

    ObjectTemplateMap::iterator rit;
    if(isGeneralScope)
        rit = mGeneralTemplates.insert(ObjectTemplateMap::value_type(templatename, ObjectTemplate())).first;
    else
        rit = mProjectTemplates.insert(ObjectTemplateMap::value_type(templatename, ObjectTemplate())).first;

    std::vector<CBaseEditor*> objList;

    while(oit != list.end())
    {
        CBaseEditor *item = oit->second;
        if(!item->supports(CAN_ACCEPTCOPY))
        {
            list.erase(oit);
            oit = list.begin();
        }
        else
        {
            CBaseEditor *itemParent = item->getParent();
            Ogre::String parentName = "";
            if(itemParent)
                parentName = itemParent->getName();

            if(list.find(parentName) == list.end())
            {
                list.erase(oit);
                oit = list.begin();
                objList.push_back(item);
            }
            else
                oit++;
        }
    }

    for(unsigned int objn = 0;objn < objList.size();objn++)
    {
        CBaseEditor *item = objList[objn];

        outfile << OgitorsUtils::GetObjectSaveStringV2(item, 2, false, true).c_str();

        rit->second.push_back(ObjectTemplateData());
        int itempos = rit->second.size() - 1;
        item->getPropertyMap(rit->second[itempos].mObjectProperties);
        rit->second[itempos].mObjectProperties.erase(rit->second[itempos].mObjectProperties.find("object_id"));
        OgitorsPropertyValue parentnodevalue;
        parentnodevalue.propType = PROP_STRING;
        parentnodevalue.val = Ogre::Any(item->getParent()->getName());
        rit->second[itempos].mObjectProperties.insert(OgitorsPropertyValueMap::value_type("parentnode", parentnodevalue));
        OgitorsCustomPropertySet *tmpset = OGRE_NEW OgitorsCustomPropertySet();
        item->getCustomProperties()->cloneSet(*tmpset);
        rit->second[itempos].mCustomProperties = tmpset;
        rit->second[itempos].mTypeName = item->getTypeName();
    }

    outfile << "  </OBJECTTEMPLATE>\n";
    outfile << "</TEMPLATES>\n";

    outfile.close();
    return true;
}
//----------------------------------------------------------------------------------
CBaseEditor *OgitorsClipboardManager::instantiateTemplate(const Ogre::String& templatename)
{
    CBaseEditor *retObject = OgitorsRoot::getSingletonPtr()->GetSelection();

    CBaseEditor *item = 0;
    ObjectTemplateMap::const_iterator it;

    it = mGeneralTemplates.find(templatename);
    if(it == mGeneralTemplates.end())
    {
        it = mProjectTemplates.find(templatename);
        if(it == mProjectTemplates.end())
            return 0;
    }

    ObjectTemplate objTemplate = it->second;
    OgitorsPropertyValueMap::iterator pit;
    NameObjectPairList list;
    NameObjectPairList objlist;
    std::vector<CBaseEditor*> objlist2;
    NameObjectPairList::iterator nit;

    Ogre::String parentname;

    int numParentObjects = 0;

    for(unsigned int i = 0;i < objTemplate.size();i++)
    {
        OgitorsPropertyValueMap objMap = objTemplate[i].mObjectProperties;
        if((pit = objMap.find("parentnode")) != objMap.end())
        {
            parentname = Ogre::any_cast<Ogre::String>(pit->second.val);
            if((nit = list.find(parentname)) != list.end())
            {
                pit->second.val = Ogre::Any(nit->second->getName());
            }
            else
            {
                objMap.erase(pit);
                ++numParentObjects;
            }
        }
        else
            ++numParentObjects;

        parentname = Ogre::any_cast<Ogre::String>(objMap["name"].val);
        objMap["name"].val = Ogre::Any(parentname + OgitorsRoot::getSingletonPtr()->CreateUniqueID(parentname,"",0));

        item = OgitorsRoot::getSingletonPtr()->CreateEditorObject(0, objTemplate[i].mTypeName, objMap, true, false);

        if(item)
        {
            item->load();
            item->getCustomProperties()->initFromSet(*(objTemplate[i].mCustomProperties));
            list.insert(NameObjectPairList::value_type(parentname, item));
            objlist.insert(NameObjectPairList::value_type(item->getName(), item));
            objlist2.push_back(item);
        }
    }

    Ogre::Vector3 pos(999999, 999999, 999999);

    if(numParentObjects == 0)
        return 0;
    else if(numParentObjects == 1)
    {
        retObject = objlist2[0];
        OgitorsRoot::getSingletonPtr()->GetSelection()->setSelection(retObject);
    }
    else
        static_cast<CMultiSelEditor*>(retObject)->setSelection(objlist);

    if(retObject->getProperties()->hasProperty("position"))
        retObject->getProperties()->setValue("position", pos);

    return retObject;
}
//---------------------------------------------------------------------------------
bool OgitorsClipboardManager::isTemplateInstantiable(const Ogre::String& templatename)
{
    ObjectTemplateMap::const_iterator it;

    it = mGeneralTemplates.find(templatename);
    if(it == mGeneralTemplates.end())
    {
        it = mProjectTemplates.find(templatename);
        if(it == mProjectTemplates.end())
            return false;
    }

    if(it->second.size() == 0)
        return false;

    CBaseEditorFactory *factory = OgitorsRoot::getSingletonPtr()->GetEditorObjectFactory(it->second[0].mTypeName);
    if(!factory)
        return false;

    return factory->CanInstantiate();
}
//---------------------------------------------------------------------------------
bool OgitorsClipboardManager::doesTemplateRequirePlacement(const Ogre::String& templatename)
{
    ObjectTemplateMap::const_iterator it;

    it = mGeneralTemplates.find(templatename);
    if(it == mGeneralTemplates.end())
    {
        it = mProjectTemplates.find(templatename);
        if(it == mProjectTemplates.end())
            return false;
    }

    if(it->second.size() == 0)
        return false;

    CBaseEditorFactory *factory = OgitorsRoot::getSingletonPtr()->GetEditorObjectFactory(it->second[0].mTypeName);
    if(!factory)
        return false;

    return factory->mRequirePlacement;
}
//---------------------------------------------------------------------------------
void OgitorsClipboardManager::addTemplatesFromFiles(Ogre::StringVector filenames, bool isGeneralScope)
{
    Ogre::String fname;
    for(unsigned int i = 0;i < filenames.size();i++)
    {
        fname = OgitorsUtils::QualifyPath(filenames[i]);
        addTemplateFromFile(fname, isGeneralScope);
    }
}
//---------------------------------------------------------------------------------
void OgitorsClipboardManager::addTemplateFromFile(Ogre::String filename, bool isGeneralScope)
{
    TiXmlDocument docImport(filename.c_str());

    if(!docImport.LoadFile())
        return;

    TiXmlElement* templates = 0;
    templates = docImport.FirstChildElement("TEMPLATES");
    if(!templates)
        return;

    templates = templates->FirstChildElement("OBJECTTEMPLATE");
    if(!templates)
        return;

    Ogre::String objecttype;
    Ogre::String templatename;
    OgitorsPropertyValueMap params;
    OgitorsPropertyValue tmpPropVal;

    do
    {
        templatename = ValidAttr(templates->Attribute("name"));
        if(templatename == "")
            continue;

        TiXmlElement *element = templates->FirstChildElement("OBJECT");
        if(!element)
            continue;

        ObjectTemplateMap::iterator rit;
        if(isGeneralScope)
        {
            std::pair<ObjectTemplateMap::iterator, bool> retPair = mGeneralTemplates.insert(ObjectTemplateMap::value_type(templatename, ObjectTemplate()));
            if(!retPair.second)
                continue;
            rit = retPair.first;
        }
        else
        {
            std::pair<ObjectTemplateMap::iterator, bool> retPair = mProjectTemplates.insert(ObjectTemplateMap::value_type(templatename, ObjectTemplate()));
            if(!retPair.second)
                continue;
            rit = retPair.first;
        }

        do
        {
            params.clear();

            Ogre::String objAttValue;

            objAttValue = ValidAttr(element->Attribute("parentnode"),"");
            if(objAttValue != "")
            {
                tmpPropVal.propType = PROP_STRING;
                tmpPropVal.val = Ogre::Any(objAttValue);
                params.insert(OgitorsPropertyValueMap::value_type("parentnode", tmpPropVal));
            }

            objAttValue = ValidAttr(element->Attribute("name"),"");
            if(objAttValue != "")
            {
                tmpPropVal.propType = PROP_STRING;
                tmpPropVal.val = Ogre::Any(objAttValue);
                params.insert(OgitorsPropertyValueMap::value_type("name", tmpPropVal));
            }
            else
                continue;

            objAttValue = ValidAttr(element->Attribute("typename"),"");
            if(objAttValue != "")
            {
                tmpPropVal.propType = PROP_STRING;
                tmpPropVal.val = Ogre::Any(objAttValue);
                params.insert(OgitorsPropertyValueMap::value_type("typename", tmpPropVal));
            }
            else
                continue;

            TiXmlElement *properties = element->FirstChildElement();
            if(properties)
            {
                Ogre::String elementName;
                do
                {
                    elementName = properties->Value();
                    if(elementName != "PROPERTY")
                        continue;

                    Ogre::String attID = ValidAttr(properties->Attribute("id"),"");
                    int attType = Ogre::StringConverter::parseInt(ValidAttr(properties->Attribute("type"),""));
                    Ogre::String attValue = ValidAttr(properties->Attribute("value"),"");

                    params.insert(OgitorsPropertyValueMap::value_type(attID, OgitorsPropertyValue::createFromString((OgitorsPropertyType)attType, attValue)));
                } while(properties = properties->NextSiblingElement());
            }

            objecttype = Ogre::any_cast<Ogre::String>(params["typename"].val);

            rit->second.push_back(ObjectTemplateData());
            rit->second[rit->second.size() - 1].mObjectProperties = params;
            rit->second[rit->second.size() - 1].mCustomProperties = OGRE_NEW OgitorsCustomPropertySet();
            rit->second[rit->second.size() - 1].mTypeName = objecttype;

            TiXmlElement *customprop = element->FirstChildElement("CUSTOMPROPERTIES");
            if(customprop)
            {
                OgitorsUtils::ReadCustomPropertySet(customprop, rit->second[rit->second.size() - 1].mCustomProperties);
            }
        } while (element = element->NextSiblingElement());
        if(rit->second.size() == 0)
        {
            if(isGeneralScope)
                mGeneralTemplates.erase(rit);
            else
                mProjectTemplates.erase(rit);
        }
    } while(templates = templates->NextSiblingElement());
}
//---------------------------------------------------------------------------------


text:
<?xml version='1.0' encoding='utf-8'?>
<widget id="gov.az.azgs.strabomobile" version="1.19.8" xmlns="http://www.w3.org/ns/widgets" xmlns:gap="http://phonegap.com/ns/1.0">
    <name>Strabo Mobile</name>
    <description>
    Strabo Mobile is a cross-platform app for geologic field data acquisition.
  </description>
    <author email="strabospot@gmail.com" href="http://strabospot.org/">
    StraboSpot Team
  </author>
    <content src="index.html" />
    <access origin="*" />
    <edit-config file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application" xmlns:android="http://schemas.android.com/apk/res/android">
        <application android:usesCleartextTraffic="true" />
    </edit-config>
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />
    <preference name="phonegap-version" value="cli-9.0.0" />
    <preference name="webviewbounce" value="false" />
    <preference name="UIWebViewBounce" value="false" />
    <preference name="DisallowOverscroll" value="true" />
    <preference name="BackupWebStorage" value="none" />
    <preference name="android-minSdkVersion" value="19" />
    <preference name="android-targetSdkVersion" value="28" />
    <preference name="AndroidPersistentFileLocation" value="Internal" />
    <preference name="iosPersistentFileLocation" value="Library" />
    <preference name="AutoHideSplashScreen" value="false" />
    <preference name="SplashScreenDelay" value="2000" />
    <preference name="SplashScreen" value="screen" />
    <preference name="UIFileSharingEnabled" value="true" />
    <edit-config file="*-Info.plist" mode="merge" target="NSCameraUsageDescription">
        <string>The strabospot app uses the camera to add images to field-collected sample data.</string>
    </edit-config>
    <edit-config file="*-Info.plist" mode="merge" target="NSPhotoLibraryUsageDescription">
        <string>The strabospot app uses the photo library to add images to field-collected sample data.</string>
    </edit-config>
    <edit-config file="*-Info.plist" mode="merge" target="NSLocationWhenInUseUsageDescription">
        <string>The strabospot app uses device location to find nearby sample data.</string>
    </edit-config>
    <edit-config file="*-Info.plist" mode="merge" target="NSPhotoLibraryAddUsageDescription">
        <string>The strabospot app uses the photo library to add images to field-collected sample data.</string>
    </edit-config>
    <plugin name="cordova-plugin-camera" spec="^4.1.0" />
    <plugin name="cordova-plugin-device" spec="^2.0.3" />
    <plugin name="cordova-plugin-device-motion" spec="^2.0.1" />
    <plugin name="cordova-plugin-device-orientation" spec="^2.0.1" />
    <plugin name="cordova-plugin-file" spec="^6.0.2" />
    <plugin name="cordova-plugin-file-transfer" spec="^1.7.1" />
    <plugin name="cordova-plugin-filepath" spec="^1.5.8" />
    <plugin name="cordova-plugin-geolocation" spec="4.0.2" />
    <plugin name="cordova-plugin-inappbrowser" spec="^3.2.0" />
    <plugin name="cordova-plugin-ionic-keyboard" spec="^2.2.0" />
    <plugin name="cordova-plugin-ionic-webview" spec="2.5.3">
      <variable name="ANDROID_SUPPORT_ANNOTATIONS_VERSION" value="27.+" />
    </plugin>
    <plugin name="cordova-plugin-itunesfilesharing" spec="^0.0.2" />
    <plugin name="cordova-plugin-network-information" spec="^2.0.2" />
    <plugin name="cordova-plugin-splashscreen" spec="^5.0.3" />
    <plugin name="cordova-plugin-statusbar" spec="^2.4.3" />
    <plugin name="cordova-plugin-whitelist" spec="^1.3.4" />
    <plugin name="cordova-sqlite-evcore-extbuild-free" spec="^0.12.0" />
    <plugin name="cordova-plugin-zip" spec="^3.1.0" />
    <plugin name="org.strabospot.clipboard" spec="https://github.com/StraboSpot/clipboard_plugin" />
    <platform name="ios">
        <icon height="29" src="www/res/icons/ios/icon-small.png" width="29" />
        <icon height="58" src="www/res/icons/ios/icon-small-2x.png" width="58" />
        <icon height="40" src="www/res/icons/ios/icon-40.png" width="40" />
        <icon height="80" src="www/res/icons/ios/icon-40-2x.png" width="80" />
        <icon height="50" src="www/res/icons/ios/icon-50.png" width="50" />
        <icon height="100" src="www/res/icons/ios/icon-50-2x.png" width="100" />
        <icon height="57" src="www/res/icons/ios/icon.png" width="57" />
        <icon height="114" src="www/res/icons/ios/icon-2x.png" width="114" />
        <icon height="60" src="www/res/icons/ios/icon-60.png" width="60" />
        <icon height="120" src="www/res/icons/ios/icon-60-2x.png" width="120" />
        <icon height="180" src="www/res/icons/ios/icon-60-3x.png" width="180" />
        <icon height="72" src="www/res/icons/ios/icon-72.png" width="72" />
        <icon height="144" src="www/res/icons/ios/icon-72-2x.png" width="144" />
        <icon height="76" src="www/res/icons/ios/icon-76.png" width="76" />
        <icon height="152" src="www/res/icons/ios/icon-76-2x.png" width="152" />
        <splash height="480" src="www/res/screens/ios/screen-iphone-portrait.png" width="320" />
        <splash height="960" src="www/res/screens/ios/screen-iphone-portrait-2x.png" width="640" />
        <splash height="1136" src="www/res/screens/ios/screen-iphone-portrait-568h-2x.png" width="640" />
        <splash height="1334" src="www/res/screens/ios/screen-iphone-portrait-667h.png" width="750" />
        <splash height="2208" src="www/res/screens/ios/screen-iphone-portrait-736h.png" width="1242" />
        <splash height="1024" src="www/res/screens/ios/screen-ipad-portrait.png" width="768" />
        <splash height="2048" src="www/res/screens/ios/screen-ipad-portrait-2x.png" width="1536" />
    </platform>
    <platform name="android">
        <icon qualifier="ldpi" src="www/res/icons/android/icon-36-ldpi.png" />
        <icon qualifier="mdpi" src="www/res/icons/android/icon-48-mdpi.png" />
        <icon qualifier="hdpi" src="www/res/icons/android/icon-72-hdpi.png" />
        <icon qualifier="xhdpi" src="www/res/icons/android/icon-96-xhdpi.png" />
        <icon qualifier="xxhdpi" src="www/res/icons/android/icon-144-xxhdpi.png" />
        <icon qualifier="xxxhdpi" src="www/res/icons/android/icon-192-xxxhdpi.png" />
        <splash qualifier="ldpi" src="www/res/screens/android/screen-ldpi-portrait.png" />
        <splash qualifier="mdpi" src="www/res/screens/android/screen-mdpi-portrait.png" />
        <splash qualifier="hdpi" src="www/res/screens/android/screen-hdpi-portrait.png" />
        <splash qualifier="xhdpi" src="www/res/screens/android/screen-xhdpi-portrait.png" />
    </platform>
</widget>


text:
//
//  UMSociallogMacros.h
//  UMSocialCore
//
//  Created by 张军华 on 16/9/7.
//  Copyright © 2016年 张军华. All rights reserved.
//

#import <Foundation/Foundation.h>

/**
 *  设置全局的日志等级
 *
 *  @param levelString @see UMSocialLogClosedString,UMSocialLogErrorString,UMSocialLogWarnString,UMSocialLogInfoString,UMSocialLogDebugString,UMSocialLogVerboseString
 *  @discuss 普通用户可以设置UMSocialLogClosedString,UMSocialLogErrorString,UMSocialLogWarnString,UMSocialLogInfoString,UMSocialLogDebugString的字符串,如果设置UMSocialLogVerboseString的时候,如果不是本库的开发者,是降低其等级到UMSocialLogDebugString
 */
FOUNDATION_EXPORT void setGlobalLogLevelString(NSString* levelString);
FOUNDATION_EXPORT NSString* getGlobalLogLevelString();

FOUNDATION_EXPORT NSString* const UMSocialLogClosedLevelString;
FOUNDATION_EXPORT NSString* const UMSocialLogErrorLevelString;
FOUNDATION_EXPORT NSString* const UMSocialLogWarnLevelString;
FOUNDATION_EXPORT NSString* const UMSocialLogInfoLevelString;
FOUNDATION_EXPORT NSString* const UMSocialLogDebugLevelString;
FOUNDATION_EXPORT NSString* const UMSocialLogVerboseLevelString;

/**
 *  根据等级打印日志
 *
 *  @param flagString  @see  below  UMSocialLogClosedFlagString...and so on
 *  @param file        打印日志的文件
 *  @param function    打印日志的函数
 *  @param line        打印的日志的行数
 *  @param format      需要打印的日志格式内容
 *  @param ...         可变参数
 *  @dicuss 本库不需要直接调用,可以用简易函数宏 @see UMSocialLogError,UMSocialLogWarn,UMSocialLogInfo,UMSocialLogDebug
 */
FOUNDATION_EXPORT void UMSocialLog(NSString* flagString,const char* file,const char* function,NSUInteger line,NSString *format, ...) NS_FORMAT_FUNCTION(5,6);

FOUNDATION_EXPORT NSString* const UMSocialLogErrorFlagString;
FOUNDATION_EXPORT NSString* const UMSocialLogWarnFlagString;
FOUNDATION_EXPORT NSString* const UMSocialLogInfoFlagString;
FOUNDATION_EXPORT NSString* const UMSocialLogDebugFlagString;
FOUNDATION_EXPORT NSString* const UMSocialLogVerboseFlagString;

//简易函数类似于系统的NSLog函数,线程安全
#define UMSocialLogError(format, ...)   UMSocialLog(UMSocialLogErrorFlagString,__FILE__,__PRETTY_FUNCTION__,__LINE__,format,##__VA_ARGS__)
#define UMSocialLogWarn(format, ...)    UMSocialLog(UMSocialLogWarnFlagString,__FILE__,__PRETTY_FUNCTION__,__LINE__,format,##__VA_ARGS__)
#define UMSocialLogInfo(format, ...)    UMSocialLog(UMSocialLogInfoFlagString,__FILE__,__PRETTY_FUNCTION__,__LINE__,format,##__VA_ARGS__)
#define UMSocialLogDebug(format, ...)   UMSocialLog(UMSocialLogDebugFlagString,__FILE__,__PRETTY_FUNCTION__,__LINE__,format,##__VA_ARGS__)
#define UMSocialLogVerbose(format, ...) UMSocialLog(UMSocialLogVerboseFlagString,__FILE__,__PRETTY_FUNCTION__,__LINE__,format,##__VA_ARGS__)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.ComponentModel;
using System.Windows.Forms;
using System.Net;
using System.IO;

namespace DownloadPictures
{
    /// <summary>
    /// Webページ情報を取得するための非表示ウィブブラウザクラス
    /// </summary>
    public class UnDisplayedBrowser : WebBrowser
    {
        bool isCompleted = false;

        TimeSpan timeout = new TimeSpan(0, 0, 10);

        public UnDisplayedBrowser()
        {
            this.ScriptErrorsSuppressed = true;
        }

        protected override void OnDocumentCompleted(WebBrowserDocumentCompletedEventArgs e)
        {
            if (e.Url == this.Url)
                isCompleted = true;
        }

        protected override void OnNewWindow(CancelEventArgs e)
        {
            e.Cancel = true;
        }

        public bool NavigateAndWait(string url)
        {
            base.Navigate(url);

            isCompleted = false;
            DateTime start = DateTime.Now;

            while (isCompleted == false)
            {
                if (DateTime.Now - start > timeout)
                {
                    return false;
                }
                Application.DoEvents();
            }
            return true;
        }
    }

    /// <summary>
    /// 情報を取得し、ダウンロードを行うクラス
    /// </summary>
    public class DownloadPictures
    {
        string[] invalidPathStrings = new string[9] { @"\", @"/", @"?", @":", @"|", @"*", @"<", @">", @"""" };
        List<string> picExtensions = new List<string>() { ".jpg", ".jpeg", ".gif", ".png", ".bmp" };

        bool isDownloading = false;
        int numberOfPictures;
        int count = 1;

        TimeSpan timeout = new TimeSpan(0, 0, 10);
        DateTime start = new DateTime();

        List<string> filter_ = new List<string>();

        public DownloadPictures(List<string> filter=null)
        {
            if (filter != null)
                filter_ = filter;
        }

        /// <summary>
        /// 指定したURLのWebページに表示されている画像アドレスを取得し、
        /// リストにして返す。
        /// </summary>
        /// <param name="url">Webページのアドレス</param>
        public List<string> GetPictures(string url)
        {
            List<string> pictureAdresses = new List<string>();

            UnDisplayedBrowser udb = new UnDisplayedBrowser();
            udb.NavigateAndWait(url);

            HtmlDocument doc = udb.Document;

            //Webページに表示されている画像の取得
            foreach (HtmlElement picElement in doc.GetElementsByTagName("IMG"))
            {
                string picUrl = picElement.GetAttribute("src");

                if (picExtensions.Contains(Path.GetExtension(picUrl)) == false)
                    continue;

                //フィルター式が設定されている場合、除外する
                if (filter_ != null)
                {
                    bool isFiltered = false;

                    foreach (var item in filter_)
                    {
                        if(picUrl.Contains(item))
                        {
                            isFiltered = true;
                            break;
                        }
                    }

                    if (isFiltered)
                        continue;
                }

                if (pictureAdresses.Contains(picUrl) == false)
                {
                    pictureAdresses.Add(picUrl);
                }
            }

            //サムネイル画像をリンク先画像に差し替え
            foreach (HtmlElement linkElement in doc.GetElementsByTagName("A"))
            {
                string picUrl = linkElement.GetAttribute("href");
                if (picExtensions.Contains(Path.GetExtension(picUrl)) == false)
                    continue;

                foreach (HtmlElement picElement in linkElement.GetElementsByTagName("IMG"))
                {
                    if (pictureAdresses.Contains(picElement.GetAttribute("src")))
                    {
                        pictureAdresses.Remove(picElement.GetAttribute("src"));
                        pictureAdresses.Add(picUrl);
                    }
                }
            }

            return pictureAdresses;
        }

        /// <summary>
        /// 渡されたアドレスリストを元に画像のダウンロードを開始する
        /// </summary>
        /// <param name="pictureAdresses">ダウンロード対象画像リスト</param>
        /// <param name="folder">ダウンロード先ディレクトリ</param>
        public void StartDownload(List<string> pictureAdresses, string folder)
        {
            if (folder.EndsWith(@"\") == false)
                folder = folder + @"\";

            WebClient wc = new WebClient();
            wc.DownloadFileCompleted += wc_DownloadFileCompleted;

            string downloadingfileName = string.Empty;
            numberOfPictures = pictureAdresses.Count;

            foreach (var picUrl in pictureAdresses)
            {
                if (waitforAsync() == false)
                    wc.CancelAsync();

                downloadingfileName = picUrl;

                //禁則文字の置換
                foreach (var InvalidPathChar in Path.GetInvalidPathChars())
                {
                    if (picUrl.Contains(InvalidPathChar))
                        downloadingfileName = downloadingfileName.Replace(InvalidPathChar, '_');
                }

                downloadingfileName = Path.GetFileName(downloadingfileName);

                //禁則文字の置換
                foreach (var InvalidPathString in invalidPathStrings)
                {
                    if (picUrl.Contains(InvalidPathString))
                        downloadingfileName = downloadingfileName.Replace(InvalidPathString, "_");
                }

                isDownloading = true;
                start = DateTime.Now;

                string fileName=folder + downloadingfileName;
                int count = 1;

                //保存名が既に存在する場合、末尾にナンバリングを行い重複しないようにする
                while (System.IO.File.Exists(fileName))
                {
                    string extension = Path.GetExtension(fileName);

                    fileName = fileName.Remove(fileName.Length - extension.Length, extension.Length);

                    if (count != 1)
                        fileName = fileName.Remove(fileName.Length - count.ToString().Length, count.ToString().Length);

                    fileName = fileName + count.ToString() + extension;

                    count++;
                }

                wc.DownloadFileAsync(new Uri(picUrl), fileName);
            }

            if(waitforAsync()==false)
            {
                wc.CancelAsync();
                Console.WriteLine("{0}件中{1}件目のダウンロードが失敗しました。", numberOfPictures, count);
                count++;
                isDownloading = false;
            }
        }

        void wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            Console.WriteLine("{0}件中{1}件目のダウンロードが完了しました。", numberOfPictures, count);
            count++;
            isDownloading = false;
        }

        private bool waitforAsync()
        {
            while (isDownloading)
            {
                if (DateTime.Now - start > timeout)
                    return false;

                Thread.Sleep(1000);
            }

            return true;
        }
    }
}