text:
package org.apache.samza.system.kafka_deprecated

import java.util.concurrent.atomic.AtomicReference
import java.util.concurrent.TimeUnit

import org.apache.kafka.clients.producer.Callback
import org.apache.kafka.clients.producer.Producer
import org.apache.kafka.clients.producer.ProducerRecord
import org.apache.kafka.clients.producer.RecordMetadata
import org.apache.kafka.common.PartitionInfo
import org.apache.samza.system.OutgoingMessageEnvelope
import org.apache.samza.system.SystemProducer
import org.apache.samza.system.SystemProducerException
import org.apache.samza.util.ExponentialSleepStrategy
import org.apache.samza.util.KafkaUtil
import org.apache.samza.util.Logging
import org.apache.samza.util.TimerUtil

class KafkaSystemProducer(systemName: String,
                          retryBackoff: ExponentialSleepStrategy = new ExponentialSleepStrategy,
                          getProducer: () => Producer[Array[Byte], Array[Byte]],
                          metrics: KafkaSystemProducerMetrics,
                          val clock: () => Long = () => System.nanoTime,
                          val dropProducerExceptions: Boolean = false) extends SystemProducer with Logging with TimerUtil {

  // Represents a fatal error that caused the producer to close.
  val fatalException: AtomicReference[SystemProducerException] = new AtomicReference[SystemProducerException]()
  val producerRef: AtomicReference[Producer[Array[Byte], Array[Byte]]] = new AtomicReference[Producer[Array[Byte], Array[Byte]]]()
  val producerCreationLock: Object = new Object
  @volatile var stopped = false

  def start(): Unit = {
    producerRef.set(getProducer())
  }

  def stop() {
    info("Stopping producer for system: " + this.systemName)

    stopped = true
    val currentProducer = producerRef.getAndSet(null)
    try {
      if (currentProducer != null) {
        currentProducer.close // Also performs the equivalent of a flush()
      }

      val exception = fatalException.get()
      if (exception != null) {
        error("Observed an earlier send() error while closing producer", exception)
      }
    } catch {
      case e: Exception => error("Error while closing producer for system: " + systemName, e)
    }
  }

  def register(source: String) {
  }

  def send(source: String, envelope: OutgoingMessageEnvelope) {
    trace("Enqueuing message: %s, %s." format (source, envelope))

    val topicName = envelope.getSystemStream.getStream
    if (topicName == null || topicName.isEmpty) {
      throw new IllegalArgumentException("Invalid system stream: " + envelope.getSystemStream)
    }

    val globalProducerException = fatalException.get()
    if (globalProducerException != null) {
      metrics.sendFailed.inc
      throw new SystemProducerException("Producer was unable to recover from previous exception.", globalProducerException)
    }

    val currentProducer = getOrCreateCurrentProducer

    // Java-based Kafka producer API requires an "Integer" type partitionKey and does not allow custom overriding of Partitioners
    // Any kind of custom partitioning has to be done on the client-side
    val partitions: java.util.List[PartitionInfo] = currentProducer.partitionsFor(topicName)
    val partitionKey = if (envelope.getPartitionKey != null) KafkaUtil.getIntegerPartitionKey(envelope, partitions) else null
    val record = new ProducerRecord(envelope.getSystemStream.getStream,
                                    partitionKey,
                                    envelope.getKey.asInstanceOf[Array[Byte]],
                                    envelope.getMessage.asInstanceOf[Array[Byte]])

    try {
      currentProducer.send(record, new Callback {
        def onCompletion(metadata: RecordMetadata, exception: Exception): Unit = {
          if (exception == null) {
            metrics.sendSuccess.inc
          } else {
            val producerException = new SystemProducerException("Failed to send message for Source: %s on System:%s Topic:%s Partition:%s"
              .format(source, systemName, topicName, partitionKey), exception)

            handleFatalSendException(currentProducer, producerException)
          }
        }
      })
      metrics.sends.inc
    } catch {
      case originalException : Exception =>
        val producerException = new SystemProducerException("Failed to send message for Source: %s on System:%s Topic:%s Partition:%s"
          .format(source, systemName, topicName, partitionKey), originalException)

        metrics.sendFailed.inc
        error("Got a synchronous error from Kafka producer.", producerException)
        // Synchronous exceptions are always recoverable so propagate it up and let the user decide
        throw producerException
    }
  }

  def flush(source: String) {
    updateTimer(metrics.flushNs) {
      metrics.flushes.inc

      val currentProducer = producerRef.get()
      if (currentProducer == null) {
        if (dropProducerExceptions) {
          // No producer to flush, but we're ignoring exceptions so just return.
          warn("Skipping flush because the Kafka producer is null.")
          metrics.flushFailed.inc
          return
        }
        throw new SystemProducerException("Kafka producer is null.")
      }

      // Flush only throws InterruptedException, all other errors are handled in send() callbacks
      currentProducer.flush()

      // Invariant: At this point either
      // 1. The producer is fine and there are no exceptions to handle   OR
      // 2. The producer is closed and one or more sources have exceptions to handle
      //   2a. All new sends get a ProducerClosedException or IllegalStateException (depending on kafka version)
      //   2b. There are no messages in flight because the producer is closed

      // We must check for an exception AFTER flush() because when flush() returns all callbacks for messages sent
      // in that flush() are guaranteed to have completed and we update the exception in the callback.
      // If there is an exception, we rethrow it here to prevent the checkpoint.
      val exception = fatalException.get()
      if (exception != null) {
        metrics.flushFailed.inc
        throw new SystemProducerException("Flush failed. One or more batches of messages were not sent!", exception)
      }
      trace("Flushed %s." format source)
    }
  }

  /**
    * Handles a fatal exception by closing the producer and either recreating it or storing the exception
    * to rethrow later, depending on the value of dropProducerExceptions.
    *
    * @param currentProducer   the current producer for which the exception occurred. Must not be null.
    * @param producerException the exception to handle.
    */
  private def handleFatalSendException(currentProducer: Producer[Array[Byte], Array[Byte]], producerException: SystemProducerException): Unit = {
    metrics.sendFailed.inc
    error(producerException)
    // The SystemProducer API is synchronous, so there's no way for us to guarantee that an exception will
    // be handled by the Task before we recreate the producer, and if it isn't handled, a concurrent send() from another
    // Task could send on the new producer before the first Task properly handled the exception and produce out of order messages.
    // So we have to handle it right here in the SystemProducer.
    if (dropProducerExceptions) {
      warn("Ignoring producer exception. All messages in the failed producer request will be dropped!")

      // Prevent each callback from closing and nulling producer for the same failure.
      if (currentProducer == producerRef.get()) {
        info("Closing producer for system %s." format systemName)
        try {
          // send()s can get ProducerClosedException if the producer is stopped after they get the currentProducer
          // reference but before producer.send() returns. That's ONLY ok when dropProducerExceptions is true.
          // Also, when producer.close(0) is invoked on the Kafka IO thread, when it returns there will be no more
          // messages sent over the wire. This is key to ensuring no out-of-order messages as a result of recreating
          // the producer.
          currentProducer.close(0, TimeUnit.MILLISECONDS)
        } catch {
          case exception: Exception => error("Exception while closing producer.", exception)
        }
        producerRef.compareAndSet(currentProducer, null)
      }
    } else {
      // If there is an exception in the callback, it means that the Kafka producer has exhausted the max-retries
      // Close producer to ensure messages queued in-flight are not sent and hence, avoid re-ordering
      // This works because there is only 1 IO thread and no IO can be done until the callback returns.
      // Do not create a new producer here! It cannot be done without data loss for all concurrency modes.
      fatalException.compareAndSet(null, producerException)
      try {
        currentProducer.close(0, TimeUnit.MILLISECONDS)
      } catch {
        case exception: Exception => error("Exception while closing producer.", exception)
      }
    }
  }

  /**
    * @return the current producer. Never returns null.
    */
  private def getOrCreateCurrentProducer = {
    var currentProducer = producerRef.get

    if (currentProducer == null) {
      if (dropProducerExceptions && !stopped) {
        // Note: While this lock prevents others from creating a new producer, they could still set it to null.
        producerCreationLock.synchronized {
          currentProducer = producerRef.get
          if (currentProducer == null) {
            currentProducer = getProducer()
            producerRef.set(currentProducer)
          }
        }
        // Invariant: currentProducer must not be null at this point.
      } else {
        throw new SystemProducerException("Kafka producer is null.")
      }
    }
    currentProducer
  }
}


text:
package main

import (
	"flag"
	"fmt"
	"net/http"
	_ "net/http/pprof"
	"os"
	"sort"
	"strings"
	"sync"
	"time"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"github.com/prometheus/common/log"
	"github.com/prometheus/common/version"
	"github.com/prometheus/node_exporter/collector"
)

const (
	defaultCollectors = "arp,conntrack,cpu,diskstats,entropy,edac,exec,filefd,filesystem,hwmon,infiniband,loadavg,mdadm,meminfo,netdev,netstat,sockstat,stat,textfile,time,uname,vmstat,wifi,xfs,zfs"
)

var (
	scrapeDurationDesc = prometheus.NewDesc(
		prometheus.BuildFQName(collector.Namespace, "scrape", "collector_duration_seconds"),
		"node_exporter: Duration of a collector scrape.",
		[]string{"collector"},
		nil,
	)
	scrapeSuccessDesc = prometheus.NewDesc(
		prometheus.BuildFQName(collector.Namespace, "scrape", "collector_success"),
		"node_exporter: Whether a collector succeeded.",
		[]string{"collector"},
		nil,
	)
)

// NodeCollector implements the prometheus.Collector interface.
type NodeCollector struct {
	collectors map[string]collector.Collector
}

// Describe implements the prometheus.Collector interface.
func (n NodeCollector) Describe(ch chan<- *prometheus.Desc) {
	ch <- scrapeDurationDesc
	ch <- scrapeSuccessDesc
}

// Collect implements the prometheus.Collector interface.
func (n NodeCollector) Collect(ch chan<- prometheus.Metric) {
	wg := sync.WaitGroup{}
	wg.Add(len(n.collectors))
	for name, c := range n.collectors {
		go func(name string, c collector.Collector) {
			execute(name, c, ch)
			wg.Done()
		}(name, c)
	}
	wg.Wait()
}

func filterAvailableCollectors(collectors string) string {
	var availableCollectors []string
	for _, c := range strings.Split(collectors, ",") {
		_, ok := collector.Factories[c]
		if ok {
			availableCollectors = append(availableCollectors, c)
		}
	}
	return strings.Join(availableCollectors, ",")
}

func execute(name string, c collector.Collector, ch chan<- prometheus.Metric) {
	begin := time.Now()
	err := c.Update(ch)
	duration := time.Since(begin)
	var success float64

	if err != nil {
		log.Errorf("ERROR: %s collector failed after %fs: %s", name, duration.Seconds(), err)
		success = 0
	} else {
		log.Debugf("OK: %s collector succeeded after %fs.", name, duration.Seconds())
		success = 1
	}
	ch <- prometheus.MustNewConstMetric(scrapeDurationDesc, prometheus.GaugeValue, duration.Seconds(), name)
	ch <- prometheus.MustNewConstMetric(scrapeSuccessDesc, prometheus.GaugeValue, success, name)
}

func loadCollectors(list string) (map[string]collector.Collector, error) {
	collectors := map[string]collector.Collector{}
	for _, name := range strings.Split(list, ",") {
		fn, ok := collector.Factories[name]
		if !ok {
			return nil, fmt.Errorf("collector '%s' not available", name)
		}
		c, err := fn()
		if err != nil {
			return nil, err
		}
		collectors[name] = c
	}
	return collectors, nil
}

func init() {
	prometheus.MustRegister(version.NewCollector("node_exporter"))
}

