text:
package water.nbhm;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.AbstractSet;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.concurrent.atomic.AtomicInteger;

import sun.misc.Unsafe;

/*
 * Written by Cliff Click and released to the public domain, as explained at
 * http://creativecommons.org/licenses/publicdomain
 */

/**
 * A multi-threaded bit-vector set, implemented as an array of primitive
 * {@code longs}.  All operations are non-blocking and multi-threaded safe.
 * {@link #contains(int)} calls are roughly the same speed as a {load, mask}
 * sequence.  {@link #add(int)} and {@link #remove(int)} calls are a tad more
 * expensive than a {load, mask, store} sequence because they must use a CAS.
 * The bit-vector is auto-sizing.
 *
 *
General note of caution: The Set API allows the use of {@link Integer}
 * with silent autoboxing - which can be very expensive if many calls are
 * being made.  Since autoboxing is silent you may not be aware that this is
 * going on.  The built-in API takes lower-case {@code ints} and is much more
 * efficient.
 *
 *
Space: space is used in proportion to the largest element, as opposed to
 * the number of elements (as is the case with hash-table based Set
 * implementations).  Space is approximately (largest_element/8 + 64) bytes.
 *
 * The implementation is a simple bit-vector using CAS for update.
 *
 * @since 1.5
 * @author Cliff Click
 */

public class NonBlockingSetInt extends AbstractSet<Integer> implements Serializable {
  private static final long serialVersionUID = 1234123412341234123L;
  private static final Unsafe _unsafe = UtilUnsafe.getUnsafe();

  // --- Bits to allow atomic update of the NBSI
  private static final long _nbsi_offset;
  static {                      // <clinit>
    Field f = null;
    try {
      f = NonBlockingSetInt.class.getDeclaredField("_nbsi");
    } catch( java.lang.NoSuchFieldException e ) {
    }
    _nbsi_offset = _unsafe.objectFieldOffset(f);
  }
  private final boolean CAS_nbsi( NBSI old, NBSI nnn ) {
    return _unsafe.compareAndSwapObject(this, _nbsi_offset, old, nnn );
  }

  // The actual Set of Joy, which changes during a resize event.  The
  // Only Field for this class, so I can atomically change the entire
  // set implementation with a single CAS.
  private transient NBSI _nbsi;

  /** Create a new empty bit-vector */
  public NonBlockingSetInt( ) {
    _nbsi = new NBSI(63, new ConcurrentAutoTable(), this); // The initial 1-word set
  }

  /**
   * Add {@code i} to the set.  Uppercase {@link Integer} version of add,
   * requires auto-unboxing.  When possible use the {@code int} version of
   * {@link #add(int)} for efficiency.
   * @throws IllegalArgumentException if i is negative.
   * @return <tt>true</tt> if i was added to the set.
   */
  public boolean add ( final Integer i ) {
    return add(i.intValue());
  }
  /**
   * Test if {@code o} is in the set.  This is the uppercase {@link Integer}
   * version of contains, requires a type-check and auto-unboxing.  When
   * possible use the {@code int} version of {@link #contains(int)} for
   * efficiency.
   * @return <tt>true</tt> if i was in the set.
   */
  public boolean contains( final Object  o ) {
    return o instanceof Integer && contains(((Integer) o).intValue());
  }
  /**
   * Remove {@code o} from the set.  This is the uppercase {@link Integer}
   * version of remove, requires a type-check and auto-unboxing.  When
   * possible use the {@code int} version of {@link #remove(int)} for
   * efficiency.
   * @return <tt>true</tt> if i was removed to the set.
   */
  public boolean remove( final Object  o ) {
    return o instanceof Integer && remove(((Integer) o).intValue());
  }

  /**
   * Add {@code i} to the set.  This is the lower-case '{@code int}' version
   * of {@link #add} - no autoboxing.  Negative values throw
   * IllegalArgumentException.
   * @throws IllegalArgumentException if i is negative.
   * @return <tt>true</tt> if i was added to the set.
   */
  public boolean add( final int i ) {
    if( i < 0 ) throw new IllegalArgumentException(""+i);
    return _nbsi.add(i);
  }
  /**
   * Test if {@code i} is in the set.  This is the lower-case '{@code int}'
   * version of {@link #contains} - no autoboxing.
   * @return <tt>true</tt> if i was int the set.
   */
  public boolean contains( final int i ) { return i >= 0 && _nbsi.contains(i); }
  /**
   * Remove {@code i} from the set.  This is the fast lower-case '{@code int}'
   * version of {@link #remove} - no autoboxing.
   * @return <tt>true</tt> if i was added to the set.
   */
  public boolean remove  ( final int i ) { return i >= 0 && _nbsi.remove(i); }

  /**
   * Current count of elements in the set.  Due to concurrent racing updates,
   * the size is only ever approximate.  Updates due to the calling thread are
   * immediately visible to calling thread.
   * @return count of elements.
   */
  public int     size    (             ) { return _nbsi.size( );                   }
  /** Approx largest element in set; at least as big (but max might be smaller).  */
  public int length() { return _nbsi._bits.length<<6; }
  /** Empty the bitvector. */
  public void    clear   (             ) {
    NBSI cleared = new NBSI(63, new ConcurrentAutoTable(), this); // An empty initial NBSI
    while( !CAS_nbsi( _nbsi, cleared ) ) // Spin until clear works
      ;
  }

  /** Verbose printout of internal structure for debugging. */
  public void print() { _nbsi.print(0); }

  /**
   * Standard Java {@link Iterator}.  Not very efficient because it
   * auto-boxes the returned values.
   */
  public Iterator<Integer> iterator( ) { return new iter(); }

  private class iter implements Iterator<Integer> {
    NBSI _nbsi2;
    int _idx  = -1;
    int _prev = -1;
    iter() { _nbsi2 = _nbsi; advance(); }
    public boolean hasNext() { return _idx != -2; }
    private void advance() {
      while( true ) {
        _idx++;                 // Next index
        while( (_idx>>6) >= _nbsi2._bits.length ) { // Index out of range?
          if( _nbsi2._new == null ) { // New table?
            _idx = -2;          // No, so must be all done
            return;             //
          }
          _nbsi2 = _nbsi2._new; // Carry on, in the new table
        }
        if( _nbsi2.contains(_idx) ) return;
      }
    }
    public Integer next() {
      if( _idx == -1 ) throw new NoSuchElementException();
      _prev = _idx;
      advance();
      return _prev;
    }
    public void remove() {
      if( _prev == -1 ) throw new IllegalStateException();
      _nbsi2.remove(_prev);
      _prev = -1;
    }
  }

  // --- writeObject -------------------------------------------------------
  // Write a NBSI to a stream
  private void writeObject(java.io.ObjectOutputStream s) throws IOException  {
    s.defaultWriteObject();     // Nothing to write
    final NBSI nbsi = _nbsi;    // The One Field is transient
    final int len = _nbsi._bits.length<<6;
    s.writeInt(len);            // Write max element
    for( int i=0; i<len; i++ )
      s.writeBoolean( _nbsi.contains(i) );
  }

  // --- readObject --------------------------------------------------------
  // Read a CHM from a stream
  private void readObject(java.io.ObjectInputStream s) throws IOException, ClassNotFoundException  {
    s.defaultReadObject();      // Read nothing
    final int len = s.readInt(); // Read max element
    _nbsi = new NBSI(len, new ConcurrentAutoTable(), this);
    for( int i=0; i<len; i++ )  // Read all bits
      if( s.readBoolean() )
        _nbsi.add(i);
  }

  // --- NBSI ----------------------------------------------------------------
  private static final class NBSI {
    // Back pointer to the parent wrapper; sorta like make the class non-static
    private transient final NonBlockingSetInt _non_blocking_set_int;

    // Used to count elements: a high-performance counter.
    private transient final ConcurrentAutoTable _size;

    // The Bits
    private final long _bits[];
    // --- Bits to allow Unsafe access to arrays
    private static final int _Lbase  = _unsafe.arrayBaseOffset(long[].class);
    private static final int _Lscale = _unsafe.arrayIndexScale(long[].class);
    private static long rawIndex(final long[] ary, final int idx) {
      assert idx >= 0 && idx < ary.length;
      return _Lbase + idx * _Lscale;
    }
    private final boolean CAS( int idx, long old, long nnn ) {
      return _unsafe.compareAndSwapLong( _bits, rawIndex(_bits, idx), old, nnn );
    }

    // --- Resize
    // The New Table, only set once to non-zero during a resize.
    // Must be atomically set.
    private NBSI _new;
    private static final long _new_offset;
    static {                      // <clinit>
      Field f = null;
      try {
        f = NBSI.class.getDeclaredField("_new");
      } catch( java.lang.NoSuchFieldException e ) {
      }
      _new_offset = _unsafe.objectFieldOffset(f);
    }
    private final boolean CAS_new( NBSI nnn ) {
      return _unsafe.compareAndSwapObject(this, _new_offset, null, nnn );
    }

    private transient final AtomicInteger _copyIdx;   // Used to count bits started copying
    private transient final AtomicInteger _copyDone;  // Used to count words copied in a resize operation
    private transient final int _sum_bits_length; // Sum of all nested _bits.lengths

    private static final long mask( int i ) { return 1L<<(i&63); }

    // I need 1 free bit out of 64 to allow for resize.  I do this by stealing
    // the high order bit - but then I need to do something with adding element
    // number 63 (and friends).  I could use a mod63 function but it's more
    // efficient to handle the mod-64 case as an exception.
    //
    // Every 64th bit is put in it's own recursive bitvector.  If the low 6 bits
    // are all set, we shift them off and recursively operate on the _nbsi64 set.
    private final NBSI _nbsi64;

    private NBSI( int max_elem, ConcurrentAutoTable ctr, NonBlockingSetInt nonb ) {
      super();
      _non_blocking_set_int = nonb;
      _size = ctr;
      _copyIdx  = ctr == null ? null : new AtomicInteger();
      _copyDone = ctr == null ? null : new AtomicInteger();
      // The main array of bits
      _bits = new long[(int)(((long)max_elem+63)>>>6)];
      // Every 64th bit is moved off to it's own subarray, so that the
      // sign-bit is free for other purposes
      _nbsi64 = ((max_elem+1)>>>6) == 0 ? null : new NBSI((max_elem+1)>>>6, null, null);
      _sum_bits_length = _bits.length + (_nbsi64==null ? 0 : _nbsi64._sum_bits_length);
    }

