text:
import sys
from unittest import TestCase
try:
    from queue import PriorityQueue
except ImportError:
    from Queue import PriorityQueue

from mock import Mock, patch, call

from .fixtures import MockClient
from kafka_rest.message import Message
from kafka_rest.events import FlushReason

class TestProducer(TestCase):
    def setUp(self):
        self.client = MockClient.with_basic_setup()
        self.producer = self.client.producer
        self.callback_mock = Mock(wraps=self.client.io_loop.add_callback)
        self.client.io_loop.add_callback = self.callback_mock

        self.io_loop_patch = patch('kafka_rest.producer.IOLoop.current')
        self.io_loop_mock = self.io_loop_patch.start()
        self.io_loop_mock.return_value = self.client.io_loop

        self.test_schema = {
            'type': 'record',
            'name': 'test_driver',
            'fields': [
                {'name': 'val', 'type': 'int'}
            ]
        }
        self.test_value = {'val': 1}

        self.client.schema_cache['test_driver']['value-id'] = 1
        self.client.schema_cache['test_driver']['key-id'] = 2

        self.producer.inflight_requests = {1: None}

    def tearDown(self):
        if not self.client.in_shutdown:
            self.client.shutdown(block=False)
        self.io_loop_patch.stop()

    def test_message_batches_from_queue_single_batch(self):
        m1 = Message('test_driver', {'val': 1}, None, None, 0, 1)
        m2 = Message('test_driver', {'val': 2}, None, None, 0, 1)
        queue = self.client.message_queues['test_driver']
        for m in [m1, m2]:
            queue.put(m)

        result = list(self.producer._message_batches_from_queue(queue))
        self.assertEqual(len(result), 1)
        self.assertEqual(result[0], [m1, m2])

    def test_message_batches_from_queue_multiple_batches(self):
        self.client.flush_max_batch_size = 1
        m1 = Message('test_driver', {'val': 1}, None, None, 0, 1)
        m2 = Message('test_driver', {'val': 2}, None, None, 0, 1)
        queue = self.client.message_queues['test_driver']
        for m in [m1, m2]:
            queue.put(m)

        result = list(self.producer._message_batches_from_queue(queue))
        self.assertEqual(len(result), 2)
        self.assertEqual(result[0], [m1])
        self.assertEqual(result[1], [m2])

    def test_message_batches_from_retry_queue(self):
        m1 = Message('test_driver', {'val': 1}, None, None, sys.maxsize, 1)
        m2 = Message('test_driver', {'val': 2}, None, None, 0, 1)
        queue = self.client.retry_queues['test_driver']
        for m in [m1, m2]:
            queue.put(m)

        result = list(self.producer._message_batches_from_queue(queue))
        self.assertEqual(len(result), 1)
        self.assertEqual(result[0], [m2])
        self.assertEqual(queue.qsize(), 1)

    @patch('kafka_rest.producer.request_for_batch')
    def test_send_batch_produce_request(self, fake_request):
        m1 = Message('test_driver', {'val': 1}, None, None, 0, 1)
        m2 = Message('test_driver', {'val': 2}, None, None, 0, 1)
        batch = [m1, m2]
        fake_request._id = 1

        self.producer._send_batch_produce_request('test_driver', batch)
        call_args = fake_request.mock_calls[0][1]

        self.assertEqual(call_args[2], 10)
        self.assertEqual(call_args[3], 60)
        self.assertEqual(call_args[5], 'test_driver')
        self.assertEqual(call_args[6], batch)

    @patch('kafka_rest.producer.request_for_batch')
    def test_send_batch_produce_request_in_shutdown(self, fake_request):
        m1 = Message('test_driver', {'val': 1}, None, None, 0, 1)
        m2 = Message('test_driver', {'val': 2}, None, None, 0, 1)
        batch = [m1, m2]
        fake_request._id = 1

        self.client.in_shutdown = True
        self.producer._send_batch_produce_request('test_driver', batch)
        call_args = fake_request.mock_calls[0][1]

        self.assertEqual(call_args[2], 0)
        self.assertEqual(call_args[3], 0)
        self.assertEqual(call_args[5], 'test_driver')
        for idx, m in enumerate(batch):
            self.assertTrue(m.true_equals(call_args[6][idx]))

    def test_queue_message_for_retry(self):
        m1 = Message('test_driver', {'val': 1}, None, None, 0, 1)
        self.producer._queue_message_for_retry('test_driver', m1)
        retry_message = self.client.retry_queues['test_driver'].get()

        self.assertEqual(retry_message.attempt_number,
                         m1.attempt_number + 1)
        self.assertNotEqual(retry_message.retry_after_time,
                            m1.retry_after_time)
        self.client.mock_for('retry_message').assert_called_once_with('test_driver',
                                                                      retry_message)

    def test_queue_message_for_retry_when_full(self):
        m1 = Message('test_driver', {'val': 1}, None, None, 0, 1)
        self.client.retry_queues['test_driver'] = PriorityQueue(maxsize=1)
        self.client.retry_queues['test_driver'].put('whatever')

        self.producer._queue_message_for_retry('test_driver', m1)
        self.client.mock_for('drop_message').assert_called_once_with('test_driver',
                                                                     m1,
                                                                     'retry_queue_full')

    def test_queue_message_for_retry_nonretriable(self):
        m1 = Message('test_driver', {'val': 1}, None, None, 0, 10)
        self.producer._queue_message_for_retry('test_driver', m1)
        self.client.mock_for('drop_message').assert_called_once_with('test_driver',
                                                                     m1,
                                                                     'max_retries_exceeded')

    def test_handle_produce_success_stores_value_schema_id(self):
        self.client.schema_cache['test_driver']['value-id'] = None
        body = {'offsets': [], 'value_schema_id': 5, 'key_schema_id': 2}

        self.producer._handle_produce_success('test_driver', None, body)

        self.assertEqual(self.client.schema_cache['test_driver']['value-id'], 5)
        self.assertEqual(self.client.schema_cache['test_driver']['key-id'], 2)

    def test_handle_produce_success_simple_success(self):
        m1 = Message('test_driver', {'val': 1}, None, None, 0, 1)
        response = Mock()
        response.request = Mock()
        response.request._batch = [m1]
        body = {'offsets': [{}], 'value_schema_id': 1, 'key_schema_id': 2}

        self.producer._handle_produce_success('test_driver', response, body)

        self.client.mock_for('produce_success').assert_called_once_with('test_driver',
                                                                        [(m1, {})],
                                                                        [])

    @patch('kafka_rest.producer.AsyncProducer._queue_message_for_retry')
    def test_handle_produce_success_mixed_success(self, fake_retry):
        m1 = Message('test_driver', {'val': 1}, None, None, 0, 1)
        m2 = Message('test_driver', {'val': 2}, None, None, 0, 1)
        m3 = Message('test_driver', {'val': 3}, None, None, 0, 1)
        offsets = [{},
                   {'error_code': 1, 'message': 'Nonretriable'},
                   {'error_code': 2, 'message': 'Retriable'}]
        response = Mock()
        response.request = Mock()
        response.request._batch = [m1, m2, m3]
        response.request._id = 1
        body = {'offsets': offsets,
                'value_schema_id': 1,
                'key_schema_id': 2}

        self.producer._handle_produce_success('test_driver', response, body)

        self.client.mock_for('produce_success').assert_called_once_with('test_driver',
                                                                        [(m1, {})],
                                                                        [(m2, offsets[1]),
                                                                         (m3, offsets[2])])
        self.client.mock_for('drop_message').assert_called_once_with('test_driver',
                                                                     m2,
                                                                     'nonretriable')
        fake_retry.assert_called_once_with('test_driver', m3)

    @patch('kafka_rest.producer.AsyncProducer._queue_message_for_retry')
    def test_handle_produce_response_transport_error(self, fake_retry):
        m1 = Message('test_driver', {'val': 1}, None, None, 0, 1)
        m2 = Message('test_driver', {'val': 2}, None, None, 0, 1)
        response = Mock()
        response.code = 599
        response.error = object()
        response.request = Mock()
        response.request._batch = [m1, m2]
        response.request._id = 1

        self.producer._handle_produce_response('test_driver', response)

        self.client.mock_for('response_5xx').assert_called_once_with('test_driver', response)
        fake_retry.assert_has_calls([call('test_driver', m1),
                                     call('test_driver', m2)])

    @patch('kafka_rest.producer.AsyncProducer._handle_produce_success')
    @patch('kafka_rest.producer.json_decode')
    def test_handle_produce_response_on_200(self, fake_decode, fake_handle_success):
        m1 = Message('test_driver', {'val': 1}, None, None, 0, 1)
        m2 = Message('test_driver', {'val': 2}, None, None, 0, 1)
        response = Mock()
        response.code = 200
        response.error = False
        response.request = Mock()
        response.request._batch = [m1, m2]
        response.request._id = 1
        body = {'offsets': [{}, {}],
                'value_schema_id': 1,
                'key_schema_id': 2}
        fake_decode.return_value = body

        self.producer._handle_produce_response('test_driver', response)

        fake_handle_success.assert_called_once_with('test_driver',
                                                    response,
                                                    body)

    @patch('kafka_rest.producer.AsyncProducer._queue_message_for_retry')
    @patch('kafka_rest.producer.json_decode')
    def test_handle_produce_response_on_retriable(self, fake_decode, fake_retry):
        m1 = Message('test_driver', {'val': 1}, None, None, 0, 1)
        m2 = Message('test_driver', {'val': 2}, None, None, 0, 1)
        response = Mock()
        response.code = 500
        response.error = False
        response.request = Mock()
        response.request._batch = [m1, m2]
        response.request._id = 1
        body = {'offsets': [{}, {}],
                'value_schema_id': 1,
                'key_schema_id': 2,
                'error_code': 50001,
                'message': 'Retriable'}
        fake_decode.return_value = body

        self.producer._handle_produce_response('test_driver', response)

        fake_retry.assert_has_calls([call('test_driver', m1),
                                     call('test_driver', m2)])

    @patch('kafka_rest.producer.AsyncProducer._queue_message_for_retry')
    @patch('kafka_rest.producer.json_decode')
    def test_handle_produce_response_on_nonretriable(self, fake_decode, fake_retry):
        m1 = Message('test_driver', {'val': 1}, None, None, 0, 1)
        m2 = Message('test_driver', {'val': 2}, None, None, 0, 1)
        response = Mock()
        response.code = 500
        response.error = False
        response.request = Mock()
        response.request._batch = [m1, m2]
        response.request._id = 1
        body = {'offsets': [{}, {}],
                'value_schema_id': 1,
                'key_schema_id': 2,
                'error_code': 50101,
                'message': 'Nonretriable'}
        fake_decode.return_value = body

        self.producer._handle_produce_response('test_driver', response)

        calls = [call('test_driver', m1, 'nonretriable'),
                 call('test_driver', m2, 'nonretriable')]
        self.client.mock_for('drop_message').assert_has_calls(calls)

    @patch('kafka_rest.producer.AsyncProducer._reset_flush_timer')
    def test_flush_topic_resets_flush_timer_normally(self, fake_flush_timer):
        self.producer._flush_topic('test_driver', 'testing')
        fake_flush_timer.assert_called_once_with('test_driver')

    @patch('kafka_rest.producer.AsyncProducer._reset_flush_timer')
    def test_flush_topic_resets_flush_timer_under_circuit_breaker(self, fake_flush_timer):
        self.client.response_5xx_circuit_breaker.failure_count = sys.maxsize
        self.producer._flush_topic('test_driver', 'testing')
        fake_flush_timer.assert_called_once_with('test_driver')

    @patch('kafka_rest.producer.AsyncProducer._reset_flush_timer')
    def test_flush_topic_does_not_reset_flush_timer_in_shutdown(self, fake_flush_timer):
        self.client.shutdown(block=False)
        self.producer._flush_topic('test_driver', 'testing')
        self.assertFalse(fake_flush_timer.called)

    def test_flush_topic_sends_batches(self):
        self.client.flush_max_batch_size = 1
        m1 = Message('test_driver', {'val': 1}, None, None, 0, 1)
        m2 = Message('test_driver', {'val': 2}, None, None, 0, 1)
        queue = self.client.message_queues['test_driver']
        for m in [m1, m2]:
            queue.put(m)

        self.producer._flush_topic('test_driver', 'testing')

        self.client.mock_for('flush_topic').assert_called_with('test_driver', 'testing')
        self.callback_mock.assert_has_calls([call(self.producer._send_batch_produce_request, 'test_driver', [m1]),
                                             call(self.producer._send_batch_produce_request, 'test_driver', [m2])])

    @patch('kafka_rest.producer.AsyncProducer._reset_flush_timer')
    def test_evaluate_queue_on_empty(self, fake_flush_timer):
        self.producer.evaluate_queue('test_driver', self.client.message_queues['test_driver'])
        fake_flush_timer.assert_called_with('test_driver')
        fake_flush_timer.reset_mock()

    @patch('kafka_rest.producer.AsyncProducer._reset_flush_timer')
    def test_evaluate_queue_on_empty_timer_set(self, fake_flush_timer):
        self.producer.flush_timers['test_driver'] = None
        self.producer.evaluate_queue('test_driver', self.client.message_queues['test_driver'])
        self.assertFalse(fake_flush_timer.called)

    @patch('kafka_rest.producer.AsyncProducer._reset_flush_timer')
    @patch('kafka_rest.producer.AsyncProducer._flush_topic')
    def test_evaluate_queue_on_length(self, fake_flush, fake_flush_timer):
        self.client.flush_length_threshold = 1
        m1 = Message('test_driver', {'val': 1}, None, None, 0, 1)
        m2 = Message('test_driver', {'val': 2}, None, None, 0, 1)
        queue = self.client.message_queues['test_driver']
        for m in [m1, m2]:
            queue.put(m)

        self.producer.evaluate_queue('test_driver', self.client.message_queues['test_driver'])

        fake_flush.assert_called_with('test_driver', FlushReason.LENGTH)
        self.assertFalse(fake_flush_timer.called)