func main() {
	var (
		showVersion       = flag.Bool("version", false, "Print version information.")
		listenAddress     = flag.String("web.listen-address", ":9100", "Address on which to expose metrics and web interface.")
		metricsPath       = flag.String("web.telemetry-path", "/metrics", "Path under which to expose metrics.")
		enabledCollectors = flag.String("collectors.enabled", filterAvailableCollectors(defaultCollectors), "Comma-separated list of collectors to use.")
		printCollectors   = flag.Bool("collectors.print", false, "If true, print available collectors and exit.")
	)
	flag.Parse()

	if *showVersion {
		fmt.Fprintln(os.Stdout, version.Print("node_exporter"))
		os.Exit(0)
	}

	log.Infoln("Starting node_exporter", version.Info())
	log.Infoln("Build context", version.BuildContext())

	if *printCollectors {
		collectorNames := make(sort.StringSlice, 0, len(collector.Factories))
		for n := range collector.Factories {
			collectorNames = append(collectorNames, n)
		}
		collectorNames.Sort()
		fmt.Printf("Available collectors:\n")
		for _, n := range collectorNames {
			fmt.Printf(" - %s\n", n)
		}
		return
	}
	collectors, err := loadCollectors(*enabledCollectors)
	if err != nil {
		log.Fatalf("Couldn't load collectors: %s", err)
	}

	log.Infof("Enabled collectors:")
	for n := range collectors {
		log.Infof(" - %s", n)
	}

	if err := prometheus.Register(NodeCollector{collectors: collectors}); err != nil {
		log.Fatalf("Couldn't register collector: %s", err)
	}
	handler := promhttp.HandlerFor(prometheus.DefaultGatherer,
		promhttp.HandlerOpts{
			ErrorLog:      log.NewErrorLogger(),
			ErrorHandling: promhttp.ContinueOnError,
		})

	// TODO(ts): Remove deprecated and problematic InstrumentHandler usage.
	http.Handle(*metricsPath, prometheus.InstrumentHandler("prometheus", handler))
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(`
			<title>Node Exporter</title>

Node Exporter

<a href="` + *metricsPath + `">Metrics

			`))
	})

	log.Infoln("Listening on", *listenAddress)
	err = http.ListenAndServe(*listenAddress, nil)
	if err != nil {
		log.Fatal(err)
	}
}

redpajama_set_name: RedPajamaGithub


text:
package com.pinterest.pinlater.backends.redis;

/**
 * RedisClientBuilders abstract away redis client's from RedisPools.
 *
 * RedisClientBuilders MUST be able to handle concurrent requests.
 *
 * @param <RC> RedisClient type, for example JedisPool
 */
public interface RedisClientHelper<RC> {

  /**
   * createClient should create a new client of type RC (Redis Client)
   * @param redisClientConfig A RedisClientConfig representing the parameters the client utilize
   * @param endPoint The host that this client should connect to
   * @return A client adhering to redisClientConfig connected to endPoint
   */
  RC createClient(RedisClientConfig redisClientConfig, EndPoint endPoint);

  /**
   * destroyClient should cleanup the redis client
   * @param redisClient The client to be cleaned up.
   */
  void destroyClient(RC redisClient);

  /**
   * clientPing should ping the redis instance connected to this client.
   *
   * clientPing is used in the RedisHeartBeater to ensure redis instance liveliness.
   *
   * @param redisClient The redisClient to use to ping redis
   * @return true if ping was successful and replied PONG, false otherwise
   */
  boolean clientPing(RC redisClient);
}


text:
const jscodeshift = require('jscodeshift')
const t = jscodeshift
const b = jscodeshift
const { read,testFile } = require('./util')

const renameNavs = ast => ast
  .findVariableDeclarators('navs')
    .renameTo('bar')

const treeModder = modder => ast => {
  modder(ast)
  return ast
}

const addNav = treeModder( ast =>
   ast.findVariableDeclarators('navs')
  .find(t.ArrayExpression)
  .get('elements')
  .push(b.identifier('abc'))
)

const addContainer = treeModder( ast =>
   ast.findVariableDeclarators('Containers')
  .find(t.ArrayExpression)
  .get('elements')
  .push(b.identifier('def'))
)

const addImport = treeModder( ast =>  {
 // onsole.ast)
    const mockImport = b.importDeclaration(
      [
        b.importSpecifier(
          b.identifier('Imported'),
          b.identifier('Local')
        ),
      ] ,
      b.literal('/remote/pakcage')
    )
   ast.find(t.Program)
   .get('body').unshift(mockImport)

  }
)

const toSoruce = ast =>
  ast.toSource()

read(testFile)
  .map(jscodeshift)
  // .map(addNav)
  // .map(addContainer)
  .map(addImport)
  .map(toSoruce)
  .fork(err => console.log('error: ',err.stack),
        //data => console.log('done..')
        data => console.log('recast output :\n',data)
  )


text:
package ua.com.fielden.platform.algorithm.search;

import java.util.List;

/**
 * An contract, which should be supported by every type that needs to be serve a role of the tree node.
 *
 * @author TG Team
 *
 * @param <T>
 */
public interface ITreeNode<T> {

    List<? extends ITreeNode<T>> daughters();

    T state();

}


text:
/**
 *
 * See [the RTM client events](../events/client) for details of the client event lifecycle.
 */

var Promise = require('bluebird');
var bind = require('lodash').bind;
var cloneDeep = require('lodash').cloneDeep;
var includes = require('lodash').includes;
var hasKey = require('lodash').has;
var inherits = require('inherits');
var isFunction = require('lodash').isFunction;
var isUndefined = require('lodash').isUndefined;
var forEach = require('lodash').forEach;
var noop = require('lodash').noop;
var keys = require('lodash').keys;

var RTM_API_EVENTS = require('../events/rtm').EVENTS;
var RTM_CLIENT_INTERNAL_EVENT_TYPES = [
  'pong',
  RTM_API_EVENTS.HELLO,
  RTM_API_EVENTS.TEAM_MIGRATION_STARTED
];
var UNRECOVERABLE_RTM_START_ERRS = [
  'not_authed',
  'invalid_auth',
  'account_inactive'
];
var CLIENT_EVENTS = require('../events/client').RTM;
var BaseAPIClient = require('../client');
var DataStore = require('../../data-store/data-store');
var MemoryDataStore = require('../../data-store/memory-data-store');
var RtmFacet = require('../web/facets').RtmFacet;
var ChatFacet = require('../web/facets').ChatFacet;
var SlackRTMSendError = require('../errors').SlackRTMSendError;
var makeMessageEventWithSubtype = require('../events/utils').makeMessageEventWithSubtype;
var wsSocketFn = require('../transports/ws');

/**
 *
 * @param {String} token
 * @param {object?} opts
 * @param {Function} opts.socketFn A function to call, passing in a websocket URL, that should
 *     return a websocket instance connected to that URL.
 * @param {object} opts.dataStore A store to cache Slack info, e.g. channels, users etc. in.
 *     If you don't want a store, pass false or null as the value for this.
 * @param {boolean} opts.autoReconnect Whether or not to automatically reconnect when the connection
 *     closes.
 * @param {number} opts.maxReconnectionAttempts
 * @param {number} opts.reconnectionBackoff
 * @param {number} opts.wsPingInterval
 * @param {number} opts.maxPongInterval
 * @param {string} opts.logLevel The log level for the logger.
 * @param {Function} opts.logger Function to use for log calls, takes (logLevel, logString)
 *     parameters.
 * @constructor
 */
function RTMClient(token, opts) {
  var clientOpts = opts || {};

  // Force the max request concurrency to 1 for the RTM client. This is because it should not be
  // trying to rtm.start in parallel.
  clientOpts.maxRequestConcurrency = 1;

  BaseAPIClient.call(this, token, clientOpts);

  /**
   * @type {Function}
   */
  this._socketFn = clientOpts.socketFn || wsSocketFn;

  /**
   * The active websocket.
   * @type {Object}
   */
  this.ws = undefined;

  /**
   *
   * @type {number}
   * @private
   */
  this._messageId = 1;

  /**
   * @type {{}}
   * @private
   */
  this._pendingMessages = {};

  /**
   *
   * @type {{}}
   * @private
   */
  this._msgResponseHandlers = {};

  /**
   *
   * @type {{}}
   * @private
   */
  this._msgChannelLookup = {};

  if (clientOpts.dataStore instanceof DataStore) {
    this.registerDataStore(clientOpts.dataStore);
  } else {
    // Default to using the memory data store if the user didn't set anything here
    if (isUndefined(clientOpts.dataStore)) {
      this.registerDataStore(new MemoryDataStore());
    }
  }

  this.MAX_RECONNECTION_ATTEMPTS = clientOpts.maxReconnectionAttempts || 10;
  this.RECONNECTION_BACKOFF = clientOpts.reconnectionBackoff || 3000;

  // NOTE: see the "Ping and Pong" section of https://api.slack.com/rtm
  //       these are to do with the RTM API level connection and not the underlying ws connection.
  this.MAX_PONG_INTERVAL = clientOpts.maxPongInterval || 10000;
  this.WS_PING_INTERVAL = clientOpts.wsPingInterval || 5000;

  this.autoReconnect = clientOpts.autoReconnect !== false;
}

inherits(RTMClient, BaseAPIClient);

/**
 * @type {boolean}
 */
RTMClient.prototype.connected = false;

/**
 * @type {boolean}
 */
RTMClient.prototype.authenticated = false;

/**
 * The id of the user that's currently connected via this client.
 * @type {string}
 */
RTMClient.prototype.activeUserId = undefined;

/**
 * The id of the team that's currently connected via this client.
 * @type {string}
 */
RTMClient.prototype.activeTeamId = undefined;

/**
 * The timer repeatedly pinging the server to let it know the client is still alive.
 * @type {?}
 */
RTMClient.prototype._pingTimer = null;

/**
 * The time the last pong was received from the server.
 * @type {number}
 * @private
 */
RTMClient.prototype._lastPong = 0;

/**
 *
 * @type {number}
 * @private
 */
RTMClient.prototype._connAttempts = 0;

/**
 * Whether the server is currently connecting.
 * @type {boolean}
 * @private
 */
RTMClient.prototype._connecting = false;

/**
 * Whether the server is currently re-connecting.
 * @type {boolean}
 * @private
 */
RTMClient.prototype._reconnecting = false;

/**
 * @type {SlackDataStore}
 */
RTMClient.prototype.dataStore = undefined;

/** @inheritDoc */
RTMClient.prototype._createFacets = function _createFacets() {
  RTMClient.super_.prototype._createFacets.call(this);

  /**
   * Allows the RTM client to get setup without needing to have a full web client.
   * @type {RtmFacet}
   * @private
   */
  this._rtm = new RtmFacet(bind(this._makeAPICall, this));

  /**
   * Allows access to some chat functions
   * @type {ChatFacet}
   * @private
   */
  this._chat = new ChatFacet(bind(this._makeAPICall, this));
};

/**
 *
 * @param {object} opts
 */
RTMClient.prototype.start = function start(opts) {
  // Check whether the client is currently attempting to connect to the RTM API.
  if (!this._connecting) {
    this.logger('verbose', 'attempting to connect via the RTM API');
    this.emit(CLIENT_EVENTS.CONNECTING);
    this._connecting = true;

    this._rtm.start(opts, bind(this._onStart, this));
  }
};

/**
 * @deprecated since version 2.0.0, use start() instead.
 */
RTMClient.prototype.login = function login(opts) {
  this.start(opts);
};

/**
 * Generates the next message id to use.
 *
 * NOTE: This id must be unique per RTM connection.
 */
RTMClient.prototype.nextMessageId = function nextMessageId() {
  return this._messageId++;
};

/**
 *
 * @param err
 * @param data
 * @private
 */
RTMClient.prototype._onStart = function _onStart(err, data) {
  var errMsg;
  this._connecting = false;
  this._reconnecting = false;

  if (err || !data.url) {
    this.emit(CLIENT_EVENTS.UNABLE_TO_RTM_START, err || data.error);

    // Any of these mean this client is unusable, so don't attempt to auto-reconnect
    if (data && includes(UNRECOVERABLE_RTM_START_ERRS, data.error)) {
      errMsg = 'unrecoverable failure connecting to the RTM API';
      this.logger('error', errMsg + ': ' + data.error);
      this.disconnect(errMsg, data.error);
    } else {
      this.logger('info', 'unable to RTM start, attempting reconnect: ' + err || data.error);
      this.authenticated = false;
      if (this.autoReconnect) {
        this.reconnect();
      }
    }
  } else {
    this.logger('verbose', 'rtm.start successful, attempting to open websocket URL');
    this.authenticated = true;
    this.activeUserId = data.self.id;
    this.activeTeamId = data.team.id;
    if (!isUndefined(this.dataStore)) {
      this.dataStore.cacheRtmStart(data);
    }

    this.emit(CLIENT_EVENTS.AUTHENTICATED, data);
    this.connect(data.url);
  }
};