    // Lower-case 'int' versions - no autoboxing, very fast.
    // 'i' is known positive.
    public boolean add( final int i ) {
      // Check for out-of-range for the current size bit vector.
      // If so we need to grow the bit vector.
      if( (i>>6) >= _bits.length )
        return install_larger_new_bits(i). // Install larger pile-o-bits (duh)
          help_copy().add(i);              // Finally, add to the new table

      // Handle every 64th bit via using a nested array
      NBSI nbsi = this;         // The bit array being added into
      int j = i;                // The bit index being added
      while( (j&63) == 63 ) {   // Bit 64? (low 6 bits are all set)
        nbsi = nbsi._nbsi64;    // Recurse
        j = j>>6;               // Strip off low 6 bits (all set)
      }

      final long mask = mask(j);
      long old;
      do {
        old = nbsi._bits[j>>6]; // Read old bits
        if( old < 0 )           // Not mutable?
          // Not mutable: finish copy of word, and retry on copied word
          return help_copy_impl(i).help_copy().add(i);
        if( (old & mask) != 0 ) return false; // Bit is already set?
      } while( !nbsi.CAS( j>>6, old, old | mask ) );
      _size.add(1);
      return true;
    }

    public boolean remove( final int i ) {
      if( (i>>6) >= _bits.length ) // Out of bounds?  Not in this array!
        return _new != null && help_copy().remove(i);

      // Handle every 64th bit via using a nested array
      NBSI nbsi = this;         // The bit array being added into
      int j = i;                // The bit index being added
      while( (j&63) == 63 ) {   // Bit 64? (low 6 bits are all set)
        nbsi = nbsi._nbsi64;    // Recurse
        j = j>>6;               // Strip off low 6 bits (all set)
      }

      final long mask = mask(j);
      long old;
      do {
        old = nbsi._bits[j>>6]; // Read old bits
        if( old < 0 )           // Not mutable?
          // Not mutable: finish copy of word, and retry on copied word
          return help_copy_impl(i).help_copy().remove(i);
        if( (old & mask) == 0 ) return false; // Bit is already clear?
      } while( !nbsi.CAS( j>>6, old, old & ~mask ) );
      _size.add(-1);
      return true;
    }

    public boolean contains( final int i ) {
      if( (i>>6) >= _bits.length ) // Out of bounds?  Not in this array!
        return _new != null && help_copy().contains(i);

      // Handle every 64th bit via using a nested array
      NBSI nbsi = this;         // The bit array being added into
      int j = i;                // The bit index being added
      while( (j&63) == 63 ) {   // Bit 64? (low 6 bits are all set)
        nbsi = nbsi._nbsi64;    // Recurse
        j = j>>6;               // Strip off low 6 bits (all set)
      }

      final long mask = mask(j);
      long old = nbsi._bits[j>>6]; // Read old bits
      if( old < 0 )             // Not mutable?
        // Not mutable: finish copy of word, and retry on copied word
        return help_copy_impl(i).help_copy().contains(i);
      // Yes mutable: test & return bit
      return (old & mask) != 0;
    }

    public int size() { return (int)_size.get(); }

    // Must grow the current array to hold an element of size i
    private NBSI install_larger_new_bits( final int i ) {
      if( _new == null ) {
        // Grow by powers of 2, to avoid minor grow-by-1's.
        // Note: must grow by exact powers-of-2 or the by-64-bit trick doesn't work right
        int sz = (_bits.length<<6)<<1;
        // CAS to install a new larger size.  Did it work?  Did it fail?  We
        // don't know and don't care.  Only One can be installed, so if
        // another thread installed a too-small size, we can't help it - we
        // must simply install our new larger size as a nested-resize table.
        CAS_new(new NBSI(sz, _size, _non_blocking_set_int));
      }
      // Return self for 'fluid' programming style
      return this;
    }

    // Help any top-level NBSI to copy until completed.
    // Always return the _new version of *this* NBSI, in case we're nested.
    private NBSI help_copy() {
      // Pick some words to help with - but only help copy the top-level NBSI.
      // Nested NBSI waits until the top is done before we start helping.
      NBSI top_nbsi = _non_blocking_set_int._nbsi;
      final int HELP = 8;       // Tuning number: how much copy pain are we willing to inflict?
      // We "help" by forcing individual bit indices to copy.  However, bits
      // come in lumps of 64 per word, so we just advance the bit counter by 64's.
      int idx = top_nbsi._copyIdx.getAndAdd(64*HELP);
      for( int i=0; i<HELP; i++ ) {
        int j = idx+i*64;
        j %= (top_nbsi._bits.length<<6); // Limit, wrap to array size; means we retry indices
        top_nbsi.help_copy_impl(j   );
        top_nbsi.help_copy_impl(j+63); // Also force the nested-by-64 bit
      }

      // Top level guy ready to promote?
      // Note: WE may not be the top-level guy!
      if( top_nbsi._copyDone.get() == top_nbsi._sum_bits_length )
        // One shot CAS to promote - it may fail since we are racing; others
        // may promote as well
        if( _non_blocking_set_int.CAS_nbsi( top_nbsi, top_nbsi._new ) ) {
          //System.out.println("Promote at top level to size "+(_non_blocking_set_int._nbsi._bits.length<<6));
        }

      // Return the new bitvector for 'fluid' programming style
      return _new;
    }

    // Help copy this one word.  State Machine.
    // (1) If not "made immutable" in the old array, set the sign bit to make
    //     it immutable.
    // (2) If non-zero in old array & zero in new, CAS new from 0 to copy-of-old
    // (3) If non-zero in old array & non-zero in new, CAS old to zero
    // (4) Zero in old, new is valid
    // At this point, old should be immutable-zero & new has a copy of bits
    private NBSI help_copy_impl( int i ) {
      // Handle every 64th bit via using a nested array
      NBSI old = this;          // The bit array being copied from
      NBSI nnn = _new;          // The bit array being copied to
      if( nnn == null ) return this; // Promoted already
      int j = i;                // The bit index being added
      while( (j&63) == 63 ) {   // Bit 64? (low 6 bits are all set)
        old = old._nbsi64;      // Recurse
        nnn = nnn._nbsi64;      // Recurse
        j = j>>6;               // Strip off low 6 bits (all set)
      }

      // Transit from state 1: word is not immutable yet
      // Immutable is in bit 63, the sign bit.
      long bits = old._bits[j>>6];
      while( bits >= 0 ) {      // Still in state (1)?
        long oldbits = bits;
        bits |= mask(63);       // Target state of bits: sign-bit means immutable
        if( old.CAS( j>>6, oldbits, bits ) ) {
          if( oldbits == 0 ) _copyDone.addAndGet(1);
          break;                // Success - old array word is now immutable
        }
        bits = old._bits[j>>6]; // Retry if CAS failed
      }

      // Transit from state 2: non-zero in old and zero in new
      if( bits != mask(63) ) {  // Non-zero in old?
        long new_bits = nnn._bits[j>>6];
        if( new_bits == 0 ) {   // New array is still zero
          new_bits = bits & ~mask(63); // Desired new value: a mutable copy of bits
          // One-shot CAS attempt, no loop, from 0 to non-zero.
          // If it fails, somebody else did the copy for us
          if( !nnn.CAS( j>>6, 0, new_bits ) )
            new_bits = nnn._bits[j>>6]; // Since it failed, get the new value
          assert new_bits != 0;
        }

        // Transit from state 3: non-zero in old and non-zero in new
        // One-shot CAS attempt, no loop, from non-zero to 0 (but immutable)
        if( old.CAS( j>>6, bits, mask(63) ) )
          _copyDone.addAndGet(1); // One more word finished copying
      }

      // Now in state 4: zero (and immutable) in old

      // Return the self bitvector for 'fluid' programming style
      return this;
    }

    private void print( int d, String msg ) {
      for( int i=0; i<d; i++ )
        System.out.print("  ");
      System.out.println(msg);
    }

    private void print(int d) {
      StringBuilder buf = new StringBuilder();
      buf.append("NBSI - _bits.len=");
      NBSI x = this;
      while( x != null ) {
        buf.append(" "+x._bits.length);
        x = x._nbsi64;
      }
      print(d,buf.toString());

      x = this;
      while( x != null ) {
        for( int i=0; i<x._bits.length; i++ )
          System.out.print(Long.toHexString(x._bits[i])+" ");
        x = x._nbsi64;
        System.out.println();
      }

      if( _copyIdx.get() != 0 || _copyDone.get() != 0 )
        print(d,"_copyIdx="+_copyIdx.get()+" _copyDone="+_copyDone.get()+" _words_to_cpy="+_sum_bits_length);
      if( _new != null ) {
        print(d,"__has_new - ");
        _new.print(d+1);
      }
    }
  }
}


text:
package org.drools.model;

import java.util.Collections;
import java.util.List;

public interface Condition {

    default List<Condition> getSubConditions() {
        return Collections.emptyList();
    }

    Type getType();

    Variable<?>[] getBoundVariables();

    default Condition cloneCondition() {
        throw new UnsupportedOperationException();
    }

    enum Type {
        PATTERN( false ), EVAL( false ), QUERY( false ),
        ACCUMULATE( false ), GROUP_BY( false ), TEMPORAL( false ),
        RECEIVER( false ), SENDER( false ),
        OR( true ), AND( true ), NOT( false ), EXISTS( false ), FORALL( false ), CONSEQUENCE( false );

        private final boolean composite;

        Type( boolean composite ) {
            this.composite = composite;
        }

        public boolean isComposite() {
            return composite;
        }