text:
package scalashop

import org.scalameter._
import common._

object VerticalBoxBlurRunner {

  val standardConfig = config(
    Key.exec.minWarmupRuns -> 5,
    Key.exec.maxWarmupRuns -> 10,
    Key.exec.benchRuns -> 10,
    Key.verbose -> true
  ) withWarmer(new Warmer.Default)

  def main(args: Array[String]): Unit = {
    val radius = 3
    val width = 1920
    val height = 1080
    val src = new Img(width, height)
    val dst = new Img(width, height)
    val seqtime = standardConfig measure {
      VerticalBoxBlur.blur(src, dst, 0, width, radius)
    }
    println(s"sequential blur time: $seqtime ms")

    val numTasks = 32
    val partime = standardConfig measure {
      VerticalBoxBlur.parBlur(src, dst, numTasks, radius)
    }
    println(s"fork/join blur time: $partime ms")
    println(s"speedup: ${seqtime / partime}")
  }

}

/** A simple, trivially parallelizable computation. */
object VerticalBoxBlur {

  /** Blurs the columns of the source image `src` into the destination image
   *  `dst`, starting with `from` and ending with `end` (non-inclusive).
   *
   *  Within each column, `blur` traverses the pixels by going from top to
   *  bottom.
   */
  def blur(src: Img, dst: Img, from: Int, end: Int, radius: Int): Unit = {
    for (x <- from until end) {
      for (y <- 0 until src.height) {
        dst.update(x, y, boxBlurKernel(src, x, y, radius))
      }
    }
  }