/**
 * Closes the websocket and tears down the ping function.
 * @private
 */
RTMClient.prototype._safeDisconnect = function _safeDisconnect() {
  if (this._pingTimer) {
    clearInterval(this._pingTimer);
    this._pingTimer = null;
  }
  if (this.ws) {
    // Stop listening to the websocket's close event, so that the auto-reconnect logic doesn't fire
    // twice.
    this.ws.removeAllListeners('close');
    this.ws.close();
  }
  this.authenticated = false;
  this.connected = false;
};

/**
 * Connects to the RTM API.
 * @param {string} socketUrl The URL of the websocket to connect to.
 */
RTMClient.prototype.connect = function connect(socketUrl) {
  this.emit(CLIENT_EVENTS.WS_OPENING);
  this.ws = this._socketFn(socketUrl);

  this.ws.on('open', bind(this.handleWsOpen, this));
  this.ws.on('message', bind(this.handleWsMessage, this));
  this.ws.on('error', bind(this.handleWsError, this));
  this.ws.on('close', bind(this.handleWsClose, this));
};

/**
 * Disconnects from the RTM API.
 * @param optReason
 * @param optCode
 */
RTMClient.prototype.disconnect = function disconnect(optErr, optCode) {
  this.emit(CLIENT_EVENTS.DISCONNECT, optErr, optCode);
  this.autoReconnect = false;
  this._safeDisconnect();
};

/**
 *
 */
RTMClient.prototype.reconnect = function reconnect() {
  if (!this._reconnecting) {
    this.emit(CLIENT_EVENTS.ATTEMPTING_RECONNECT);
    this._reconnecting = true;
    this._safeDisconnect();

    // TODO(leah): Update this to remove the reconn logic in the RTM client as it should be covered
    //             by the web client policy
    this._connAttempts++;
    if (this._connAttempts > this.MAX_RECONNECTION_ATTEMPTS) {
      this.emit(
        CLIENT_EVENTS.UNABLE_TO_RTM_START,
        'unable to connect to Slack RTM API, failed after max reconnection attempts'
      );
    }
    setTimeout(bind(this.start, this), this._connAttempts * this.RECONNECTION_BACKOFF);
  }
};

/**
 * Pings the remote server to let it know the client is still alive.
 * @private
 */
RTMClient.prototype._pingServer = function _pingServer() {
  var pongInterval;

  if (this.connected) {
    // If the last pong was more than MAX_PONG_INTERVAL, force a reconnect
    pongInterval = Date.now() - this._lastPong;
    if (pongInterval > this.MAX_PONG_INTERVAL) {
      this.reconnect();
    } else {
      this.send({ type: 'ping' }, noop);
    }
  }
};

/**
 * Handler to deal with the WebSocket open event.
 * NOTE: this.connected doesn't get set to true until the helloHandler is called.
 */
RTMClient.prototype.handleWsOpen = function handleWsOpen() {
  this.emit(CLIENT_EVENTS.WS_OPENED);
  this._lastPong = Date.now();
  this._connAttempts = 0;
  if (this._pingTimer) {
    clearInterval(this._pingTimer);
  } else {
    this._pingTimer = setInterval(bind(this._pingServer, this), this.WS_PING_INTERVAL);
  }
};

/**
 * Handler to deal with the WebSocket message event.
 * @param {object} wsMsg
 */
RTMClient.prototype.handleWsMessage = function handleWsMessage(wsMsg) {
  var message;
  this.logger('debug', wsMsg);
  this.emit(CLIENT_EVENTS.RAW_MESSAGE, wsMsg);

  try {
    message = JSON.parse(wsMsg);
  } catch (err) {
    // TODO(leah): Emit an event here?
    this.logger('debug', 'unable to parse message: ' + err);
    return;
  }

  if (includes(RTM_CLIENT_INTERNAL_EVENT_TYPES, message.type)) {
    this._handleWsMessageInternal(message.type, message);
  } else {
    this._handleWsMessageViaEventHandler(message.type, message);
  }
};

/**
 *
 * @param {String} messageType
 * @param {Object} message
 * @private
 */
RTMClient.prototype._handleWsMessageInternal = function _handleWsMessageInternal(
  messageType, message) {
  if (messageType === 'pong') {
    this._handlePong(message);
  } else if (messageType === RTM_API_EVENTS.HELLO) {
    this._handleHello();
  } else if (messageType === RTM_API_EVENTS.TEAM_MIGRATION_STARTED) {
    this.reconnect();
    this.emit(messageType, message);
  }
};

/**
 *
 * @param {String} messageType
 * @param {Object} message
 * @private
 */
RTMClient.prototype._handleWsMessageViaEventHandler = function _handleWsMessageViaEventHandler(
  messageType, message) {
  var replyTo = message.reply_to;

  if (!isUndefined(this.dataStore)) {
    this.dataStore.handleRtmMessage(this.activeUserId, this.activeTeamId, messageType, message);
  }

  if (replyTo) {
    if (!messageType) {
      this._handleMessageAck(replyTo, message);
    } else {
      this._handleMostRecentMsgReply(replyTo, message);
    }
  } else {
    // Non reply_to messages should *always* have a type
    this.emit(messageType, message);
    if (messageType === RTM_API_EVENTS.MESSAGE && !isUndefined(message.subtype)) {
      this.emit(makeMessageEventWithSubtype(message.subtype), message);
    }
  }
};

/**
 * Handler for the remote server's response to a message being sent on the websocket.
 * @param replyTo
 * @param message
 */
RTMClient.prototype._handleMessageAck = function handleMessageAck(replyTo, message) {
  var msg;
  var channelId;

  // This means that the message is an ack of a message sent via the websocket from the client.
  // The expected structure is something like:
  // {
  //   "ok": true,
  //   "reply_to": 1,
  //   "ts": "1355517523.000005",
  //   "text": "Hello world"
  // }
  // ... in the case of success.
  //
  // See the Sending messages section of https://api.slack.com/rtm for details.

  if (hasKey(this._msgResponseHandlers, replyTo)) {
    if (!message.ok) {
      this._handleMsgResponse(replyTo, new SlackRTMSendError(message.error.msg, message), null);
    } else {
      channelId = this._msgChannelLookup[replyTo];

      // Make a synthetic message, rather than passing back the raw ack response
      msg = {
        type: 'message',
        channel: channelId,
        user: this.activeUserId,
        text: message.text,
        ts: message.ts
      };

      if (this.dataStore) {
        // NOTE: this will treat the message response as canonical and assumes that no temporary
        //       message has been put in place.
        this.dataStore.handleRtmMessage(this.activeUserId, this.activeTeamId, 'message', msg);
      }

      this._handleMsgResponse(replyTo, null, msg);
    }
  } else {
    // This should be impossible. If the message is received with no message type, it's a response
    // to a message sent by this client, so the absence of a handler for it should never happen.
    this.logger('error', 'message received with unknown reply_to: ' + JSON.stringify(message));
  }
};

/**
 * Handler for the server
 * @param {} replyTo
 * @param {{}} message
 * @private
 */
RTMClient.prototype._handleMostRecentMsgReply = function _handleMostRecentMsgReply(
  replyTo, message) {
  var msg;
  var pendingMessageIds;
  var failedToSendErr;

  // The server will send the most recent reply message to the client when it first connects,
  // so will receive a message that looks like:
  //
  // {
  //   "reply_to": 848,
  //   "type": "message",
  //   "channel": "C0CHZA86Q",
  //   "user": "U0CJ5PC7L",
  //   "text": "meh-mah",
  //   "ts": "1457327357.000011"
  // }
  //
  // This should generally only happen in the case of disconnections. If that happens, the last
  // message should be handled gracefully.

  if (this._msgResponseHandlers[replyTo]) {
    msg = cloneDeep(message);
    delete msg.reply_to;
    this._handleMsgResponse(replyTo, null, msg);
  } else {
    // The only time this should happen is when a client first connects
    this.logger('info', 'message received on reconnect with no registered callback:\n'
      + JSON.stringify(message));
  }

  pendingMessageIds = keys(this._pendingMessages);
  forEach(pendingMessageIds, bind(function handlePendingMessage(messageId) {
    // If the message id is less than the most recent reply to id, assume that the message has
    // been processed. If it's greater than the most recent reply to, then it's likely that the
    // message didn't get sent to the remote server. This should almost never happen, so for now if
    // it does, call the pending callback with a custom error

    if (messageId > replyTo) {
      failedToSendErr = new SlackRTMSendError(
        'message not sent due to connection trouble', this._pendingMessages[messageId]);
      this._handleMsgResponse(messageId, failedToSendErr, null);
    } else {
      this._clearMessageState(messageId);
    }
  }, this));
};

/**
 * Emits the websocket error.
 * @param {Object} err
 */
RTMClient.prototype.handleWsError = function handleWsError(err) {
  this.logger('debug', err);
  this.emit(CLIENT_EVENTS.WS_ERROR, err);
};

/**
 *
 */
RTMClient.prototype.handleWsClose = function handleWsClose(code, reason) {
  this.connected = false;

  this.emit(CLIENT_EVENTS.WS_CLOSE, code, reason);

  if (this.autoReconnect) {
    if (!this._connecting) {
      this.reconnect();
    }
  } else {
    this.disconnect('websocket closed with auto-reconnect false on the RTM client');
  }
};

/**
 * Handles the RTM API's pong message, updating the lastPong time on the client.
 * @param {Object} message
 */
RTMClient.prototype._handlePong = function _handlePong(message) {
  this._lastPong = Date.now();
  this._handleMsgResponse(message.reply_to, null, message);
};

/** {@link https://api.slack.com/events/hello|hello} */
RTMClient.prototype._handleHello = function _handleHello() {
  this.connected = true;
  this.emit(CLIENT_EVENTS.RTM_CONNECTION_OPENED);
};

/**
 * Helper for sending a simple message to a channel|group|DM etc via the RTM API.
 * @param {string} text The text of the messsage to send.
 * @param {string} channelId The id of the channel|group|DM to send this message to.
 * @param {Function=} optCb
 */
RTMClient.prototype.sendMessage = function sendMessage(text, channelId, optCb) {
  return this.send({
    text: text,
    channel: channelId,
    type: RTM_API_EVENTS.MESSAGE
  }, optCb);
};

/**
 * Helper for updating a sent message via the 'chat.update' API call
 * @param message {object} message The message object to be updated,
 * see /lib/clients/web/facets/chat.js for more details
 * @param {Function=} optCb Optional callback
 */
RTMClient.prototype.updateMessage = function updateMessage(message, optCb) {
  return this._chat.update(message.ts, message.channel, message.text, message.opts, optCb);
};

/**
 * Sends a typing indicator to indicate that the user with `activeUserId` is typing.
 * @param {string} channelId The id of the channel|group|DM to send this message to.
 */
RTMClient.prototype.sendTyping = function sendTyping(channelId) {
  this.send({
    type: 'typing',
    channel: channelId
  }, noop);
};

/**
 * Sends a message over the websocket to the server.
 * @param {*} message The message to send back to the server.
 * @param {Function=} optCb
 */
RTMClient.prototype.send = function send(message, optCb) {
  var err;
  var ret;

  if (this.connected) {
    ret = this._send(message, optCb);
  } else {
    err = new SlackRTMSendError('ws not connected, unable to send message', message);
    this.logger('error', err);

    if (optCb) {
      setTimeout(function wsSendDisconnectedCb() {
        optCb(err, null);
      }, 1);
    } else {
      ret = new Promise(function wsSendDisconnectedPromise(fulfill, reject) {
        reject(err);
      });
    }
  }

  return ret;
};

/**
 *
 * @param message
 * @param optCb
 * @returns {*}
 * @private
 */