        public boolean createsScope() {
            return this == OR;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
import { test as it } from 'babel-tap';
import expect from 'expect';
import reactNativeCSS from '../src/index';

it('Parse CSS', (t) => {
  const data = reactNativeCSS`
    main {
      background: #000;
    }
  `;
  expect(data).toEqual({ main: { background: '#000' } });

  t.end();
});

it('Parse complex css', (t) => {
  const data = reactNativeCSS`

      description {
        flex: 102;
        margin: 2, 3, 4;
        font-size: 18;
        text-align: center;
        color: #656656;
      }

      container {
        padding: 30;
        margin-top: 65;
        align-items: center;
      }
  `;

  expect(data).toEqual({
    description: {
      flex: 102,
      marginLeft: 3,
      marginRight: 3,
      marginTop: 2,
      marginBottom: 4,
      fontSize: 18,
      textAlign: 'center',
      color: '#656656',
    },
    container: {
      padding: 30,
      marginTop: 65,
      alignItems: 'center',
    },
  });
  t.end();
});

it('Parse CSS and ignore unsupported property', (t) => {
  const data = reactNativeCSS`
  container {
    display: block;
    background: white;
  }
  `;

  expect(data).toEqual({ container: { background: 'white' } });

  t.end();
});

it('Parse CSS and turn properties into numbers', (t) => {
  const data = reactNativeCSS(`
  text {
  font-size: 12px;
  width: 100px;
}

  `);
  expect(data).toEqual({
    text: {
      fontSize: 12,
      width: 100,
    },
  });
  t.end();
});

it('Regression test for issue #26', (t) => {
  const data = reactNativeCSS`
    row {
      top: 50px;
      padding: 10px 10px 10px 5px;
      flex-direction: row;
      margin: 10px;
      margin-bottom: 2px;
      border-bottom-width: 5px;
      opacity: 0.6;
    }
    `;

  expect(data).toEqual({
    row: {
      top: 50,
      paddingTop: 10,
      paddingBottom: 10,
      paddingRight: 10,
      paddingLeft: 5,
      flexDirection: 'row',
      margin: 10,
      marginBottom: 2,
      borderBottomWidth: 5,
      opacity: 0.6,
    },
  });

  t.end();
});

it('Argument --literal generates a javascript literal object', (t) => {
  const data = reactNativeCSS`
        maincontainer {
            flex: 1;
            justify-content: center;
            align-items: center;
            background-color: #F5FCFF;
        }
        rootcontainer {
            flex: 1;
            font-size: 18;
        }
    `;

  expect(data.maincontainer.backgroundColor).toEqual('#F5FCFF');
  t.end();
});

it('Parse CSS and expand shorthand properties', (t) => {
  const data = reactNativeCSS`
        container {
          padding: 10px 20px;
          margin: 10px 15px 30px;
          border-width: 10px 30px;
          border-radius: 10px 30px;
        }

        second {
          margin: 10px;
          padding: 1px 2px 3px 4px;
          border-width: 1px 2px 3px 4px;
          border-radius: 1px 2px 3px 4px;
        }

        borderSimple {
          border: 1px solid #eee;
        }

        borderNoStyle {
          border: 1px #eee;
        }

        borderNoUnit {
          border: 1 solid #eee;
        }

        borderNamedColor {
          border: 1px solid blue;
        }

        borderRGBColor {
          border: 1px solid rgb(100, 32, 250);
        }

        borderRGBAColor {
          border: 1px solid rgba(100, 32, 250, .5);
        }
    `;

  expect(data).toEqual({
    container: {
      paddingTop: 10,
      paddingBottom: 10,
      paddingLeft: 20,
      paddingRight: 20,
      marginLeft: 15,
      marginRight: 15,
      marginTop: 10,
      marginBottom: 30,
      borderTopWidth: 10,
      borderBottomWidth: 10,
      borderLeftWidth: 30,
      borderRightWidth: 30,
      borderTopLeftRadius: 10,
      borderBottomRightRadius: 10,
      borderBottomLeftRadius: 30,
      borderTopRightRadius: 30,
    },
    second: {
      margin: 10,
      paddingTop: 1,
      paddingRight: 2,
      paddingBottom: 3,
      paddingLeft: 4,
      borderTopWidth: 1,
      borderRightWidth: 2,
      borderBottomWidth: 3,
      borderLeftWidth: 4,
      borderTopLeftRadius: 1,
      borderTopRightRadius: 2,
      borderBottomRightRadius: 3,
      borderBottomLeftRadius: 4,
    },
    borderSimple: { borderWidth: 1, borderStyle: 'solid', borderColor: '#eee' },
    borderNoStyle: { borderWidth: 1, borderColor: '#eee' },
    borderNoUnit: { borderWidth: 1, borderStyle: 'solid', borderColor: '#eee' },
    borderNamedColor: { borderWidth: 1, borderStyle: 'solid', borderColor: 'blue' },
    borderRGBColor: { borderWidth: 1, borderStyle: 'solid', borderColor: 'rgb(100, 32, 250)' },
    borderRGBAColor: {
      borderWidth: 1,
      borderStyle: 'solid',
      borderColor: 'rgba(100, 32, 250, .5)',
    },
  });
  t.end();
});

it('Parse CSS and transform properties', (t) => {
  const data = reactNativeCSS`
    container {
      flex-grow: unset;
      text-decoration: none;
      vertical-align: bottom;
    }
  `;

  expect(data).toEqual({
    container: {
      flex: 'unset',
      textDecorationLine: 'none',
      textVerticalAlign: 'bottom',
    },
  });
  t.end();
});
it('Parse CSS and template literals', (t) => {
  const bottom = 'bottom';
  const data = reactNativeCSS`
    container {
      flex-grow: unset;
      text-decoration: none;
      vertical-align: ${bottom};
    }
  `;

  expect(data).toEqual({
    container: {
      flex: 'unset',
      textDecorationLine: 'none',
      textVerticalAlign: 'bottom',
    },
  });
  t.end();
});


text:
package org.ovirt.engine.core.common.businessentities;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * This annotation is used to mark a field
 * that need to be copied to vm, from a new template version
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CopyOnNewVersion {

}


text:
Meteor.startup(function() {

    Mapbox.load({
        plugins: ['markercluster', 'zoomslider']
    });

})


text:
package br.furb.packing;

import static org.jenetics.engine.EvolutionResult.toBestPhenotype;
import static org.jenetics.engine.limit.byExecutionTime;
import static org.jenetics.engine.limit.bySteadyFitness;

import java.awt.geom.Line2D;
import java.time.Clock;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.function.Function;

import org.jenetics.Chromosome;
import org.jenetics.Genotype;
import org.jenetics.IntegerChromosome;
import org.jenetics.IntegerGene;
import org.jenetics.Mutator;
import org.jenetics.Optimize;
import org.jenetics.Phenotype;
import org.jenetics.SinglePointCrossover;
import org.jenetics.StochasticUniversalSelector;
import org.jenetics.TournamentSelector;
import org.jenetics.engine.Codec;
import org.jenetics.engine.Engine;
import org.jenetics.engine.codecs;
import org.jenetics.util.Factory;
import org.jenetics.util.IntRange;

import br.furb.common.MathHelper;
import br.furb.common.Point;
import br.furb.common.Polygon;
import br.furb.common.Transform;

public class JeneticBottomLeftFillAgorithm {

	static Polygon[] mPolygonsList;
	static int mRotationsNumber;
	static double mSheetHeight;
	static NFPImplementation mNFP;
	static int countExecution = 0;
	static Integer syncSemaphore = 0;

	static Double fitness(final int[] gt) {
		ArrayList<Integer> rotationSequence =  new ArrayList<>(); // voltar aqui
		for(int i=0; i< gt.length; i++) {
			rotationSequence.add(gt[i]);
		}
		 double height = __doPacking(mPolygonsList, rotationSequence, mRotationsNumber, mSheetHeight).getHeight();

		 assert (height > 0);
		 assert (height > 1);

		 return height;
	}

	public PackingResult doPacking(NFPImplementation nfp, Polygon[] polygonsList, int rotationsNumber,
			double sheetHeight, int generations, int populationSize, int time) {

		JeneticBottomLeftFillAgorithm.mPolygonsList = polygonsList;
		JeneticBottomLeftFillAgorithm.mRotationsNumber = rotationsNumber;
		JeneticBottomLeftFillAgorithm.mSheetHeight = sheetHeight;
		JeneticBottomLeftFillAgorithm.mNFP = nfp;

		int ITEMS_LEN = polygonsList.length;
		int GENERATIONS = generations;

		int maxPhenenonAge = (int) (GENERATIONS * 0.2);
		int tournamentSelectorFactor = (int) (GENERATIONS * 0.10);
		double mutatorFactor = 0.1;
		double crossoverFactor = 0.5;
		int steadyFitness = (int) (GENERATIONS * 0.3);

		boolean hasMaxPhenenonAge = System.getProperty( "pmaxPhenenonAge" ) != null;
		boolean hasTournamentSelectorFactor = System.getProperty("tournamentSelectorFactor") != null;
		boolean hasMutatorFactor = System.getProperty( "pmutatorFactor" ) != null;
		boolean hasCrossoverFactor = System.getProperty( "pcrossoverFactor" ) != null;
		boolean hasSteadyFitness = System.getProperty( "psteadyFitness" ) != null;

		if (hasMaxPhenenonAge) {
			maxPhenenonAge = Integer.parseInt(System.getProperty("pmaxPhenenonAge"));
			System.out.println("maxPhenenonAge changed to: " + String.valueOf(maxPhenenonAge));
		}

		if (hasTournamentSelectorFactor) {
			tournamentSelectorFactor = (int)(GENERATIONS * Double.parseDouble(System.getProperty("tournamentSelectorFactor")));
			System.out.println("tournamentSelectorFactor changed to: " + String.valueOf(tournamentSelectorFactor));
		}

		if (hasMutatorFactor) {
			mutatorFactor = Double.parseDouble(System.getProperty("pswapMutatorFactor"));
			System.out.println("swapMutatorFactor changed to: " + String.valueOf(mutatorFactor));
		}

		if (hasCrossoverFactor) {
			crossoverFactor = Double.parseDouble(System.getProperty("pcrossoverFactor"));
			System.out.println("crossoverFactor changed to: " + String.valueOf(crossoverFactor));
		}

		if (hasSteadyFitness) {
			steadyFitness = Integer.parseInt(System.getProperty("psteadyFitness"));
			System.out.println("steadyFitness changed to: " + String.valueOf(steadyFitness));
		}

		if (tournamentSelectorFactor < 2 ) {
			tournamentSelectorFactor = 2;
		}

		if (maxPhenenonAge < 2) {
			maxPhenenonAge = 2;
		}

		Codec<int[], IntegerGene> gtf = codecs.ofVector(IntRange.of(1, mRotationsNumber), ITEMS_LEN);
		final Engine<IntegerGene, Double> engine = Engine.builder(JeneticBottomLeftFillAgorithm::fitness, gtf)
				.optimize(Optimize.MINIMUM)
				.maximalPhenotypeAge(maxPhenenonAge)
				.populationSize(populationSize)
				.survivorsSelector(new StochasticUniversalSelector<IntegerGene, Double>())
				.offspringSelector(new TournamentSelector<>(tournamentSelectorFactor))
				.alterers(
						new Mutator<>(mutatorFactor),
						new SinglePointCrossover<>(crossoverFactor))
				.executor(Executors.newFixedThreadPool(8))
				.build();

		final Phenotype<IntegerGene, Double> best =
				engine.stream()
				// Truncate the evolution stream after `steadyFitness` "steady" generations.
				.limit(bySteadyFitness(steadyFitness))
				// The evolution will stop after maximal time.
				.limit(byExecutionTime(Duration.ofMillis(time), Clock.systemUTC()))
				// The evolution will stop after maximal GENERATIONS generations.
				.limit(GENERATIONS)
				// Collect (reduce) the evolution stream to its best phenotype.
				.collect(toBestPhenotype());

		Genotype<IntegerGene> gt = best.getGenotype();
		ArrayList<Integer> rotationSequence =  new ArrayList<>(); // voltar aqui
		for(int i=0; i< gt.getNumberOfGenes(); i++) {
			rotationSequence.add(gt.get(0, i).getAllele());
		}

		 assert(rotationSequence.size() > 0);
		 assert(rotationSequence.size() > 1);
		 PackingResult packing = __doPacking(mPolygonsList, rotationSequence, mRotationsNumber, mSheetHeight);
		 double height = packing.getHeight();
		 assert (height > 0);
		 assert (height > 1);
		 return packing;

	}

	private static PackingResult __doPacking(Polygon[] polygonsList, ArrayList<Integer> rotationSequence, int maxRotationNumber, double sheetHeight) {

		double resolution = 0.0;
		double maxHeight = 0;

		resolution = sheetHeight * 0.01;

		Polygon[] rotadedPolygons = generatePolygons(polygonsList, rotationSequence, maxRotationNumber);
		ArrayList<Polygon> sheetShapes = new ArrayList<>();
		Point currentXPosition = new Point();

		currentXPosition.x = 0;
		placeShape(rotadedPolygons[0], currentXPosition, 0);
		sheetShapes.add(rotadedPolygons[0]);

		// try all rotations configured
		for (int j = 1; j < rotadedPolygons.length; j++) {
			currentXPosition.x = 0;

			// place shape[i][j] at bottom left of sheet;
			placeShape(rotadedPolygons[j], currentXPosition, 0);

			boolean overlapped = false;
			do {
				// rever esse j no overlap
				overlapped = comparePolygons(rotadedPolygons[j], sheetShapes, sheetHeight, resolution, currentXPosition);
			} while (overlapped);

			sheetShapes.add(rotadedPolygons[j]);
		}

		assert (sheetShapes.size() == polygonsList.length);

		Polygon[] arraySheetShapes = new Polygon[sheetShapes.size()];
		for (int i=0; i<sheetShapes.size(); i++) {
			arraySheetShapes[i] = sheetShapes.get(i);
		}

		return new PackingResult(arraySheetShapes, maxHeight);
	}

	private static boolean comparePolygons(Polygon polygon, ArrayList<Polygon> sheetShapes, double sheetHeight, double resolution, Point currentXPosition) {
		boolean resolvedOverlapping = false;

		// while (Overlap(shapes[i][j], sheetshape[1..q])) // find feasible
		// position
		for (int j = 0; j < sheetShapes.size(); j++) {

			if (overlap(polygon, sheetShapes.get(j))) {
				// Resolve Overlapping
				resolvedOverlapping |= resolveOverlapping(polygon, sheetShapes.get(j));
				if (overlap(polygon, sheetShapes.get(j))) {
					assert resolveOverlapping(polygon, sheetShapes.get(j)) == false : "Overlapping error: sheetShape: "
							+ sheetShapes.get(j) + "polygon: " + polygon;
				}
			}
			// if (shape[i][j] off top of sheet) { x = x + resolution; place
			// shape[i][j] at (x,0); }
			if (polygon.maxY().getY() > sheetHeight) {
				currentXPosition.x += resolution;
				// Restart comparisons
				j = -1;
				// place shape[i][j] at bottom left of sheet plus
				// currentXPosition;
				placeShape(polygon, currentXPosition, 0);

			}
		}
		return resolvedOverlapping;
	}

	private static boolean resolveOverlapping(Polygon polygon, Polygon sheetShape) {
		Polygon noFitPolygonCached = getNoFitPolygon(polygon, sheetShape);

		Point ref = new Point();
		ref.x = polygon.getRefPoint().x;
		ref.y = polygon.getRefPoint().y;

		boolean overlapping = false;
		double maxDistance = 0;

		List<Point> points = noFitPolygonCached.getPoints();
		for (Point point : points) {

			Line2D line2d = new Line2D.Double(point.x, point.y, point.next.x, point.next.y);
			if (line2d.intersectsLine(ref.x, ref.y, ref.x, Double.MAX_VALUE)) {

				// intersecting lines segment intersection point
				Point intesectionPoint = MathHelper.findIntersection(/**/polygon.getRefPoint(),
						new Point(ref.x, Float.MAX_VALUE), /**/new Point(line2d.getX1(), line2d.getY1()),
						new Point(line2d.getX2(), line2d.getY2()));

				double distance = MathHelper.calcularDistancia(polygon.getRefPoint(), intesectionPoint);
				distance = Double.isNaN(distance) ? 0 : distance;
				// System.out.println(distance);

				// if (distance > Transform.THRESHOLD) {
				// placeShape(polygon, refX, refY + distance);
				// overlapping = true;
				// break;
				// }

				if (distance > maxDistance) {
					maxDistance = distance;
				}

			}
		}
		if (maxDistance > Transform.THRESHOLD) {
			placeShape(polygon, ref, ref.y + maxDistance);
			overlapping = true;
			// break;
		}
		return overlapping;
	}

	private static boolean overlap(Polygon polygon, Polygon sheetShape) {
		Polygon noFitPolygonCached = getNoFitPolygon(polygon, sheetShape);
		return MathHelper.isInside(polygon.getRefPoint(), noFitPolygonCached);
	}

	private static void placeShape(Polygon polygon, Point currentXPosition, double y) {
		Transform transform = new Transform();
		if (y == 0) {
			transform.executeTranslationPolygon(new Point(polygon.minY().x - polygon.minX().x + currentXPosition.x, y), polygon.minY(),
					polygon);
		} else {
			transform.executeTranslationPolygon(new Point(currentXPosition.x, y), polygon.getRefPoint(), polygon);
		}
	}

	private static Polygon getNoFitPolygon(Polygon polygon, Polygon sheetShape) {
		NFPImplementation nfp = JeneticBottomLeftFillAgorithm.mNFP.getnewInstance();
		Polygon noFitPolygonCached = nfp.calculateNotFitPolygon(sheetShape, polygon);
		moveShape(noFitPolygonCached, sheetShape.minYRight());
		return noFitPolygonCached;
	}

	private static void moveShape(Polygon polygon, Point target) {
		Transform transform = new Transform();
		transform.executeTranslationPolygon(target, polygon.minYRight(), polygon);
	}

	/**
	 * Gera os polígonos rotacionados
	 *
	 * @param polygonsList
	 * @param rotationsNumber
	 * @return
	 */
	private static Polygon[] generatePolygons(Polygon[] polygonsList, ArrayList<Integer> rotationSequence, int maxRotationNumber) {
		double angleAlpha = 360 / maxRotationNumber;
		Polygon[] polygonsRotated= new Polygon[rotationSequence.size()];

		for (int i = 0; i < rotationSequence.size(); i++) {
			Transform transform = new Transform();
			Polygon originalPolygon = polygonsList[i];

			Polygon rotatedPolygon = transform.executeRotation(originalPolygon.getRefPoint(), //
					angleAlpha * rotationSequence.get(i), -1, originalPolygon);

			assert originalPolygon.getPoints().size() == rotatedPolygon.getPoints().size();

			polygonsRotated[i] = rotatedPolygon;
		}

		return polygonsRotated;
	}
}


text:
using DevExpress.Web.Mvc;
using DevExpress.XtraReports.UI;
using DReporting.Models;
using DReporting.Web.Mvc.ViewModels;
using System;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace DReporting.Web.Mvc.Controllers
{
    public class DesignController : ControllerBase
    {
        public ActionResult Index(string templateId)
        {
            return View(Designer(templateId));
        }

        public ActionResult Create()
        {
            return View(Designer(null));
        }

        private DesignerVM Designer(string templateId)
        {
            TemplateModel template = null;

            if (string.IsNullOrEmpty(templateId))
            {
                template = TemplateMgr.GetDefaultTemplate();
            }
            else
            {
                template = TemplateMgr.GetTemplate(templateId, true);
            }

            var query = HttpUtility.ParseQueryString(Request.Url.Query);

            var dataSources = DataProviderMgr.QueryDataProviders().ToDictionary(
                x => x.Entity.DataProviderName,
                x => x.Entity.GetDataSource(query, true));

            return new DesignerVM
            {
                TemplateID = template.TemplateID,
                TemplateName = template.TemplateName,
                DataSources = dataSources,
                XtraReport = template.XtraReport
            };
        }

        [HttpPost]
        public ActionResult Save(string templateId, string templateName, string returnUrl)
        {
            var xmlContent = ReportDesignerExtension.GetReportXml("reportDesigner");
            var xtraReport = XtraReport.FromStream(new MemoryStream(xmlContent), true);

            var old = TemplateMgr.GetTemplate(templateId, false);

            var model = TemplateMgr.SaveTemplate(new TemplateModel
            {
                TemplateID = templateId,
                TemplateName = templateName,
                TemplateCode = old != null ? old.TemplateCode : null,
                CategoryID = old != null ? old.CategoryID : null,
                CreationTime = old != null ? old.CreationTime : DateTime.UtcNow,
                LastUpdateTime = old != null ? DateTime.UtcNow : new Nullable<DateTime>(),
                XtraReport = xtraReport
            });

            return Content(Url.Action("Index", "Design", new
            {
                Area = ReportingGlobal.AreaName,
                TemplateID = model.TemplateID,
                ReturnUrl = returnUrl
            }));
        }
    }
}


text:
package com.liyu.fakeweather.ui.weather.adapter;

import android.support.v7.widget.RecyclerView;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.liyu.fakeweather.R;
import com.liyu.fakeweather.model.FakeWeather;
import com.liyu.fakeweather.model.WeatherBean;
import com.liyu.fakeweather.utils.SimpleSubscriber;
import com.liyu.fakeweather.utils.SizeUtils;
import com.liyu.fakeweather.utils.WeatherUtil;

import java.util.List;

import rx.android.schedulers.AndroidSchedulers;

/**
 * Created by liyu on 2017/8/25.
 */

public class HourlyAdapter extends BaseQuickAdapter<FakeWeather.FakeForecastHourly, BaseViewHolder> {

    public HourlyAdapter(int layoutResId, List<FakeWeather.FakeForecastHourly> data) {
        super(layoutResId, data);
    }

    @Override
    protected void convert(final BaseViewHolder helper, FakeWeather.FakeForecastHourly item) {
        int width = SizeUtils.getScreenWidth(mContext) / 5;
        RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) helper.itemView.getLayoutParams();
        params.width = width;
        helper.itemView.setLayoutParams(params);
        helper.setText(R.id.tv_hourly_temp, item.getTemp() + "°");
        helper.setText(R.id.tv_hourly_time, item.getTime());
        final ImageView imageView = helper.getView(R.id.iv_hourly_weather);
        WeatherUtil.getInstance().getWeatherDict(item.getCode()).observeOn(AndroidSchedulers.mainThread()).subscribe(new SimpleSubscriber<WeatherBean>() {
            @Override
            public void onNext(WeatherBean weatherBean) {
                Glide.with(mContext).load(weatherBean.getIcon()).diskCacheStrategy(DiskCacheStrategy.ALL).into(imageView);
            }
        });
    }
}


text:
CREATE OR REPLACE FUNCTION "LLVM_IR"."LEAVE_PROGRAM"(_NodeID integer)
RETURNS void
LANGUAGE plpgsql
AS $$
DECLARE
BEGIN
PERFORM LLVMIR(_NodeID, '
ret i32 0
}
');

RETURN;
END;
$$;


text:
MY_PATH="`dirname \"$0\"`"
. $MY_PATH/config.sh

cd $MY_PATH/../client_app
#node_modules/.bin/http-server
npm run dev-server --no-inline


text:
/*
 * Minio Cloud Storage, (C) 2015 Minio, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implieapi.XL.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package main

import (
	"net/http"
	"strconv"

	"github.com/gorilla/mux"
	"github.com/minio/minio-xl/pkg/probe"
	signv4 "github.com/minio/minio-xl/pkg/signature"
	"github.com/minio/minio-xl/pkg/xl"
)

const (
	maxPartsList = 1000
)

// GetObjectHandler - GET Object
// ----------
// This implementation of the GET operation retrieves object. To use GET,
// you must have READ access to the object.
func (api API) GetObjectHandler(w http.ResponseWriter, req *http.Request) {
	// ticket master block
	{
		op := APIOperation{}
		op.ProceedCh = make(chan struct{})
		api.OP <- op
		// block until Ticket master gives us a go
		<-op.ProceedCh
	}

	var object, bucket string
	vars := mux.Vars(req)
	bucket = vars["bucket"]
	object = vars["object"]

	metadata, err := api.XL.GetObjectMetadata(bucket, object)
	if err != nil {
		errorIf(err.Trace(), "GetObject failed.", nil)
		switch err.ToGoError().(type) {
		case xl.BucketNameInvalid:
			writeErrorResponse(w, req, InvalidBucketName, req.URL.Path)
		case xl.BucketNotFound:
			writeErrorResponse(w, req, NoSuchBucket, req.URL.Path)
		case xl.ObjectNotFound:
			writeErrorResponse(w, req, NoSuchKey, req.URL.Path)
		case xl.ObjectNameInvalid:
			writeErrorResponse(w, req, NoSuchKey, req.URL.Path)
		default:
			writeErrorResponse(w, req, InternalError, req.URL.Path)
		}
		return
	}
	var hrange *httpRange
	hrange, err = getRequestedRange(req.Header.Get("Range"), metadata.Size)
	if err != nil {
		writeErrorResponse(w, req, InvalidRange, req.URL.Path)
		return
	}
	setObjectHeaders(w, metadata, hrange)
	if _, err = api.XL.GetObject(w, bucket, object, hrange.start, hrange.length); err != nil {
		errorIf(err.Trace(), "GetObject failed.", nil)
		return
	}
}

// HeadObjectHandler - HEAD Object
// -----------
// The HEAD operation retrieves metadata from an object without returning the object itself.
func (api API) HeadObjectHandler(w http.ResponseWriter, req *http.Request) {
	// ticket master block
	{
		op := APIOperation{}
		op.ProceedCh = make(chan struct{})
		api.OP <- op
		// block until Ticket master gives us a go
		<-op.ProceedCh
	}

	var object, bucket string
	vars := mux.Vars(req)
	bucket = vars["bucket"]
	object = vars["object"]

	metadata, err := api.XL.GetObjectMetadata(bucket, object)
	if err != nil {
		errorIf(err.Trace(), "GetObjectMetadata failed.", nil)
		switch err.ToGoError().(type) {
		case xl.BucketNameInvalid:
			writeErrorResponse(w, req, InvalidBucketName, req.URL.Path)
		case xl.BucketNotFound:
			writeErrorResponse(w, req, NoSuchBucket, req.URL.Path)
		case xl.ObjectNotFound:
			writeErrorResponse(w, req, NoSuchKey, req.URL.Path)
		case xl.ObjectNameInvalid:
			writeErrorResponse(w, req, NoSuchKey, req.URL.Path)
		default:
			writeErrorResponse(w, req, InternalError, req.URL.Path)
		}
		return
	}
	setObjectHeaders(w, metadata, nil)
	w.WriteHeader(http.StatusOK)
}

// PutObjectHandler - PUT Object
// ----------
// This implementation of the PUT operation adds an object to a bucket.
func (api API) PutObjectHandler(w http.ResponseWriter, req *http.Request) {
	// Ticket master block
	{
		op := APIOperation{}
		op.ProceedCh = make(chan struct{})
		api.OP <- op
		// block until Ticket master gives us a go
		<-op.ProceedCh
	}

	var object, bucket string
	vars := mux.Vars(req)
	bucket = vars["bucket"]
	object = vars["object"]

	// get Content-MD5 sent by client and verify if valid
	md5 := req.Header.Get("Content-MD5")
	if !isValidMD5(md5) {
		writeErrorResponse(w, req, InvalidDigest, req.URL.Path)
		return
	}
	/// if Content-Length missing, deny the request
	size := req.Header.Get("Content-Length")
	if size == "" {
		writeErrorResponse(w, req, MissingContentLength, req.URL.Path)
		return
	}
	/// maximum Upload size for objects in a single operation
	if isMaxObjectSize(size) {
		writeErrorResponse(w, req, EntityTooLarge, req.URL.Path)
		return
	}
	/// minimum Upload size for objects in a single operation
	//
	// Surprisingly while Amazon in their document states that S3 objects have 1byte
	// as the minimum limit, they do not seem to enforce it one can successfully
	// create a 0byte file using a regular putObject() operation
	//
	// if isMinObjectSize(size) {
	//      writeErrorResponse(w, req, EntityTooSmall,  req.URL.Path)
	//	return
	// }
	var sizeInt64 int64
	{
		var err error
		sizeInt64, err = strconv.ParseInt(size, 10, 64)
		if err != nil {
			writeErrorResponse(w, req, InvalidRequest, req.URL.Path)
			return
		}
	}

	var signature *signv4.Signature
	if !api.Anonymous {
		if _, ok := req.Header["Authorization"]; ok {
			// Init signature V4 verification
			var err *probe.Error
			signature, err = initSignatureV4(req)
			if err != nil {
				errorIf(err.Trace(), "Initializing signature v4 failed.", nil)
				writeErrorResponse(w, req, InternalError, req.URL.Path)
				return
			}
		}
	}

	metadata, err := api.XL.CreateObject(bucket, object, md5, sizeInt64, req.Body, nil, signature)
	if err != nil {
		errorIf(err.Trace(), "CreateObject failed.", nil)
		switch err.ToGoError().(type) {
		case xl.BucketNotFound:
			writeErrorResponse(w, req, NoSuchBucket, req.URL.Path)
		case xl.BucketNameInvalid:
			writeErrorResponse(w, req, InvalidBucketName, req.URL.Path)
		case xl.ObjectExists:
			writeErrorResponse(w, req, MutableWriteNotAllowed, req.URL.Path)
		case xl.BadDigest:
			writeErrorResponse(w, req, BadDigest, req.URL.Path)
		case signv4.MissingDateHeader:
			writeErrorResponse(w, req, RequestTimeTooSkewed, req.URL.Path)
		case signv4.DoesNotMatch:
			writeErrorResponse(w, req, SignatureDoesNotMatch, req.URL.Path)
		case xl.IncompleteBody:
			writeErrorResponse(w, req, IncompleteBody, req.URL.Path)
		case xl.EntityTooLarge:
			writeErrorResponse(w, req, EntityTooLarge, req.URL.Path)
		case xl.InvalidDigest:
			writeErrorResponse(w, req, InvalidDigest, req.URL.Path)
		default:
			writeErrorResponse(w, req, InternalError, req.URL.Path)
		}
		return
	}
	w.Header().Set("ETag", metadata.MD5Sum)
	writeSuccessResponse(w)
}

/// Multipart API

// NewMultipartUploadHandler - New multipart upload
func (api API) NewMultipartUploadHandler(w http.ResponseWriter, req *http.Request) {
	// Ticket master block
	{
		op := APIOperation{}
		op.ProceedCh = make(chan struct{})
		api.OP <- op
		// block until Ticket master gives us a go
		<-op.ProceedCh
	}

	var object, bucket string
	vars := mux.Vars(req)
	bucket = vars["bucket"]
	object = vars["object"]

	uploadID, err := api.XL.NewMultipartUpload(bucket, object, req.Header.Get("Content-Type"))
	if err != nil {
		errorIf(err.Trace(), "NewMultipartUpload failed.", nil)
		switch err.ToGoError().(type) {
		case xl.ObjectExists:
			writeErrorResponse(w, req, MutableWriteNotAllowed, req.URL.Path)
		default:
			writeErrorResponse(w, req, InternalError, req.URL.Path)
		}
		return
	}

	response := generateInitiateMultipartUploadResponse(bucket, object, uploadID)
	encodedSuccessResponse := encodeSuccessResponse(response)
	// write headers
	setCommonHeaders(w, len(encodedSuccessResponse))
	// write body
	w.Write(encodedSuccessResponse)
}

// PutObjectPartHandler - Upload part
func (api API) PutObjectPartHandler(w http.ResponseWriter, req *http.Request) {
	// Ticket master block
	{
		op := APIOperation{}
		op.ProceedCh = make(chan struct{})
		api.OP <- op
		// block until Ticket master gives us a go
		<-op.ProceedCh
	}

	// get Content-MD5 sent by client and verify if valid
	md5 := req.Header.Get("Content-MD5")
	if !isValidMD5(md5) {
		writeErrorResponse(w, req, InvalidDigest, req.URL.Path)
		return
	}

	/// if Content-Length missing, throw away
	size := req.Header.Get("Content-Length")
	if size == "" {
		writeErrorResponse(w, req, MissingContentLength, req.URL.Path)
		return
	}

	/// maximum Upload size for multipart objects in a single operation
	if isMaxObjectSize(size) {
		writeErrorResponse(w, req, EntityTooLarge, req.URL.Path)
		return
	}

	var sizeInt64 int64
	{
		var err error
		sizeInt64, err = strconv.ParseInt(size, 10, 64)
		if err != nil {
			writeErrorResponse(w, req, InvalidRequest, req.URL.Path)
			return
		}
	}

	vars := mux.Vars(req)
	bucket := vars["bucket"]
	object := vars["object"]

	uploadID := req.URL.Query().Get("uploadId")
	partIDString := req.URL.Query().Get("partNumber")

	var partID int
	{
		var err error
		partID, err = strconv.Atoi(partIDString)
		if err != nil {
			writeErrorResponse(w, req, InvalidPart, req.URL.Path)
			return
		}
	}

	var signature *signv4.Signature
	if !api.Anonymous {
		if _, ok := req.Header["Authorization"]; ok {
			// Init signature V4 verification
			var err *probe.Error
			signature, err = initSignatureV4(req)
			if err != nil {
				errorIf(err.Trace(), "Initializing signature v4 failed.", nil)
				writeErrorResponse(w, req, InternalError, req.URL.Path)
				return
			}
		}
	}

	calculatedMD5, err := api.XL.CreateObjectPart(bucket, object, uploadID, partID, "", md5, sizeInt64, req.Body, signature)
	if err != nil {
		errorIf(err.Trace(), "CreateObjectPart failed.", nil)
		switch err.ToGoError().(type) {
		case xl.InvalidUploadID:
			writeErrorResponse(w, req, NoSuchUpload, req.URL.Path)
		case xl.ObjectExists:
			writeErrorResponse(w, req, MutableWriteNotAllowed, req.URL.Path)
		case xl.BadDigest:
			writeErrorResponse(w, req, BadDigest, req.URL.Path)
		case signv4.DoesNotMatch:
			writeErrorResponse(w, req, SignatureDoesNotMatch, req.URL.Path)
		case xl.IncompleteBody:
			writeErrorResponse(w, req, IncompleteBody, req.URL.Path)
		case xl.EntityTooLarge:
			writeErrorResponse(w, req, EntityTooLarge, req.URL.Path)
		case xl.InvalidDigest:
			writeErrorResponse(w, req, InvalidDigest, req.URL.Path)
		default:
			writeErrorResponse(w, req, InternalError, req.URL.Path)
		}
		return
	}
	w.Header().Set("ETag", calculatedMD5)
	writeSuccessResponse(w)
}

// AbortMultipartUploadHandler - Abort multipart upload
func (api API) AbortMultipartUploadHandler(w http.ResponseWriter, req *http.Request) {
	// Ticket master block
	{
		op := APIOperation{}
		op.ProceedCh = make(chan struct{})
		api.OP <- op
		// block until Ticket master gives us a go
		<-op.ProceedCh
	}

	vars := mux.Vars(req)
	bucket := vars["bucket"]
	object := vars["object"]

	objectResourcesMetadata := getObjectResources(req.URL.Query())

	err := api.XL.AbortMultipartUpload(bucket, object, objectResourcesMetadata.UploadID)
	if err != nil {
		errorIf(err.Trace(), "AbortMutlipartUpload failed.", nil)
		switch err.ToGoError().(type) {
		case xl.InvalidUploadID:
			writeErrorResponse(w, req, NoSuchUpload, req.URL.Path)
		default:
			writeErrorResponse(w, req, InternalError, req.URL.Path)
		}
		return
	}
	setCommonHeaders(w, 0)
	w.WriteHeader(http.StatusNoContent)
}

// ListObjectPartsHandler - List object parts
func (api API) ListObjectPartsHandler(w http.ResponseWriter, req *http.Request) {
	// Ticket master block
	{
		op := APIOperation{}
		op.ProceedCh = make(chan struct{})
		api.OP <- op
		// block until Ticket master gives us a go
		<-op.ProceedCh
	}

	objectResourcesMetadata := getObjectResources(req.URL.Query())
	if objectResourcesMetadata.PartNumberMarker < 0 {
		writeErrorResponse(w, req, InvalidPartNumberMarker, req.URL.Path)
		return
	}
	if objectResourcesMetadata.MaxParts < 0 {
		writeErrorResponse(w, req, InvalidMaxParts, req.URL.Path)
		return
	}
	if objectResourcesMetadata.MaxParts == 0 {
		objectResourcesMetadata.MaxParts = maxPartsList
	}

	vars := mux.Vars(req)
	bucket := vars["bucket"]
	object := vars["object"]

	objectResourcesMetadata, err := api.XL.ListObjectParts(bucket, object, objectResourcesMetadata)
	if err != nil {
		errorIf(err.Trace(), "ListObjectParts failed.", nil)
		switch err.ToGoError().(type) {
		case xl.InvalidUploadID:
			writeErrorResponse(w, req, NoSuchUpload, req.URL.Path)
		default:
			writeErrorResponse(w, req, InternalError, req.URL.Path)
		}
		return
	}
	response := generateListPartsResponse(objectResourcesMetadata)
	encodedSuccessResponse := encodeSuccessResponse(response)
	// write headers
	setCommonHeaders(w, len(encodedSuccessResponse))
	// write body
	w.Write(encodedSuccessResponse)
}

// CompleteMultipartUploadHandler - Complete multipart upload
func (api API) CompleteMultipartUploadHandler(w http.ResponseWriter, req *http.Request) {
	// Ticket master block
	{
		op := APIOperation{}
		op.ProceedCh = make(chan struct{})
		api.OP <- op
		// block until Ticket master gives us a go
		<-op.ProceedCh
	}

	vars := mux.Vars(req)
	bucket := vars["bucket"]
	object := vars["object"]

	objectResourcesMetadata := getObjectResources(req.URL.Query())

	var signature *signv4.Signature
	if !api.Anonymous {
		if _, ok := req.Header["Authorization"]; ok {
			// Init signature V4 verification
			var err *probe.Error
			signature, err = initSignatureV4(req)
			if err != nil {
				errorIf(err.Trace(), "Initializing signature v4 failed.", nil)
				writeErrorResponse(w, req, InternalError, req.URL.Path)
				return
			}
		}
	}

	metadata, err := api.XL.CompleteMultipartUpload(bucket, object, objectResourcesMetadata.UploadID, req.Body, signature)
	if err != nil {
		errorIf(err.Trace(), "CompleteMultipartUpload failed.", nil)
		switch err.ToGoError().(type) {
		case xl.InvalidUploadID:
			writeErrorResponse(w, req, NoSuchUpload, req.URL.Path)
		case xl.InvalidPart:
			writeErrorResponse(w, req, InvalidPart, req.URL.Path)
		case xl.InvalidPartOrder:
			writeErrorResponse(w, req, InvalidPartOrder, req.URL.Path)
		case signv4.MissingDateHeader:
			writeErrorResponse(w, req, RequestTimeTooSkewed, req.URL.Path)
		case signv4.DoesNotMatch:
			writeErrorResponse(w, req, SignatureDoesNotMatch, req.URL.Path)
		case xl.IncompleteBody:
			writeErrorResponse(w, req, IncompleteBody, req.URL.Path)
		case xl.MalformedXML:
			writeErrorResponse(w, req, MalformedXML, req.URL.Path)
		default:
			writeErrorResponse(w, req, InternalError, req.URL.Path)
		}
		return
	}
	response := generateCompleteMultpartUploadResponse(bucket, object, "", metadata.MD5Sum)
	encodedSuccessResponse := encodeSuccessResponse(response)
	// write headers
	setCommonHeaders(w, len(encodedSuccessResponse))
	// write body
	w.Write(encodedSuccessResponse)
}

/// Delete API

// DeleteBucketHandler - Delete bucket
func (api API) DeleteBucketHandler(w http.ResponseWriter, req *http.Request) {
	writeErrorResponse(w, req, DeleteNotAllowed, req.URL.Path)
}

// DeleteObjectHandler - Delete object
func (api API) DeleteObjectHandler(w http.ResponseWriter, req *http.Request) {
	writeErrorResponse(w, req, DeleteNotAllowed, req.URL.Path)
}


text:
import crypto from 'crypto'
import mongoose from 'mongoose'
import uniqueValidator from 'mongoose-unique-validator'
import jwt from 'jsonwebtoken'
import {secret} from '../config'

export default getUserSchema

function getUserSchema() {
  const UserSchema = new mongoose.Schema(
    {
      username: {
        type: String,
        lowercase: true,
        unique: true,
        required: [true, `can't be blank`],
        match: [/^[a-zA-Z0-9]+$/, 'is invalid'],
        index: true,
      },
      email: {
        type: String,
        lowercase: true,
        unique: true,
        required: [true, `can't be blank`],
        match: [/\S+@\S+\.\S+/, 'is invalid'],
        index: true,
      },
      bio: String,
      image: String,
      favorites: [{type: mongoose.Schema.Types.ObjectId, ref: 'Article'}],
      following: [{type: mongoose.Schema.Types.ObjectId, ref: 'User'}],
      hash: String,
      salt: String,
    },
    {timestamps: true},
  )

  UserSchema.plugin(uniqueValidator, {message: 'is already taken.'})

  UserSchema.methods.validPassword = function(password) {
    const hash = crypto
      .pbkdf2Sync(password, this.salt, 10000, 512, 'sha512')
      .toString('hex')
    return this.hash === hash
  }

  UserSchema.methods.setPassword = function(password) {
    this.salt = crypto.randomBytes(16).toString('hex')
    this.hash = crypto
      .pbkdf2Sync(password, this.salt, 10000, 512, 'sha512')
      .toString('hex')
  }

  UserSchema.methods.generateJWT = function() {
    const today = new Date()
    const exp = new Date(today)
    exp.setDate(today.getDate() + 60)

    return jwt.sign(
      {
        id: this._id,
        username: this.username,
        exp: parseInt(exp.getTime() / 1000, 10),
      },
      secret,
    )
  }

  UserSchema.methods.toAuthJSON = function() {
    return {
      username: this.username,
      email: this.email,
      bio: this.bio,
      token: this.generateJWT(),
      image: this.image,
    }
  }

  UserSchema.methods.toProfileJSONFor = function(user) {
    return {
      username: this.username,
      bio: this.bio,
      // WORKSHOP_START
      // this is where the bug is...
      // we're not adding this.image
      // to the object!
      // WORKSHOP_END
      // FINAL_START
      image: this.image,
      // FINAL_END
      following: user ? user.isFollowing(this._id) : false,
    }
  }

  UserSchema.methods.favorite = function(id) {
    if (this.favorites.indexOf(id) === -1) {
      this.favorites.push(id)
    }

    return this.save()
  }

  UserSchema.methods.unfavorite = function(id) {
    this.favorites.remove(id)
    return this.save()
  }

  UserSchema.methods.isFavorite = function(id) {
    return this.favorites.some(favoriteId => {
      return favoriteId.toString() === id.toString()
    })
  }

  UserSchema.methods.follow = function(id) {
    if (this.following.indexOf(id) === -1) {
      this.following.push(id)
    }

    return this.save()
  }

  UserSchema.methods.unfollow = function(id) {
    this.following.remove(id)
    return this.save()
  }

  UserSchema.methods.isFollowing = function(id) {
    return this.following.some(followId => {
      return followId.toString() === id.toString()
    })
  }

  return UserSchema
}


text:
package me.stevenkin.boomvc.mvc.resolver.imp;

import me.stevenkin.boomvc.common.kit.ReflectKit;
import me.stevenkin.boomvc.common.resolver.MethodParameter;
import me.stevenkin.boomvc.http.HttpQueryParameter;
import me.stevenkin.boomvc.http.HttpRequest;
import me.stevenkin.boomvc.http.HttpResponse;
import me.stevenkin.boomvc.ioc.annotation.Bean;
import me.stevenkin.boomvc.mvc.annotation.QueryParam;
import me.stevenkin.boomvc.mvc.exception.ParameterResolverException;

import java.lang.reflect.Type;
import java.util.*;
import java.util.stream.Collectors;

@Bean
public class QueryParamResolver extends AbstractParameterResolver {

    @Override
    public boolean support(MethodParameter parameter) {
        return parameter.getParameterAnnotation() != null && parameter.getParameterAnnotation() instanceof QueryParam &&
                (ReflectKit.isBasicType(parameter.getParameterType()) || ReflectKit.isCollectionType(parameter.getParameterType()));
    }

    @Override
    public Object resolve(MethodParameter parameter, HttpRequest request, HttpResponse response) throws Exception {
        QueryParam queryParam = (QueryParam) parameter.getParameterAnnotation();
        Type type = parameter.getParameterType();
        if(queryParam == null)
            return null;
        String name = "".equals(queryParam.value()) ? parameter.getParameterName() : queryParam.value();
        Optional<HttpQueryParameter> queryParameter = request.firstParameter(name);
        if(!queryParameter.isPresent())
            throw new ParameterResolverException("query key [" + name + "] not exist");
        if(ReflectKit.isBasicType(parameter.getParameterType())){
            String value = queryParameter.get().value();
            return basicTypeParameterResolve(value, parameter.getParameterType());
        }
        if(ReflectKit.isCollectionType(type)){
            return collectionTypeResolve(request.parameters(name).stream().map(HttpQueryParameter::value).collect(Collectors.toList()), type);
        }
        throw new ParameterResolverException("type [" + type + "] is wrong");
    }
}


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=../../../../libc/constant.NLMSG_DONE.html">

Redirecting to ../../../../libc/constant.NLMSG_DONE.html...


text:
#undef G_DISABLE_ASSERT
#undef G_LOG_DOMAIN

#include <glib.h>

#define NSOURCES 50000

static gboolean
callback (gpointer user_data)
{
  g_assert_not_reached ();
  return FALSE;
}

static void
shuffle (GSource **sources, int num)
{
  int i, a, b;
  GSource *tmp;

  for (i = 0; i < num * 10; i++)
    {
      a = g_random_int_range (0, num);
      b = g_random_int_range (0, num);
      tmp = sources[a];
      sources[a] = sources[b];
      sources[b] = tmp;
    }
}

static void
thread_pool_attach_func (gpointer data,
                         gpointer user_data)
{
  GMainContext *context = user_data;
  GSource *source = data;

  g_source_attach (source, context);
}

static void
thread_pool_destroy_func (gpointer data,
                          gpointer user_data)
{
  GSource *source = data;

  g_source_destroy (source);
}

int
main (int argc, char **argv)
{
  int i;
  gint64 start;
  gint64 end;
  GMainContext *context;
  GSource **sources;
  GThreadPool *pool;
  GError *error = NULL;

  context = g_main_context_default ();
  sources = g_new0 (GSource *, NSOURCES);

  start = g_get_monotonic_time ();
  for (i = 0; i < NSOURCES; i++)
    {
      sources[i] = g_idle_source_new ();
      g_source_set_callback (sources[i], callback, NULL, NULL);
      g_source_attach (sources[i], context);
    }
  end = g_get_monotonic_time ();
  g_print ("Add same-priority sources: %" G_GINT64_FORMAT "\n",
           (end - start) / 1000);

#ifdef SLOW
  start = g_get_monotonic_time ();
  for (i = 0; i < NSOURCES; i++)
    g_assert (sources[i] == g_main_context_find_source_by_id (context, g_source_get_id (sources[i])));
  end = g_get_monotonic_time ();
  g_print ("Find each source: %" G_GINT64_FORMAT "\n",
           (end - start) / 1000);
#endif

  shuffle (sources, NSOURCES);

  start = g_get_monotonic_time ();
  for (i = 0; i < NSOURCES; i++)
    g_source_destroy (sources[i]);
  end = g_get_monotonic_time ();
  g_print ("Remove in random order: %" G_GINT64_FORMAT "\n",
           (end - start) / 1000);

  /* Make sure they really did get removed */
  g_main_context_iteration (context, FALSE);

