text:
<tool id="fastq_filter" name="Filter FASTQ" version="1.0.0">
  <description>reads by quality score and length</description>
  <requirements>
    <requirement type="package" version="1.0.0">galaxy_sequence_utils</requirement>
  </requirements>
  <command interpreter="python">fastq_filter.py $input_file $fastq_filter_file $output_file $output_file.files_path '${input_file.extension[len( 'fastq' ):]}'</command>
  <inputs>
    <page>
      <param name="input_file" type="data" format="fastqsanger,fastqcssanger" label="FASTQ File" help="Requires groomed data: if your data does not appear here try using the FASTQ groomer."/>
       <param name="min_size" label="Minimum Size" value="0" type="integer">
        <validator type="in_range" message="Minimum size must be positive" min="0"/>
      </param>
      <param name="max_size" label="Maximum Size" value="0" type="integer" help="A maximum size less than 1 indicates no limit."/>
      <param name="min_quality" label="Minimum Quality" value="0" type="float"/>
      <param name="max_quality" label="Maximum Quality" value="0" type="float" help="A maximum quality less than 1 indicates no limit."/>
      <param name="max_num_deviants" label="Maximum number of bases allowed outside of quality range" value="0" type="integer">
        <validator type="in_range" message="Maximum number of deviate bases must be positive" min="0"/>
      </param>
     <param name="paired_end" label="This is paired end data" type="boolean" truevalue="paired_end" falsevalue="single_end" checked="False"/>
      <repeat name="fastq_filters" title="Quality Filter on a Range of Bases" help="The above settings do not apply to these filters.">
        <conditional name="offset_type">
          <param name="base_offset_type" type="select" label="Define Base Offsets as" help="Use Absolute for fixed length reads (Illumina, SOLiD)<br>Use Percentage for variable length reads (Roche/454)">
            <option value="offsets_absolute" selected="true">Absolute Values</option>
            <option value="offsets_percent">Percentage of Read Length</option>
          </param>
          <when value="offsets_absolute">
            <param name="left_column_offset" label="Offset from 5' end" value="0" type="integer" help="Values start at 0, increasing from the left">
              <validator type="in_range" message="Base Offsets must be positive" min="0" max="inf"/>
              <validator type="expression" message="An integer is required.">int( float( value ) ) == float( value )</validator>
            </param>
            <param name="right_column_offset" label="Offset from 3' end" value="0" type="integer" help="Values start at 0, increasing from the right">
              <validator type="in_range" message="Base Offsets must be positive" min="0" max="inf"/>
              <validator type="expression" message="An integer is required.">int( float( value ) ) == float( value )</validator>
            </param>
          </when>
          <when value="offsets_percent">
            <param name="left_column_offset" label="Offset from 5' end" value="0" type="float">
              <validator type="in_range" message="Base Offsets must be between 0 and 100" min="0" max="100"/>
            </param>
            <param name="right_column_offset" label="Offset from 3' end" value="0" type="float">
              <validator type="in_range" message="Base Offsets must be between 0 and 100" min="0" max="100"/>
            </param>
          </when>
        </conditional>
        <param name="score_operation" type="select" label="Aggregate read score for specified range">
          <option value="min" selected="True">min score</option>
          <option value="max">max score</option>
          <option value="sum">sum of scores</option>
          <option value="mean">mean of scores</option>
        </param>
        <param name="score_comparison" type="select" label="Keep read when aggregate score is">
          <option value=">">></option>
          <option value=">=" selected="true">>=</option>
          <option value="==">==</option>
          <option value="<"><</option>
          <option value="<="><=</option>
          <sanitizer sanitize="False"/>
        </param>
        <param name="score" label="Quality Score" value="0" type="float" />
      </repeat>
    </page>
  </inputs>
  <configfiles>
    <configfile name="fastq_filter_file">
def fastq_read_pass_filter( fastq_read ):
    def mean( score_list ):
        return float( sum( score_list ) ) / float( len( score_list ) )
    if len( fastq_read ) < $min_size:
        return False
    if $max_size > 0 and len( fastq_read ) > $max_size:
        return False
    num_deviates = $max_num_deviants
    qual_scores = fastq_read.get_decimal_quality_scores()
    for qual_score in qual_scores:
        if qual_score < $min_quality or ( $max_quality > 0 and qual_score > $max_quality ):
            if num_deviates == 0:
                return False
            else:
                num_deviates -= 1
#if not $paired_end:
    qual_scores_split = [ qual_scores ]
#else:
    qual_scores_split = [ qual_scores[ 0:int( len( qual_scores ) / 2 ) ], qual_scores[ int( len( qual_scores ) / 2 ): ] ]
#end if
#for $fastq_filter in $fastq_filters:
    for split_scores in qual_scores_split:
        left_column_offset = $fastq_filter[ 'offset_type' ][ 'left_column_offset' ]
        right_column_offset = $fastq_filter[ 'offset_type' ][ 'right_column_offset' ]
#if $fastq_filter[ 'offset_type' ]['base_offset_type'] == 'offsets_percent':
        left_column_offset = int( round( float( left_column_offset ) / 100.0 * float( len( split_scores ) ) ) )
        right_column_offset = int( round( float( right_column_offset ) / 100.0 * float( len( split_scores ) ) ) )
#end if
        if right_column_offset > 0:
            split_scores = split_scores[ left_column_offset:-right_column_offset]
        else:
            split_scores = split_scores[ left_column_offset:]
        if split_scores: ##if a read doesn't have enough columns, it passes by default
            if not ( ${fastq_filter[ 'score_operation' ]}( split_scores ) $fastq_filter[ 'score_comparison' ] $fastq_filter[ 'score' ]  ):
                return False
#end for
    return True
</configfile>
  </configfiles>
  <outputs>
    <data format="input" name="output_file" />
  </outputs>
  <tests>
    <!-- Do nothing filter -->
    <test>
      <param name="input_file" value="sanger_full_range_original_sanger.fastqsanger" ftype="fastqsanger"/>
      <param name="min_size" value="0"/>
      <param name="max_size" value="0"/>
      <param name="min_quality" value="0"/>
      <param name="max_quality" value="0"/>
      <param name="max_num_deviants" value="0"/>
      <param name="paired_end" value="False"/>
      <param name="base_offset_type" value="offsets_absolute"/>
      <param name="left_column_offset" value="0"/>
      <param name="right_column_offset" value="0"/>
      <param name="score_operation" value="min"/>
      <param name="score_comparison" value=">="/>
      <param name="score" value="0"/>
      <output name="out_file1" file="sanger_full_range_original_sanger.fastqsanger"/>
    </test>
    <!-- crippled input types prevent this test <test>
      <param name="input_file" value="solexa_full_range_original_solexa.fastqsolexa" ftype="fastqsolexa"/>
      <param name="min_size" value="0"/>
      <param name="max_size" value="0"/>
      <param name="min_quality" value="-5"/>
      <param name="max_quality" value="0"/>
      <param name="max_num_deviants" value="0"/>
      <param name="paired_end" value="False"/>
      <param name="base_offset_type" value="offsets_absolute"/>
      <param name="left_column_offset" value="0"/>
      <param name="right_column_offset" value="0"/>
      <param name="score_operation" value="min"/>
      <param name="score_comparison" value=">="/>
      <param name="score" value="-5"/>
      <output name="out_file1" file="solexa_full_range_original_solexa.fastqsolexa"/>
    </test> -->
    <!-- No trim, so does not remove Adapter from cssanger -->
    <test>
      <param name="input_file" value="sanger_full_range_as_cssanger.fastqcssanger" ftype="fastqcssanger"/>
      <param name="min_size" value="0"/>
      <param name="max_size" value="0"/>
      <param name="min_quality" value="0"/>
      <param name="max_quality" value="0"/>
      <param name="max_num_deviants" value="0"/>
      <param name="paired_end" value="False"/>
      <param name="base_offset_type" value="offsets_absolute"/>
      <param name="left_column_offset" value="0"/>
      <param name="right_column_offset" value="0"/>
      <param name="score_operation" value="min"/>
      <param name="score_comparison" value=">="/>
      <param name="score" value="0"/>
      <output name="out_file1" file="sanger_full_range_as_cssanger.fastqcssanger"/>
    </test>
    <!-- Remove all Filter -->
    <test>
      <param name="input_file" value="sanger_full_range_original_sanger.fastqsanger" ftype="fastqsanger"/>
      <param name="min_size" value="0"/>
      <param name="max_size" value="0"/>
      <param name="min_quality" value="1"/>
      <param name="max_quality" value="0"/>
      <param name="max_num_deviants" value="0"/>
      <param name="paired_end" value="False"/>
      <param name="base_offset_type" value="offsets_absolute"/>
      <param name="left_column_offset" value="0"/>
      <param name="right_column_offset" value="0"/>
      <param name="score_operation" value="min"/>
      <param name="score_comparison" value=">="/>
      <param name="score" value="0"/>
      <output name="out_file1" file="empty_file.dat"/>
    </test>
    <!-- crippled input types prevent this test <test>
      <param name="input_file" value="solexa_full_range_original_solexa.fastqsolexa" ftype="fastqsolexa"/>
      <param name="min_size" value="0"/>
      <param name="max_size" value="0"/>
      <param name="min_quality" value="-4"/>
      <param name="max_quality" value="0"/>
      <param name="max_num_deviants" value="0"/>
      <param name="paired_end" value="False"/>
      <param name="base_offset_type" value="offsets_absolute"/>
      <param name="left_column_offset" value="0"/>
      <param name="right_column_offset" value="0"/>
      <param name="score_operation" value="min"/>
      <param name="score_comparison" value=">="/>
      <param name="score" value="-5"/>
      <output name="out_file1" file="empty_file.dat"/>
    </test> -->
    <!-- Keep all by allowing 1 deviant -->
    <test>
      <param name="input_file" value="sanger_full_range_original_sanger.fastqsanger" ftype="fastqsanger"/>
      <param name="min_size" value="0"/>
      <param name="max_size" value="0"/>
      <param name="min_quality" value="1"/>
      <param name="max_quality" value="0"/>
      <param name="max_num_deviants" value="1"/>
      <param name="paired_end" value="False"/>
      <param name="base_offset_type" value="offsets_absolute"/>
      <param name="left_column_offset" value="0"/>
      <param name="right_column_offset" value="0"/>
      <param name="score_operation" value="min"/>
      <param name="score_comparison" value=">="/>
      <param name="score" value="0"/>
      <output name="out_file1" file="sanger_full_range_original_sanger.fastqsanger"/>
    </test>
    <!-- crippled input types prevent this test<test>
      <param name="input_file" value="solexa_full_range_original_solexa.fastqsolexa" ftype="fastqsolexa"/>
      <param name="min_size" value="0"/>
      <param name="max_size" value="0"/>
      <param name="min_quality" value="-5"/>
      <param name="max_quality" value="61"/>
      <param name="max_num_deviants" value="1"/>
      <param name="paired_end" value="False"/>
      <param name="base_offset_type" value="offsets_absolute"/>
      <param name="left_column_offset" value="0"/>
      <param name="right_column_offset" value="0"/>
      <param name="score_operation" value="min"/>
      <param name="score_comparison" value=">="/>
      <param name="score" value="-5"/>
      <output name="out_file1" file="solexa_full_range_original_solexa.fastqsolexa"/>
    </test> -->
    <!-- Filter inner range -->
    <test>
      <param name="input_file" value="sanger_full_range_original_sanger.fastqsanger" ftype="fastqsanger"/>
      <param name="min_size" value="0"/>
      <param name="max_size" value="0"/>
      <param name="min_quality" value="0"/>
      <param name="max_quality" value="0"/>
      <param name="max_num_deviants" value="0"/>
      <param name="paired_end" value="False"/>
      <param name="base_offset_type" value="offsets_absolute"/>
      <param name="left_column_offset" value="1"/>
      <param name="right_column_offset" value="1"/>
      <param name="score_operation" value="min"/>
      <param name="score_comparison" value=">="/>
      <param name="score" value="1"/>
      <output name="out_file1" file="sanger_full_range_original_sanger.fastqsanger"/>
    </test>
    <test>
      <param name="input_file" value="sanger_full_range_original_sanger.fastqsanger" ftype="fastqsanger"/>
      <param name="min_size" value="0"/>
      <param name="max_size" value="0"/>
      <param name="min_quality" value="0"/>
      <param name="max_quality" value="0"/>
      <param name="max_num_deviants" value="0"/>
      <param name="paired_end" value="False"/>
      <param name="base_offset_type" value="offsets_absolute"/>
      <param name="left_column_offset" value="1"/>
      <param name="right_column_offset" value="1"/>
      <param name="score_operation" value="max"/>
      <param name="score_comparison" value="<="/>
      <param name="score" value="92"/>
      <output name="out_file1" file="sanger_full_range_original_sanger.fastqsanger"/>
    </test>
    <!-- percent based offsets -->
    <test>
      <param name="input_file" value="sanger_full_range_original_sanger.fastqsanger" ftype="fastqsanger"/>
      <param name="min_size" value="0"/>
      <param name="max_size" value="0"/>
      <param name="min_quality" value="0"/>
      <param name="max_quality" value="0"/>
      <param name="max_num_deviants" value="0"/>
      <param name="paired_end" value="False"/>
      <param name="base_offset_type" value="offsets_percent"/>
      <param name="left_column_offset" value="1.075"/>
      <param name="right_column_offset" value="1.075"/>
      <param name="score_operation" value="min"/>
      <param name="score_comparison" value=">="/>
      <param name="score" value="1"/>
      <output name="out_file1" file="sanger_full_range_original_sanger.fastqsanger"/>
    </test>
    <test>
      <param name="input_file" value="sanger_full_range_original_sanger.fastqsanger" ftype="fastqsanger"/>
      <param name="min_size" value="0"/>
      <param name="max_size" value="0"/>
      <param name="min_quality" value="0"/>
      <param name="max_quality" value="0"/>
      <param name="max_num_deviants" value="0"/>
      <param name="paired_end" value="True"/>
      <param name="base_offset_type" value="offsets_percent"/>
      <param name="left_column_offset" value="1"/>
      <param name="right_column_offset" value="1"/>
      <param name="score_operation" value="min"/>
      <param name="score_comparison" value=">="/>
      <param name="score" value="1"/>
      <output name="out_file1" file="empty_file.dat"/>
    </test>
  </tests>