RTMClient.prototype._send = function _send(message, optCb) {
  var _this = this;
  var jsonMessage;
  var ret;
  var msgId = this.nextMessageId();
  var _handleWsSendResponse = bind(this._handleWsSendResponse, this, msgId);
  var wsMsg = cloneDeep(message);
  wsMsg.id = msgId;

  // Track the message from the client's perspective
  this._pendingMessages[msgId] = message;

  jsonMessage = JSON.stringify(wsMsg);
  this.logger('debug', 'sending message via ws: ' + jsonMessage);

  if (optCb) {
    _this._registerMsgHandler(msgId, wsMsg, optCb);
    this.ws.send(jsonMessage, undefined, _handleWsSendResponse);
  } else {
    ret = new Promise(function wsSendPromiseInner(fulfill, reject) {
      _this._registerMsgHandler(msgId, wsMsg, { fulfill: fulfill, reject: reject });
      _this.ws.send(jsonMessage, undefined, _handleWsSendResponse);
    });
  }

  return ret;
};

/**
 *
 * @param msgId
 * @param wsRespErr
 * @private
 */
RTMClient.prototype._handleWsSendResponse = function _handleWsSendResponse(msgId, wsRespErr) {
  if (wsRespErr) {
    this._handleMsgResponse(msgId, wsRespErr, null);
  } else {
    // TODO(leah): This should probably clear the enqueued message object from _pendingMessages, as
    //             the server has the data at this point. Figure out how this will interact with
    //             the logic in _handleMostRecentMsgReply
  }
};

/**
 * Registers a handler, either a function or {fulfill: fn, reject: fn}, for a message id.
 * @param {number} msgId The id of the message to handle.
 * @param {object} wsMsg
 * @param {*} handler
 * @private
 */
RTMClient.prototype._registerMsgHandler = function _registerMsgHandler(msgId, wsMsg, handler) {
  //
  // Track the channel a message was sent to.
  //
  // This is so that the client can create a synthetic message object when it receives the message
  // ack from the RTM API server. This allows:
  //   - passing back a full message object, rather than an ack message, to the client that sent the
  //     message
  //   - pushing a standard message into the relevant channel's history
  //
  if (wsMsg.type === 'message' && wsMsg.channel) {
    this._msgChannelLookup[msgId] = wsMsg.channel;
  }

  this._msgResponseHandlers[msgId] = handler;
};

/**
 * Calls the handler registered for a given msgId and cleans it up on completion.
 *
 * @param {number} msgId The id of the message to handle.
 * @param {Object} err
 * @param {Object} res
 * @private
 */
RTMClient.prototype._handleMsgResponse = function _handleMsgResponse(msgId, err, res) {
  var responseHandler = this._msgResponseHandlers[msgId];
  if (err) {
    this.logger('debug', 'Error sending message: ' + err);
  }

  if (!responseHandler) {
    this.logger('debug', 'no response handler for message ID: ' + msgId);
    return;
  }

  if (isFunction(responseHandler)) {
    responseHandler(err, res);
  } else {
    if (err) {
      responseHandler.reject(err);
    } else {
      responseHandler.fulfill(res);
    }
  }

  this._clearMessageState(msgId);
};

RTMClient.prototype._clearMessageState = function _clearMessageState(msgId) {
  delete this._msgChannelLookup[msgId];
  delete this._msgResponseHandlers[msgId];
  delete this._pendingMessages[msgId];
};

module.exports = RTMClient;


text:
id: 5900f5191000cf542c51002b
challengeType: 5
title: 'Problem 428: Necklace of Circles'
videoUrl: ''
localeTitle: ''
---

## Description
undefined

## Instructions

## Tests

```yml
tests:
  - text: ''
    testString: 'assert.strictEqual(necklace(1000000000), 747215561862, "<code>necklace(1000000000)</code> should return 747215561862.");'

```

## Challenge Seed

```js
function necklace(n) {
  // Good luck!
  return true;
}

necklace(1000000000)

```

## Solution

```js
// solution required
```


text:
. ../../toolchain.sh
make clean
make configure
cd busybox-1.22.1
make -j 2
make install
cd ..
make misc


text:
Resets the hit counter of an exception breakpoint.

## arguments

`arg1` The name, exception code or name of the exception breakpoint.

`[arg2]` The new hit count (zero when not specified).

## result

This command does not set any result variables.


text:
/* config.h.  Generated by configure.  */
/* config.h.in.  Generated from configure.ac by autoheader.  */

/* Define to enable diagnostic debugging support. */
/* #undef DEBUG */

/* Define to 1 if you have the <assert.h> header file. */
#define HAVE_ASSERT_H 1

/* Define to 1 if you have the <dlfcn.h> header file. */
/* #undef HAVE_DLFCN_H */

/* Define to 1 if you have the `ftruncate' function. */
/* #undef HAVE_FTRUNCATE */

/* Define to 1 if you have the <inttypes.h> header file. */
#define HAVE_INTTYPES_H 1

/* Define to 1 if you have the `z' library (-lz). */
#define HAVE_LIBZ 1

/* Define to 1 if you have the <memory.h> header file. */
#define HAVE_MEMORY_H 1

/* Define to 1 if you have the <stdint.h> header file. */
#define HAVE_STDINT_H 1

/* Define to 1 if you have the <stdlib.h> header file. */
#define HAVE_STDLIB_H 1

/* Define to 1 if you have the <strings.h> header file. */
#define HAVE_STRINGS_H 1

/* Define to 1 if you have the <string.h> header file. */
#define HAVE_STRING_H 1

/* Define to 1 if you have the <sys/stat.h> header file. */
#define HAVE_SYS_STAT_H 1

/* Define to 1 if you have the <sys/types.h> header file. */
#define HAVE_SYS_TYPES_H 1

/* Define to 1 if you have the <unistd.h> header file. */
/* #undef HAVE_UNISTD_H */

/* Define to disable debugging assertions. */
/* #undef NDEBUG */

/* Name of package */
#define PACKAGE "libid3tag"

/* Define to the address where bug reports for this package should be sent. */
#define PACKAGE_BUGREPORT "support@underbit.com"

/* Define to the full name of this package. */
#define PACKAGE_NAME "ID3 Tag"

/* Define to the full name and version of this package. */
#define PACKAGE_STRING "ID3 Tag 0.15.1b"

/* Define to the one symbol short name of this package. */
#define PACKAGE_TARNAME "libid3tag"

/* Define to the version of this package. */
#define PACKAGE_VERSION "0.15.1b"

/* Define to 1 if you have the ANSI C header files. */
#define STDC_HEADERS 1

/* Version number of package */
#define VERSION "0.15.1b"

/* Define to empty if `const' does not conform to ANSI C. */
/* #undef const */

/* Define as `__inline' if that's what the C compiler calls it, or to nothing
   if it is not supported. */
/* #undef inline */


text:
var zrUtil = require("zrender/core/util");

function bb() {
  zrUtil();
}

var _default = bb;
module.exports = _default;


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

#include "ui/events/ozone/evdev/touch_event_converter_evdev.h"

#include <errno.h>
#include <fcntl.h>
#include <linux/input.h>
#include <poll.h>
#include <stdio.h>
#include <unistd.h>

#include <cmath>
#include <limits>

#include "base/bind.h"
#include "base/callback.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/message_loop/message_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/trace_event/trace_event.h"
#include "ui/events/devices/device_data_manager.h"
#include "ui/events/devices/device_util_linux.h"
#include "ui/events/event.h"
#include "ui/events/event_constants.h"
#include "ui/events/event_switches.h"
#include "ui/events/event_utils.h"
#include "ui/events/ozone/evdev/device_event_dispatcher_evdev.h"
#include "ui/events/ozone/evdev/touch_evdev_types.h"
#include "ui/events/ozone/evdev/touch_noise/touch_noise_finder.h"
#include "ui/ozone/public/input_controller.h"

namespace {

const int kMaxTrackingId = 0xffff;  // TRKID_MAX in kernel.

struct TouchCalibration {
  int bezel_left;
  int bezel_right;
  int bezel_top;
  int bezel_bottom;
};

void GetTouchCalibration(TouchCalibration* cal) {
  std::vector<std::string> parts = base::SplitString(
      base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
          switches::kTouchCalibration),
      ",", base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
  if (parts.size() >= 4) {
    if (!base::StringToInt(parts[0], &cal->bezel_left))
      LOG(ERROR) << "Incorrect left border calibration value passed.";
    if (!base::StringToInt(parts[1], &cal->bezel_right))
      LOG(ERROR) << "Incorrect right border calibration value passed.";
    if (!base::StringToInt(parts[2], &cal->bezel_top))
      LOG(ERROR) << "Incorrect top border calibration value passed.";
    if (!base::StringToInt(parts[3], &cal->bezel_bottom))
      LOG(ERROR) << "Incorrect bottom border calibration value passed.";
  }
}

int32_t AbsCodeToMtCode(int32_t code) {
  switch (code) {
    case ABS_X:
      return ABS_MT_POSITION_X;
    case ABS_Y:
      return ABS_MT_POSITION_Y;
    case ABS_PRESSURE:
      return ABS_MT_PRESSURE;
    case ABS_DISTANCE:
      return ABS_MT_DISTANCE;
    default:
      return -1;
  }
}

ui::PointerDetails GetEventPointerDetails(
    const ui::InProgressTouchEvdev& event) {
  ui::EventPointerType type;
  switch (event.tool_code) {
    case BTN_TOOL_PEN:
      type = ui::EventPointerType::POINTER_TYPE_PEN;
      break;
    case BTN_TOOL_RUBBER:
      type = ui::EventPointerType::POINTER_TYPE_ERASER;
      break;
    default:
      type = ui::EventPointerType::POINTER_TYPE_TOUCH;
  }
  return ui::PointerDetails(type, event.radius_x, event.radius_y,
                            event.pressure,
                            /* tilt_x */ 0.0f,
                            /* tilt_y */ 0.0f);
}

const int kTrackingIdForUnusedSlot = -1;

}  // namespace

namespace ui {

TouchEventConverterEvdev::TouchEventConverterEvdev(
    int fd,
    base::FilePath path,
    int id,
    const EventDeviceInfo& devinfo,
    DeviceEventDispatcherEvdev* dispatcher)
    : EventConverterEvdev(fd,
                          path,
                          id,
                          devinfo.device_type(),
                          devinfo.name(),
                          devinfo.vendor_id(),
                          devinfo.product_id()),
      dispatcher_(dispatcher) {
  if (base::CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kExtraTouchNoiseFiltering)) {
    touch_noise_finder_.reset(new TouchNoiseFinder);
  }
  touch_evdev_debug_buffer_.Initialize(devinfo);
}

TouchEventConverterEvdev::~TouchEventConverterEvdev() {
}