  start = g_get_monotonic_time ();
  for (i = 0; i < NSOURCES; i++)
    {
      sources[i] = g_idle_source_new ();
      g_source_set_callback (sources[i], callback, NULL, NULL);
      g_source_set_priority (sources[i], i % 100);
      g_source_attach (sources[i], context);
    }
  end = g_get_monotonic_time ();
  g_print ("Add different-priority sources: %" G_GINT64_FORMAT "\n",
           (end - start) / 1000);

#ifdef SLOW
  start = g_get_monotonic_time ();
  for (i = 0; i < NSOURCES; i++)
    g_assert (sources[i] == g_main_context_find_source_by_id (context, g_source_get_id (sources[i])));
  end = g_get_monotonic_time ();
  g_print ("Find each source: %" G_GINT64_FORMAT "\n",
           (end - start) / 1000);
#endif

  shuffle (sources, NSOURCES);

  start = g_get_monotonic_time ();
  for (i = 0; i < NSOURCES; i++)
    g_source_destroy (sources[i]);
  end = g_get_monotonic_time ();
  g_print ("Remove in random order: %" G_GINT64_FORMAT "\n",
           (end - start) / 1000);

  /* Make sure they really did get removed */
  g_main_context_iteration (context, FALSE);

  pool = g_thread_pool_new (thread_pool_attach_func, context,
                            20, TRUE, NULL);
  start = g_get_monotonic_time ();
  for (i = 0; i < NSOURCES; i++)
    {
      sources[i] = g_idle_source_new ();
      g_source_set_callback (sources[i], callback, NULL, NULL);
      g_thread_pool_push (pool, sources[i], &error);
      g_assert_no_error (error);
    }
  g_thread_pool_free (pool, FALSE, TRUE);
  end = g_get_monotonic_time ();
  g_print ("Add sources from threads: %" G_GINT64_FORMAT "\n",
           (end - start) / 1000);