  /** Blurs the columns of the source image in parallel using `numTasks` tasks.
   *
   *  Parallelization is done by stripping the source image `src` into
   *  `numTasks` separate strips, where each strip is composed of some number of
   *  columns.
   */
  def parBlur(src: Img, dst: Img, numTasks: Int, radius: Int): Unit = {
    val colsPerTask = math.max(src.width / numTasks, 1)
    val strips      = 0 until src.width by colsPerTask

    val tasks = strips.map(strip => {
      task { blur(src, dst, strip, math.min(strip + colsPerTask, src.width), radius) }
    })

    tasks.foreach(_.join)
  }

}

redpajama_set_name: RedPajamaGithub


text:
//
//  ContextView.m
//  ADKModalMaskView
//
//  Created by Chih Feng Sung on 6/20/16.
//  Copyright © 2016 Yahoo. All rights reserved.
//

#import "ContextView.h"

@implementation ContextView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end


text:
import AWS = require('../index');
import {Agent} from 'https';

// Create Config
AWS.config = new AWS.Config({
    region: 'us-east-1',
    credentials: {
        accessKeyId: 'fake',
        secretAccessKey: 'key'
    },
    correctClockSkew: true,
    s3: {
        region: 'us-west-2',
        params: {
            Bucket: 'bucket'
        },
        useDualstack: true
    },
    apiVersion: 'latest',
});

// Lock api versions
AWS.config.apiVersions = {
    acm: "2015-12-08",
    lambda: "2015-03-31"
};

// update credentials
AWS.config.update({
    credentials: new AWS.Credentials('accessKeyId', 'secretAccessKey', 'sessionToken')
});

// update credentials using direct CredentialsOptions
AWS.config.update({
    accessKeyId: 'accessKeyId',
    secretAccessKey: 'secretAccessKey',
    sessionToken: 'sessionToken'
});