void TouchEventConverterEvdev::Initialize(const EventDeviceInfo& info) {
  has_mt_ = info.HasMultitouch();
  has_pen_ = info.HasKeyEvent(BTN_TOOL_PEN);

  if (has_mt_) {
    pressure_min_ = info.GetAbsMinimum(ABS_MT_PRESSURE);
    pressure_max_ = info.GetAbsMaximum(ABS_MT_PRESSURE);
    x_min_tuxels_ = info.GetAbsMinimum(ABS_MT_POSITION_X);
    x_num_tuxels_ = info.GetAbsMaximum(ABS_MT_POSITION_X) - x_min_tuxels_ + 1;
    y_min_tuxels_ = info.GetAbsMinimum(ABS_MT_POSITION_Y);
    y_num_tuxels_ = info.GetAbsMaximum(ABS_MT_POSITION_Y) - y_min_tuxels_ + 1;
    touch_points_ =
        std::min<int>(info.GetAbsMaximum(ABS_MT_SLOT) + 1, kNumTouchEvdevSlots);
    major_max_ = info.GetAbsMaximum(ABS_MT_TOUCH_MAJOR);
    current_slot_ = info.GetAbsValue(ABS_MT_SLOT);
  } else {
    pressure_min_ = info.GetAbsMinimum(ABS_PRESSURE);
    pressure_max_ = info.GetAbsMaximum(ABS_PRESSURE);
    x_min_tuxels_ = info.GetAbsMinimum(ABS_X);
    x_num_tuxels_ = info.GetAbsMaximum(ABS_X) - x_min_tuxels_ + 1;
    y_min_tuxels_ = info.GetAbsMinimum(ABS_Y);
    y_num_tuxels_ = info.GetAbsMaximum(ABS_Y) - y_min_tuxels_ + 1;
    touch_points_ = 1;
    major_max_ = 0;
    current_slot_ = 0;
  }

  quirk_left_mouse_button_ =
      !has_mt_ && !info.HasKeyEvent(BTN_TOUCH) && info.HasKeyEvent(BTN_LEFT);

  // Apply --touch-calibration.
  if (type() == INPUT_DEVICE_INTERNAL) {
    TouchCalibration cal = {};
    GetTouchCalibration(&cal);
    x_min_tuxels_ += cal.bezel_left;
    x_num_tuxels_ -= cal.bezel_left + cal.bezel_right;
    y_min_tuxels_ += cal.bezel_top;
    y_num_tuxels_ -= cal.bezel_top + cal.bezel_bottom;

    VLOG(1) << "applying touch calibration: "
            << base::StringPrintf("[%d, %d, %d, %d]", cal.bezel_left,
                                  cal.bezel_right, cal.bezel_top,
                                  cal.bezel_bottom);
  }

  // TODO(denniskempin): Use EVIOCGKEY to synchronize key state.

  events_.resize(touch_points_);

  if (has_mt_) {
    for (size_t i = 0; i < events_.size(); ++i) {
      events_[i].x = info.GetAbsMtSlotValueWithDefault(ABS_MT_POSITION_X, i, 0);
      events_[i].y = info.GetAbsMtSlotValueWithDefault(ABS_MT_POSITION_Y, i, 0);
      events_[i].tracking_id = info.GetAbsMtSlotValueWithDefault(
          ABS_MT_TRACKING_ID, i, kTrackingIdForUnusedSlot);
      events_[i].touching = (events_[i].tracking_id >= 0);
      events_[i].slot = i;

      // Dirty the slot so we'll update the consumer at the first opportunity.
      events_[i].altered = true;

      // Optional bits.
      int touch_major =
          info.GetAbsMtSlotValueWithDefault(ABS_MT_TOUCH_MAJOR, i, 0);
      events_[i].radius_x = touch_major / 2.0f;
      events_[i].radius_y =
          info.GetAbsMtSlotValueWithDefault(ABS_MT_TOUCH_MINOR, i, 0) / 2.0f;
      events_[i].pressure = ScalePressure(
          info.GetAbsMtSlotValueWithDefault(ABS_MT_PRESSURE, i, 0));
      events_[i].cancelled = (major_max_ > 0 && touch_major == major_max_);
    }
  } else {
    // TODO(spang): Add key state to EventDeviceInfo to allow initial contact.
    // (and make sure to take into account quirk_left_mouse_button_)
    events_[0].x = 0;
    events_[0].y = 0;
    events_[0].tracking_id = kTrackingIdForUnusedSlot;
    events_[0].touching = false;
    events_[0].slot = 0;
    events_[0].radius_x = 0;
    events_[0].radius_y = 0;
    events_[0].pressure = 0;
    events_[0].tool_code = 0;
    events_[0].cancelled = false;
  }
}

void TouchEventConverterEvdev::Reinitialize() {
  ReleaseButtons();

  EventDeviceInfo info;
  if (!info.Initialize(fd_, path_)) {
    LOG(ERROR) << "Failed to synchronize state for touch device: "
               << path_.value();
    Stop();
    return;
  }
  Initialize(info);
}

bool TouchEventConverterEvdev::HasTouchscreen() const {
  return true;
}

bool TouchEventConverterEvdev::HasPen() const {
  return has_pen_;
}

gfx::Size TouchEventConverterEvdev::GetTouchscreenSize() const {
  return gfx::Size(x_num_tuxels_, y_num_tuxels_);
}

int TouchEventConverterEvdev::GetTouchPoints() const {
  return touch_points_;
}

void TouchEventConverterEvdev::OnEnabled() {
}

void TouchEventConverterEvdev::OnDisabled() {
  ReleaseTouches();
  ReleaseButtons();
  if (enable_palm_suppression_callback_) {
    enable_palm_suppression_callback_.Run(false);
  }
}

void TouchEventConverterEvdev::OnFileCanReadWithoutBlocking(int fd) {
  TRACE_EVENT1("evdev",
               "TouchEventConverterEvdev::OnFileCanReadWithoutBlocking", "fd",
               fd);

  input_event inputs[kNumTouchEvdevSlots * 6 + 1];
  ssize_t read_size = read(fd, inputs, sizeof(inputs));
  if (read_size < 0) {
    if (errno == EINTR || errno == EAGAIN)
      return;
    if (errno != ENODEV)
      PLOG(ERROR) << "error reading device " << path_.value();
    Stop();
    return;
  }

  for (unsigned i = 0; i < read_size / sizeof(*inputs); i++) {
    if (!has_mt_) {
      // Emulate the device as an MT device with only 1 slot by inserting extra
      // MT protocol events in the stream.
      EmulateMultitouchEvent(inputs[i]);
    }

    ProcessMultitouchEvent(inputs[i]);
  }
}

void TouchEventConverterEvdev::DumpTouchEventLog(const char* filename) {
  touch_evdev_debug_buffer_.DumpLog(filename);
}

void TouchEventConverterEvdev::SetTouchEventLoggingEnabled(bool enabled) {
  touch_logging_enabled_ = enabled;
}

void TouchEventConverterEvdev::SetPalmSuppressionCallback(
    const base::Callback<void(bool)>& callback) {
  enable_palm_suppression_callback_ = callback;
}

void TouchEventConverterEvdev::ProcessMultitouchEvent(
    const input_event& input) {
  if (touch_logging_enabled_)
    touch_evdev_debug_buffer_.ProcessEvent(current_slot_, &input);

  if (input.type == EV_SYN) {
    ProcessSyn(input);
  } else if (dropped_events_) {
    // Do nothing. This branch indicates we have lost sync with the driver.
  } else if (input.type == EV_ABS) {
    if (events_.size() <= current_slot_) {
      LOG(ERROR) << "current_slot_ (" << current_slot_
                 << ") >= events_.size() (" << events_.size() << ")";
    } else {
      ProcessAbs(input);
    }
  } else if (input.type == EV_KEY) {
    ProcessKey(input);
  } else if (input.type == EV_MSC) {
    // Ignored.
  } else {
    NOTIMPLEMENTED() << "invalid type: " << input.type;
  }
}

void TouchEventConverterEvdev::EmulateMultitouchEvent(
    const input_event& event) {
  input_event emulated_event = event;

  if (event.type == EV_ABS) {
    emulated_event.code = AbsCodeToMtCode(event.code);
    if (emulated_event.code >= 0)
      ProcessMultitouchEvent(emulated_event);
  } else if (event.type == EV_KEY) {
    if (event.code == BTN_TOUCH ||
        (quirk_left_mouse_button_ && event.code == BTN_LEFT)) {
      emulated_event.type = EV_ABS;
      emulated_event.code = ABS_MT_TRACKING_ID;
      emulated_event.value =
          event.value ? NextTrackingId() : kTrackingIdForUnusedSlot;
      ProcessMultitouchEvent(emulated_event);
    }
  }
}

void TouchEventConverterEvdev::ProcessKey(const input_event& input) {
  switch (input.code) {
    case BTN_TOUCH:
    case BTN_LEFT:
    case BTN_0:
      events_[current_slot_].btn_left.down = input.value;
      events_[current_slot_].btn_left.changed = true;
      break;
    case BTN_STYLUS:
      events_[current_slot_].btn_right.down = input.value;
      events_[current_slot_].btn_right.changed = true;
      break;
    case BTN_STYLUS2:
      events_[current_slot_].btn_middle.down = input.value;
      events_[current_slot_].btn_middle.changed = true;
      break;
    case BTN_TOOL_PEN:
    case BTN_TOOL_RUBBER:
      // Do not change tool types while touching to prevent inconsistencies
      // from switching between Mouse and TouchEvents.
      if (events_[current_slot_].was_touching)
        break;

      if (input.value > 0) {
        events_[current_slot_].tool_code = input.code;
      } else {
        events_[current_slot_].tool_code = 0;
      }
      events_[current_slot_].altered = true;
      break;
    default:
      NOTIMPLEMENTED() << "invalid code for EV_KEY: " << input.code;
  }
}

void TouchEventConverterEvdev::ProcessAbs(const input_event& input) {
  switch (input.code) {
    case ABS_MT_TOUCH_MAJOR:
      // TODO(spang): If we have all of major, minor, and orientation,
      // we can scale the ellipse correctly. However on the Pixel we get
      // neither minor nor orientation, so this is all we can do.
      events_[current_slot_].radius_x = input.value / 2.0f;

      // The MT protocol cannot communicate cancelled touches, so some kernel
      // drivers will identify palms by setting touch major to max.
      if (major_max_ > 0 && input.value == major_max_)
        events_[current_slot_].cancelled = true;
      break;
    case ABS_MT_TOUCH_MINOR:
      events_[current_slot_].radius_y = input.value / 2.0f;
      break;
    case ABS_MT_POSITION_X:
      events_[current_slot_].x = input.value;
      break;
    case ABS_MT_POSITION_Y:
      events_[current_slot_].y = input.value;
      break;
    case ABS_MT_TRACKING_ID:
      UpdateTrackingId(current_slot_, input.value);
      break;
    case ABS_MT_PRESSURE:
      events_[current_slot_].pressure = ScalePressure(input.value);
      break;
    case ABS_MT_SLOT:
      if (input.value >= 0 &&
          static_cast<size_t>(input.value) < events_.size()) {
        current_slot_ = input.value;
      } else {
        LOG(ERROR) << "invalid touch event index: " << input.value;
        return;
      }
      break;
    default:
      DVLOG(5) << "unhandled code for EV_ABS: " << input.code;
      return;
  }
  events_[current_slot_].altered = true;
}

void TouchEventConverterEvdev::ProcessSyn(const input_event& input) {
  switch (input.code) {
    case SYN_REPORT:
      ReportEvents(EventConverterEvdev::TimeTicksFromInputEvent(input));
      break;
    case SYN_DROPPED:
      // Some buffer has overrun. We ignore all events up to and
      // including the next SYN_REPORT.
      dropped_events_ = true;
      break;
    default:
      NOTIMPLEMENTED() << "invalid code for EV_SYN: " << input.code;
  }
}

EventType TouchEventConverterEvdev::GetEventTypeForTouch(
    const InProgressTouchEvdev& touch) {
  if (touch.was_cancelled)
    return ET_UNKNOWN;

  if (touch.cancelled)
    return touch.was_touching ? ET_TOUCH_CANCELLED : ET_UNKNOWN;

  if (touch.touching)
    return touch.was_touching ? ET_TOUCH_MOVED : ET_TOUCH_PRESSED;
  return touch.was_touching ? ET_TOUCH_RELEASED : ET_UNKNOWN;
}

void TouchEventConverterEvdev::ReportTouchEvent(
    const InProgressTouchEvdev& event,
    EventType event_type,
    base::TimeTicks timestamp) {
  dispatcher_->DispatchTouchEvent(TouchEventParams(
      input_device_.id, event.slot, event_type, gfx::PointF(event.x, event.y),
      GetEventPointerDetails(event), timestamp));
}

void TouchEventConverterEvdev::ReportStylusEvent(
    const InProgressTouchEvdev& event,
    base::TimeTicks timestamp) {
  if (event.btn_left.changed)
    ReportButton(BTN_LEFT, event.btn_left.down, event, timestamp);
  if (event.btn_right.changed)
    ReportButton(BTN_RIGHT, event.btn_right.down, event, timestamp);
  if (event.btn_middle.changed)
    ReportButton(BTN_MIDDLE, event.btn_middle.down, event, timestamp);

  dispatcher_->DispatchMouseMoveEvent(MouseMoveEventParams(
      input_device_.id, EF_DIRECT_INPUT, gfx::PointF(event.x, event.y),
      GetEventPointerDetails(event), timestamp));
}

void TouchEventConverterEvdev::ReportButton(unsigned int button,
                                            bool down,
                                            const InProgressTouchEvdev& event,
                                            base::TimeTicks timestamp) {
  dispatcher_->DispatchMouseButtonEvent(MouseButtonEventParams(
      input_device_.id, EF_DIRECT_INPUT, gfx::PointF(event.x, event.y), button,
      down, false /* allow_remap */, GetEventPointerDetails(event), timestamp));
}