  pool = g_thread_pool_new (thread_pool_destroy_func, context,
                            20, TRUE, NULL);
  start = g_get_monotonic_time ();
  for (i = 0; i < NSOURCES; i++)
    {
      g_thread_pool_push (pool, sources[i], &error);
      g_assert_no_error (error);
    }
  g_thread_pool_free (pool, FALSE, TRUE);
  end = g_get_monotonic_time ();
  g_print ("Remove sources from threads: %" G_GINT64_FORMAT "\n",
           (end - start) / 1000);

  /* Make sure they really did get removed */
  g_main_context_iteration (context, FALSE);

  return 0;
}


text:
package com.thoughtworks.go.server.service.dd;

import java.util.Map;

import com.thoughtworks.go.config.PipelineConfig;
import com.thoughtworks.go.config.ValidationContext;
import com.thoughtworks.go.config.materials.AbstractMaterialConfig;
import com.thoughtworks.go.config.materials.Filter;

public class SomeRandomMaterialConfig extends AbstractMaterialConfig {
    public SomeRandomMaterialConfig() {
        super("SomeRandomMaterial");
    }

    @Override
    protected void appendCriteria(Map<String, Object> parameters) {
        throw new RuntimeException("Ouch!");
    }

    @Override
    protected void appendAttributes(Map<String, Object> parameters) {
        throw new RuntimeException("Ouch!");
    }