// set all normal config
AWS.config.update({
    apiVersion: "latest",
    computeChecksums: true,
    convertResponseTypes: true,
    correctClockSkew: false,
    credentials: {
        accessKeyId: 'id',
        secretAccessKey: 'secret',
        sessionToken: 'token'
    },
    httpOptions: {
        agent: new Agent(),
        proxy: 'http://localhost:8080',
        timeout: 1000 * 60,
        xhrAsync: true,
        xhrWithCredentials: true
    },
    logger: console,
    maxRedirects: 2,
    maxRetries: 3,
    paramValidation: {
        min: true,
        max: false,
        pattern: false,
        enum: false
    },
    region: 'us-east-1',
    retryDelayOptions: {
        base: 100,
        customBackoff: function(retryCount){return 0;}
    },
    s3BucketEndpoint: false,
    s3DisableBodySigning: false,
    s3ForcePathStyle: true,
    signatureCache: false,
    signatureVersion: 'v4',
    sslEnabled: true,
    systemClockOffset: 0,
    useAccelerateEndpoint: true
});

//test config methods
AWS.config.getCredentials(function(err) {});
// make sure we can get the Promise constructor
var Promise = AWS.config.getPromisesDependency();
if (Promise) {
    console.log(typeof Promise.resolve);
}
AWS.config.setPromisesDependency(Promise);

var config = AWS.config.loadFromPath('/to/path');

// test update allowing unknown keys
AWS.config.update({
   fake: 'fake'
}, true);

//Test httpOption interface
var httpOptions:AWS.HTTPOptions = {
  timeout: 6000
}

// Test constructing with a CredentialProviderChain
var options = {
    credentialProvider: new AWS.CredentialProviderChain([
        () => new AWS.EC2MetadataCredentials()
    ]),
    httpOptions
};
var s3 = new AWS.S3(options);
var ses = new AWS.SES(options);


text:
__css-aid__ doesn't propose any new syntax rules, it just helps with tedious issues that we approach when writing standard CSS.
e.g. it expands experimental properties into collection containing all vendor prefixes, or resolves CSS variables syntax so it can be used in browsers that do not support it.

How it works? Currently it's just primitive regular expression based search and replace algorithm. As project may expand it's possible it'll be upgraded to use more syntax bulletproof solution

### Installation

	$ npm install css-aid

#### Usage

```javascript
var cssAid = require('css-aid');
var processedCss = cssAid(plainCSS);
```