void TouchEventConverterEvdev::ReportEvents(base::TimeTicks timestamp) {
  if (dropped_events_) {
    Reinitialize();
    dropped_events_ = false;
  }

  if (touch_noise_finder_)
    touch_noise_finder_->HandleTouches(events_, timestamp);

  for (size_t i = 0; i < events_.size(); i++) {
    InProgressTouchEvdev* event = &events_[i];
    if (!event->altered)
      continue;

    if (enable_palm_suppression_callback_)
      enable_palm_suppression_callback_.Run(event->tool_code > 0);

    if (touch_noise_finder_ && touch_noise_finder_->SlotHasNoise(event->slot))
      event->cancelled = true;

    if (event->tool_code > 0) {
      ReportStylusEvent(*event, timestamp);
    } else {
      EventType event_type = GetEventTypeForTouch(*event);
      if (event_type != ET_UNKNOWN)
        ReportTouchEvent(*event, event_type, timestamp);
    }

    event->was_cancelled = event->cancelled;
    event->was_touching = event->touching;
    event->altered = false;
    event->btn_left.changed = false;
    event->btn_right.changed = false;
    event->btn_middle.changed = false;
  }
}

void TouchEventConverterEvdev::UpdateTrackingId(int slot, int tracking_id) {
  InProgressTouchEvdev* event = &events_[slot];

  if (event->tracking_id == tracking_id)
    return;

  event->tracking_id = tracking_id;
  event->touching = (tracking_id >= 0);
  event->altered = true;

  if (tracking_id >= 0) {
    event->was_cancelled = false;
    event->cancelled = !enabled_;
  }
}

void TouchEventConverterEvdev::ReleaseTouches() {
  for (size_t slot = 0; slot < events_.size(); slot++) {
    events_[slot].cancelled = true;
    events_[slot].altered = true;
  }

  ReportEvents(EventTimeForNow());
}

void TouchEventConverterEvdev::ReleaseButtons() {
  for (size_t slot = 0; slot < events_.size(); slot++) {
    InProgressTouchEvdev* event = &events_[slot];

    if (event->btn_left.down) {
      event->btn_left.down = false;
      event->btn_left.changed = true;
    }
    if (event->btn_right.down) {
      event->btn_right.down = false;
      event->btn_right.changed = true;
    }
    if (event->btn_middle.down) {
      event->btn_middle.down = false;
      event->btn_middle.changed = true;
    }
  }

  ReportEvents(EventTimeForNow());
}

float TouchEventConverterEvdev::ScalePressure(int32_t value) {
  float pressure = value - pressure_min_;
  if (pressure_max_ - pressure_min_)
    pressure /= pressure_max_ - pressure_min_;
  return pressure;
}

int TouchEventConverterEvdev::NextTrackingId() {
  return next_tracking_id_++ & kMaxTrackingId;
}

}  // namespace ui


text:
/**
 *      @file InterClustersEventHandler.h
 *
 *      @brief A class to handle inter-cluster events.
 */

/**
 **
 ** @class InterClustersEventHandler InterClustersEventHandler.h "InterClustersEventHandler.h"
 **
 ** \latexonly  \subsubsection*{Implementation} \endlatexonly
 ** \htmlonly
Implementation
 \endhtmlonly
 **
 ** The InterClustersEventHandler class handles inter-clusters events of EventQueue.
 ** When EventQueue::addAnEvent() is called and cluserID is different from the caller's
 ** cluser, the function calls InterClustersEventHandler::addAnEvent() and the event will be added to
 ** the event queue of clusterID specified by the parameter.
 **
 ** \latexonly  \subsubsection*{Credits} \endlatexonly
 ** \htmlonly
Credits
 \endhtmlonly
 **
 ** Some models in this simulator is a rewrite of CSIM (2006) and other
 ** work (Stiber and Kawasaki (2007?))
 **
 **
 **     @author Fumitaka Kawasaki
 **/

#pragma once

#include "Global.h"
#include <vector>

class EventQueue;

class InterClustersEventHandler
{
    public:
        //! The constructor for InterClustersEventHandler.
        InterClustersEventHandler();

        //! The destructor for InterClustersEventHandler.
        virtual ~InterClustersEventHandler();

        /**
         * Initializes the event handler.
         *
         * @param size  Size of the EventQueue vector.
         */
        void initEventHandler(const int size);

        /**
         * Register the eventQueue of the cluster specified by clusterID.
         *
         * @param clusterID   Cluster ID of the EventQueue.
         * @param eventQueue  Pointer to the EventQueue.
         */
        void addEventQueue(CLUSTER_INDEX_TYPE clusterID, EventQueue* eventQueue);

        /**
         * Add an eventin the queue of specified cluster.
         *
         * @param idx        The queue index of the collection.
         * @param clusterID  The cluster ID where the event to be added.
         * @param iStepOffset  offset from the current simulation step.
         */
        void addAnEvent(const BGSIZE idx, const CLUSTER_INDEX_TYPE clusterID, int iStepOffset);

    private:
        //! Vector to store pointers to each cluster's EventQueue.
        std::vector<EventQueue *> *m_vtEventQueue;
};


text: Login in with VK


text:
yii2-ckeditor widget
===========================

## Установка

```
php composer.phar require --prefer-dist mranger/yii2-ckeditor "*"
```

или

```json
"mranger/yii2-ckeditor": "*"
```

Так как у меня не получилось нормально реализовать зависимость от пакета CKEditor, бог его знает почему. Вам придется самим добавить зависимость от данного пакета в вашем composer.json
 Я обычно прописываю зависимость от полного пакета последней версии.

 ```
 "ckeditor/ckeditor": "dev-full/4.7.x",
 ```

 Более подробно можно прочитать по ссылке: [http://docs.ckeditor.com/#!/guide/dev_package_managers](http://docs.ckeditor.com/#!/guide/dev_package_managers).

## Использование

```php
use mranger\ckeditor\CKEditor;

echo $form->field($model, 'content')->widget(CKEditor::className());
```

Можно создавать свои пресеты, которые будут хранить настройки вашего редактора, для этого нужно будет сначала определить папку где будут лежать файлы с пресетами (стандартный путь "@app/ckeditor-presets").

Пример кода пресета и вызова виджета:

пресет: default.php
```php
return [
    'height' => '300px',
    'toolbarGroups'        => [
        ['name' => 'basicstyles', 'groups' => ['basicstyles', 'colors', 'cleanup']],
    	['name' => 'styles'],
    	['name' => 'blocks'],
    	['name' => 'colors'],
    	['name' => 'document', 'groups' => ['mode', 'document', 'doctools']],
    	['name' => 'tools'],
        ['name' => 'others'],
    	'/',
    	['name' => 'paragraph', 'groups' => ['list', 'indent', 'blocks', 'align', 'bidi']],
    	['name' => 'links'],
    	['name' => 'insert'],
    	['name' => 'clipboard', 'groups' => ['clipboard', 'undo']],
    	['name' => 'editing', 'groups' => ['find', 'selection', 'spellchecker']],
    ],
    'filebrowserUploadUrl' => Url::to(['wysiwyg/image-upload'], true),
];
```

Вызов виджета:
```php
echo $form->field($model, 'content')->widget(CKEditor::className(), [
    'preset' => 'default',
    'presetDirPath' => '@app/presets', //стандартный путь "@app/ckeditor-presets" можно не указывать
]);
```

Что бы дать возможность загрузки файлов через редактор, необходимо сначала подключить необходимый экшен для загрузки файлов. Контролер может быть абсолютно любой.
```php
public function actions() {
		return [
			'ckeditor-file-upload' => [
				'class' => 'mranger\ckeditor\actions\FileUploadAction',
			],
		];
	}
```
После этого в настройках(пресете) указать url по которому должны производиться запросы для загрузки файлов.
```php
[
 'filebrowserUploadUrl' => Url::to(['your-controller/ckeditor-file-upload'], true),
]
```

По умолчанию разрешена загрузка только файлов с расширениями: "png, jpg, jpeg, bmp, gif, ico, swf", файлы загружаются по пути: '@webroot/upload'.
Если же необходимо изменить данные параметры, то в массиве params приложения можно определить свои параметры, а именно:
```php
[
 'CKEditorFileUploadAllowedExtensions' => 'gif, png, jpg', // разрешенные расширения файлов
 'CKEditorFileUploadPath' => '@webroot/ckeditor',          // путь для сохранения файлов
 'CKEditorFileUploadedUrl' => 'http://mysite.ru/ckeditor', // ссылка, по которой будут доступны сохраненые файлы
]
```

В настройках виджета можно подключить сторонние плагины для CKEditor, для этого необходимо в пресете добавить массив 'externalPlugins' c содержимым следующего формата:
```php
return [
    'externalPlugins'        => [
        [
            'name' => '', // название плагина
            'url' => '',  // url до папки плагином
            'fileName' => '' , // файл плагина
        ],
    ],
];
```


text:
<?php
/**
 * Navigate to Last Edit Location.
 *
 * Navigate back to where code was last edited.
 *
 * Ctrl+Shift+Backspace (Windows/Linux)
 * Shift+Command+Delete (Mac OS X)
 */

namespace Navigation3\JetBrains;

class NavigateRecent {
    public function startingPoint() {
        // 1. Navigate to step1().
        $this->step1();
    }

    public function step1() {
        // 2. Uncomment the following line.
        // echo 'In step 1.';

        // 3. Navigate to step2().
        $this->step2();
    }

    public function step2() {
        // 4. Navigate back to where we last edited using the keyboard shortcut.
    }
}


text:
package org.smoothbuild.compile.lang.define;

import org.smoothbuild.compile.lang.base.Loc;
import org.smoothbuild.compile.lang.base.Tapanal;
import org.smoothbuild.compile.lang.type.TypeS;

/**
 * Type definition.
 */
public class TDefS extends Tapanal {
  public TDefS(TypeS type, ModPath modPath, String name, Loc loc) {
    super(type, modPath, name, loc);
  }
}


text:
.class public Landroid/support/v4/media/session/MediaSessionCompatApi18;
.super Ljava/lang/Object;
.source "MediaSessionCompatApi18.java"

# annotations
.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Landroid/support/v4/media/session/MediaSessionCompatApi18$OnPlaybackPositionUpdateListener;
    }
.end annotation

# static fields
.field private static final ACTION_SEEK_TO:J = 0x100L

# direct methods
.method public constructor <init>()V
    .locals 0

    .prologue
    .line 24
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 80
    return-void
.end method

.method public static createPlaybackPositionUpdateListener(Landroid/support/v4/media/session/MediaSessionCompatApi14$Callback;)Ljava/lang/Object;
    .locals 1
    .param p0, "callback"    # Landroid/support/v4/media/session/MediaSessionCompatApi14$Callback;

    .prologue
    .line 30
    new-instance v0, Landroid/support/v4/media/session/MediaSessionCompatApi18$OnPlaybackPositionUpdateListener;

    invoke-direct {v0, p0}, Landroid/support/v4/media/session/MediaSessionCompatApi18$OnPlaybackPositionUpdateListener;-><init>(Landroid/support/v4/media/session/MediaSessionCompatApi14$Callback;)V

    return-object v0
.end method

.method static getRccTransportControlFlagsFromActions(J)I
    .locals 6
    .param p0, "actions"    # J

    .prologue
    .line 72
    invoke-static {p0, p1}, Landroid/support/v4/media/session/MediaSessionCompatApi14;->getRccTransportControlFlagsFromActions(J)I

    move-result v0

    .line 74
    .local v0, "transportControlFlags":I
    const-wide/16 v2, 0x100

    and-long/2addr v2, p0

    const-wide/16 v4, 0x0

    cmp-long v1, v2, v4

    if-eqz v1, :cond_0

    .line 75
    or-int/lit16 v0, v0, 0x100

    .line 77
    :cond_0
    return v0
.end method

.method public static registerMediaButtonEventReceiver(Landroid/content/Context;Landroid/app/PendingIntent;)V
    .locals 2
    .param p0, "context"    # Landroid/content/Context;
    .param p1, "pi"    # Landroid/app/PendingIntent;

    .prologue
    .line 34
    const-string v1, "audio"

    invoke-virtual {p0, v1}, Landroid/content/Context;->getSystemService(Ljava/lang/String;)Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Landroid/media/AudioManager;

    .line 35
    .local v0, "am":Landroid/media/AudioManager;
    invoke-virtual {v0, p1}, Landroid/media/AudioManager;->registerMediaButtonEventReceiver(Landroid/app/PendingIntent;)V

    .line 36
    return-void