    @Override
    protected void appendPipelineUniqueCriteria(Map<String, Object> basicCriteria) {
        throw new RuntimeException("Ouch!");
    }

    @Override
    protected void validateConcreteMaterial(ValidationContext validationContext) {
        throw new RuntimeException("Ouch!");
    }

    @Override
    public String getFolder() {
        throw new RuntimeException("Ouch!");
    }

    @Override
    public Filter filter() {
        throw new RuntimeException("Ouch!");
    }

    @Override
    public boolean isInvertFilter() {
        throw new RuntimeException("Ouch!");
    }

    @Override
    public boolean matches(String name, String regex) {
        throw new RuntimeException("Ouch!");
    }

    @Override
    public String getDescription() {
        throw new RuntimeException("Ouch!");
    }

    @Override
    public String getTypeForDisplay() {
        throw new RuntimeException("Ouch!");
    }

    @Override
    public String getDisplayName() {
        throw new RuntimeException("Ouch!");
    }

    @Override
    public boolean isAutoUpdate() {
        throw new RuntimeException("Ouch!");
    }

    @Override
    public void setAutoUpdate(boolean autoUpdate)  {
        throw new RuntimeException("Ouch!");
    }

    @Override
    public String getUriForDisplay() {
        throw new RuntimeException("Ouch!");
    }