Optionally you can manually decide which rules (see [list below](#rules)) you want to apply:

```javascript
// Apply only 'border-radius' and 'variables' rules
var processedCss = cssAid(plainCSS, [require('css-aid/rules/border-radius'), require('css-aid/rules/variables')]);
```

### Rules

_Following list is still not perceived as complete and is extended on demand_

#### align-self

Replaces:
`align-self: <value>`
with:
`-webkit-align-self: <value>; align-self: <value>`

#### border-radius

Replaces:
`border-radius: <value>`
with:
`-webkit-border-radius: <value>; -moz-border-radius: <value>; -khtml-border-radius: <value>; border-radius: <value>`

#### box-shadow

Replaces:
`box-shadow: <value>`
with:
`-moz-box-shadow: <value>; -webkit-box-shadow: <value>; box-shadow: <value>`

#### box-sizing

Replaces:
`box-sizing: <value>`
with:
`-moz-box-sizing: <value>; -webkit-box-sizing: <value>; box-sizing: <value>`

#### flex-wrap

Replaces:
`flex-wrap: <value>`
with:
`-webkit-flex-wrap: <value>; flex-wrap: <value>`

#### flex

Replaces:
`display: flex`
with:
`display: -webkit-box; display: -moz-box; display: -ms-flexbox; display: -webkit-flex; display: flex`

#### justify-content

Replaces:
`justify-content: <value>`
with:
`-webkit-justify-content: <value>; justify-content: <value>`

#### variables

Supports only variables defined in `::root` rule.

e.g. for following code:

```css
::root {
	--foo: rgba(200, 200, 200, 0.5);
--lorem-ipsum: 20px 30px;
}
div.test {
	color: black;
background: var(--foo);
	margin: var(--lorem-ipsum);
}
```

It will produce:
```css
div.test {
	color: black;
background: rgba(200, 200, 200, 0.5);
	margin: 20px 30px;
}
```

## Tests [![Build Status](https://travis-ci.org/medikoo/css-aid.png)](https://travis-ci.org/medikoo/css-aid)

	$ npm test


text: declare module '@popperjs/core/dist/esm/popper';


text:
use std::fmt;
use std::str::FromStr;

use mime_parse::{Mime, Parse};

use crate::{InvalidMime, MediaType, Value};

/// A parsed media range used to match media types.
///
/// Commonly found in the HTTP `Accept` header, these are used for agents
/// to indicate general classes of content that they can understand.
///
/// # Example
///
/// ```
/// use mime::MediaRange;
///
/// // Suppose this was parsed from an `Accept` header
/// let range = MediaRange::parse("text/*").unwrap();
///
/// // The formats of the resource that we have:
/// let formats = vec![
///     mime::APPLICATION_JSON,
///     mime::TEXT_PLAIN_UTF_8,
///     mime::TEXT_HTML,
/// ];
///
/// for format in &formats {
///     if range.matches(format) {
///         // This should print for the plain and HTML text...
///         println!("We could send in {:?} format!", format);
///     }
/// }
/// ```
#[derive(Clone)]
pub struct MediaRange {
    pub(super) mime: Mime,
}

impl MediaRange {
    /// Parse a string as a `MediaRange`.
    ///
    /// # Example
    ///
    /// ```
    /// let range = mime::MediaRange::parse("*/*").unwrap();
    /// assert_eq!(range, mime::STAR_STAR);
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if the source is not a valid media range.
    #[inline]
    pub fn parse(source: impl Parse) -> Result<Self, InvalidMime> {
        mime_parse::Parser::can_range()
            .parse(source)
            .map(|mime| MediaRange { mime })
            .map_err(|e| InvalidMime { inner: e })
    }

    /// Get the top level media type for this `MediaRange`.
    ///
    /// # Example
    ///
    /// ```
    /// let range = mime::TEXT_STAR;
    /// assert_eq!(range.type_(), "text");
    /// assert_eq!(range.type_(), mime::TEXT);
    /// ```
    #[inline]
    pub fn type_(&self) -> &str {
        self.mime.type_()
    }

    /// Get the subtype of this `MediaRange`.
    ///
    /// # Example
    ///
    /// ```
    /// let range = mime::TEXT_STAR;
    ///
    /// assert_eq!(range.subtype(), "*");
    /// assert_eq!(range.subtype(), mime::STAR);
    ///
    /// let exact = mime::MediaRange::from(mime::TEXT_PLAIN);
    /// assert_eq!(exact.subtype(), mime::PLAIN);
    /// assert_eq!(exact.subtype(), "plain");
    /// ```
    #[inline]
    pub fn subtype(&self) -> &str {
        self.mime.subtype()
    }

    /// Get an optional +suffix for this `MediaRange`.
    ///
    /// # Example
    ///
    /// ```
    /// let svg = mime::MediaRange::from(mime::IMAGE_SVG);
    ///
    /// assert_eq!(svg.suffix(), Some(mime::XML));
    /// assert_eq!(svg.suffix().unwrap(), "xml");
    ///
    ///
    /// let any = mime::STAR_STAR;
    ///
    /// assert_eq!(any.suffix(), None);
    /// ```
    #[inline]
    pub fn suffix(&self) -> Option<&str> {
        self.mime.suffix()
    }

    /// Checks if this `MediaRange` matches a specific `MediaType`.
    ///
    /// # Example
    ///
    /// ```
    /// let images = mime::IMAGE_STAR;
    ///
    /// assert!(images.matches(&mime::IMAGE_JPEG));
    /// assert!(images.matches(&mime::IMAGE_PNG));
    ///
    /// assert!(!images.matches(&mime::TEXT_PLAIN));
    /// ```
    pub fn matches(&self, mt: &MediaType) -> bool {
        let type_ = self.type_();

        if type_ == crate::STAR {
            // sanity check there's no `*/plain` or whatever
            debug_assert_eq!(self.subtype(), crate::STAR);

            return self.matches_params(mt);
        }

        if type_ != mt.type_() {
            return false;
        }

        let subtype = self.subtype();

        if subtype == crate::STAR {
            return self.matches_params(mt);
        }

        if subtype != mt.subtype() {
            return false;
        }

        // type and subtype are the same, last thing to do is check
        // that the MediaType contains all this range's parameters...
        self.matches_params(mt)
    }

    fn matches_params(&self, mt: &MediaType) -> bool {
        for (name, value) in self.params() {
            if name != "q" && mt.param(name) != Some(value) {
                return false;
            }
        }

        true
    }

    /// Look up a parameter by name.
    ///
    /// # Example
    ///
    /// ```
    /// let range = mime::MediaRange::from(mime::TEXT_PLAIN_UTF_8);
    ///
    /// assert_eq!(range.param(mime::CHARSET), Some(mime::UTF_8));
    /// assert_eq!(range.param("charset").unwrap(), "utf-8");
    /// assert_eq!(range.param("boundary"), None);
    /// ```
    pub fn param<'a>(&'a self, attr: &str) -> Option<Value<'a>> {
        crate::value::param(&self.mime, attr)
    }

    /// Returns an iterator over the parameters.
    ///
    /// # Example
    ///
    /// ```
    /// let pkcs7 = mime::MediaRange::parse(
    ///     "application/pkcs7-mime; smime-type=enveloped-data; name=smime.p7m"
    /// ).unwrap();
    ///
    /// let mut params = pkcs7.params();
    ///
    /// let (name, value) = params.next().unwrap();
    /// assert_eq!(name, "smime-type");
    /// assert_eq!(value, "enveloped-data");
    ///
    /// let (name, value) = params.next().unwrap();
    /// assert_eq!(name, "name");
    /// assert_eq!(value, "smime.p7m");
    ///
    /// assert!(params.next().is_none());
    /// ```
    #[inline]
    pub fn params(&self) -> impl Iterator<Item = (&str, Value)> {
        crate::value::params(&self.mime)
    }

    /// Returns true if the media type has at last one parameter.
    ///
    /// # Example
    ///
    /// ```
    /// let plain_text: mime::MediaType = "text/plain".parse().unwrap();
    /// assert_eq!(plain_text.has_params(), false);
    ///
    /// let plain_text_utf8: mime::MediaType = "text/plain; charset=utf-8".parse().unwrap();
    /// assert_eq!(plain_text_utf8.has_params(), true);
    /// ```
    #[inline]
    pub fn has_params(&self) -> bool {
        self.mime.has_params()
    }

    #[cfg(test)]
    pub(super) fn test_assert_asterisks(&self) {
        // asterisks are allowed in MediaRange constants
    }
}

/// Any `MediaType` can freely be a `MediaRange`.
///
/// # Example
///
/// ```
/// // If we only supported `text/plain`:
/// let range = mime::MediaRange::from(mime::TEXT_PLAIN);
/// ```
impl From<MediaType> for MediaRange {
    fn from(mt: MediaType) -> MediaRange {
        MediaRange {
            mime: mt.mime,
        }
    }
}

impl PartialEq for MediaRange {
    fn eq(&self, other: &MediaRange) -> bool {
        crate::cmp::mime_eq(&self.mime, &other.mime)
    }
}

impl PartialEq<str> for MediaRange {
    fn eq(&self, s: &str) -> bool {
        crate::cmp::str_eq(&self.mime, s)
    }
}

impl<'a> PartialEq<&'a str> for MediaRange {
    #[inline]
    fn eq(&self, s: & &'a str) -> bool {
        self == *s
    }
}

impl<'a> PartialEq<MediaRange> for &'a str {
    #[inline]
    fn eq(&self, mr: &MediaRange) -> bool {
        mr == self
    }
}

impl PartialEq<MediaRange> for str {
    #[inline]
    fn eq(&self, mr: &MediaRange) -> bool {
        mr == self
    }
}

impl FromStr for MediaRange {
    type Err = InvalidMime;

    fn from_str(s: &str) -> Result<MediaRange, Self::Err> {
        MediaRange::parse(s)
    }
}