<help>
This tool allows you to build complex filters to be applied to each read in a FASTQ file.

**Basic Options:**
    * You can specify a minimum and maximum read lengths.
    * You can specify minimum and maximum per base quality scores, with optionally specifying the number of bases that are allowed to deviate from this range (default of 0 deviant bases).
    * If your data is paired-end, select the proper checkbox; this will cause each read to be internally split down the middle and filters applied to each half using the offsets specified.

**Advance Options:**
    * You can specify any number of advanced filters.
    * 5' and 3' offsets are defined, starting at zero, increasing from the respective end of the reads. For example, a quality string of "ABCDEFG", with 5' and 3' offsets of 1 and 1, respectively, specified will yield "BCDEF".
    * You can specify either absolute offset values, or percentage offset values. *Absolute Values* based offsets are useful for fixed length reads (e.g. Illumina or SOLiD data). *Percentage of Read Length* based offsets are useful for variable length reads (e.g. 454 data). When using the percent-based method, offsets are rounded to the nearest integer.
    * The user specifies the aggregating action (min, max, sum, mean) to perform on the quality score values found between the specified offsets to be used with the user defined comparison operation and comparison value.
    * If a set of offsets is specified that causes the remaining quality score list to be of length zero, then the read will **pass** the quality filter unless the size range filter is used to remove these reads.

-----

.. class:: warningmark

Adapter bases in color space reads are excluded from filtering.

------

</help>

<citations>
  <citation type="doi">10.1093/bioinformatics/btq281</citation>
</citations>

</tool>


text:
using UnityEngine;
using System.Collections;

public class PanelSwith2 : MonoBehaviour
{
    public bool sb2 = false;
    public bool bl = true;
    public Renderer sl;
    private GameObject l2;
    private Light light2;

    void Start()
    {
        l2 = GameObject.Find("Point light2").gameObject;
        light2 = l2.GetComponent<Light>();
        sl = sl.transform.GetComponent<Renderer>();
        sl.material.color = Color.red;
        light2.color = Color.red;
    }

    void OnCollisionStay(Collision col)
    {
        if (col.gameObject.tag == "Player" || col.gameObject.tag == "Cat")
        {
            sb2 = true;
            sl.material.color = Color.blue;
            light2.color = Color.cyan;
        }
    }