    @Override
    public Boolean isUsedInFetchArtifact(PipelineConfig pipelineConfig) {
        throw new RuntimeException("Ouch!");
    }

    @Override
    public String getLongDescription() {
        throw new RuntimeException("Ouch!");
    }
}


text:
package cd4017be.kineng.tileentity;

import static cd4017be.kineng.block.BlockGear.DIAMETER;
import static cd4017be.lib.network.Sync.Type.F32;
import static java.lang.Double.*;
import static net.minecraft.util.EnumFacing.getFacingFromAxis;
import static net.minecraft.util.EnumFacing.AxisDirection.NEGATIVE;
import static net.minecraft.util.EnumFacing.AxisDirection.POSITIVE;
import java.util.List;
import java.util.Random;
import cd4017be.kineng.block.BlockTurbine;
import cd4017be.kineng.physics.*;
import cd4017be.lib.block.AdvancedBlock.IInteractiveTile;
import cd4017be.lib.block.AdvancedBlock.ITilePlaceHarvest;
import cd4017be.lib.network.Sync;
import cd4017be.lib.tileentity.BaseTileEntity.ITickableServerOnly;
import cd4017be.lib.util.Utils;
import cd4017be.math.cplx.CplxD;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumFacing.Axis;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.BlockPos.MutableBlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.world.World;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.chunk.Chunk;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

/**
 * @author CD4017BE */
public class WindTurbine extends ShaftPart implements ITickableServerOnly, IInteractiveTile, ITilePlaceHarvest {