impl AsRef<str> for MediaRange {
    fn as_ref(&self) -> &str {
        self.mime.as_ref()
    }
}

impl fmt::Debug for MediaRange {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(&self.mime, f)
    }
}

impl fmt::Display for MediaRange {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(&self.mime, f)
    }
}

#[cfg(test)]
mod tests {
    use crate::*;

    #[test]
    fn media_range_from_str() {
        // exact types
        assert_eq!(MediaRange::parse("text/plain").unwrap(), MediaRange::from(TEXT_PLAIN));

        // stars
        let any = "*/*".parse::<MediaRange>().unwrap();
        assert_eq!(any, "*/*");
        assert_eq!(any, STAR_STAR);
        assert_eq!("image/*".parse::<MediaRange>().unwrap(), "image/*");
        assert_eq!("text/*; charset=utf-8".parse::<MediaRange>().unwrap(), "text/*; charset=utf-8");

        // bad stars
        MediaRange::parse("text/*plain").unwrap_err();
    }

    #[test]
    fn media_range_matches() {
        assert!(STAR_STAR.matches(&TEXT_PLAIN), "*/* matches everything");

        assert!(TEXT_STAR.matches(&TEXT_PLAIN), "text/* matches text/plain");
        assert!(TEXT_STAR.matches(&TEXT_HTML), "text/* matches text/html");
        assert!(TEXT_STAR.matches(&TEXT_HTML_UTF_8), "text/* matches text/html; charset=utf-8");

        assert!(!TEXT_STAR.matches(&IMAGE_GIF), "text/* doesn't match image/gif");
    }

    #[test]
    fn media_range_matches_params() {
        let text_any_utf8 = MediaRange::parse("text/*; charset=utf-8").unwrap();

        assert!(text_any_utf8.matches(&TEXT_PLAIN_UTF_8));
        assert!(text_any_utf8.matches(&TEXT_HTML_UTF_8));

        assert!(!text_any_utf8.matches(&TEXT_HTML));

        let many_params = MediaType::parse("text/plain; charset=utf-8; foo=bar").unwrap();
        assert!(text_any_utf8.matches(&many_params));

        let text_plain = MediaRange::parse("text/plain").unwrap();
        assert!(text_plain.matches(&many_params));
    }

    #[test]
    fn media_range_matches_skips_q() {
        let range = MediaRange::parse("text/*; q=0.8").unwrap();

        assert!(range.matches(&TEXT_PLAIN_UTF_8));
        assert!(range.matches(&TEXT_HTML_UTF_8));

        let range = MediaRange::parse("text/*; charset=utf-8; q=0.8").unwrap();

        assert!(range.matches(&TEXT_PLAIN_UTF_8));
        assert!(range.matches(&TEXT_HTML_UTF_8));
        assert!(!range.matches(&TEXT_HTML));
    }
}


text:
package com.homelink.ljrecyclerview;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;

import java.util.ArrayList;

/**
 * 创建时间:2017年06月24日17:08

 * 作者:zhangqiang

 * 描述:继承自基础LJSimpleRecyclerView
 *       扩展功能: 1、支持header、footer
 *                  2、支持空白页
 */
public class LJHeaderWrappedRecyclerView extends LJSimpleRecyclerView {

  private static final String TAG = "LJHeaderWrappedRecyclerView";

  private HeaderWrappedAdapter mOriginalAdapter;

  protected ArrayList<View> mHeaderViews = new ArrayList<>();

  protected ArrayList<View> mFooterViews = new ArrayList<>();

  protected View mEmpty;

  protected int mEmptyFlag;

  public LJHeaderWrappedRecyclerView(Context context) {
    this(context, null);
  }

  public LJHeaderWrappedRecyclerView(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  /**
   * 设置adapter
   * @param adapter
   */
  public void setAdapter(HeaderWrappedAdapter adapter){
    this.mOriginalAdapter = adapter;
    initRefreshConfig();
    initLayoutManager();
    initListener();
    mOriginalAdapter.setHeaderViews(mHeaderViews);
    mOriginalAdapter.setFooterViews(mFooterViews);
    mOriginalAdapter.setEmpty(mEmpty);
    mOriginalAdapter.setEmptyArea(mEmptyFlag);
    mRecyclerView.setAdapter(mOriginalAdapter);
  }

  /**
   * 添加header
   * @param header
   */
  public void addHeaderView(View header){
    mHeaderViews.add(header);
  }

  /**
   * 添加footer
   * @param footer
   */
  public void addFooterView(View footer){
    mFooterViews.add(footer);
  }

  /**
   * 设置空白页
   * @param empty
   */
  public void setEmptyView(View empty){
    this.mEmpty = empty;
  }

  /**
   * 设置空白页位置
   * @param flag
   */
  public void setEmptyArea(@Empty int flag){
    this.mEmptyFlag = flag;
  }

  /**
   * 获得adapter
   * @return
   */
  public HeaderWrappedAdapter getAdapter(){
    return mOriginalAdapter;
  }

  private void initListener() {
    if (mOnItemClickListener != null){
      mOriginalAdapter.setOnItemClickListener(mOnItemClickListener);
    }

    if (mOnItemLongClickListener != null){
      mOriginalAdapter.setOnItemLongClickListener(mOnItemLongClickListener);
    }
  }
}


text:
'use strict';

angular
	.module('StratioUI.layout.menutab',[])
	.directive('stMenuTab', stMenuTab);

stMenuTab.$inject = ['TEMPLATE_URL'];
function stMenuTab(TEMPLATE_URL){
	var directive = {
		restrict: 'AE',
		require: 'ngModel',
		transclude: true,
		scope: {
			title: '=title',
			visible: '@visible',
			route: '@route',
			sref: '@sref',
			icon: '@icon',
			label: '@label',
			qaref: '@qaref'
		},
		templateUrl: TEMPLATE_URL('layout', 'menutab'),
		controller: controller
	};

	controller.$inject = ["$scope","$state"];

	return directive;

	function controller (  $scope,  $state){
		$scope.$state = $state;
	}
}


text:
using System;
using System.Threading;
using Leap;

class SampleListener : Listener
{
    private Object thisLock = new Object();