    void OnCollisionExit(Collision col)
    {
        if (col.gameObject.tag == "Player" || col.gameObject.tag == "Cat")
        {
            sb2 = false;
            if (bl)
            {
                sl.material.color = Color.red;
                light2.color = Color.red;
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
'''
@author: shylent
'''
from tftp.datagram import (split_opcode, WireProtocolError, TFTPDatagramFactory,
    RQDatagram, DATADatagram, ACKDatagram, ERRORDatagram, errors, OP_RRQ, OP_WRQ,
    OACKDatagram)
from tftp.errors import OptionsDecodeError
from twisted.trial import unittest

class OpcodeProcessing(unittest.TestCase):

    def test_zero_length(self):
        self.assertRaises(WireProtocolError, split_opcode, '')

    def test_incomplete_opcode(self):
        self.assertRaises(WireProtocolError, split_opcode, '0')

    def test_empty_payload(self):
        self.assertEqual(split_opcode('\x00\x01'), (1, ''))

    def test_non_empty_payload(self):
        self.assertEqual(split_opcode('\x00\x01foo'), (1, 'foo'))

    def test_unknown_opcode(self):
        opcode = 17
        self.assertRaises(WireProtocolError, TFTPDatagramFactory, opcode, 'foobar')

class ConcreteDatagrams(unittest.TestCase):

    def test_rq(self):
        # Only one field - not ok
        self.assertRaises(WireProtocolError, RQDatagram.from_wire, 'foobar')
        # Two fields - ok (unterminated, slight deviation from the spec)
        dgram = RQDatagram.from_wire('foo\x00bar')
        dgram.opcode = OP_RRQ
        self.assertEqual(dgram.to_wire(), '\x00\x01foo\x00bar\x00')
        # Two fields terminated is ok too
        RQDatagram.from_wire('foo\x00bar\x00')
        dgram.opcode = OP_RRQ
        self.assertEqual(dgram.to_wire(), '\x00\x01foo\x00bar\x00')
        # More than two fields is also ok (unterminated, slight deviation from the spec)
        dgram = RQDatagram.from_wire('foo\x00bar\x00baz\x00spam')
        self.assertEqual(dgram.options, {'baz':'spam'})
        dgram.opcode = OP_WRQ
        self.assertEqual(dgram.to_wire(), '\x00\x02foo\x00bar\x00baz\x00spam\x00')
        # More than two fields is also ok (terminated)
        dgram = RQDatagram.from_wire('foo\x00bar\x00baz\x00spam\x00one\x00two\x00')
        self.assertEqual(dgram.options, {'baz':'spam', 'one':'two'})
        dgram.opcode = OP_RRQ
        self.assertEqual(dgram.to_wire(),
            '\x00\x01foo\x00bar\x00baz\x00spam\x00one\x00two\x00')
        # Option with no value - not ok
        self.assertRaises(OptionsDecodeError,
            RQDatagram.from_wire, 'foo\x00bar\x00baz\x00spam\x00one\x00')
        # Duplicate option - not ok
        self.assertRaises(OptionsDecodeError,
            RQDatagram.from_wire,
            'foo\x00bar\x00baz\x00spam\x00one\x00two\x00baz\x00val\x00')

    def test_rrq(self):
        self.assertEqual(TFTPDatagramFactory(*split_opcode('\x00\x01foo\x00bar')).to_wire(),
                         '\x00\x01foo\x00bar\x00')

    def test_wrq(self):
        self.assertEqual(TFTPDatagramFactory(*split_opcode('\x00\x02foo\x00bar')).to_wire(),
                         '\x00\x02foo\x00bar\x00')

    def test_oack(self):
        # Zero options (I don't know if it is ok, the standard doesn't say anything)
        dgram = OACKDatagram.from_wire('')
        self.assertEqual(dgram.to_wire(), '\x00\x06')
        # One option, terminated
        dgram = OACKDatagram.from_wire('foo\x00bar\x00')
        self.assertEqual(dgram.options, {'foo':'bar'})
        self.assertEqual(dgram.to_wire(), '\x00\x06foo\x00bar\x00')
        # Not terminated
        dgram = OACKDatagram.from_wire('foo\x00bar\x00baz\x00spam')
        self.assertEqual(dgram.options, {'foo':'bar', 'baz':'spam'})
        self.assertEqual(dgram.to_wire(), '\x00\x06foo\x00bar\x00baz\x00spam\x00')
        # Option with no value
        self.assertRaises(OptionsDecodeError, OACKDatagram.from_wire,
            'foo\x00bar\x00baz')
        # Duplicate option
        self.assertRaises(OptionsDecodeError,
            OACKDatagram.from_wire,
            'baz\x00spam\x00one\x00two\x00baz\x00val\x00')

    def test_data(self):
        # Zero-length payload
        self.assertRaises(WireProtocolError, DATADatagram.from_wire, '')
        # One byte payload
        self.assertRaises(WireProtocolError, DATADatagram.from_wire, '\x00')
        # Zero-length data
        self.assertEqual(DATADatagram.from_wire('\x00\x01').to_wire(),
                         '\x00\x03\x00\x01')
        # Full-length data
        self.assertEqual(DATADatagram.from_wire('\x00\x01foobar').to_wire(),
                         '\x00\x03\x00\x01foobar')

    def test_ack(self):
        # Zero-length payload
        self.assertRaises(WireProtocolError, ACKDatagram.from_wire, '')
        # One byte payload
        self.assertRaises(WireProtocolError, ACKDatagram.from_wire, '\x00')
        # Full-length payload
        self.assertEqual(ACKDatagram.from_wire('\x00\x0a').blocknum, 10)
        self.assertEqual(ACKDatagram.from_wire('\x00\x0a').to_wire(), '\x00\x04\x00\x0a')
        # Extra data in payload
        self.assertRaises(WireProtocolError, ACKDatagram.from_wire, '\x00\x10foobarz')

    def test_error(self):
        # Zero-length payload
        self.assertRaises(WireProtocolError, ERRORDatagram.from_wire, '')
        # One byte payload
        self.assertRaises(WireProtocolError, ERRORDatagram.from_wire, '\x00')
        # Errorcode only (maybe this should fail)
        dgram = ERRORDatagram.from_wire('\x00\x01')
        self.assertEqual(dgram.errorcode, 1)
        self.assertEqual(dgram.errmsg, errors[1])
        # Errorcode with errstring - not terminated
        dgram = ERRORDatagram.from_wire('\x00\x01foobar')
        self.assertEqual(dgram.errorcode, 1)
        self.assertEqual(dgram.errmsg, 'foobar')
        # Errorcode with errstring - terminated
        dgram = ERRORDatagram.from_wire('\x00\x01foobar\x00')
        self.assertEqual(dgram.errorcode, 1)
        self.assertEqual(dgram.errmsg, 'foobar')
        # Unknown errorcode
        self.assertRaises(WireProtocolError, ERRORDatagram.from_wire, '\x00\x0efoobar')
        # Unknown errorcode in from_code
        self.assertRaises(WireProtocolError, ERRORDatagram.from_code, 13)
        # from_code with custom message
        dgram = ERRORDatagram.from_code(3, "I've accidentally the whole message")
        self.assertEqual(dgram.errorcode, 3)
        self.assertEqual(dgram.errmsg, "I've accidentally the whole message")
        self.assertEqual(dgram.to_wire(), "\x00\x05\x00\x03I've accidentally the whole message\x00")
        # from_code default message
        dgram = ERRORDatagram.from_code(3)
        self.assertEqual(dgram.errorcode, 3)
        self.assertEqual(dgram.errmsg, "Disk full or allocation exceeded")
        self.assertEqual(dgram.to_wire(), "\x00\x05\x00\x03Disk full or allocation exceeded\x00")


text:
/** \file matching_datatypes.cpp
 *	\brief matching data structures implementation
 *
 */
// Author: Tianwei Shen <shentianweipku@gmail.com>

#include "matching_datatypes.h"

#include <iostream>
#include "utils/data_types.h"
#include "utils/io_utils.h"

#ifdef LIBVOT_USE_OPENCV
#include "opencv_matching_api.h"
#endif

namespace vot {

// ====================================================
// ---------------- SiftMatchPair class ---------------
// ====================================================
SiftMatchPair::SiftMatchPair(std::string filename1)
{
	filename1_ = filename1;
	match_pairs_ = NULL;
}

SiftMatchPair::SiftMatchPair(int match_buf[][2], const int nmatch,
const std::vector<bool>& homography_inlier_flag, const std::vector<bool>& fundamental_inlier_flag,
std::string filename1, std::string filename2,
const Eigen::Matrix3d &homography, const Eigen::Matrix3d &fundamental_matrix,
int homography_inlier_num, int fundamental_inlier_num)
{
	match_pairs_ = new FeatureMatchPair[nmatch];
	nmatch_ = nmatch;
	filename1_ = filename1;
	filename2_ = filename2;
	homography_ = homography;
	fundamental_matrix_ = fundamental_matrix;
	homography_inlier_num_ = homography_inlier_num;
	fundamental_inlier_num_ = fundamental_inlier_num;

	for(size_t i = 0; i < (size_t)(nmatch_); i++)
	{
		match_pairs_[i].first = match_buf[i][0];
		match_pairs_[i].second = match_buf[i][1];
		match_pairs_[i].flag = (FeatureMatchPair::OUTLIER | homography_inlier_flag[i] | (fundamental_inlier_flag[i] << 1));
	}
}

// copy constructor
SiftMatchPair::SiftMatchPair(const SiftMatchPair &obj):
    filename1_(obj.filename1_), filename2_(obj.filename2_),
    nmatch_(obj.nmatch_), homography_inlier_num_(obj.homography_inlier_num_),
    fundamental_inlier_num_(obj.fundamental_inlier_num_),
    homography_(obj.homography_), fundamental_matrix_(obj.fundamental_matrix_)
{
	match_pairs_ = new FeatureMatchPair [obj.nmatch_];
	for (int i = 0; i < obj.nmatch_; i++) {
		match_pairs_[i] = obj.match_pairs_[i];
	}
}

bool SiftMatchPair::operator==(const SiftMatchPair &rhs)
{
	//NOTE(tianwei): this is a incomplete comparison
	if (this->filename1_ == rhs.filename1_ && this->filename2_ == rhs.filename2_ &&
	    this->nmatch_ == rhs.nmatch_ &&
	    this->fundamental_inlier_num_ == rhs.fundamental_inlier_num_ &&
	    this->homography_inlier_num_ == rhs.homography_inlier_num_)
		return true;
	else
		return false;
}

// copy assignment operator
SiftMatchPair & SiftMatchPair::operator=(const SiftMatchPair & rhs)
{
	if (*this == rhs)
		return *this;
	filename1_ = rhs.filename1_;
	filename2_ = rhs.filename2_;
	nmatch_ = rhs.nmatch_;
	homography_inlier_num_ = rhs.homography_inlier_num_;
	fundamental_inlier_num_ = rhs.fundamental_inlier_num_;
	homography_ = rhs.homography_;
	fundamental_matrix_ = rhs.fundamental_matrix_;
	FeatureMatchPair *originMatchPairs = match_pairs_;
	if (rhs.match_pairs_ != NULL) {
		match_pairs_ = new FeatureMatchPair [rhs.nmatch_];
		for(int i = 0; i < rhs.nmatch_; i++)
			match_pairs_[i] = rhs.match_pairs_[i];
	}
	else
		match_pairs_ = NULL;
	if (originMatchPairs != NULL)
		delete [] originMatchPairs;
	return *this;
}

// destructor
SiftMatchPair::~SiftMatchPair()
{
	if (match_pairs_ != NULL)
		delete [] match_pairs_;
}

bool SiftMatchPair::WriteSiftMatchPair(FILE *file) const
{
	// write information
	int filename2_length = filename2_.size();
	fwrite((void*)&filename2_length, sizeof(int), 1, file);
	fwrite((void*)filename2_.c_str(), sizeof(char), filename2_length, file);
	fwrite((void*)&nmatch_, sizeof(int), 1, file);
	fwrite((void*)&homography_inlier_num_, sizeof(int), 1, file);
	fwrite((void*)&fundamental_inlier_num_, sizeof(int), 1, file);

	fwrite((void*)homography_.data(), sizeof(double), 9, file);
	fwrite((void*)fundamental_matrix_.data(), sizeof(double), 9, file);

	// write match correspondence (int, int, char)
	fwrite((void*)match_pairs_, sizeof(FeatureMatchPair), nmatch_, file);

	return true;
}

bool SiftMatchPair::ReadSiftMatchPair(FILE *file)
{
	char filename2_temp[256];
	int filename2_length;

	int check = fread((void*)&filename2_length, sizeof(int), 1, file);
	if (check != 1)  return false;

	fread((void*)filename2_temp, sizeof(char), filename2_length, file);
	filename2_temp[filename2_length] = '\0';
	filename2_ = std::string(filename2_temp);

	fread((void*)&nmatch_, sizeof(int), 1, file);
	fread((void*)&homography_inlier_num_, sizeof(int), 1, file);
	fread((void*)&fundamental_inlier_num_, sizeof(int), 1, file);

	fread((void*)homography_.data(), sizeof(double), 9, file);
	fread((void*)fundamental_matrix_.data(), sizeof(double), 9, file);

	// read match correspondence (int, int, char)
	if (match_pairs_ != NULL) {
		delete [] match_pairs_;
		match_pairs_ = NULL;
	}
	match_pairs_ = new FeatureMatchPair [nmatch_];
	fread((void*)match_pairs_, nmatch_, sizeof(FeatureMatchPair), file);
	return true;
}

void SiftMatchPair::showInfo() const
{
	std::cout << "filename1: " << filename1_ << '\n';
	std::cout << "filename2: " << filename2_ << '\n';
	std::cout << "nmatch: " << nmatch_ << '\n';
	std::cout << "homography_inlier_num: " << homography_inlier_num_ << '\n';
	std::cout << "fundamental_inlier_num: " << fundamental_inlier_num_ << '\n';
	std::cout << "homography: " << homography_ << '\n';
	std::cout << "fundamental_matrix: " << fundamental_matrix_ << '\n';

	// random shuffle
	std::vector<int> index_array(nmatch_);
	for (size_t i = 0; i < index_array.size(); ++i) index_array[i] = static_cast<int>(i);
	std::random_shuffle(index_array.begin(), index_array.end());

	for (size_t i = 0; i < 10; i++) {
		int index = index_array[i];
		match_pairs_[index].showInfo();
	}
}

// Helper functions
const FeatureMatchPair* SiftMatchPair::matchPairs() const { return match_pairs_; }
FeatureMatchPair* SiftMatchPair::matchPairs() { return match_pairs_; }

// ====================================================
// ---------------- SiftMatchFile class ---------------
// ====================================================
SiftMatchFile::SiftMatchFile()
{
	image_num_ = 0;
}

SiftMatchFile::SiftMatchFile(std::string mat_path)
{
	mat_filename_ = mat_path;
	image_num_ = 0;
}

bool SiftMatchFile::ReadMatchFile(std::string mat_path)
{
	FILE *fd = fopen(mat_path.c_str(), "rb");
	if (fd == NULL) {
		std::cerr << "Can't read .mat file. Exit...\n";
		return false;
	}
	std::string sift_path = tw::IO::SplitPath(tw::IO::SplitPathExt(mat_path).first + ".sift").second;
	SiftMatchPair temp_mp = SiftMatchPair(sift_path);
	while (temp_mp.ReadSiftMatchPair(fd)) {
		match_pairs_.push_back(temp_mp);
	}
	image_num_ = match_pairs_.size();
	fclose(fd);
	return true;
}

const int & SiftMatchFile::getMatchNum() const { return image_num_; }
const std::string & SiftMatchFile::getMatFilename() const { return mat_filename_; }
const std::vector<SiftMatchPair> & SiftMatchFile::getSiftMatchPairs() const { return match_pairs_; }

// ====================================================
// ---------------- SiftMatcher class ---------------
// ====================================================
SiftMatcher::SiftMatcher(int max_sift,
                         MatcherDevice match_device,
                         int feature_dim,
                         DistanceType dist_type):
    max_sift_(max_sift),
    dist_type_(dist_type),
    feature_dim_(feature_dim),
    match_device_(match_device),
    matcher_(nullptr) {}

SiftMatcher::~SiftMatcher()
{
	if (matcher_) delete matcher_;
}

bool SiftMatcher::Init()
{
	if (matcher_) delete matcher_;
	switch (match_device_) {
		case SiftMatcher::SIFT_MATCH_CPU:
			matcher_ = new SiftMatcherCPU(max_sift_);
			break;
		case SiftMatcher::SIFT_MATCH_CUDA:
#ifdef LIBVOT_USE_CUDA
			matcher_ = new SiftMatcherCUDA(max_sift_);
			break;
#else
			matcher_ = NULL;
			return false;
#endif
		case SiftMatcher::SIFT_MATCH_GLSL:
			matcher_ = new SiftMatcherGL(max_sift_);
			break;
		case SiftMatcher::SIFT_MATCH_OPENCV:
#ifdef LIBVOT_USE_OPENCV
			matcher_ = new SiftMatcherOpencv(max_sift_);
			break;
#else
			match_device_ = SiftMatcher::SIFT_MATCH_CPU;
			return false;
#endif
		default:
			return false;
	}

	return true;
}

void SiftMatcher::SetMaxSift(int max_sift) { max_sift_ = max_sift; }

const int SiftMatcher::GetMaxSift() const { return (const int) max_sift_; }

bool SiftMatcher::SetMatchDevice(int device)
{
	switch (device) {
		case SiftMatcher::SIFT_MATCH_CPU:
			match_device_ = device;
			return true;
		case SiftMatcher::SIFT_MATCH_CUDA:
#ifdef LIBVOT_USE_CUDA				// if cude is available
			match_device_ = device;
			return true;
#else
			match_device_ = SiftMatcher::SIFT_MATCH_CPU;
			return false;
#endif
		case SiftMatcher::SIFT_MATCH_GLSL:
			match_device_ = device;
			return true;
		case SiftMatcher::SIFT_MATCH_OPENCV:
#ifdef LIBVOT_USE_OPENCV
			match_device_ = device;
			return true;
#else
			match_device_ = SiftMatcher::SIFT_MATCH_CPU;
			return false;
#endif
		default:
			match_device_ = SiftMatcher::SIFT_MATCH_CPU;
			return false;
	}
}

int SiftMatcher::GetMatchDevice() const { return (int) match_device_; }

bool SiftMatcher::SetDescriptors(int index, int num, const float *descriptors)
{
	if (matcher_)
		return matcher_->SetDescriptors(index, num, descriptors);
	return false;
}

bool SiftMatcher::SetDescriptors(int index, int num, const unsigned char *descriptors)
{
	if (matcher_)
		return matcher_->SetDescriptors(index, num, descriptors);
	return false;
}

bool SiftMatcher::SetLocation(int index, int feature_num, const float *loc, const int loc_dim)
{
	if (matcher_)
		return matcher_->SetLocation(index, feature_num, loc, loc_dim);
	return true;
}

int SiftMatcher::GetSiftMatch(int max_match,  int match_buffer[][2], int mutual_best_match)
{
	if (matcher_)
		return matcher_->GetSiftMatch(max_match, match_buffer, mutual_best_match);
	return false;
}

bool SiftMatcher::ShowMatches(std::string imagefile1, std::string imagefile2)
{
	if (matcher_)
		return matcher_->ShowMatches(imagefile1, imagefile2);
	return false;
}

// ====================================================
// ---------------- SiftMatcherCPU class ---------------
// ====================================================
SiftMatcherCPU::SiftMatcherCPU(int max_sift): SiftMatcher(max_sift)
{
}

SiftMatcherCPU::~SiftMatcherCPU() {}

bool SiftMatcherCPU::SetDescriptors(int index, int num, const unsigned char *descriptors)
{
	if (index != 0 && index != 1) {
		std::cerr << "[SiftMatcherCPU] SetDescriptors get index other than 0/1\n";
		return false;
	}
	if (num > max_sift_)
		num = max_sift_;
	num_sift_[index] = num;

	assert(sizeof(float) == 4);		// a float is 4 char
	sift_buffer_[index].resize(feature_dim_ * num/4);
	memcpy(&sift_buffer_[index][0], descriptors, feature_dim_ * num);

	return true;
}

bool SiftMatcherCPU::SetDescriptors(int index, int num, const float *descriptors)
{
	if (index != 0 || index != 1) {
		std::cerr << "[SiftMatcherCPU] SetDescriptors get index other than 0/1\n";
		return false;
	}
	if (num > max_sift_)
		num = max_sift_;
	num_sift_[index] = num;

	assert(sizeof(float) == 4);		// a float is 4 char
	sift_buffer_[index].resize(feature_dim_ * num/4);
	// convert float sift to unsigned char sift
	unsigned char *pub = (unsigned char*) &sift_buffer_[index][0];
	const int num_char = feature_dim_ * num;
	for (size_t i = 0; i < num_char; i++)
		pub[i] = int(512 * descriptors[i] + 0.5);

	return true;
}

float SiftMatcherCPU::GetDescriptorDist(std::vector<float> vec1, std::vector<float> vec2)
{
	float distance;
	switch(dist_type_) {
		case ARCCOS:
		{
			// compute l2 norm of each descriptors
			float vec1_norm = 0, vec2_norm = 0, dot_prod = 0;
			for (int i = 0; i < feature_dim_; i++) {
				vec1_norm += vec1[i] * vec2[i];
				vec2_norm += vec2[i] * vec2[i];
			}
			vec1_norm = std::sqrt(vec1_norm);
			vec2_norm = std::sqrt(vec2_norm);
			// normalize  each descriptor using l2norm
			for (int i = 0; i < feature_dim_; i++) {
				vec1[i] /= vec1_norm;
				vec2[i] /= vec2_norm;
				dot_prod += vec1[i] * vec2[i];
			}

			distance = dot_prod;
			break;
		}
		default:
			break;
	}
	return distance;
}

// brute force cpu matcher
int SiftMatcherCPU::GetSiftMatch(int max_match,
                                 int match_buffer[][2],
int mutual_best_match)
{
	int num_matches = 0;
	std::vector<float> vec1, vec2;
	vec1.resize(feature_dim_);
	vec2.resize(feature_dim_);
	unsigned char *pv1 = (unsigned char*) &sift_buffer_[0][0];
	for (int i = 0, c1 = 0; i < num_sift_[0]; i++) {
		for(int j = 0; j < feature_dim_; j++, c1++)
			vec1[j] = pv1[c1];

		float best_match, sbest_match;
		int best_index = -1, sbest_index = -1;
		// initialize match distance
		switch (dist_type_) {
			case ARCCOS:
				best_match = -1; sbest_match = -1;
				break;
			default:	// TODO(tianwei): other distance type is invalid
				break;
		}
		unsigned char *pv2 = (unsigned char*) &sift_buffer_[1][0];
		for (int j = 0, c2 = 0; j < num_sift_[1]; j++) {
			for (int k = 0; k < feature_dim_; k++, c2++)
				vec2[k] = pv2[c2];
			float dist = GetDescriptorDist(vec1, vec2);
			if (dist > best_match) {
				sbest_match = best_match;
				sbest_index = best_index;
				best_match = dist;
				best_index = j;
			}
		}
		switch (dist_type_) {
			case ARCCOS:
			{
				const float distmax = 0.7;
				const float ratiomax = 0.8;
				if (best_match > distmax && (sbest_match/best_match) < ratiomax) {
					if (num_matches < max_match) {
						match_buffer[num_matches][0] = i;
						match_buffer[num_matches][1] = best_index;
						num_matches++;
					}
				}
				break;
			}
			default:
				break;
		}
	}

	return num_matches;
}

// ====================================================
// ---------------- SiftMatcherCUDA class ---------------
// ====================================================
SiftMatcherCUDA::SiftMatcherCUDA(int max_sift): SiftMatcher(max_sift)
{
}

SiftMatcherCUDA::~SiftMatcherCUDA()
{

}

int SiftMatcherCUDA::GetSiftMatch(int max_match,
                                  int match_buffer[][2],
int mutual_best_match)
{
	int num_matches = 0;

	return num_matches;
}

// ====================================================
// ---------------- SiftMatcherGLSL class ---------------
// ====================================================
SiftMatcherGL::SiftMatcherGL(int max_sift): SiftMatcher(max_sift)
{
}

SiftMatcherGL::~SiftMatcherGL()
{

}

int SiftMatcherGL::GetSiftMatch(int max_match,
                                int match_buffer[][2],
int mutual_best_match)
{
	int num_matches = 0;

	return num_matches;
}

}	// end of namespace vot


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>ALZW: alzw::stream_breader Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

ALZW

Main Page

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

alzw

stream_breader

Public Member Functions |
Protected Attributes |
List of all members

alzw::stream_breader Class Reference

Stream bit-reader.
 More...

#include <bit-io.hpp>

Inheritance diagram for alzw::stream_breader:

  <map id="alzw::stream_breader_map" name="alzw::stream_breader_map">
<area href="classalzw_1_1breader.html" title="Abstract bit-reader. " alt="alzw::breader" shape="rect" coords="0,0,132,24"/>
<area href="classalzw_1_1file__breader.html" title="File bit-reader. " alt="alzw::file_breader" shape="rect" coords="0,112,132,136"/>
</map>

Public Member Functions

 	stream_breader (FILE *stream)

 	Create a new bit-reader for a given stream.  More...

virtual int 	read (uint64_t &bits, int width)

 	Read a given number of bits.  More...

 Public Member Functions inherited from alzw::breader

virtual int 	read_int ()

 	Read integer in big endian order.  More...

virtual uint64_t 	read_gamma ()

 	Read a gamma-encoded number.  More...

virtual uint64_t 	read_delta ()

 	Read a delta-encoded number.  More...

virtual size_t 	read_str (char *buffer, size_t size)

 	Read a null-terminated string (max size - 1 characters will be read).  More...

Protected Attributes

FILE * 	stream

Detailed Description

Stream bit-reader.

Constructor & Destructor Documentation

          stream_breader::stream_breader
          (
          FILE *
          stream	)

Create a new bit-reader for a given stream.

Parameters

stream	stream

Member Function Documentation

          int stream_breader::read
          (
          uint64_t &
          bits,

          int
          width

          )

virtual

Read a given number of bits.

Bits will be read in big endian order and put into a given integer variable as its least significant bits. Note that up to 64 bits can be read at once.

Parameters

bits	output variable

width	number of bits to be read

Returns

number of bits actually read (0 means EOF)

Implements alzw::breader.

The documentation for this class was generated from the following files:

include/bit-io.hpp

src/bit-io.cpp

<address class="footer">
Generated on Thu Apr 16 2015 19:12:41 for ALZW by

 1.8.9.1
</address>


text:
layout: page
title: OTP Concurrency
category: advanced
order: 5
lang: vi
---

We've looked at the Elixir abstractions for concurrency but sometimes we need greater control and for that we turn to the OTP behaviors that Elixir built on.

In this lesson we'll focus on two important pieces: GenServers and GenEvents.

{% include toc.html %}

## GenServer

An OTP server is a module with the GenServer behavior that implements a set of callbacks.  At it's most basic level a GenServer is a loop that handles one request per iteration passing along an updated state.

To demonstrate the GenServer API we'll implement a basic queue to store and retrieve values.

To begin our GenServer we need to start it and handle the initialization. In most cases we'll want to link processes so we use `GenServer.start_link/3`.  We pass in the GenServer module we're starting, initial arguments, and a set of GenServer options.  The arguments are be passed to `GenServer.init/1` which sets the initial state through it's return value.  In our example the arguments will be our initial state:

```elixir
defmodule SimpleQueue do
  use GenServer

  @doc """
  Start our queue and link it.  This is a helper method
  """
  def start_link(state \\ []) do
    GenServer.start_link(__MODULE__, state, name: __MODULE__)
  end

  @doc """
  GenServer.init/1 callback
  """
  def init(state), do: {:ok, state}
end
```

### Synchronous Functions

It's often necessary to interact with GenServers in a synchronous way, calling a function and waiting for it's response.  To handle synchronous requests we need to implement the `GenServer.handle_call/3` callback which takes: the request, caller's PID, and existing state; it is expected to reply by returning a tuple: `{:reply, response, state}`.

With pattern matching we can define callbacks for many different requests and states. A complete list of accepted return values can be found in the [`GenServer.handle_call/3`](http://elixir-lang.org/docs/stable/elixir/GenServer.html#c:handle_call/3) docs.

To demonstrate synchronous requests let's add the ability to display our current queue and to remove a value:

```elixir
defmodule SimpleQueue do
  use GenServer

  ### GenServer API

  @doc """
  GenServer.init/1 callback
  """
  def init(state), do: {:ok, state}

  @doc """
  GenServer.handle_call/3 callback
  """
  def handle_call(:dequeue, _from, [value|state]) do
    {:reply, value, state}
  end
  def handle_call(:dequeue, _from, []), do: {:reply, nil, []}

  def handle_call(:queue, _from, state), do: {:reply, state, state}

  ### Client API / Helper methods

  def start_link(state \\ []) do
    GenServer.start_link(__MODULE__, state, name: __MODULE__)
  end

  def queue, do: GenServer.call(__MODULE__, :queue)
  def dequeue, do: GenServer.call(__MODULE__, :dequeue)
end

```

Let's start our SimpleQueue and test out our new dequeue functionality:

```elixir
iex> SimpleQueue.start_link([1, 2, 3])
{:ok, #PID<0.90.0>}
iex> SimpleQueue.dequeue
1
iex> SimpleQueue.dequeue
2
iex> SimpleQueue.queue
[3]
```

### Asynchronous Functions

Asynchronous requests are handled with the `handle_cast/2` callback.  This works much like `handle_cast/3` but does not receive the caller and is not expected to reply.

We'll implement our enqueue functionality to be asynchronous, updating the queue but not blocking our current execution:

```elixir
defmodule SimpleQueue do
  use GenServer

  ### GenServer API

  @doc """
  GenServer.init/1 callback
  """
  def init(state), do: {:ok, state}

  @doc """
  GenServer.handle_call/3 callback
  """
  def handle_call(:dequeue, _from, [value|state]) do
    {:reply, value, state}
  end
  def handle_call(:dequeue, _from, []), do: {:reply, nil, []}

  def handle_call(:queue, _from, state), do: {:reply, state, state}

  @doc """
  GenServer.handle_cast/2 callback
  """
  def handle_cast({:enqueue, value}, state) do
    {:noreply, state ++ [value]}
  end

  ### Client API / Helper methods

  def start_link(state \\ []) do
    GenServer.start_link(__MODULE__, state, name: __MODULE__)
  end
  def queue, do: GenServer.call(__MODULE__, :queue)
  def enqueue(value), do: GenServer.cast(__MODULE__, {:enqueue, value})
  def dequeue, do: GenServer.call(__MODULE__, :dequeue)
end
```

Let's put our new functionality to use:

```elixir
iex> SimpleQueue.start_link([1, 2, 3])
{:ok, #PID<0.100.0>}
iex> SimpleQueue.queue
[1, 2, 3]
iex> SimpleQueue.enqueue(20)
:ok
iex> SimpleQueue.queue
[1, 2, 3, 20]
```

For more information check out the official [GenServer](http://elixir-lang.org/docs/stable/elixir/GenServer.html#content) documentation.

## GenEvent

We learned that GenServers are processes that can maintain state and handle synchronous and asynchronous requests so what is a GenEvent?  GenEvents are generic event managers that receive incoming events and notify subscribed consumers.  They provide a mechanism for dynamically adding and removing handlers to flow of events.

### Handling Events

The most important callback in GenEvents as you can imagine is `handle_event/2`.  This receives the event and the handler's current state and is expected to return a tuple: `{:ok, state}`.

To demonstrate the GenEvent functionality let's start by creating two handlers, one to keep a log of messages and the other to persist them (theoretically):

```elixir
defmodule LoggerHandler do
  use GenEvent

  def handle_event({:msg, msg}, messages) do
    IO.puts "Logging new message: #{msg}"
    {:ok, [msg|messages]}
  end
end

defmodule PersistenceHandler do
  use GenEvent

  def handle_event({:msg, msg}, state) do
    IO.puts "Persisting log message: #{msg}"

    # Save message

    {:ok, state}
  end
end
```

### Calling Handlers

In addition to `handle_event/2` GenEvents also support `handle_call/2` among other callbacks.  With `handle_call/2` we can handle specific synchronous messages with our handler.

Let's update our `LoggerHandler` to include a method for retrieving the current message log:

```elixir
defmodule LoggerHandler do
  use GenEvent

  def handle_event({:msg, msg}, messages) do
    IO.puts "Logging new message: #{msg}"
    {:ok, [msg|messages]}
  end

  def handle_call(:messages, messages) do
    {:ok, Enum.reverse(messages), messages}
  end
end
```

### Using GenEvents

With our handlers ready to go we need to familiarize ourselves with a few of GenEvent's functions.  The three most important functions are: `add_handler/3`, `notify/2`, and `call/4`.  These allow us to add handlers, broadcast new messages, and call specific handler functions respectively.

If we put it all together we can see our handlers in action:

```elixir
iex> {:ok, pid} = GenEvent.start_link([])
iex> GenEvent.add_handler(pid, LoggerHandler, [])
iex> GenEvent.add_handler(pid, PersistenceHandler, [])

iex> GenEvent.notify(pid, {:msg, "Hello World"})
Logging new message: Hello World
Persisting log message: Hello World

iex> GenEvent.call(pid, LoggerHandler, :messages)
["Hello World"]
```

See the official [GenEvent](http://elixir-lang.org/docs/stable/elixir/GenEvent.html#content) documentation for a complete list of callbacks and GenEvent functionality.


text:
using System;
using System.Collections.Generic;

using Xamarin.Forms;

namespace Moments
{
	public partial class FriendRequestsPage : BasePage
	{
		public FriendRequestsPage ()
		{
			BindingContext = new FriendRequestsPage ();

			InitializeComponent ();
			SetupToolbar ();
			SetupEventHandlers ();
		}

		private FriendRequestsViewModel ViewModel
		{
			get { return BindingContext as FriendRequestsViewModel; }
		}

		private void SetupToolbar ()
		{
			ToolbarItems.Add (new ToolbarItem {
				Icon = Images.CancelButton,
				Command = new Command (() => Navigation.PopModalAsync (true)),
				Priority = 1
			});
		}

		private void SetupEventHandlers ()
		{
			pendingFriendsListView.Refreshing += (sender, e) => {
				pendingFriendsListView.IsRefreshing = true;
				ViewModel.FetchFriendRequestsCommand.Execute (null);
				pendingFriendsListView.IsRefreshing = false;
			};
		}
	}
}


text:
import collections
from concurrent import futures
import contextlib
import distutils.spawn
import errno
import os
import shutil
import subprocess
import sys
import tempfile
import threading
import unittest

from six import moves

import grpc
from tests.unit.framework.common import test_constants

import tests.protoc_plugin.protos.payload.test_payload_pb2 as payload_pb2
import tests.protoc_plugin.protos.requests.r.test_requests_pb2 as request_pb2
import tests.protoc_plugin.protos.responses.test_responses_pb2 as response_pb2
import tests.protoc_plugin.protos.service.test_service_pb2_grpc as service_pb2_grpc

# Identifiers of entities we expect to find in the generated module.
STUB_IDENTIFIER = 'TestServiceStub'
SERVICER_IDENTIFIER = 'TestServiceServicer'
ADD_SERVICER_TO_SERVER_IDENTIFIER = 'add_TestServiceServicer_to_server'

class _ServicerMethods(object):

    def __init__(self):
        self._condition = threading.Condition()
        self._paused = False
        self._fail = False

    @contextlib.contextmanager
    def pause(self):  # pylint: disable=invalid-name
        with self._condition:
            self._paused = True
        yield
        with self._condition:
            self._paused = False
            self._condition.notify_all()

    @contextlib.contextmanager
    def fail(self):  # pylint: disable=invalid-name
        with self._condition:
            self._fail = True
        yield
        with self._condition:
            self._fail = False

    def _control(self):  # pylint: disable=invalid-name
        with self._condition:
            if self._fail:
                raise ValueError()
            while self._paused:
                self._condition.wait()

    def UnaryCall(self, request, unused_rpc_context):
        response = response_pb2.SimpleResponse()
        response.payload.payload_type = payload_pb2.COMPRESSABLE
        response.payload.payload_compressable = 'a' * request.response_size
        self._control()
        return response

    def StreamingOutputCall(self, request, unused_rpc_context):
        for parameter in request.response_parameters:
            response = response_pb2.StreamingOutputCallResponse()
            response.payload.payload_type = payload_pb2.COMPRESSABLE
            response.payload.payload_compressable = 'a' * parameter.size
            self._control()
            yield response

    def StreamingInputCall(self, request_iter, unused_rpc_context):
        response = response_pb2.StreamingInputCallResponse()
        aggregated_payload_size = 0
        for request in request_iter:
            aggregated_payload_size += len(request.payload.payload_compressable)
        response.aggregated_payload_size = aggregated_payload_size
        self._control()
        return response

    def FullDuplexCall(self, request_iter, unused_rpc_context):
        for request in request_iter:
            for parameter in request.response_parameters:
                response = response_pb2.StreamingOutputCallResponse()
                response.payload.payload_type = payload_pb2.COMPRESSABLE
                response.payload.payload_compressable = 'a' * parameter.size
                self._control()
                yield response

    def HalfDuplexCall(self, request_iter, unused_rpc_context):
        responses = []
        for request in request_iter:
            for parameter in request.response_parameters:
                response = response_pb2.StreamingOutputCallResponse()
                response.payload.payload_type = payload_pb2.COMPRESSABLE
                response.payload.payload_compressable = 'a' * parameter.size
                self._control()
                responses.append(response)
        for response in responses:
            yield response

class _Service(
        collections.namedtuple('_Service', ('servicer_methods', 'server',
                                            'stub',))):
    """A live and running service.

  Attributes:
    servicer_methods: The _ServicerMethods servicing RPCs.
    server: The grpc.Server servicing RPCs.
    stub: A stub on which to invoke RPCs.
  """

def _CreateService():
    """Provides a servicer backend and a stub.

  Returns:
    A _Service with which to test RPCs.
  """
    servicer_methods = _ServicerMethods()

    class Servicer(getattr(service_pb2_grpc, SERVICER_IDENTIFIER)):

        def UnaryCall(self, request, context):
            return servicer_methods.UnaryCall(request, context)

        def StreamingOutputCall(self, request, context):
            return servicer_methods.StreamingOutputCall(request, context)

        def StreamingInputCall(self, request_iter, context):
            return servicer_methods.StreamingInputCall(request_iter, context)

        def FullDuplexCall(self, request_iter, context):
            return servicer_methods.FullDuplexCall(request_iter, context)

        def HalfDuplexCall(self, request_iter, context):
            return servicer_methods.HalfDuplexCall(request_iter, context)

    server = grpc.server(
        futures.ThreadPoolExecutor(max_workers=test_constants.POOL_SIZE))
    getattr(service_pb2_grpc, ADD_SERVICER_TO_SERVER_IDENTIFIER)(Servicer(),
                                                                 server)
    port = server.add_insecure_port('[::]:0')
    server.start()
    channel = grpc.insecure_channel('localhost:{}'.format(port))
    stub = getattr(service_pb2_grpc, STUB_IDENTIFIER)(channel)
    return _Service(servicer_methods, server, stub)

def _CreateIncompleteService():
    """Provides a servicer backend that fails to implement methods and its stub.

  Returns:
    A _Service with which to test RPCs. The returned _Service's
      servicer_methods implements none of the methods required of it.
  """

    class Servicer(getattr(service_pb2_grpc, SERVICER_IDENTIFIER)):
        pass

    server = grpc.server(
        futures.ThreadPoolExecutor(max_workers=test_constants.POOL_SIZE))
    getattr(service_pb2_grpc, ADD_SERVICER_TO_SERVER_IDENTIFIER)(Servicer(),
                                                                 server)
    port = server.add_insecure_port('[::]:0')
    server.start()
    channel = grpc.insecure_channel('localhost:{}'.format(port))
    stub = getattr(service_pb2_grpc, STUB_IDENTIFIER)(channel)
    return _Service(None, server, stub)

def _streaming_input_request_iterator():
    for _ in range(3):
        request = request_pb2.StreamingInputCallRequest()
        request.payload.payload_type = payload_pb2.COMPRESSABLE
        request.payload.payload_compressable = 'a'
        yield request

def _streaming_output_request():
    request = request_pb2.StreamingOutputCallRequest()
    sizes = [1, 2, 3]
    request.response_parameters.add(size=sizes[0], interval_us=0)
    request.response_parameters.add(size=sizes[1], interval_us=0)
    request.response_parameters.add(size=sizes[2], interval_us=0)
    return request

def _full_duplex_request_iterator():
    request = request_pb2.StreamingOutputCallRequest()
    request.response_parameters.add(size=1, interval_us=0)
    yield request
    request = request_pb2.StreamingOutputCallRequest()
    request.response_parameters.add(size=2, interval_us=0)
    request.response_parameters.add(size=3, interval_us=0)
    yield request

class PythonPluginTest(unittest.TestCase):
    """Test case for the gRPC Python protoc-plugin.

  While reading these tests, remember that the futures API
  (`stub.method.future()`) only gives futures for the *response-unary*
  methods and does not exist for response-streaming methods.
  """

    def testImportAttributes(self):
        # check that we can access the generated module and its members.
        self.assertIsNotNone(getattr(service_pb2_grpc, STUB_IDENTIFIER, None))
        self.assertIsNotNone(
            getattr(service_pb2_grpc, SERVICER_IDENTIFIER, None))
        self.assertIsNotNone(
            getattr(service_pb2_grpc, ADD_SERVICER_TO_SERVER_IDENTIFIER, None))

    def testUpDown(self):
        service = _CreateService()
        self.assertIsNotNone(service.servicer_methods)
        self.assertIsNotNone(service.server)
        self.assertIsNotNone(service.stub)

    def testIncompleteServicer(self):
        service = _CreateIncompleteService()
        request = request_pb2.SimpleRequest(response_size=13)
        with self.assertRaises(grpc.RpcError) as exception_context:
            service.stub.UnaryCall(request)
        self.assertIs(exception_context.exception.code(),
                      grpc.StatusCode.UNIMPLEMENTED)

    def testUnaryCall(self):
        service = _CreateService()
        request = request_pb2.SimpleRequest(response_size=13)
        response = service.stub.UnaryCall(request)
        expected_response = service.servicer_methods.UnaryCall(
            request, 'not a real context!')
        self.assertEqual(expected_response, response)

    def testUnaryCallFuture(self):
        service = _CreateService()
        request = request_pb2.SimpleRequest(response_size=13)
        # Check that the call does not block waiting for the server to respond.
        with service.servicer_methods.pause():
            response_future = service.stub.UnaryCall.future(request)
        response = response_future.result()
        expected_response = service.servicer_methods.UnaryCall(
            request, 'not a real RpcContext!')
        self.assertEqual(expected_response, response)

    def testUnaryCallFutureExpired(self):
        service = _CreateService()
        request = request_pb2.SimpleRequest(response_size=13)
        with service.servicer_methods.pause():
            response_future = service.stub.UnaryCall.future(
                request, timeout=test_constants.SHORT_TIMEOUT)
            with self.assertRaises(grpc.RpcError) as exception_context:
                response_future.result()
        self.assertIs(exception_context.exception.code(),
                      grpc.StatusCode.DEADLINE_EXCEEDED)
        self.assertIs(response_future.code(), grpc.StatusCode.DEADLINE_EXCEEDED)

    def testUnaryCallFutureCancelled(self):
        service = _CreateService()
        request = request_pb2.SimpleRequest(response_size=13)
        with service.servicer_methods.pause():
            response_future = service.stub.UnaryCall.future(request)
            response_future.cancel()
        self.assertTrue(response_future.cancelled())
        self.assertIs(response_future.code(), grpc.StatusCode.CANCELLED)

    def testUnaryCallFutureFailed(self):
        service = _CreateService()
        request = request_pb2.SimpleRequest(response_size=13)
        with service.servicer_methods.fail():
            response_future = service.stub.UnaryCall.future(request)
            self.assertIsNotNone(response_future.exception())
        self.assertIs(response_future.code(), grpc.StatusCode.UNKNOWN)

    def testStreamingOutputCall(self):
        service = _CreateService()
        request = _streaming_output_request()
        responses = service.stub.StreamingOutputCall(request)
        expected_responses = service.servicer_methods.StreamingOutputCall(
            request, 'not a real RpcContext!')
        for expected_response, response in moves.zip_longest(expected_responses,
                                                             responses):
            self.assertEqual(expected_response, response)

    def testStreamingOutputCallExpired(self):
        service = _CreateService()
        request = _streaming_output_request()
        with service.servicer_methods.pause():
            responses = service.stub.StreamingOutputCall(
                request, timeout=test_constants.SHORT_TIMEOUT)
            with self.assertRaises(grpc.RpcError) as exception_context:
                list(responses)
        self.assertIs(exception_context.exception.code(),
                      grpc.StatusCode.DEADLINE_EXCEEDED)

    def testStreamingOutputCallCancelled(self):
        service = _CreateService()
        request = _streaming_output_request()
        responses = service.stub.StreamingOutputCall(request)
        next(responses)
        responses.cancel()
        with self.assertRaises(grpc.RpcError) as exception_context:
            next(responses)
        self.assertIs(responses.code(), grpc.StatusCode.CANCELLED)

    def testStreamingOutputCallFailed(self):
        service = _CreateService()
        request = _streaming_output_request()
        with service.servicer_methods.fail():
            responses = service.stub.StreamingOutputCall(request)
            self.assertIsNotNone(responses)
            with self.assertRaises(grpc.RpcError) as exception_context:
                next(responses)
        self.assertIs(exception_context.exception.code(),
                      grpc.StatusCode.UNKNOWN)

    def testStreamingInputCall(self):
        service = _CreateService()
        response = service.stub.StreamingInputCall(
            _streaming_input_request_iterator())
        expected_response = service.servicer_methods.StreamingInputCall(
            _streaming_input_request_iterator(), 'not a real RpcContext!')
        self.assertEqual(expected_response, response)

    def testStreamingInputCallFuture(self):
        service = _CreateService()
        with service.servicer_methods.pause():
            response_future = service.stub.StreamingInputCall.future(
                _streaming_input_request_iterator())
        response = response_future.result()
        expected_response = service.servicer_methods.StreamingInputCall(
            _streaming_input_request_iterator(), 'not a real RpcContext!')
        self.assertEqual(expected_response, response)

    def testStreamingInputCallFutureExpired(self):
        service = _CreateService()
        with service.servicer_methods.pause():
            response_future = service.stub.StreamingInputCall.future(
                _streaming_input_request_iterator(),
                timeout=test_constants.SHORT_TIMEOUT)
            with self.assertRaises(grpc.RpcError) as exception_context:
                response_future.result()
        self.assertIsInstance(response_future.exception(), grpc.RpcError)
        self.assertIs(response_future.exception().code(),
                      grpc.StatusCode.DEADLINE_EXCEEDED)
        self.assertIs(exception_context.exception.code(),
                      grpc.StatusCode.DEADLINE_EXCEEDED)

    def testStreamingInputCallFutureCancelled(self):
        service = _CreateService()
        with service.servicer_methods.pause():
            response_future = service.stub.StreamingInputCall.future(
                _streaming_input_request_iterator())
            response_future.cancel()
        self.assertTrue(response_future.cancelled())
        with self.assertRaises(grpc.FutureCancelledError):
            response_future.result()

    def testStreamingInputCallFutureFailed(self):
        service = _CreateService()
        with service.servicer_methods.fail():
            response_future = service.stub.StreamingInputCall.future(
                _streaming_input_request_iterator())
            self.assertIsNotNone(response_future.exception())
            self.assertIs(response_future.code(), grpc.StatusCode.UNKNOWN)

    def testFullDuplexCall(self):
        service = _CreateService()
        responses = service.stub.FullDuplexCall(_full_duplex_request_iterator())
        expected_responses = service.servicer_methods.FullDuplexCall(
            _full_duplex_request_iterator(), 'not a real RpcContext!')
        for expected_response, response in moves.zip_longest(expected_responses,
                                                             responses):
            self.assertEqual(expected_response, response)

    def testFullDuplexCallExpired(self):
        request_iterator = _full_duplex_request_iterator()
        service = _CreateService()
        with service.servicer_methods.pause():
            responses = service.stub.FullDuplexCall(
                request_iterator, timeout=test_constants.SHORT_TIMEOUT)
            with self.assertRaises(grpc.RpcError) as exception_context:
                list(responses)
        self.assertIs(exception_context.exception.code(),
                      grpc.StatusCode.DEADLINE_EXCEEDED)

    def testFullDuplexCallCancelled(self):
        service = _CreateService()
        request_iterator = _full_duplex_request_iterator()
        responses = service.stub.FullDuplexCall(request_iterator)
        next(responses)
        responses.cancel()
        with self.assertRaises(grpc.RpcError) as exception_context:
            next(responses)
        self.assertIs(exception_context.exception.code(),
                      grpc.StatusCode.CANCELLED)

    def testFullDuplexCallFailed(self):
        request_iterator = _full_duplex_request_iterator()
        service = _CreateService()
        with service.servicer_methods.fail():
            responses = service.stub.FullDuplexCall(request_iterator)
            with self.assertRaises(grpc.RpcError) as exception_context:
                next(responses)
        self.assertIs(exception_context.exception.code(),
                      grpc.StatusCode.UNKNOWN)

    def testHalfDuplexCall(self):
        service = _CreateService()

        def half_duplex_request_iterator():
            request = request_pb2.StreamingOutputCallRequest()
            request.response_parameters.add(size=1, interval_us=0)
            yield request
            request = request_pb2.StreamingOutputCallRequest()
            request.response_parameters.add(size=2, interval_us=0)
            request.response_parameters.add(size=3, interval_us=0)
            yield request

        responses = service.stub.HalfDuplexCall(half_duplex_request_iterator())
        expected_responses = service.servicer_methods.HalfDuplexCall(
            half_duplex_request_iterator(), 'not a real RpcContext!')
        for expected_response, response in moves.zip_longest(expected_responses,
                                                             responses):
            self.assertEqual(expected_response, response)

    def testHalfDuplexCallWedged(self):
        condition = threading.Condition()
        wait_cell = [False]

        @contextlib.contextmanager
        def wait():  # pylint: disable=invalid-name
            # Where's Python 3's 'nonlocal' statement when you need it?
            with condition:
                wait_cell[0] = True
            yield
            with condition:
                wait_cell[0] = False
                condition.notify_all()

        def half_duplex_request_iterator():
            request = request_pb2.StreamingOutputCallRequest()
            request.response_parameters.add(size=1, interval_us=0)
            yield request
            with condition:
                while wait_cell[0]:
                    condition.wait()

        service = _CreateService()
        with wait():
            responses = service.stub.HalfDuplexCall(
                half_duplex_request_iterator(),
                timeout=test_constants.SHORT_TIMEOUT)
            # half-duplex waits for the client to send all info
            with self.assertRaises(grpc.RpcError) as exception_context:
                next(responses)
        self.assertIs(exception_context.exception.code(),
                      grpc.StatusCode.DEADLINE_EXCEEDED)

if __name__ == '__main__':
    unittest.main(verbosity=2)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Model.Models
{
	public interface IContainerControlModel : IControlModel
	{
		IControlModel[] controls { get; }
		string bindingContext { get; } // TODO: think about moving this property to a separate interface between IContainerControlModel and IControlModel
	}
}


text:
iced-cream
==========

A Node module to help write cleaner code, especially around error checking, when using Iced Coffee Script

**iced-cream** contains these functions:

### _checkError(err, message, data, callback)_

Example:

```coffee
    ic = require 'iced-cream'

        ...

    await
        db.run "CREATE TABLE IF NOT EXISTS my_table (some_columb INTEGER, last_updated_time INTEGER)", {}, defer err
    ic.checkError err, "Failed setting up my_table table. Bailing.", { db: db }, callback
```

`err` gets checked for an error from the deferred callback. If there is an error, then the `message` is logged and the error is thrown, so that you stop proceeding down your current code path. `data` is just extra data to be logged. `callback` is the callback passed into your async function. If it is a function, it will be called with `err` in either the success or failure case

### _error(message, data, callback)_

Example:
```coffee
    ic = require 'iced-cream'

        ...

    # err from previous await block is null because everything
    # went fine, but we have a runtime problem we've detected based
    # on data we've received
    if someValue > maxValueItShouldBe
        ic.error "Your value is too big; we have a problem", { someValue: someValue, maxValueItShouldBe: maxValueItShouldBe }, callback
```

`message` is the error messsge you want to log; `data` is additional data for hte log; and `callback` is the callback passed into your async function. A new `Error` object will be created and pass as `err` to the callback in this case. And from there, we will throw that Error so that things don't continue down this code path since there is a problem. If you do want to continue down this code path, but want to log the error, you should be able to just use your logging module

### _assert(shouldBeTrue, message, data, callback)_

Asserts that something is true; if not, it calls the callback with an appropriate value of `err` and throws that AssertionError to stop executing the current code path.

Example:

```coffee
    ic = require 'iced-cream'
    await
        db_.run_ "DELETE FROM users WHERE userId = $userId", { $userId: userId }, defer(err, result)
    ic.assert (result.changes == 1), "When deleting user from database, changed #{ result.changes } rows (should have been exactly 1)", { userId: userId, result: result }, callback
```

### *saveTo(name, this_)*

A common pattern when using the iced REPL is to want to call a function,
capture its return value and then inspect and manipulate that value, or maybe
call another function with it. This is tricky in the world of async programming
since the value isn't actually returned but is instead passed on to the
callback, which then passes that on to another callback, etc.

To be able to work more easily with things in the shell, you can

```coffee
    ic = require 'iced-cream'
    model = require './model'
    ic.saveTo('feross') model.User.newUser, { name: "Feross Aboukhadijeh" }
```

And then once that code is finished running, the global variable `feross` will be set to the value of the new user object that was passed to the callback.

The `this_` parameter is optional and can be used if you want to store the
value not as a global, but as a property of some other object (which you
would pass in as `this_`)

### *deferThis(fn, this_)*

This is useful for times when a function transmits some information to
a callback by binding it to `this` instead of passing it as a parameter.
`deferThis` will add the value of `this` as an extra parameter to the
callback when it gets called.

`fn` is the function you want to transform; `this_` is optional;
if you need the function to be a bound method, you can specify the
object it should be bound to with `this_`.

Example:

One time when this is useful is when working with the node-sqlite3
library

The reason for this  here is that .run only calls a callback with
one paramter -- err -- and to pass values, it binds the `this` of
the callback to an object with lastID and/or changes if applicable
but `defer` doesn't give us access to `this` in any easy way, so
we use a helper function -- `ic.deferThis` -- to wrap the
original function call so it will call the callback with `this`
not only bound to it but passed as a last parameter, which lets
us capture its value using `defer`.

Also, we add this method *inside* the await block so that it is·
available even before the database has finished opening, since
that will sometimes happen and the database API supports that

```coffee
    db_.run_ = ic.deferThis db_.run, db_
```

### _setLogger(logger)_

You won't normally need to call this, but if you have some custom logger
that implements a similar interface to `winston` then you can call `setLogger` on it, and it will be used instead of vanilla winston.

Example:

```coffee
    ic = require 'iced-cream'
    log = require './log'
    ic.setLogger log
```


text:
{% if entry %}

{{ entry.title }}

{{ entry.published }}

{% firstof entry.summary entry.desc %}

    {% autoescape off %}
    {{ content }}
    {% endautoescape %}

  {% if comment %}

  {% endif %}

{% endif %}


text:
/*doc
---
title: Portals
name: portals_react
categories:
 - react_components_portals
 - react_all
---

npm install pui-react-portals --save

## Props

PortalSource/PortalDestination

Property | Required | Type | Default | Description
---------|----------|------|---------|------------
name | yes | String | | Use same name to connect sources and destinations

## Basic usage

Import the subcomponents:

```
import {PortalSource, PortalDestination} from 'pui-react-portals';
```

The `Portal` components render DOM nodes elsewhere on the page. This is useful for things like
modals, tooltips, and dropdowns, when you want to define the content near the trigger, but have
it display at the bottom of the page (generally to solve z-index and overflow incompatibilities).

For example, modals can be rendered at the bottom of `<body>`, but the React component that creates
the modal content (e.g. a `<button>`) does not have access to `<body>` directly.
If a `PortalDestination` is put at the bottom of `<body>`, a `PortalSource` can then be used
anywhere without knowing about `<body>`.

```react_example
<div>
  <section>
    <span>Content will be transported from here:</span>
    <PortalSource name="modal">Transported content</PortalSource>
  </section>
  <section className="mvxxl">Unrelated content</section>
  <section>
    <span>To here:</span>
    <PortalDestination name="modal"/>
  </section>
</div>
```
*/


text:
@extends('app-dashboard')

@section('content')

Dashboard

								 Transaksi Jual {{$transaksi_jual}}

							 Transaksi Beli {{$transaksi_beli}}

							 Rate Jual 1 BTC = Rp. {{number_format($bitcoin_rate->rate_jual, 2,'.', ',')}}

						 Rate Beli 1 BTC = Rp. {{number_format($bitcoin_rate->rate_beli, 2,'.', ',')}}

@endsection


text:
<!DOCTYPE html>

	<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no"/>
	<meta name="apple-mobile-web-app-capable" content="yes" />
	<title>Page Turning</title>
	<link href="../themes/common/PageTurning.css" rel="stylesheet">

Page Turning

<input type="button" onclick="add()" value="Add" style="width:50px">	index: <input id="input_add" style="width:20px;text-align:right" value="">

<input type="button" onclick="remove()" value="Remove" style="width:50px">	index: <input id="input_remove" style="width:20px;text-align:right" value="">

			<button onclick="prev()" style="width:50px">Prev</button>
			<button onclick="next()" style="width:50px">Next</button>

onPageTurned:


text:
Title: FastPM100 - High speed acquisition and visualization of ThorLabs PM100 power meter readings
Date: 2016-03-21
Category: articles
thumbnail_image: /images/wasatch-images/fastpm100_thumbnail.gif

Visualize much higher speed laser power meter readings than the [ThorLabs
Optical power
meter](https://www.thorlabs.com/software_pages/ViewSoftwarePage.cfm?Code=PM100x) software. Use [zmq](http://zeromq.org) and multiple visualization modes
to show instantaneous and long term laser power meter trends. This is
used at [Wasatch Photonics](http://wasatchphotonics.com) for laser output power stability of our laser
can diodes.

It's also useful for power on visualizations of the various mode hops
and other instabilities as the laser transitions through various
temperatures and feedback loops.

We use this in concert with a
[BoardTester](https://github.com/WasatchPhotonics/BoardTester) script to create a long term
data logging setup that also permits high resolution instantaneous
visualization.

FastPM100 is one of the first applications that uses the
[PySideApp](https://github.com/WasatchPhotonics/PySideApp)
starter project. This is essential for high speed visualization and
lag-free hardware acquisitions.

Available on [GitHub](https://github.com/WasatchPhotonics/FastPM100)


text:
<ivy-module version="1.0">
    <info organisation="edu.mit.broad" module="picard-private-parts" revision="2181" status="integration" publication="20120110094400" />
</ivy-module>


text:
package debop4s.data.orm.jtests.jpa.mysql;

import debop4s.data.orm.jpa.spring.AbstractJpaMySqlReplicationConfiguration;
import debop4s.data.orm.jtests.jpa.config.JpaAccount;
import debop4s.data.orm.jtests.mapping.Employee;
import org.hibernate.cache.rediscala.SingletonRedisRegionFactory;
import org.hibernate.cfg.Environment;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.util.Properties;

/**
 * 실제 제품에서는 AbstractJpaMySqlConfiguration을 상속 받으세요.
 *
 * @author sunghyouk.bae@gmail.com 2014. 9. 7.
 */
@Configuration
@EnableAspectJAutoProxy
@EnableTransactionManagement
@EnableJpaRepositories(basePackageClasses = { SimpleEntityRepository.class })
@ComponentScan(basePackageClasses = { SimpleEntityService.class })
public class JpaMySqlReplicationConfig extends AbstractJpaMySqlReplicationConfiguration {

    @Override
    public String[] getMappedPackageNames() {
        return new String[] {
                Employee.class.getPackage().getName(),
                JpaAccount.class.getPackage().getName()
        };
    }

    @Override
    public Properties jpaProperties() {
        Properties props = super.jpaProperties();

        props.put(Environment.HBM2DDL_AUTO, "update"); // create | spawn | spawn-drop | update | validate | none

        // 2nd cache
        props.put(Environment.USE_SECOND_LEVEL_CACHE, false);
        props.put(Environment.USE_QUERY_CACHE, false);
        props.put(Environment.CACHE_REGION_FACTORY, SingletonRedisRegionFactory.class.getName());
        props.put(Environment.CACHE_PROVIDER_CONFIG, "hibernate-redis.conf");

        return props;
    }

}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _classnames = require('classnames');

var _classnames2 = _interopRequireDefault(_classnames);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

var propTypes = {
    active: _react.PropTypes.bool,
    className: _react.PropTypes.string,
    component: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.element, _react.PropTypes.func]),
    cssPrefix: _react.PropTypes.string,
    onTabClick: _react.PropTypes.func,
    style: _react.PropTypes.object,
    tabId: _react.PropTypes.number
};

var defaultProps = {
    style: {}
};

var Tab = function Tab(props) {
    var _classNames;

    var active = props.active,
        className = props.className,
        component = props.component,
        children = props.children,
        cssPrefix = props.cssPrefix,
        onTabClick = props.onTabClick,
        style = props.style,
        tabId = props.tabId,
        otherProps = _objectWithoutProperties(props, ['active', 'className', 'component', 'children', 'cssPrefix', 'onTabClick', 'style', 'tabId']);

    var classes = (0, _classnames2.default)((_classNames = {}, _defineProperty(_classNames, cssPrefix + '__tab', true), _defineProperty(_classNames, 'is-active', active), _classNames), className);

    style.cursor = 'pointer';

    return _react2.default.createElement(component || 'a', _extends({
        className: classes,
        onClick: function onClick() {
            return onTabClick(tabId);
        },
        style: style
    }, otherProps), children);
};

Tab.propTypes = propTypes;
Tab.defaultProps = defaultProps;

exports.default = Tab;


text:
<?php namespace Phonad\Traits;

/**
 * Traversable provides operations that may be used in Traversable monads.
 */
trait Traversable
{
    /**
     * at returns a callback for retrieving a value of a keyed type at the given key.
     *
     * @param $key string
     */
    protected static function at($key)
    {
        return function ($element) use ($key) {
            if (is_array($element)) {
                return isset($element[$key])
                ? $element[$key]
                : null;
            }
            if (is_object($element)) {
                return property_exists($element, $key)
                ? $element->{$key}
                : null;
            }
            return null;
        };
    }
}


text:
require 'spec_helper'

describe SimplePaginate::ActiveRecordExtension do
  before :all do
    1.upto(100) {|i| User.create name: "user#{'%03d' % i}"}
  end

  after :all do
    DatabaseCleaner.clean_with(:truncation)
  end

  describe '#paginate' do
    subject { User.paginate(page: page) }

    context 'page 1' do
      let(:page) { 1 }

      it { expect(subject.first.name).to eq('user001') }
    end

    context 'page 2' do
      let(:page) { 2 }

      it { expect(subject.first.name).to eq('user026') }
    end

    context 'page < 1' do
      let(:page) { 0 }

      it { expect(subject.first.name).to eq('user001') }
    end

    context 'page > max page' do
      let(:page) { 5 }

      it { expect(subject).to be_empty }
    end
  end

  describe '#page' do
    subject { User.page(page) }

    context 'page 1' do
      let(:page) { 1 }

      it { expect(subject.first.name).to eq('user001') }
    end

    context 'page 2' do
      let(:page) { 2 }

      it { expect(subject.first.name).to eq('user026') }
    end

    context 'page < 1' do
      let(:page) { 0 }

      it { expect(subject.first.name).to eq('user001') }
    end

    context 'page > max page' do
      let(:page) { 5 }

      it { expect(subject).to be_empty }
    end
  end

  describe '#per' do
    context 'page 1 per 5' do
      subject { User.page(1).per(5) }
      it { expect(subject.last.name).to eq('user006') }
    end
  end

  describe '#current_page' do
    context 'page 1' do
      subject { User.paginate(page: 1) }
      it { expect(subject.current_page).to eq 1 }
    end
  end

  describe '#first_page?' do
    context 'on first page' do
      subject { User.paginate(page: 1) }
      it { expect(subject.first_page?).to be_truthy }
    end

    context 'not on first page' do
      subject { User.paginate(page: 2) }
      it { expect(subject.first_page?).to be_falsey }
    end
  end

  describe '#last_page?' do
    context 'on last page' do
      subject { User.paginate(page: 4) }

      it { expect(subject.last_page?).to be_truthy }
    end

    context 'not on last page' do
      subject { User.paginate(page: 3) }
      it { expect(subject.last_page?).to be_falsey }
    end
  end
end


text:
import $script = require('scriptjs');

const callback = (): void => console.log('done');

function main(): void {
  $script('foo.js', callback);
  $script(['foo.js', 'bar.js'], callback);

  $script('foo.js', 'foo', callback);
  $script(['foo.js', 'bar.js'], 'bundle', callback);

  $script('foo', callback);
  $script('bundle', callback);

  $script.ready('foo', callback);
  $script.ready('bundle', callback);

  $script.ready(['foo', 'bar', 'thunk'], callback, (missing: string[]): void => console.log('missing deps:', missing));

  $script.path('/js/modules/');

  $script.get('http://example.com/base.js', callback);

  $script.urlArgs('key=value&foo=bar');

  $script.order(['foo.js', 'bar.js'], 'bundle', callback);
}


text:
Use this Role to add a file to the management root on the ISAM Appliance.

## Requirements

start_config role is a required dependencies. It contains the Ansible Custom Modules and handlers.

## Role Variables

The following variables are required:
* create_mgmt_root_file_instance_id
* create_mgmt_root_file_id
* create_mgmt_root_file_name
* create_mgmt_root_file_contents

## Dependencies

start_config role is a required dependencies. It contains the Ansible Custom Modules and handlers.

## Example Playbook

Here is an example on how to use this role:

    - name: Add testpage to junction root
      hosts: restricted_nodes
      connection: local
      roles:
        - start_config
        - role: create_mgmt_root_file
          create_mgmt_root_file_instance_id: "rp-demo"
          create_mgmt_root_file_id: 'junction-root'
          create_mgmt_root_file_name: 'test.html'
          create_mgmt_root_file_contents: "{{ lookup('file', '/ansible/playbooks/isam-test-playbook/inventories/test/group_vars/restricted_nodes/junction-root/test.html') | replace('\n', '') }}"

Replacing newlines is required otherwise an EOL exception is thrown and playbook execution will fail.

## License

Apache

## Author Information

Dries Eestermans (dries.eestermans@is4u.be)


text:
Buttons

    <button mat-stroked-button matBadge="7" matBadgeDescription="7 unread messages">
      Inbox
    </button>

    <button mat-stroked-button matBadge="7" matBadgePosition="below after"
        matBadgeDescription="7 unread messages">
      Inbox
    </button>

    <button mat-stroked-button matBadge="7" disabled matBadgeDisabled
        matBadgeDescription="7 unread messages">
      Inbox
    </button>

    <button mat-stroked-button matBadge="7" matBadgeColor="accent"
        matBadgeDescription="7 unread messages">
      Inbox
    </button>

Icons

    <mat-icon [matBadge]="badgeContent">
      home
    </mat-icon>

    <mat-icon color="primary" matBadge="22" matBadgePosition="below after" matBadgeColor="accent">
      home
    </mat-icon>

    <mat-icon color="primary" matBadge="22" matBadgePosition="above before" matBadgeColor="warn">
      home
    </mat-icon>

    <mat-icon color="primary" matBadge="22" matBadgePosition="below before">
      home
    </mat-icon>

Size

    <mat-icon [matBadge]="badgeContent" matBadgeSize="small">
      home
    </mat-icon>
    <mat-icon [matBadge]="badgeContent" matBadgeSize="large">
      home
    </mat-icon>

Text

      Hello

      Hello

      Hello

      Hello

      Hello

      Aria

      Hidden

    <input type="text" [(ngModel)]="badgeContent" />
    <button (click)="visible = !visible">Toggle</button>


text:
namespace XSharp.Assembler.x86
{
    [XSharp.Assembler.OpCode("ror")]
    public class RotateRight : InstructionWithDestinationAndSourceAndSize {
    }
}


text:
_NFS_SH=1

# Checks if the NFS shared folder is already mounted on the Docker Machine.
#
# $1 - The Docker Machie name.
# $2 - Path to the mount directory to check.
nfs_is_mounted ()
{
  local DOCKER_MACHINE_NAME=$1
  local MOUNT_DIR=$2
  local HOST_IP=$(dm_host_ip $DOCKER_MACHINE_NAME)

  if run_as_user docker-machine ssh $DOCKER_MACHINE_NAME sudo df | grep -q "$HOST_IP:$MOUNT_DIR"; then
    return $true
  else
    return $false
  fi
}

# Configures the NFSD on Mac OS.
#
# $1 - The Docker Machie name.
# $2 - Path to the mount directory.
# $3 - NFS exports options for specifed directory. By default "-alldirs -maproot=0".
# $4 - Optional. Location to the NFSD config location. by default "/etc/exports".
nfs_setup_nfsd_on_host ()
{
  local DOCKER_MACHINE_NAME=$1
  local MOUNT_DIR=$2
  local NFS_CONFIG=$3;
  local OUTPUT_FILE=$4
  local IP=$(run_as_user docker-machine ip $DOCKER_MACHINE_NAME)

  if [[ -z $NFS_CONFIG ]]; then
    NFS_CONFIG="-alldirs -maproot=0"
  fi

  if [[ -z $OUTPUT_FILE ]]; then
    OUTPUT_FILE="/etc/exports"
  fi

  sed -i .bak "/# Generated by docker-dev-env/{N;d;}" $OUTPUT_FILE

  # Add new line at the end of file if file dosn't ends with new line
  if ! test `tail -c 1 $OUTPUT_FILE` && ! [[ -s $OUTPUT_FILE ]]; then
    printf "\n" >> $OUTPUT_FILE
  fi

  printf "# Generated by docker-dev-env\n$MOUNT_DIR $IP $NFS_CONFIG\n" >> $OUTPUT_FILE

  err_catch nfsd restart
  err_catch nfsd checkexports
}

# Mounts NFS shares on the Docker Machine.
#
# $1 - The Docker Machie name.
# $2 - Path to the mount directory.
# $3 - Mount opitions on the Docker Machine. By default "nolock,noacl,async".
nfs_setup_on_docker_machine ()
{
  local DOCKER_MACHINE_NAME=$1
  local MOUNT_DIR=$2
  local MOUNT_OPTIONS=$3;
  local HOST_IP=$(dm_host_ip $DOCKER_MACHINE_NAME)

  if [[ -z $MOUNT_OPTIONS ]]; then
    MOUNT_OPTIONS="nolock,noacl,async"
  fi

  local BOOTLOCAL_FILE='#/bin/bash
sudo umount /Users
sudo mkdir -p '$MOUNT_DIR'
sudo /usr/local/etc/init.d/nfs-client start
sudo mount -t nfs -o '$MOUNT_OPTIONS' '$HOST_IP':'$MOUNT_DIR' '$MOUNT_DIR

  run_as_user docker-machine ssh $DOCKER_MACHINE_NAME \
    "echo '$BOOTLOCAL_FILE' | sudo tee /var/lib/boot2docker/bootlocal.sh && sudo chmod +x /var/lib/boot2docker/bootlocal.sh" \
    > /dev/null

  if ! nfs_is_mounted $DOCKER_MACHINE_NAME $MOUNT_DIR; then
    dm_restart $DOCKER_MACHINE_NAME
  fi

  if ! nfs_is_mounted $DOCKER_MACHINE_NAME $MOUNT_DIR; then
    return $false
  fi

  return $true;
}


text:
from uuid import uuid4

import pytest

import photonpump.exceptions as exn
import photonpump.messages as msg
import photonpump.messages_pb2 as proto
from photonpump.conversations import Ping, WriteEvents

from ..fakes import TeeQueue

@pytest.mark.asyncio
async def test_bad_request():

    output = TeeQueue()

    event_id = uuid4()
    conversation_id = uuid4()
    error_message = "That's not an acceptable message, man"

    event_type = "pony_jumped"
    data = {"pony_name": "Burning Sulphur", "distance": 6}
    event_data = msg.NewEventData(event_id, event_type, data, None)

    conversation = WriteEvents(
        "my-stream", [event_data], conversation_id=conversation_id
    )

    await conversation.start(output)
    await conversation.respond_to(
        msg.InboundMessage(
            conversation_id, msg.TcpCommand.BadRequest, error_message.encode("UTF-8")
        ),
        output,
    )

    with pytest.raises(exn.BadRequest) as exc:
        await conversation.result
        assert exc.message == error_message

@pytest.mark.asyncio
async def test_not_authenticated():

    output = TeeQueue()

    event_id = uuid4()
    conversation_id = uuid4()
    error_message = "Dude, like who even are you?"

    event_type = "pony_jumped"
    data = {"pony_name": "Burning Sulphur", "distance": 6}
    event_data = msg.NewEventData(event_id, event_type, data, None)

    conversation = WriteEvents(
        "my-stream", [event_data], conversation_id=conversation_id
    )

    await conversation.start(output)
    await conversation.respond_to(
        msg.InboundMessage(
            conversation_id,
            msg.TcpCommand.NotAuthenticated,
            error_message.encode("UTF-8"),
        ),
        output,
    )

    with pytest.raises(exn.NotAuthenticated) as exc:
        await conversation.result
        assert exc.message == error_message

@pytest.mark.asyncio
async def test_notready_message():

    output = TeeQueue()
    payload = proto.NotHandled()
    payload.reason = msg.NotHandledReason.NotReady
    conversation = Ping()

    with pytest.raises(exn.NotReady):
        await conversation.respond_to(
            msg.InboundMessage(
                uuid4(), msg.TcpCommand.NotHandled, payload.SerializeToString()
            ),
            output,
        )

        await conversation.result

    assert conversation.is_complete

@pytest.mark.asyncio
async def test_too_busy_message():

    output = TeeQueue()

    payload = proto.NotHandled()
    payload.reason = msg.NotHandledReason.TooBusy

    conversation = Ping()
    await conversation.respond_to(
        msg.InboundMessage(
            uuid4(), msg.TcpCommand.NotHandled, payload.SerializeToString()
        ),
        output,
    )

    with pytest.raises(exn.TooBusy) as exc:
        await conversation.result
        assert exc.conversatio_id == conversation.conversation_id

@pytest.mark.asyncio
async def test_not_master():

    output = TeeQueue()
    payload = proto.NotHandled()
    payload.reason = msg.NotHandledReason.NotMaster

    conversation = Ping()
    await conversation.respond_to(
        msg.InboundMessage(
            uuid4(), msg.TcpCommand.NotHandled, payload.SerializeToString()
        ),
        output,
    )

    with pytest.raises(exn.NotMaster) as exc:
        await conversation.result
        assert exc.conversation_id == conversation.conversation_id

@pytest.mark.asyncio
async def test_decode_error():
    """
    If we give the conversation an invalid payload, it should
    raise PayloadUnreadable.
    """

    output = TeeQueue()
    conversation = Ping()
    await conversation.respond_to(
        msg.InboundMessage(uuid4(), msg.TcpCommand.NotHandled, b"\x08\2A"), output
    )

    with pytest.raises(exn.PayloadUnreadable) as exc:
        await conversation.result
        assert exc.conversation_id == conversation.conversation_id

    assert conversation.is_complete


text:
package com.wrapper.spotify.requests.data.browse.miscellaneous;

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.google.gson.Gson;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.wrapper.spotify.exceptions.SpotifyWebApiException;
import com.wrapper.spotify.requests.data.AbstractDataRequest;
import org.apache.hc.core5.http.ParseException;

import java.io.IOException;
import java.util.List;

/**
 * Retrieve a list of available genres seed parameter values for recommendations.
 */
@JsonDeserialize(builder = GetAvailableGenreSeedsRequest.Builder.class)
public class GetAvailableGenreSeedsRequest extends AbstractDataRequest<String[]> {

  /**
   * The private {@link GetAvailableGenreSeedsRequest} constructor.
   *
   * @param builder A {@link GetAvailableGenreSeedsRequest.Builder}.
   */
  private GetAvailableGenreSeedsRequest(final Builder builder) {
    super(builder);
  }

  /**
   * Get all available genre seeds.
   *
   * @return All available genre seeds.
   * @throws IOException            In case of networking issues.
   * @throws SpotifyWebApiException The Web API returned an error further specified in this exception's root cause.
   */
  public String[] execute() throws
    IOException,
    SpotifyWebApiException,
    ParseException {
    List<String> genres = new Gson().fromJson(
      JsonParser
        .parseString(getJson())
        .getAsJsonObject()
        .get("genres")
        .getAsJsonArray(),
      new TypeToken<List<String>>() {
      }.getType()
    );

    return genres.toArray(new String[0]);
  }

  /**
   * Builder class for building a {@link GetAvailableGenreSeedsRequest.Builder}.
   */
  public static final class Builder extends AbstractDataRequest.Builder<String[], Builder> {

    /**
     * Create a new {@link GetAvailableGenreSeedsRequest.Builder} instance.
     *
     * @param accessToken Required. A valid access token from the Spotify Accounts service.
     */
    public Builder(final String accessToken) {
      super(accessToken);
    }

    /**
     * The request build method.
     *
     * @return A custom {@link GetAvailableGenreSeedsRequest}.
     */
    @Override
    public GetAvailableGenreSeedsRequest build() {
      setPath("/v1/recommendations/available-genre-seeds");
      return new GetAvailableGenreSeedsRequest(this);
    }

    @Override
    protected Builder self() {
      return this;
    }
  }
}