	/** [kg/m³] */
	public static double AIR_DENSITY;
	public static int DT0 = 20, DT_RAND = 40;
	public static float WIND_SCALE;

	ForceCon con;
	double a;
	@Sync(type = F32) public double v0;
	@Sync(tag = "cl") public float obstr = 1F;
	int t;

	@Override
	public void update() {
		if (con == null) return;
		((Turbine)con.force).v_air += a;
		if (--t > 0) return;
		updateWindSpeed();
	}

	public void updateWindSpeed() {
		Random rand = world.rand;
		t = DT0 + rand.nextInt(DT_RAND);
		int r = (int)Math.ceil(block().radius(getBlockState()) * 2.0), d1, d2;
		do {
			d1 = rand.nextInt(r) - rand.nextInt(r);
			d2 = rand.nextInt(r) - rand.nextInt(r);
		} while(d1 == 0 && d2 == 0);
		Axis axis = axis();
		BlockPos pos0;
		switch(axis) {
		case X: pos0 = new BlockPos(pos.getX(), pos.getY() + d1, pos.getZ() + d2); break;
		case Y: pos0 = new BlockPos(pos.getX() + d1, pos.getY(), pos.getZ() + d2); break;
		default: pos0 = new BlockPos(pos.getX() + d1, pos.getY() + d2, pos.getZ());
		}
		boolean dir = rand.nextBoolean();
		EnumFacing face = getFacingFromAxis(dir ? POSITIVE : NEGATIVE, axis);
		obstr += (1F - obstr) * 0.0625F;
		for (int i = r; i >= 0; i--) {
			pos0 = pos0.offset(face);
			Chunk chunk = world.getChunkProvider().getLoadedChunk(pos0.getX() >> 4, pos0.getZ() >> 4);
			if (chunk == null) break;
			else if (chunk.getBlockState(pos0).getMaterial().blocksMovement()) {
				float d = 1F - (float)i / (float)r;
				d *= dir ^ v0 > 0 ? 2F : 8F;
				obstr -= 0.0625F / (d*d + 1F);
				break;
			}
		}
		float v = (1F + 0.5F * world.thunderingStrength * (rand.nextFloat() + 1F)) * obstr;
		a = (v * v0 - ((Turbine)con.force).v_air) / (double)t;
	}

	@Override
	public double setShaft(ShaftAxis shaft) {
		if (con == null && shaft != null) {
			BlockTurbine block = block();
			IBlockState state = getBlockState();
			double r = block.radius(state);
			con = new ForceCon(this, 2.5);
			con.link(new Turbine(r, AIR_DENSITY));
			con.maxF = block.maxF[state.getValue(DIAMETER)];
		}
		con.setShaft(shaft);
		return super.setShaft(shaft);
	}

	@Override
	public void onPlaced(EntityLivingBase entity, ItemStack item) {
		if (world.isRemote) return;
		Vec3d v = baseWindSpeed(world, pos);
		switch(axis()) {
		case X: v0 = v.x; break;
		case Y: v0 = v.y; break;
		default: v0 = v.z; break;
		}
		if (entity instanceof EntityPlayer)
			((EntityPlayer)entity).sendStatusMessage(new TextComponentString(
				String.format("base wind speed: %.3g m/s", v0)
			), true);
	}

	@Override
	public List<ItemStack> dropItem(IBlockState state, int fortune) {
		return makeDefaultDrops(null);
	}

	@Override
	public boolean onActivated(
		EntityPlayer player, EnumHand hand, ItemStack item, EnumFacing s, float X, float Y, float Z
	) {
		if (con == null || world.isRemote) return true;
		double v = ((Turbine)con.force).v_air;
		if (Utils.coord(X, Y, Z, getFacingFromAxis(POSITIVE, axis())) > 0.5) v = -v;
		player.sendStatusMessage(new TextComponentString(
			String.format("current wind: %.1f m/s", v)
		), true);
		return true;
	}

	@Override
	public void onClicked(EntityPlayer player) {}

	@Override
	@SideOnly(Side.CLIENT)
	public int[] capModel(boolean end) {
		return null;
	}

	static class Turbine extends DynamicForce {

		final double A;
		double v_air;

		public Turbine(double r, double d) {
			A = 0.5 * Math.PI * r * r * d;
		}

		@Override
		public ForceCon getM(CplxD M, double av) {
			//Fdv = -abs((v_air - v) * A)
			Fdv = longBitsToDouble(doubleToRawLongBits((v_air - av * r) * A) | 0x80000000_00000000L);
			F = -v_air * Fdv;
			return super.getM(M, av);
		}

	}

	public static Vec3d baseWindSpeed(World world, BlockPos pos) {
		MutableBlockPos pos1 = new MutableBlockPos();
		final int r = 7;
		float[] arr = new float[(r+r+1) * (r+r+1) << 1];
		float y = 0, ud = 0;
		for (int i = 0, dx = -r; dx <= r; dx++)
			for (int dz = -r; dz <= r; dz++, i+=2) {
				y += getAtmParam(world, pos1.setPos(
					pos.getX() + (dx << 4), pos.getY(), pos.getZ() + (dz << 4)
				), arr, i);
				ud += arr[i];
			}
		y /= arr.length >> 1;
		ud /= arr.length >> 1;
		float vx = 0, vz = 0, vy = 0, c = 0, s = 0, d = 0;
		for (int i = 0, x = -r; x <= r; x++)
			for (int z = -r; z <= r; z++, i+=2) {
				float w = 1F / (x*x + z*z + y*y);
				float updraft = arr[i] * w;
				vx += updraft * x;
				vz += updraft * z;
				vy += (updraft - ud * w) * y;
				c += arr[i+1] * w;
				s += w;
				d += w * Math.abs(x);
			}
		d = WIND_SCALE * c / (s * d);
		s = WIND_SCALE * c / (s * s);
		vx *= d; vy *= s; vz *= d;
		return new Vec3d(
			Math.copySign(Math.sqrt(Math.abs(vx)), vx),
			Math.copySign(Math.sqrt(Math.abs(vy)), vy),
			Math.copySign(Math.sqrt(Math.abs(vz)), vz)
		);
	}

	/**@param world
	 * @param pos
	 * @param buffer [updraft, clearance]
	 * @param i buffer store base pointer */
	static float getAtmParam(World world, BlockPos pos, float[] buffer, int i) {
		Biome b = world.getBiome(pos);
		buffer[i] = b.getDefaultTemperature();
		float forest = 0.2F - 1F / (5F + b.decorator.treesPerChunk);
		float height = b.getBaseHeight() + forest * 0.5F;
		float var = b.getHeightVariation() + forest;
		if (height < var)
			var = height = Math.max((height + var) * 0.5F, 0);
		height = Math.max((pos.getY() - world.getSeaLevel()) / 32F - height, 0.5F);
		buffer[i+1] = height / (height + var);
		return height;
	}

}


text:
package fr.adrienbrault.idea.symfony2plugin.form.dict;

import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.jetbrains.php.lang.psi.elements.PhpClass;
import fr.adrienbrault.idea.symfony2plugin.util.PhpElementsUtil;
import org.jetbrains.annotations.Nullable;

public class FormTypeClass {

    final private String name;
    private PhpClass phpClass;
    private String phpClassName;
    private PsiElement returnPsiElement;
    final private EnumFormTypeSource source;

    public FormTypeClass(String name, PhpClass phpClass, PsiElement returnPsiElement, EnumFormTypeSource source) {
        this.name = name;
        this.phpClass = phpClass;
        this.returnPsiElement = returnPsiElement;
        this.source = source;
    }

    public FormTypeClass(String name, String phpClassName, EnumFormTypeSource source) {
        this.name = name;
        this.phpClassName = phpClassName;
        this.source = source;
    }

    public String getName() {
        return name;
    }

    @Nullable
    public PhpClass getPhpClass() {
        return phpClass;
    }

    @Nullable
    public PhpClass getPhpClass(Project project) {

        if(phpClass != null) {
            return phpClass;
        }

        if(this.phpClassName == null) {
            return null;
        }

        return PhpElementsUtil.getClass(project, this.phpClassName);
    }

    @Nullable
    public PsiElement getReturnPsiElement() {
        return returnPsiElement;
    }

    public EnumFormTypeSource getSource() {
        return source;
    }

    public String getPhpClassName() {
        return phpClassName;
    }

}