    private void SafeWriteLine( String line )
    {
        lock ( thisLock ) {
            Console.WriteLine( line );
        }
    }

    public override void OnInit( Controller controller )
    {
        SafeWriteLine( "Initialized" );
    }

    public override void OnConnect( Controller controller )
    {
        SafeWriteLine( "Connected" );
        controller.EnableGesture( Gesture.GestureType.TYPE_CIRCLE );
        controller.EnableGesture( Gesture.GestureType.TYPE_KEY_TAP );
        controller.EnableGesture( Gesture.GestureType.TYPE_SCREEN_TAP );
        controller.EnableGesture( Gesture.GestureType.TYPE_SWIPE );
    }

    public override void OnDisconnect( Controller controller )
    {
        //Note: not dispatched when running in a debugger.
        SafeWriteLine( "Disconnected" );
    }

    public override void OnExit( Controller controller )
    {
        SafeWriteLine( "Exited" );
    }

    public override void OnFrame( Controller controller )
    {
        // Get the most recent frame and report some basic information
        Frame frame = controller.Frame();

        SafeWriteLine( "Frame id: " + frame.Id
                    + ", timestamp: " + frame.Timestamp
                    + ", hands: " + frame.Hands.Count
                    + ", fingers: " + frame.Fingers.Count
                    + ", tools: " + frame.Tools.Count
                    + ", gestures: " + frame.Gestures().Count );

        foreach ( Hand hand in frame.Hands ) {
            SafeWriteLine( "  Hand id: " + hand.Id
						+ ", palm position: " + hand.PalmPosition );
            // Get the hand's normal vector and direction
            Vector normal = hand.PalmNormal;
            Vector direction = hand.Direction;

            // Calculate the hand's pitch, roll, and yaw angles
            SafeWriteLine( "  Hand pitch: " + direction.Pitch * 180.0f / (float)Math.PI + " degrees, "
                        + "roll: " + normal.Roll * 180.0f / (float)Math.PI + " degrees, "
                        + "yaw: " + direction.Yaw * 180.0f / (float)Math.PI + " degrees" );

            // Get the Arm bone
            Arm arm = hand.Arm;
            SafeWriteLine( "  Arm direction: " + arm.Direction
                        + ", wrist position: " + arm.WristPosition
                        + ", elbow position: " + arm.ElbowPosition );

            // Get fingers
            foreach ( Finger finger in hand.Fingers ) {
                SafeWriteLine( "    Finger id: " + finger.Id
					        + ", " + finger.Type.ToString()
					        + ", length: " + finger.Length
					        + "mm, width: " + finger.Width + "mm" );

                // Get finger bones
                Bone bone;
                foreach ( Bone.BoneType boneType in (Bone.BoneType[])Enum.GetValues( typeof( Bone.BoneType ) ) ) {
                    bone = finger.Bone( boneType );
                    SafeWriteLine( "      Bone: " + boneType
						        + ", start: " + bone.PrevJoint
						        + ", end: " + bone.NextJoint
						        + ", direction: " + bone.Direction );
                }
            }

        }

        // Get tools
        foreach ( Tool tool in frame.Tools ) {
            SafeWriteLine( "  Tool id: " + tool.Id
				        + ", position: " + tool.TipPosition
				        + ", direction " + tool.Direction );
        }

        // Get gestures
        GestureList gestures = frame.Gestures();
        for ( int i = 0; i < gestures.Count; i++ ) {
            Gesture gesture = gestures[i];

            switch ( gesture.Type ) {
            case Gesture.GestureType.TYPE_CIRCLE:
                CircleGesture circle = new CircleGesture( gesture );

                // Calculate clock direction using the angle between circle normal and pointable
                String clockwiseness;
                if ( circle.Pointable.Direction.AngleTo( circle.Normal ) <= Math.PI / 2 ) {
                    //Clockwise if angle is less than 90 degrees
                    clockwiseness = "clockwise";
                }
                else {
                    clockwiseness = "counterclockwise";
                }

                float sweptAngle = 0;

                // Calculate angle swept since last frame
                if ( circle.State != Gesture.GestureState.STATE_START ) {
                    CircleGesture previousUpdate = new CircleGesture( controller.Frame( 1 ).Gesture( circle.Id ) );
                    sweptAngle = (circle.Progress - previousUpdate.Progress) * 360;
                }

                SafeWriteLine( "  Circle id: " + circle.Id
                               + ", " + circle.State
                               + ", progress: " + circle.Progress
                               + ", radius: " + circle.Radius
                               + ", angle: " + sweptAngle
                               + ", " + clockwiseness );
                break;
            case Gesture.GestureType.TYPE_SWIPE:
                SwipeGesture swipe = new SwipeGesture( gesture );
                SafeWriteLine( "  Swipe id: " + swipe.Id
                               + ", " + swipe.State
                               + ", position: " + swipe.Position
                               + ", direction: " + swipe.Direction
                               + ", speed: " + swipe.Speed );
                break;
            case Gesture.GestureType.TYPE_KEY_TAP:
                KeyTapGesture keytap = new KeyTapGesture( gesture );
                SafeWriteLine( "  Tap id: " + keytap.Id
                               + ", " + keytap.State
                               + ", position: " + keytap.Position
                               + ", direction: " + keytap.Direction );
                break;
            case Gesture.GestureType.TYPE_SCREEN_TAP:
                ScreenTapGesture screentap = new ScreenTapGesture( gesture );
                SafeWriteLine( "  Tap id: " + screentap.Id
                               + ", " + screentap.State
                               + ", position: " + screentap.Position
                               + ", direction: " + screentap.Direction );
                break;
            default:
                SafeWriteLine( "  Unknown gesture type." );
                break;
            }
        }

        if ( !frame.Hands.IsEmpty || !frame.Gestures().IsEmpty ) {
            SafeWriteLine( "" );
        }
    }
}

class Sample
{
    public static void Main()
    {
        // Create a sample listener and controller
        SampleListener listener = new SampleListener();
        Controller controller = new Controller();

        // Have the sample listener receive events from the controller
        controller.AddListener( listener );

        // Keep this process running until Enter is pressed
        Console.WriteLine( "Press Enter to quit..." );
        Console.ReadLine();

        // Remove the sample listener when done
        controller.RemoveListener( listener );
        controller.Dispose();
    }
}


text:
import isEqual from "lodash-es/isEqual";

/** (c) 2017 Objective Systems Integrators, Inc. (MYCOM OSI) All Rights Reserved.
 *
 *   ReduxViewBinder
 */
export default class ReduxViewBinder {
    /**
     *  Creates a new ReduxViewBinder
     *
     * @param {Object} store - The Redux store.
     */
    constructor(store){
        this._store = store;
    }