.end method

.method public static setOnPlaybackPositionUpdateListener(Ljava/lang/Object;Ljava/lang/Object;)V
    .locals 0
    .param p0, "rccObj"    # Ljava/lang/Object;
    .param p1, "onPositionUpdateObj"    # Ljava/lang/Object;

    .prologue
    .line 67
    check-cast p0, Landroid/media/RemoteControlClient;

    .end local p0    # "rccObj":Ljava/lang/Object;
    check-cast p1, Landroid/media/RemoteControlClient$OnPlaybackPositionUpdateListener;

    .end local p1    # "onPositionUpdateObj":Ljava/lang/Object;
    invoke-virtual {p0, p1}, Landroid/media/RemoteControlClient;->setPlaybackPositionUpdateListener(Landroid/media/RemoteControlClient$OnPlaybackPositionUpdateListener;)V

    .line 69
    return-void
.end method

.method public static setState(Ljava/lang/Object;IJFJ)V
    .locals 8
    .param p0, "rccObj"    # Ljava/lang/Object;
    .param p1, "state"    # I
    .param p2, "position"    # J
    .param p4, "speed"    # F
    .param p5, "updateTime"    # J

    .prologue
    const-wide/16 v6, 0x0

    .line 45
    invoke-static {}, Landroid/os/SystemClock;->elapsedRealtime()J

    move-result-wide v0

    .line 46
    .local v0, "currTime":J
    const/4 v4, 0x3

    if-ne p1, v4, :cond_1

    cmp-long v4, p2, v6

    if-lez v4, :cond_1

    .line 47
    const-wide/16 v2, 0x0

    .line 48
    .local v2, "diff":J
    cmp-long v4, p5, v6

    if-lez v4, :cond_0

    .line 49
    sub-long v2, v0, p5

    .line 50
    const/4 v4, 0x0

    cmpl-float v4, p4, v4

    if-lez v4, :cond_0

    const/high16 v4, 0x3f800000    # 1.0f

    cmpl-float v4, p4, v4

    if-eqz v4, :cond_0

    .line 51
    long-to-float v4, v2

    mul-float/2addr v4, p4

    float-to-long v2, v4

    .line 54
    :cond_0
    add-long/2addr p2, v2

    .line 56
    .end local v2    # "diff":J
    :cond_1
    invoke-static {p1}, Landroid/support/v4/media/session/MediaSessionCompatApi14;->getRccStateFromState(I)I

    move-result p1

    .line 57
    check-cast p0, Landroid/media/RemoteControlClient;

    .end local p0    # "rccObj":Ljava/lang/Object;
    invoke-virtual {p0, p1, p2, p3, p4}, Landroid/media/RemoteControlClient;->setPlaybackState(IJF)V

    .line 58
    return-void
.end method

.method public static setTransportControlFlags(Ljava/lang/Object;J)V
    .locals 1
    .param p0, "rccObj"    # Ljava/lang/Object;
    .param p1, "actions"    # J

    .prologue
    .line 61
    check-cast p0, Landroid/media/RemoteControlClient;

    .end local p0    # "rccObj":Ljava/lang/Object;
    invoke-static {p1, p2}, Landroid/support/v4/media/session/MediaSessionCompatApi18;->getRccTransportControlFlagsFromActions(J)I

    move-result v0

    invoke-virtual {p0, v0}, Landroid/media/RemoteControlClient;->setTransportControlFlags(I)V

    .line 63
    return-void
.end method

.method public static unregisterMediaButtonEventReceiver(Landroid/content/Context;Landroid/app/PendingIntent;)V
    .locals 2
    .param p0, "context"    # Landroid/content/Context;
    .param p1, "pi"    # Landroid/app/PendingIntent;

    .prologue
    .line 39
    const-string v1, "audio"

    invoke-virtual {p0, v1}, Landroid/content/Context;->getSystemService(Ljava/lang/String;)Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Landroid/media/AudioManager;

    .line 40
    .local v0, "am":Landroid/media/AudioManager;
    invoke-virtual {v0, p1}, Landroid/media/AudioManager;->unregisterMediaButtonEventReceiver(Landroid/app/PendingIntent;)V

    .line 41
    return-void
.end method


text:
using System;
using System.IO;
using System.Linq;
using OpenCvSharp.Dnn;
using Xunit;
using Xunit.Abstractions;

namespace OpenCvSharp.Tests.Dnn;

[Collection(nameof(YoloTest))]
public class YoloTest : TestBase
{
    private readonly ITestOutputHelper testOutputHelper;

    public YoloTest(ITestOutputHelper testOutputHelper)
    {
        this.testOutputHelper = testOutputHelper;
    }

    // https://github.com/opencv/opencv/blob/24bed38c2b2c71d35f2e92aa66648f8485a70892/samples/dnn/yolo_object_detection.cpp
    [ExplicitFact]
    public void LoadYoloV2Model()
    {
        RunGC();

        const string cfgFile = @"_data/model/yolov2.cfg";
        const string cfgFileUrl = "https://raw.githubusercontent.com/pjreddie/darknet/master/cfg/yolov2.cfg";
        const string darknetModel = "_data/model/yolov2.weights";
        const string darknetModelUrl = "https://pjreddie.com/media/files/yolov2.weights";

        testOutputHelper.WriteLine("Downloading YoloV2 Model...");
        PrepareFile(new Uri(cfgFileUrl), cfgFile);
        PrepareFile(new Uri(darknetModelUrl), darknetModel);
        testOutputHelper.WriteLine("Done");

        RunGC();

        using var net = CvDnn.ReadNetFromDarknet(cfgFile, darknetModel);
        Assert.NotNull(net);
        Assert.False(net!.Empty());

        // Convert Mat to batch of images
        using var img = Image(@"space_shuttle.jpg");
        using var inputBlob = CvDnn.BlobFromImage(img, 1, new Size(224, 224), new Scalar(104, 117, 123));
        // Set input blob
        net.SetInput(inputBlob, "data");

        // Make forward pass
        using var detectionMat = net.Forward("detection_out");
        // TODO
        GC.KeepAlive(detectionMat);
    }

    // https://github.com/opencv/opencv/blob/24bed38c2b2c71d35f2e92aa66648f8485a70892/samples/dnn/yolo_object_detection.cpp
    [ExplicitFact]
    public void LoadYoloV3Model()
    {
        RunGC();

        const string cfgFile = @"_data/model/yolov3.cfg";
        const string cfgFileUrl = "https://raw.githubusercontent.com/pjreddie/darknet/master/cfg/yolov3.cfg";
        const string darknetModel = "_data/model/yolov3.weights";
        const string darknetModelUrl = "https://pjreddie.com/media/files/yolov3.weights";

        testOutputHelper.WriteLine("Downloading YoloV3 Model...");
        PrepareFile(new Uri(cfgFileUrl), cfgFile);
        PrepareFile(new Uri(darknetModelUrl), darknetModel);
        testOutputHelper.WriteLine("Done");

        RunGC();

        using (var net = CvDnn.ReadNetFromDarknet(cfgFile, darknetModel))
        using (var img = Image(@"space_shuttle.jpg"))
        {
            Assert.NotNull(net);
            Assert.False(net!.Empty());

            var outNames = net.GetUnconnectedOutLayersNames();
            Assert.NotEmpty(outNames);
            Assert.DoesNotContain(outNames, elem => elem == null);
            testOutputHelper.WriteLine("UnconnectedOutLayersNames: {0}", string.Join(",", outNames));

            // Convert Mat to batch of images
            using (var inputBlob = CvDnn.BlobFromImage(img, 1, new Size(224, 224), new Scalar(104, 117, 123)))
            {
                // Set input blob
                net.SetInput(inputBlob, "data");

                // Make forward pass
                using (var detection82 = net.Forward("yolo_82"))
                using (var detection94 = net.Forward("yolo_94"))
                using (var detection106 = net.Forward("yolo_106"))
                {
                    // TODO
                    Assert.False(detection82.Empty());
                    Assert.False(detection94.Empty());
                    Assert.False(detection106.Empty());
                }

                Mat[] outs = outNames.Select(_ => new Mat()).ToArray();
                net.Forward(outs, outNames!);

                foreach (var m in outs)
                {
                    Assert.False(m.Empty());
                    m.Dispose();
                }
            }
        }
    }

    private void PrepareFile(Uri uri, string fileName)
    {
        lock (lockObj)
        {
            if (File.Exists(fileName))
                return;

            var contents = FileDownloader.DownloadData(uri);
            File.WriteAllBytes(fileName, contents);
        }
    }
    private readonly object lockObj = new object();

    private static void RunGC()
    {
        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.Collect();
    }
}


text:
<bill session="110" type="hj" number="94" updated="2009-01-08T16:39:35-05:00">
	<status><introduced date="1214193600" datetime="2008-06-23"/></status>

	<introduced date="1214193600" datetime="2008-06-23"/>
	<titles>
		<title type="official" as="introduced">Whereas there is no greater expression of freedom and liberty than the defense of the God-given right of an individual to hold, possess, and use private property.</title>
	</titles>
	<sponsor id="412252"/>
	<cosponsors>
		<cosponsor id="412201" joined="2008-07-16"/>
	</cosponsors>
	<actions>
		<action date="1214193600" datetime="2008-06-23"><text>Sponsor introductory remarks on measure. (CR H5862)</text></action>
		<action date="1214193600" datetime="2008-06-23"><text>Referred to the House Committee on the Judiciary.</text></action>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>

	6/23/2008--Introduced.
Declares that all U.S. citizens should remain secure in the possession of private property and no court, legislature, or executive shall, by predatory law or tyrannical force, obtain the property of any U.S. citizen for the benefit of another private citizen or corporation.

</bill>


text:
using Abp.Runtime.Validation;

namespace AbpSwagger.Application.Students.Dto
{
    public class GetStudentInput : PagedAndSortedInputDto, IShouldNormalize
    {
        public void Normalize()
        {
            if (string.IsNullOrEmpty(Sorting))
            {
                Sorting = "FirstName";
            }
        }
    }
}


text:
define([
	'jquery',
	'data/episodes'
], function($, EpisodesFactory) {
	return {
		fetch: function(data) {
			var collection = EpisodesFactory(data.id);

			if (collection.length) {
				return $.Deferred().resolve();
			}
			return collection.fetch();
		}
	};
});


text:
<?php

namespace Http\Client;

/**
 * Every HTTP Client related Exception must implement this interface.
 *
 * @author Márk Sági-Kazár <mark.sagikazar@gmail.com>
 */
interface Exception
{
}


text:
/* Sasikanth Avancha, Dhiraj Kalamkar (Intel Corp.)
******************************************************************************/

#pragma once
#include <string>
#include <assert.h>
#include "Shape.h"
#include "proto/gxm.pb.h"

using namespace std;
using namespace gxm;

class MLParams
{
  protected:

  public:

    MLParams(void) {}

    virtual ~MLParams(void) {}
};


text:
from .json_import import simplejson
from six.moves.urllib.parse import urlencode
from httplib2 import Http
from hashlib import sha256
import mimetypes
import six
import hmac

class OAuth2AuthExchangeError(Exception):
    def __init__(self, description):
        self.description = description

    def __str__(self):
        return self.description

class OAuth2API(object):
    host = None
    base_path = None
    authorize_url = None
    access_token_url = None
    redirect_uri = None
    # some providers use "oauth_token"
    access_token_field = "access_token"
    protocol = "https"
    # override with 'Instagram', etc
    api_name = "Generic API"

    def __init__(self, client_id=None, client_secret=None, client_ips=None, access_token=None, redirect_uri=None):
        self.client_id = client_id
        self.client_secret = client_secret
        self.client_ips = client_ips
        self.access_token = access_token
        self.redirect_uri = redirect_uri

    def get_authorize_url(self, scope=None):
        req = OAuth2AuthExchangeRequest(self)
        return req.get_authorize_url(scope=scope)

    def get_authorize_login_url(self, scope=None):
        """ scope should be a tuple or list of requested scope access levels """
        req = OAuth2AuthExchangeRequest(self)
        return req.get_authorize_login_url(scope=scope)

    def exchange_code_for_access_token(self, code):
        req = OAuth2AuthExchangeRequest(self)
        return req.exchange_for_access_token(code=code)

    def exchange_user_id_for_access_token(self, user_id):
        req = OAuth2AuthExchangeRequest(self)
        return req.exchange_for_access_token(user_id=user_id)

    def exchange_xauth_login_for_access_token(self, username, password, scope=None):
        """ scope should be a tuple or list of requested scope access levels """
        req = OAuth2AuthExchangeRequest(self)
        return req.exchange_for_access_token(username=username, password=password,
                                             scope=scope)