    /**
    * Specifies which part of the Redux state object is observed. When this
    * sub-part of the Redux state changes then the onChange method is called.
    * The equality is tested using JSON.stringify.
    *
    * @callback watchCb
    * @param {Object} state - The current Redux state.
    * @Returns {Object} the sub-part of the Redux state object that should be observed.
    *
    */

    /**
    * Specifies which part of the Redux state object is passed to the onChange method. It is especialy useful to pass a higher level sub-part of the Redux state object that the one watched.
    *
    * @callback filterCb
    * @param {Object} state - The current Redux state.
    * @Returns {Object} the sub-part of the Redux state object that should be observed.
    *
    */

    /**
    * The Reduc dispatch function.
    *
    * @callback dispatchCb
    * @param {Object} action - The action to dispatch.
    *
    */

    /**
    * Specifies which part of the Redux state object is passed to the onChange method.
    *
    * @callback onChangeCb
    * @param {Object} filteredModel - The filtered Redux state object.
    * @param {dispatchCb} dispatch - The dispatch function.
    * @param {Object} [view] - The view bound.
    *
    */

    /**
    * Use this method to bind the view to model changes. The view can be passed as parameter or using side effects inside the onChange method.
    *
    * @param {watchCb} watch - The watch function.
    * @param {onChangeCb} onChange - The onChange function.
    * @param {Object} [view] - The view to be bound to model changes.
    * @param {filterCb} [filter] - The filter function.
    *
    */
    bind(watch, onChange, view, filter){
        let currentState;

        //This is called after the reducer has been called with a new action
        function handleChange() {
            let model = this._store.getState();
            let nextState = watch(model);
            if (!isEqual(nextState, currentState)) {
                currentState = nextState; //save in the closure for next time
                let filteredModel = currentState;
                if (filter)
                    filteredModel = filter(model);
                onChange(filteredModel, this._store.dispatch, view);
            }
        }

        let fn = handleChange.bind(this);
        // subscribing to futur changes of Redux state
        let unsubscribe = this._store.subscribe(fn);
        //Force first execution of handleChange
        fn();
        return unsubscribe;
    }
}


text:
% Experimenting with Matlab's image registration features

img1 = imread('BanteaySrei_01.jpg');
img2 = imread('BanteaySrei_02.jpg');

%registrationEstimator(rgb2gray(img1), rgb2gray(img2));

%[optimizer, metric] = imregconfig('monomodal');
%imgTForm = imregtform(rgb2gray(img1),rgb2gray(img2),'affine',...
%    optimizer,metric);

merge = registerImages(rgb2gray(img2), rgb2gray(img1));
imshowpair(img2,(imwarp(img1, merge.Transformation)), 'diff');

function [MOVINGREG] = registerImages(MOVING,FIXED)
%registerImages  Register grayscale images using auto-generated code from Registration Estimator app.
%  [MOVINGREG] = registerImages(MOVING,FIXED) Register grayscale images
%  MOVING and FIXED using auto-generated code from the Registration
%  Estimator app. The values for all registration parameters were set
%  interactively in the app and result in the registered image stored in the
%  structure array MOVINGREG.

% Auto-generated by registrationEstimator app on 27-Jan-2021
%-----------------------------------------------------------

% Feature-based techniques require license to Computer Vision Toolbox
checkLicense()

% Default spatial referencing objects
fixedRefObj = imref2d(size(FIXED));
movingRefObj = imref2d(size(MOVING));

% Detect SURF features
fixedPoints = detectSURFFeatures(FIXED,'MetricThreshold',750.000000,'NumOctaves',3,'NumScaleLevels',5);
movingPoints = detectSURFFeatures(MOVING,'MetricThreshold',750.000000,'NumOctaves',3,'NumScaleLevels',5);

% Extract features
[fixedFeatures,fixedValidPoints] = extractFeatures(FIXED,fixedPoints,'Upright',false);
[movingFeatures,movingValidPoints] = extractFeatures(MOVING,movingPoints,'Upright',false);

% Match features
indexPairs = matchFeatures(fixedFeatures,movingFeatures,'MatchThreshold',50.000000,'MaxRatio',0.500000);
fixedMatchedPoints = fixedValidPoints(indexPairs(:,1));
movingMatchedPoints = movingValidPoints(indexPairs(:,2));
MOVINGREG.FixedMatchedFeatures = fixedMatchedPoints;
MOVINGREG.MovingMatchedFeatures = movingMatchedPoints;

% Apply transformation - Results may not be identical between runs because of the randomized nature of the algorithm
tform = estimateGeometricTransform(movingMatchedPoints,fixedMatchedPoints,'projective');
MOVINGREG.Transformation = tform;
MOVINGREG.RegisteredImage = imwarp(MOVING, movingRefObj, tform, 'OutputView', fixedRefObj, 'SmoothEdges', true);

% Store spatial referencing object
MOVINGREG.SpatialRefObj = fixedRefObj;

end

function checkLicense()

% Check for license to Computer Vision Toolbox
CVSTStatus = license('test','Video_and_Image_Blockset');
if ~CVSTStatus
    error(message('images:imageRegistration:CVSTRequired'));
end

end