class OAuth2AuthExchangeRequest(object):
    def __init__(self, api):
        self.api = api

    def _url_for_authorize(self, scope=None):
        client_params = {
            "client_id": self.api.client_id,
            "response_type": "code",
            "redirect_uri": self.api.redirect_uri
        }
        if scope:
            client_params.update(scope=' '.join(scope))
        url_params = urlencode(client_params)
        return "%s?%s" % (self.api.authorize_url, url_params)

    def _data_for_exchange(self, code=None, username=None, password=None, scope=None, user_id=None):
        client_params = {
            "client_id": self.api.client_id,
            "client_secret": self.api.client_secret,
            "redirect_uri": self.api.redirect_uri,
            "grant_type": "authorization_code"
        }
        if code:
            client_params.update(code=code)
        elif username and password:
            client_params.update(username=username,
                                 password=password,
                                 grant_type="password")
            if scope:
                client_params.update(scope=' '.join(scope))
        elif user_id:
            client_params.update(user_id=user_id)
        return urlencode(client_params)

    def get_authorize_url(self, scope=None):
        return self._url_for_authorize(scope=scope)

    def get_authorize_login_url(self, scope=None):
        http_object = Http(disable_ssl_certificate_validation=True)

        url = self._url_for_authorize(scope=scope)
        response, content = http_object.request(url)
        if response['status'] != '200':
            raise OAuth2AuthExchangeError("The server returned a non-200 response for URL %s" % url)
        redirected_to = response['content-location']
        return redirected_to

    def exchange_for_access_token(self, code=None, username=None, password=None, scope=None, user_id=None):
        data = self._data_for_exchange(code, username, password, scope=scope, user_id=user_id)
        http_object = Http(disable_ssl_certificate_validation=True)
        url = self.api.access_token_url
        response, content = http_object.request(url, method="POST", body=data)
        parsed_content = simplejson.loads(content.decode())
        if int(response['status']) != 200:
            raise OAuth2AuthExchangeError(parsed_content.get("error_message", ""))
        return parsed_content['access_token'], parsed_content['user']

class OAuth2Request(object):
    def __init__(self, api):
        self.api = api

    def _generate_sig(self, endpoint, params, secret):
        sig = endpoint
        for key in sorted(params.keys()):
            sig += '|%s=%s' % (key, params[key])
        return  hmac.new(secret, sig, sha256).hexdigest()

    def url_for_get(self, path, parameters):
        return self._full_url_with_params(path, parameters)

    def get_request(self, path, **kwargs):
        return self.make_request(self.prepare_request("GET", path, kwargs))

    def post_request(self, path, **kwargs):
        return self.make_request(self.prepare_request("POST", path, kwargs))

    def _full_url(self, path, include_secret=False, include_signed_request=True):
        return "%s://%s%s%s%s%s" % (self.api.protocol,
                                  self.api.host,
                                  self.api.base_path,
                                  path,
                                  self._auth_query(include_secret),
                                  self._signed_request(path, {}, include_signed_request, include_secret))

    def _full_url_with_params(self, path, params, include_secret=False, include_signed_request=True):
        return (self._full_url(path, include_secret, include_signed_request=False) +
                self._full_query_with_params(params) +
                self._signed_request(path, params, include_signed_request, include_secret))

    def _full_query_with_params(self, params):
        params = ("&" + urlencode(params)) if params else ""
        return params

    def _auth_query(self, include_secret=False):
        if self.api.access_token:
            return ("?%s=%s" % (self.api.access_token_field, self.api.access_token))
        elif self.api.client_id:
            base = ("?client_id=%s" % (self.api.client_id))
            if include_secret:
                base += "&client_secret=%s" % (self.api.client_secret)
            return base

    def _signed_request(self, path, params, include_signed_request, include_secret):
        if include_signed_request:
            if self.api.access_token:
                params['access_token'] = self.api.access_token
            elif self.api.client_id:
                params['client_id'] = self.api.client_id
            if include_secret and self.api.client_secret:
                params['client_secret'] = self.api.client_secret
            return "&sig=%s" % self._generate_sig(path, params, self.api.client_secret)
        else:
            return ''

    def _post_body(self, params):
        return urlencode(params)

    def _encode_multipart(params, files):
        boundary = "MuL7Ip4rt80uND4rYF0o"

        def get_content_type(file_name):
            return mimetypes.guess_type(file_name)[0] or "application/octet-stream"

        def encode_field(field_name):
            return ("--" + boundary,
                    'Content-Disposition: form-data; name="%s"' % (field_name),
                    "", str(params[field_name]))

        def encode_file(field_name):
            file_name, file_handle = files[field_name]
            return ("--" + boundary,
                    'Content-Disposition: form-data; name="%s"; filename="%s"' % (field_name, file_name),
                    "Content-Type: " + get_content_type(file_name),
                    "", file_handle.read())

        lines = []
        for field in params:
            lines.extend(encode_field(field))
        for field in files:
            lines.extend(encode_file(field))
        lines.extend(("--%s--" % (boundary), ""))
        body = "\r\n".join(lines)

        headers = {"Content-Type": "multipart/form-data; boundary=" + boundary,
                   "Content-Length": str(len(body))}

        return body, headers

    def prepare_and_make_request(self, method, path, params, include_secret=False):
        url, method, body, headers = self.prepare_request(method, path, params, include_secret)
        return self.make_request(url, method, body, headers)

    def prepare_request(self, method, path, params, include_secret=False):
        url = body = None
        headers = {}

        if not params.get('files'):
            if method == "POST":
                body = self._post_body(params)
                headers = {'Content-type': 'application/x-www-form-urlencoded'}
                url = self._full_url(path, include_secret)
            else:
                url = self._full_url_with_params(path, params, include_secret)
        else:
            body, headers = self._encode_multipart(params, params['files'])
            url = self._full_url(path)

        return url, method, body, headers

    def make_request(self, url, method="GET", body=None, headers=None):
        headers = headers or {}
        if not 'User-Agent' in headers:
            headers.update({"User-Agent": "%s Python Client" % self.api.api_name})
        # https://github.com/jcgregorio/httplib2/issues/173
        # bug in httplib2 w/ Python 3 and disable_ssl_certificate_validation=True
        http_obj = Http() if six.PY3 else Http(disable_ssl_certificate_validation=True)
        return http_obj.request(url, method, body=body, headers=headers)


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:hudson="http://schemas.android.com/apk/res-auto"
              android:id="@+id/ll_hot_item_root"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:background="@drawable/selector_hot_item_bg"
              android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/tv_title"
            android:text="最新热门"
            style="@style/item_iv_title_style"/>

        <TextView
            android:id="@+id/tv_more"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:text="更多"
            android:drawableRight="@drawable/arrow_right"
            android:textColor="@color/halfTransparent"
            android:textSize="13sp"/>
    </RelativeLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <RelativeLayout
            android:id="@+id/rl_song1"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="3dp"
            android:layout_height="wrap_content">

            <com.hudson.donglingmusic.ui.view.RatioImageView
                android:id="@+id/iv_music_bg"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                hudson:src="@drawable/icon_player"/>
            <TextView
                android:id="@+id/tv_singer"
                android:layout_alignLeft="@id/iv_music_bg"
                android:layout_alignBottom="@id/iv_music_bg"
                android:text="许巍"
                android:background="@drawable/gedan_title_bg"
                style="@style/item_iv_singer_name"/>

            <TextView
                android:id="@+id/tv_song_title"
                android:layout_alignLeft="@id/iv_music_bg"
                android:text="曾经的你"
                android:layout_below="@id/iv_music_bg"
                style="@style/item_tv_song_title"/>
        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/rl_song2"
            android:layout_weight="1"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="3dp"
            android:layout_width="0dp"
            android:layout_height="wrap_content">

            <com.hudson.donglingmusic.ui.view.RatioImageView
                android:id="@+id/iv_music_bg2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                hudson:src="@drawable/icon_player"/>
            <TextView
                android:id="@+id/tv_singer2"
                android:layout_alignLeft="@id/iv_music_bg2"
                android:layout_alignBottom="@id/iv_music_bg2"
                android:background="@drawable/gedan_title_bg"
                android:text="许巍"
                style="@style/item_iv_singer_name"/>

            <TextView
                android:id="@+id/tv_song_title2"
                android:layout_alignLeft="@id/iv_music_bg2"
                style="@style/item_tv_song_title"
                android:text="曾经的你"
                android:layout_below="@id/iv_music_bg2"/>
        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/rl_song3"
            android:layout_weight="1"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="3dp"
            android:layout_width="0dp"
            android:layout_height="wrap_content">

            <com.hudson.donglingmusic.ui.view.RatioImageView
                android:id="@+id/iv_music_bg3"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                hudson:src="@drawable/icon_player"/>
            <TextView
                android:id="@+id/tv_singer3"
                android:layout_alignLeft="@id/iv_music_bg3"
                android:layout_alignBottom="@id/iv_music_bg3"
                android:text="许巍"
                android:background="@drawable/gedan_title_bg"
                style="@style/item_iv_singer_name"/>

            <TextView
                android:id="@+id/tv_song_title3"
                android:layout_alignLeft="@id/iv_music_bg3"
                style="@style/item_tv_song_title"
                android:text="曾经的你"
                android:layout_below="@id/iv_music_bg3"/>
        </RelativeLayout>

    </LinearLayout>

</LinearLayout>


text:
System.register(["tslib", "../aurelia"], function (exports_1, context_1) {
    "use strict";
    var tslib_1, au, MdFooter;
    var __moduleName = context_1 && context_1.id;
    return {
        setters: [
            function (tslib_1_1) {
                tslib_1 = tslib_1_1;
            },
            function (au_1) {
                au = au_1;
            }
        ],
        execute: function () {
            MdFooter = /** @class */ (function () {
                function MdFooter(element) {
                    this.element = element;
                    this.attributeManager = new au.AttributeManager(this.element);
                }
                MdFooter.prototype.bind = function () {
                    this.attributeManager.addClasses("page-footer");
                };
                MdFooter.prototype.unbind = function () {
                    this.attributeManager.removeClasses("page-footer");
                };
                MdFooter = tslib_1.__decorate([
                    au.customAttribute("md-footer"),
                    au.autoinject,
                    tslib_1.__metadata("design:paramtypes", [Element])
                ], MdFooter);
                return MdFooter;
            }());
            exports_1("MdFooter", MdFooter);
        }
    };
});
//# sourceMappingURL=footer.js.map


text:
require 'spec_helper'
describe 'check_mk::agent::mrpe', :type => :define do
  let :title do
    'checkname'
  end
  context 'Unsupported OS' do
    context 'with mandatory command' do
      let :params do
        {:command => 'command'}
      end
      it 'should fail' do
        expect { catalogue }.to raise_error(Puppet::Error, /Creating mrpe.cfg is unsupported for operatingsystem/)
      end
    end
  end
  context 'RedHat Linux' do
    let :facts do
      {
          :operatingsystem => 'redhat',
      }
    end
    context 'with mandatory command' do
      let :params do
        {:command => 'command'}
      end
      it { should contain_check_mk__agent__mrpe('checkname') }
      it { should contain_concat('/etc/check-mk-agent/mrpe.cfg').with_ensure('present') }
      it { should contain_concat__fragment('checkname-mrpe-check').with({
            :target  => '/etc/check-mk-agent/mrpe.cfg',
            :content => /^checkname command\n$/,
        })
      }
    end
  end
end


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Discom. 155 (1888)

#### Original name
Naemacyclus alpinus Fuckel, 1875

### Remarks
null