text:
package org.apache.sshd.common.util;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.NoSuchElementException;

import org.apache.sshd.util.BaseTestSupport;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;

/**
 * @author Apache MINA SSHD Project
 */
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class GenericUtilsTest extends BaseTestSupport {
    public GenericUtilsTest() {
        super();
    }

    @Test
    public void testSplitAndJoin() {
        List<String> expected = Collections.unmodifiableList(
                Arrays.asList(getClass().getPackage().getName().replace('.', '/'), getClass().getSimpleName(), getCurrentTestName()));

        // NOTE: we also test characters that have meaning in String.split(...) as regex ones
        for (char ch : new char[]{',', '.', '*', '?'}) {
            String sep = String.valueOf(ch);
            String s = GenericUtils.join(expected, sep);
            String[] actual = GenericUtils.split(s, ch);
            assertEquals("Mismatched split length for separator=" + sep, expected.size(), GenericUtils.length((Object[]) actual));

            for (int index = 0; index < actual.length; index++) {
                String e = expected.get(index), a = actual[index];
                if (!e.endsWith(a)) {
                    fail("Mismatched value at index=" + index + " for separator=" + sep + ": expected=" + e + ", actual=" + a);
                }
            }
        }
    }

    @Test
    public void testStripQuotes() {
        String expected = getCurrentTestName();
        assertSame("Unexpected un-quoted stripping", expected, GenericUtils.stripQuotes(expected));

        StringBuilder sb = new StringBuilder(2 + expected.length()).append('|').append(expected).append('|');
        for (int index = 0; index < GenericUtils.QUOTES.length(); index++) {
            char delim = GenericUtils.QUOTES.charAt(index);
            sb.setCharAt(0, delim);
            sb.setCharAt(sb.length() - 1, delim);

            CharSequence actual = GenericUtils.stripQuotes(sb);
            assertEquals("Mismatched result for delim (" + delim + ")", expected, actual.toString());
        }
    }

    @Test
    public void testStripOnlyFirstLayerQuotes() {
        StringBuilder sb = new StringBuilder().append("||").append(getCurrentTestName()).append("||");
        char[] delims = {'\'', '"', '"', '\''};
        for (int index = 0; index < delims.length; index += 2) {
            char topDelim = delims[index], innerDelim = delims[index + 1];
            sb.setCharAt(0, topDelim);
            sb.setCharAt(1, innerDelim);
            sb.setCharAt(sb.length() - 2, innerDelim);
            sb.setCharAt(sb.length() - 1, topDelim);

            CharSequence expected = sb.subSequence(1, sb.length() - 1);
            CharSequence actual = GenericUtils.stripQuotes(sb);
            assertEquals("Mismatched result for delim (" + topDelim + "/" + innerDelim + ")", expected.toString(), actual.toString());
        }
    }

    @Test
    public void testStripDelimiters() {
        String expected = getCurrentTestName();
        final char delim = '|';
        assertSame("Unexpected un-delimited stripping", expected, GenericUtils.stripDelimiters(expected, delim));

        CharSequence actual = GenericUtils.stripDelimiters(
                new StringBuilder(2 + expected.length()).append(delim).append(expected).append(delim), delim);
        assertEquals("Mismatched stripped values", expected, actual.toString());
    }

    @Test
    public void testStripDelimitersOnlyIfOnBothEnds() {
        final char delim = '$';
        StringBuilder expected = new StringBuilder().append(delim).append(getCurrentTestName()).append(delim);
        for (int index : new int[]{0, expected.length() - 1}) {
            // restore original delimiters
            expected.setCharAt(0, delim);
            expected.setCharAt(expected.length() - 1, delim);
            // trash one end
            expected.setCharAt(index, (char) (delim + 1));

            assertSame("Mismatched result for delim at index=" + index, expected, GenericUtils.stripDelimiters(expected, delim));
        }
    }

    @Test
    public void testAccumulateExceptionOnNullValues() {
        assertNull("Unexpected null/null result", GenericUtils.accumulateException(null, null));

        Throwable expected = new NoSuchMethodException(getClass().getName() + "#" + getCurrentTestName());
        assertSame("Mismatched null/extra result", expected, GenericUtils.accumulateException(null, expected));
        assertSame("Mismatched current/null result", expected, GenericUtils.accumulateException(expected, null));
    }

    @Test
    public void testAccumulateExceptionOnExistingCurrent() {
        RuntimeException[] expected = new RuntimeException[]{
                new IllegalArgumentException(getCurrentTestName()),
                new ClassCastException(getClass().getName()),
                new NoSuchElementException(getClass().getPackage().getName())
        };
        RuntimeException current = new UnsupportedOperationException("top");
        for (RuntimeException extra : expected) {
            RuntimeException actual = GenericUtils.accumulateException(current, extra);
            assertSame("Mismatched returned actual exception", current, actual);
        }

        Throwable[] actual = current.getSuppressed();
        assertArrayEquals("Suppressed", expected, actual);
    }
}


text:
package org.apache.lens.server.user;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import org.apache.lens.server.api.LensConfConstants;
import org.apache.lens.server.api.user.UserConfigLoader;
import org.apache.lens.server.api.user.UserConfigLoaderException;
import org.apache.lens.server.util.UtilityMethods;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.hadoop.hive.conf.HiveConf;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

/**
 * The Class DatabaseUserConfigLoader.
 */
public class DatabaseUserConfigLoader implements UserConfigLoader {

  /** The query sql. */
  protected final String querySql;

  /** The keys. */
  protected final String[] keys;

  /** The cache. */
  protected final Cache<String, Map<String, String>> cache;
  private final HiveConf hiveConf;

  /** The ds. */
  protected BasicDataSource ds;

  /**
   * Instantiates a new database user config loader.
   *
   * @param conf the conf
   * @throws UserConfigLoaderException the user config loader exception
   */
  public DatabaseUserConfigLoader(HiveConf conf) throws UserConfigLoaderException {
    this.hiveConf = conf;
    querySql = conf.get(LensConfConstants.USER_RESOLVER_DB_QUERY);
    keys = conf.get(LensConfConstants.USER_RESOLVER_DB_KEYS).split("\\s*,\\s*", -1);
    cache = CacheBuilder.newBuilder()
      .expireAfterWrite(conf.getInt(LensConfConstants.USER_RESOLVER_CACHE_EXPIRY, 2), TimeUnit.HOURS)
      .maximumSize(conf.getInt(LensConfConstants.USER_RESOLVER_CACHE_MAX_SIZE, 100)).build();
  }

  /*
   * (non-Javadoc)
   *
   * @see org.apache.lens.server.user.UserConfigLoader#getUserConfig(java.lang.String)
   */
  @Override
  public Map<String, String> getUserConfig(final String loggedInUser) throws UserConfigLoaderException {
    try {
      return cache.get(loggedInUser, new Callable<Map<String, String>>() {
        @Override
        public Map<String, String> call() throws Exception {
          try {
            final String[] config = queryDatabase(querySql, false, loggedInUser);
            if (config.length != keys.length) {
              throw new UserConfigLoaderException("size of columns retrieved by db query(" + config.length + ") "
                + "is not equal to the number of keys required(" + keys.length + ").");
            }
            return new HashMap<String, String>() {
              {
                for (int i = 0; i < keys.length; i++) {
                  put(keys[i], config[i]);
                }
              }
            };
          } catch (SQLException e) {
            throw new UserConfigLoaderException(e);
          }
        }
      });
    } catch (ExecutionException e) {
      throw new UserConfigLoaderException(e);
    }
  }

  private BasicDataSource refreshDataSource() {
    if (ds == null || ds.isClosed()) {
      ds = UtilityMethods.getDataSourceFromConf(hiveConf);
    }
    return ds;
  }

  String[] queryDatabase(String querySql, boolean allowNull, Object... args) throws SQLException {
    return UtilityMethods.queryDatabase(refreshDataSource(), querySql, allowNull, args);
  }
}

redpajama_set_name: RedPajamaGithub


text:
+++
date = "Thu Jun 11 10:47:24 UTC 2020"
lastmod = "Fri Jun 12 13:28:24 UTC 2020"
title = "Android: ActivityResultContractを使ってRuntime Permissionsを実装する"
tags = ["android", "jetpack", "activity"]
blogimport = true
type = "post"
draft = false
+++

Activity 1.2.0-alpha02から導入された、ActivityResultContractを使うことで、Runtime Permissionsをいい感じに実装することが可能になりました。

この記事では、どのように実装すれば良いかを簡単に説明します。

## 単一のPermissonを要求する

新しく追加された `registerForActivityResult` 拡張関数に、`ActivityResultContracts.RequestPermission()`を指定することで、単一のPermissionを要求することが出来ます。

例えば、`android.permission.ACCESS_FINE_LOCATION`が欲しい時は、次のように書くことが出来ます。

```kotlin
class HogeActivity : AppCompatActivity() {

  // 定義側
  private val requestLocation = registerForActivityResult(
    ActivityResultContracts.RequestPermission(),
    ACCESS_FINE_LOCATION
  ) { isGranted ->
    // Permissionの取得に成功したかどうか、Boolean値で返ってくる
    Toast.makeText(this@AppActivity, "isGranted $isGranted", Toast.LENGTH_LONG).show()
  }

  private fun hoge() {
    // 呼び出し側
    requestLocation.launch(Unit)
  }
}
```

## 複数のPermissonを要求する

複数の場合は、`ActivityResultContracts.RequestMultiplePermissions()`を指定します。

例えば、`android.permission.ACCESS_FINE_LOCATION`、`android.permission.READ_EXTERNAL_STORAGE`が欲しい時は、次のように書くことが出来ます。

```kotlin
class HogeActivity : AppCompatActivity(R.layout.app_act) {
  // 定義側
  private val requestPermissions = registerForActivityResult(
    ActivityResultContracts.RequestMultiplePermissions(),
    arrayOf(ACCESS_FINE_LOCATION, READ_EXTERNAL_STORAGE
  ) { grants ->
    // Permissionの取得に成功したかどうか、Map<String, Boolean>>で返ってくる
    Toast.makeText(this@AppActivity, "grants $grants", Toast.LENGTH_LONG).show()
  }

  private fun hoge() {
    // 呼び出し側
    requestPermissions.launch(Unit)
  }
}
```

## まとめ

ActivityResultContract便利〜


text:
module Agents
  class CommanderAgent < Agent
    include AgentControllerConcern

    cannot_create_events!

    description <<-MD
      This agent is triggered by schedule or an incoming event and commands other agents ("targets") to run, disable, configure, or enable themselves.

      # Action types

      Set `action` to one of the action types below:

      * `run`: Target Agents are run when this agent is triggered.

      * `disable`: Target Agents are disabled (if not) when this agent is triggered.

      * `enable`: Target Agents are enabled (if not) when this agent is triggered.

      * `configure`: Target Agents have their options updated with the contents of `configure_options`.

      Here's a tip: you can use Liquid templating to dynamically determine the action type.  For example:

      - To create a CommanderAgent that receives an event from a WeatherAgent every morning to kick an agent flow that is only useful in a nice weather, try this: `{% if conditions contains 'Sunny' or conditions contains 'Cloudy' %}` `run{% endif %}`

      - Likewise, if you have a scheduled agent flow specially crafted for rainy days, try this: `{% if conditions contains 'Rain' %}enable{% else %}disabled{% endif %}`

      - If you want to update a WeatherAgent based on a UserLocationAgent, you could use `'action': 'configure'` and set 'configure_options' to `{ 'location': '{{_location_.latlng}}' }`.

      # Targets

      Select Agents that you want to control from this CommanderAgent.
    MD

    def working?
      true
    end

    def check!
      control!
    end

    def receive(incoming_events)
      incoming_events.each do |event|
        interpolate_with(event) do
          control!
        end
      end
    end
  end
end


text:
package org.jkiss.dbeaver.runtime.net;

import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.model.DBPDataSourceContainer;
import org.jkiss.dbeaver.model.exec.DBExecUtils;
import org.jkiss.dbeaver.model.impl.net.SocksConstants;
import org.jkiss.dbeaver.model.net.DBWHandlerConfiguration;
import org.jkiss.dbeaver.model.net.DBWHandlerType;
import org.jkiss.utils.CommonUtils;

import java.io.IOException;
import java.net.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Global proxy selector
 */
public class GlobalProxySelector extends ProxySelector {

    private static final Log log = Log.getLog(GlobalProxySelector.class);
    private static final String[] LOCAL_HOSTS = { "localhost", "127.0.0.1" };

    private final ProxySelector parent;

    public GlobalProxySelector(ProxySelector parent) {
        this.parent = parent;
    }

    public ProxySelector getParent() {
        return parent;
    }

    @Override
    public List<Proxy> select(URI uri) {
        DBPDataSourceContainer dataSourceContainer = getActiveDataSourceContainer(uri);

        if (dataSourceContainer != null) {
            List<Proxy> proxies = getProxiesForDataSource(uri, dataSourceContainer);
            if (proxies != null) {
                return proxies;
            }
        }
        return parent.select(uri);
    }

    @Nullable
    protected List<Proxy> getProxiesForDataSource(@NotNull URI uri, @NotNull DBPDataSourceContainer dataSourceContainer) {
        if (SocksConstants.SOCKET_SCHEME.equals(uri.getScheme())) {
            // 2. Check for connections' proxy config
            List<Proxy> proxies = null;
            for (DBWHandlerConfiguration networkHandler : dataSourceContainer.getConnectionConfiguration().getHandlers()) {
                if (networkHandler.isEnabled() && networkHandler.getType() == DBWHandlerType.PROXY) {
                    String proxyHost = networkHandler.getStringProperty(SocksConstants.PROP_HOST);
                    int proxyPort = networkHandler.getIntProperty(SocksConstants.PROP_PORT);
                    if (!CommonUtils.isEmpty(proxyHost) && proxyPort != 0) {
                        InetSocketAddress proxyAddr = new InetSocketAddress(proxyHost, proxyPort);
                        Proxy proxy = new Proxy(Proxy.Type.SOCKS, proxyAddr);
                        if (proxies == null) {
                            proxies = new ArrayList<>();
                        }
                        proxies.add(proxy);
                        log.debug("Use SOCKS proxy [" + proxyAddr + "]");
                    }
                }
            }
            if (proxies != null) {
                return proxies;
            }
        }
        return null;
    }

    @Override
    public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
        parent.connectFailed(uri, sa, ioe);
    }

    @Nullable
    protected DBPDataSourceContainer getActiveDataSourceContainer(@NotNull URI uri) {
        String scheme = uri.getScheme();
        if (CommonUtils.isEmpty(scheme)) {
            return null;
        }

        String host = uri.getHost();
        if (CommonUtils.isEmpty(host)) {
            return null;
        }

        // Skip localhosts. In fact it is a bad idea (see #3592)
//        if (ArrayUtils.contains(LOCAL_HOSTS, host)) {
//            return parent.select(uri);
//        }
        int port = uri.getPort();
        String path = uri.getPath();

        // 2. Check for connections' proxy config
        return DBExecUtils.findConnectionContext(host, port, path);
    }

}


text:
import Ember from 'ember';

export default Ember.Mixin.create({
  queryParams: {
    q: {
      replace: true
    }
  },

  model: function() {
    return [];
  },

  setupController: function(controller, model) {
    this._super.apply(this, arguments);
    controller.filter();
  }
});


text:
/**
 * Autogenerated by Thrift Compiler (0.9.0)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
package org.apache.hadoop.hbase.thrift2.generated;

import org.apache.thrift.scheme.IScheme;
import org.apache.thrift.scheme.SchemeFactory;
import org.apache.thrift.scheme.StandardScheme;

import org.apache.thrift.scheme.TupleScheme;
import org.apache.thrift.protocol.TTupleProtocol;
import org.apache.thrift.protocol.TProtocolException;
import org.apache.thrift.EncodingUtils;
import org.apache.thrift.TException;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Set;
import java.util.HashSet;
import java.util.EnumSet;
import java.util.Collections;
import java.util.BitSet;
import java.nio.ByteBuffer;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TTimeRange implements org.apache.thrift.TBase<TTimeRange, TTimeRange._Fields>, java.io.Serializable, Cloneable {
  private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("TTimeRange");

  private static final org.apache.thrift.protocol.TField MIN_STAMP_FIELD_DESC = new org.apache.thrift.protocol.TField("minStamp", org.apache.thrift.protocol.TType.I64, (short)1);
  private static final org.apache.thrift.protocol.TField MAX_STAMP_FIELD_DESC = new org.apache.thrift.protocol.TField("maxStamp", org.apache.thrift.protocol.TType.I64, (short)2);

  private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
  static {
    schemes.put(StandardScheme.class, new TTimeRangeStandardSchemeFactory());
    schemes.put(TupleScheme.class, new TTimeRangeTupleSchemeFactory());
  }

  public long minStamp; // required
  public long maxStamp; // required

  /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
  public enum _Fields implements org.apache.thrift.TFieldIdEnum {
    MIN_STAMP((short)1, "minStamp"),
    MAX_STAMP((short)2, "maxStamp");

    private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();

    static {
      for (_Fields field : EnumSet.allOf(_Fields.class)) {
        byName.put(field.getFieldName(), field);
      }
    }

    /**
     * Find the _Fields constant that matches fieldId, or null if its not found.
     */
    public static _Fields findByThriftId(int fieldId) {
      switch(fieldId) {
        case 1: // MIN_STAMP
          return MIN_STAMP;
        case 2: // MAX_STAMP
          return MAX_STAMP;
        default:
          return null;
      }
    }

    /**
     * Find the _Fields constant that matches fieldId, throwing an exception
     * if it is not found.
     */
    public static _Fields findByThriftIdOrThrow(int fieldId) {
      _Fields fields = findByThriftId(fieldId);
      if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
      return fields;
    }

    /**
     * Find the _Fields constant that matches name, or null if its not found.
     */
    public static _Fields findByName(String name) {
      return byName.get(name);
    }

    private final short _thriftId;
    private final String _fieldName;

    _Fields(short thriftId, String fieldName) {
      _thriftId = thriftId;
      _fieldName = fieldName;
    }

    public short getThriftFieldId() {
      return _thriftId;
    }

    public String getFieldName() {
      return _fieldName;
    }
  }

  // isset id assignments
  private static final int __MINSTAMP_ISSET_ID = 0;
  private static final int __MAXSTAMP_ISSET_ID = 1;
  private byte __isset_bitfield = 0;
  public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
  static {
    Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
    tmpMap.put(_Fields.MIN_STAMP, new org.apache.thrift.meta_data.FieldMetaData("minStamp", org.apache.thrift.TFieldRequirementType.REQUIRED,
        new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64)));
    tmpMap.put(_Fields.MAX_STAMP, new org.apache.thrift.meta_data.FieldMetaData("maxStamp", org.apache.thrift.TFieldRequirementType.REQUIRED,
        new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64)));
    metaDataMap = Collections.unmodifiableMap(tmpMap);
    org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(TTimeRange.class, metaDataMap);
  }

  public TTimeRange() {
  }

  public TTimeRange(
    long minStamp,
    long maxStamp)
  {
    this();
    this.minStamp = minStamp;
    setMinStampIsSet(true);
    this.maxStamp = maxStamp;
    setMaxStampIsSet(true);
  }

  /**
   * Performs a deep copy on <i>other</i>.
   */
  public TTimeRange(TTimeRange other) {
    __isset_bitfield = other.__isset_bitfield;
    this.minStamp = other.minStamp;
    this.maxStamp = other.maxStamp;
  }

  public TTimeRange deepCopy() {
    return new TTimeRange(this);
  }

  @Override
  public void clear() {
    setMinStampIsSet(false);
    this.minStamp = 0;
    setMaxStampIsSet(false);
    this.maxStamp = 0;
  }

  public long getMinStamp() {
    return this.minStamp;
  }

  public TTimeRange setMinStamp(long minStamp) {
    this.minStamp = minStamp;
    setMinStampIsSet(true);
    return this;
  }

  public void unsetMinStamp() {
    __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __MINSTAMP_ISSET_ID);
  }

  /** Returns true if field minStamp is set (has been assigned a value) and false otherwise */
  public boolean isSetMinStamp() {
    return EncodingUtils.testBit(__isset_bitfield, __MINSTAMP_ISSET_ID);
  }

  public void setMinStampIsSet(boolean value) {
    __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __MINSTAMP_ISSET_ID, value);
  }

  public long getMaxStamp() {
    return this.maxStamp;
  }

  public TTimeRange setMaxStamp(long maxStamp) {
    this.maxStamp = maxStamp;
    setMaxStampIsSet(true);
    return this;
  }

  public void unsetMaxStamp() {
    __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __MAXSTAMP_ISSET_ID);
  }

  /** Returns true if field maxStamp is set (has been assigned a value) and false otherwise */
  public boolean isSetMaxStamp() {
    return EncodingUtils.testBit(__isset_bitfield, __MAXSTAMP_ISSET_ID);
  }

  public void setMaxStampIsSet(boolean value) {
    __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __MAXSTAMP_ISSET_ID, value);
  }

  public void setFieldValue(_Fields field, Object value) {
    switch (field) {
    case MIN_STAMP:
      if (value == null) {
        unsetMinStamp();
      } else {
        setMinStamp((Long)value);
      }
      break;

    case MAX_STAMP:
      if (value == null) {
        unsetMaxStamp();
      } else {
        setMaxStamp((Long)value);
      }
      break;

    }
  }

  public Object getFieldValue(_Fields field) {
    switch (field) {
    case MIN_STAMP:
      return Long.valueOf(getMinStamp());

    case MAX_STAMP:
      return Long.valueOf(getMaxStamp());

    }
    throw new IllegalStateException();
  }

  /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
  public boolean isSet(_Fields field) {
    if (field == null) {
      throw new IllegalArgumentException();
    }

    switch (field) {
    case MIN_STAMP:
      return isSetMinStamp();
    case MAX_STAMP:
      return isSetMaxStamp();
    }
    throw new IllegalStateException();
  }

  @Override
  public boolean equals(Object that) {
    if (that == null)
      return false;
    if (that instanceof TTimeRange)
      return this.equals((TTimeRange)that);
    return false;
  }

  public boolean equals(TTimeRange that) {
    if (that == null)
      return false;

    boolean this_present_minStamp = true;
    boolean that_present_minStamp = true;
    if (this_present_minStamp || that_present_minStamp) {
      if (!(this_present_minStamp && that_present_minStamp))
        return false;
      if (this.minStamp != that.minStamp)
        return false;
    }

    boolean this_present_maxStamp = true;
    boolean that_present_maxStamp = true;
    if (this_present_maxStamp || that_present_maxStamp) {
      if (!(this_present_maxStamp && that_present_maxStamp))
        return false;
      if (this.maxStamp != that.maxStamp)
        return false;
    }

    return true;
  }

  @Override
  public int hashCode() {
    return 0;
  }

  public int compareTo(TTimeRange other) {
    if (!getClass().equals(other.getClass())) {
      return getClass().getName().compareTo(other.getClass().getName());
    }

    int lastComparison = 0;
    TTimeRange typedOther = (TTimeRange)other;

    lastComparison = Boolean.valueOf(isSetMinStamp()).compareTo(typedOther.isSetMinStamp());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (isSetMinStamp()) {
      lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.minStamp, typedOther.minStamp);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    lastComparison = Boolean.valueOf(isSetMaxStamp()).compareTo(typedOther.isSetMaxStamp());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (isSetMaxStamp()) {
      lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.maxStamp, typedOther.maxStamp);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    return 0;
  }

  public _Fields fieldForId(int fieldId) {
    return _Fields.findByThriftId(fieldId);
  }

  public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
    schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
  }

  public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
    schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder("TTimeRange(");
    boolean first = true;

    sb.append("minStamp:");
    sb.append(this.minStamp);
    first = false;
    if (!first) sb.append(", ");
    sb.append("maxStamp:");
    sb.append(this.maxStamp);
    first = false;
    sb.append(")");
    return sb.toString();
  }

  public void validate() throws org.apache.thrift.TException {
    // check for required fields
    // alas, we cannot check 'minStamp' because it's a primitive and you chose the non-beans generator.
    // alas, we cannot check 'maxStamp' because it's a primitive and you chose the non-beans generator.
    // check for sub-struct validity
  }

  private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
    try {
      write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
    } catch (org.apache.thrift.TException te) {
      throw new java.io.IOException(te);
    }
  }

  private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
    try {
      // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
      __isset_bitfield = 0;
      read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
    } catch (org.apache.thrift.TException te) {
      throw new java.io.IOException(te);
    }
  }

  private static class TTimeRangeStandardSchemeFactory implements SchemeFactory {
    public TTimeRangeStandardScheme getScheme() {
      return new TTimeRangeStandardScheme();
    }
  }

  private static class TTimeRangeStandardScheme extends StandardScheme<TTimeRange> {

    public void read(org.apache.thrift.protocol.TProtocol iprot, TTimeRange struct) throws org.apache.thrift.TException {
      org.apache.thrift.protocol.TField schemeField;
      iprot.readStructBegin();
      while (true)
      {
        schemeField = iprot.readFieldBegin();
        if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
          break;
        }
        switch (schemeField.id) {
          case 1: // MIN_STAMP
            if (schemeField.type == org.apache.thrift.protocol.TType.I64) {
              struct.minStamp = iprot.readI64();
              struct.setMinStampIsSet(true);
            } else {
              org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
            }
            break;
          case 2: // MAX_STAMP
            if (schemeField.type == org.apache.thrift.protocol.TType.I64) {
              struct.maxStamp = iprot.readI64();
              struct.setMaxStampIsSet(true);
            } else {
              org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
            }
            break;
          default:
            org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
        }
        iprot.readFieldEnd();
      }
      iprot.readStructEnd();

      // check for required fields of primitive type, which can't be checked in the validate method
      if (!struct.isSetMinStamp()) {
        throw new org.apache.thrift.protocol.TProtocolException("Required field 'minStamp' was not found in serialized data! Struct: " + toString());
      }
      if (!struct.isSetMaxStamp()) {
        throw new org.apache.thrift.protocol.TProtocolException("Required field 'maxStamp' was not found in serialized data! Struct: " + toString());
      }
      struct.validate();
    }

    public void write(org.apache.thrift.protocol.TProtocol oprot, TTimeRange struct) throws org.apache.thrift.TException {
      struct.validate();

      oprot.writeStructBegin(STRUCT_DESC);
      oprot.writeFieldBegin(MIN_STAMP_FIELD_DESC);
      oprot.writeI64(struct.minStamp);
      oprot.writeFieldEnd();
      oprot.writeFieldBegin(MAX_STAMP_FIELD_DESC);
      oprot.writeI64(struct.maxStamp);
      oprot.writeFieldEnd();
      oprot.writeFieldStop();
      oprot.writeStructEnd();
    }

  }

  private static class TTimeRangeTupleSchemeFactory implements SchemeFactory {
    public TTimeRangeTupleScheme getScheme() {
      return new TTimeRangeTupleScheme();
    }
  }

  private static class TTimeRangeTupleScheme extends TupleScheme<TTimeRange> {

    @Override
    public void write(org.apache.thrift.protocol.TProtocol prot, TTimeRange struct) throws org.apache.thrift.TException {
      TTupleProtocol oprot = (TTupleProtocol) prot;
      oprot.writeI64(struct.minStamp);
      oprot.writeI64(struct.maxStamp);
    }

    @Override
    public void read(org.apache.thrift.protocol.TProtocol prot, TTimeRange struct) throws org.apache.thrift.TException {
      TTupleProtocol iprot = (TTupleProtocol) prot;
      struct.minStamp = iprot.readI64();
      struct.setMinStampIsSet(true);
      struct.maxStamp = iprot.readI64();
      struct.setMaxStampIsSet(true);
    }
  }

}


text:
require 'spec_helper'
require 'whois/record/parser/whois.nic.net.sb.rb'

describe Whois::Record::Parser::WhoisNicNetSb, "status_available.expected" do

  subject do
    file = fixture("responses", "whois.nic.net.sb/sb/status_available.txt")
    part = Whois::Record::Part.new(body: File.read(file))
    described_class.new(part)
  end

  describe "#domain" do
    it do
      expect(subject.domain).to eq("u34jedzcq.sb")
    end
  end
  describe "#domain_id" do
    it do
      expect(subject.domain_id).to eq(nil)
    end
  end
  describe "#status" do
    it do
      expect(subject.status).to eq(:available)
    end
  end
  describe "#available?" do
    it do
      expect(subject.available?).to eq(true)
    end
  end
  describe "#registered?" do
    it do
      expect(subject.registered?).to eq(false)
    end
  end
  describe "#created_on" do
    it do
      expect(subject.created_on).to eq(nil)
    end
  end
  describe "#updated_on" do
    it do
      expect(subject.updated_on).to eq(nil)
    end
  end
  describe "#expires_on" do
    it do
      expect(subject.expires_on).to eq(nil)
    end
  end
  describe "#registrar" do
    it do
      expect(subject.registrar).to eq(nil)
    end
  end
  describe "#nameservers" do
    it do
      expect(subject.nameservers).to be_a(Array)
      expect(subject.nameservers).to eq([])
    end
  end
end


text:
using DragonSpark.Model;

namespace DragonSpark.Compose.Model.Validation;

sealed class AssignedOutputThrowContext<TIn, TOut> : OutputOtherwiseThrowContext<TIn, TOut>
{
	public AssignedOutputThrowContext(OutputOtherwiseContext<TIn, TOut> input)
		: base(input, x => new AssignedResultGuard<TIn>(Is.Always<TIn>().Out(), x)) {}
}


text: <quarters-criteria></quarters-criteria>


text:
import Menu from '../../../engine/menu-system/Menu';
import MenuItem from '../../../engine/menu-system/MenuItem';
import BackgroundView from '../../../engine/graphics/BackgroundView';
import ViewContainer from '../../../engine/graphics/ViewContainer';
import MenuItemsView from '../views/MenuItemsView';

const HelpMenu = {
    create (menuState) {
        const menu = new Menu();
        const viewContainer = new ViewContainer();

        menu.addMenuItem(new MenuItem('back', '- back', function () {
            menuState.currentMenu = 'main';
        }));

        viewContainer.addDynamicView(new MenuItemsView(menu), { x: 300, y: 100, z: 0 });

        const background = new BackgroundView('iwo_jima', 'ui');

        background.lightness = 0.5;

        viewContainer.backgroundView = background;

        return {
            viewContainer: viewContainer,
            menu: menu
        };
    }
};

export default HelpMenu;


text:
<?php

namespace app\controllers;

use Yii;
use app\models\Locality;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * LocalityController implements the CRUD actions for Locality model.
 */
class LocalityController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Locality models.
     * @return mixed
     */
    public function actionIndex()
    {
        $dataProvider = new ActiveDataProvider([
            'query' => Locality::find(),
        ]);

        return $this->render('index', [
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Locality model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Locality model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Locality();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->locality_id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Locality model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->locality_id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Locality model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Locality model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Locality the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Locality::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}


text:
package com.arm.nevada.client.shared.events;

import com.google.gwt.event.shared.EventHandler;

public interface MemoryViewValueChangedEventHandler extends EventHandler {
	void onElementChanged(MemoryViewValueChangedEvent event);
}


text:
{"This object is already being edited by"} {{ user|User::get (%s)->name }}.

{"Back"}


text:
import scipy.stats as st
import numpy as np

def initialize(self, runInfoDict, inputFiles):
  """
    Method to generate the observed data
    @ In, runInfoDict, dict, the dictionary containing the runInfo
    @ In, inputFiles, list, the list of input files
    @ Out, None
  """
  self.dim = 10
  seed = 1086
  np.random.seed(seed)
  self.cov = 10**(np.random.randn(self.dim)*1.5)
  self.mu = st.norm(loc=0, scale=10).rvs(self.dim)

def run(self, inputDict):
  """
    Method required by RAVEN to run this as an external model.
    log likelihood function
    @ In, self, object, object to store members on
    @ In, inputDict, dict, dictionary containing inputs from RAVEN
    @ Out, None
  """
  vars = ['x1','x2','x3','x4','x5','x6','x7','x8','x9','x10']
  xin = []
  for var in vars:
    xin.extend(inputDict[var])
  xin = np.asarray(xin)
  if np.all(xin < 500) and np.all(xin > -500):
    zout = st.multivariate_normal(mean=self.mu, cov=self.cov).logpdf(xin)
  else:
    zout = -1.0E6
  self.zout = np.atleast_1d(zout)


text:
package com.opengroup.longmao.gwcommon.configuration.query.core;

import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

/**
 * query基类,注意分库分表的sharding-col是不能用使用In查询的,路由不了。
 *
 * @version
 * @author zengjq  2016年10月26日 下午3:48:02
 *
 */
public abstract class BaseQuery {
	//排序对象
	private Sort sort;
	private Pageable Page;
	public Sort getSort() {
		return sort;
	}
	public void setSort(Sort sort) {
		this.sort = sort;
	}
	public Pageable getPage() {
		return Page;
	}
	public void setPage(Pageable page) {
		Page = page;
	}

}


text:
A light-weight forking library.

While there are many other libraries available to work with forked processes, most of them
seem to be either very specific or want to include way too much.

Twine on the other hand is intended to be light weight and easy to use. Inspired by Fibers and Threads, a Twine is for producing 'heavy weight' (forked / multi-process) parallelism.

## Questions and Answers

### Why use Twine instead of `Process.fork`?

`Process.fork` gets the job done but leaves a lot of the bootstrapping to you; Forking off as a daemon can be a bit of black magic for example. Twine provides a lot of this bootstrapping for you.

* daemons / long running processes
  * pid file creation
  * output redirection
* clean forking
  * close off IO left over from the originating process
  * initialize a new seed for randomization
  * clean process traps created from the originating process
* Twine::Child API similar to Thread
  * designed to prevent zombie processes (Grrr, aaarg, brain!)

### How do I create a daemon process?
```ruby
 pid = Twine.daemonize {:output_to => '/tmp/my.log'} do
   puts "This is now a backgrounded 'daemon' process"
   trap("TERM") { exit }
   while true do
     sleep 1
   end
 end

 puts "I just made a daemon with pid #{pid}"
```

### How do I create a child process?
As an object

```ruby
 # Create a new child
 c = Twine::Child.new do
   puts "Time to do MP work!"
   sleep 5
   puts "Phew, that was hard"
 end
 c.start

 # Is it running?
 c.running?  # >>> true

 # Send it a signal
 c.signal :usr1

 # blocking wait for it to exit
 c.join
```

As a MixIn

```ruby
 class MyChild
   include Twine::ChildMixin
 protected
   def run
     trap("TERM") { exit }
     while true do
       puts "annoying yet? Then terminate me!!!"
       sleep 1
     end
   end
 end

 c = MyChild.new
 c.start
 sleep 5
 c.kill # oi... that was annoying.
```

### I just want simpler forking!

```ruby
 pid = Twine.clean_fork { puts "I'm another process" }
```

### Is there an IPC / Message Queue mechanism?

Nope! Why re-invent the wheel when [ZeroMQ][zeromq] does a fantastic job of this already.

```ruby
 require 'rubygems'
 require "bundler/setup"
 require 'twine'
 require 'ffi-rzmq'

 a = Twine::Child.new do
   ctx = ZMQ::Context.new  # Unlike threads, each fork needs its own context
   outbound = ctx.socket(ZMQ::PUSH)
   outbound.bind("ipc:///tmp/my.ipc")
   outbound.send_string("world")
   outbound.close
   ctx.terminate
 end

 b = Twine::Child.new do
   ctx = ZMQ::Context.new
   inbound = ctx.socket(ZMQ::PULL)
   inbound.connect("ipc:///tmp/my.ipc")
   puts("Hello %s" %[inbound.recv_string])
   inbound.close
   ctx.terminate
 end

 a.start; b.start
 a.join; b.join
```

### Is there an easy way to accept command line arguments for my daemon?

Not built in. Check out the awesome [Optitron][optitron] for a great solution to this.

### You mention [Optitron][optitron] and [ZeroMQ][zeromq], how do I use them with Twine?

Check out the example at https://github.com/lholden/twine/tree/master/examples/daemon

### Are there any other examples?

Check out the [examples][examples] directory.

## To be implemented
 * Pooling

## Copyright
Copyright (c) 2011 Lori Holden. See LICENSE.txt for further details.

[optitron]: https://github.com/joshbuddy/optitron  "Sensible, minimal simple options parsing and dispatching for Ruby. Build a CLI with no fuss."
[zeromq]: http://www.zeromq.org/  "The Intelligent Transport Layer"
[examples]: https://github.com/lholden/twine/tree/master/examples  "Examples of using Twine"


text:
namespace appcache {

class ManifestParserTest : public testing::Test {
};

TEST(ManifestParserTest, NoData) {
  GURL url;
  Manifest manifest;
  EXPECT_FALSE(ParseManifest(url, "", 0, manifest));
  EXPECT_FALSE(ParseManifest(url, "CACHE MANIFEST\r", 0, manifest));  // 0 len
}

TEST(ManifestParserTest, CheckSignature) {
  GURL url;
  Manifest manifest;

  const std::string kBadSignatures[] = {
    "foo",
    "CACHE MANIFEST;V2\r",          // not followed by whitespace
    "CACHE MANIFEST#bad\r",         // no whitespace before comment
    "cache manifest ",              // wrong case
    "#CACHE MANIFEST\r",            // comment
    "xCACHE MANIFEST\n",            // bad first char
    " CACHE MANIFEST\r",            // begins with whitespace
    "\xEF\xBE\xBF" "CACHE MANIFEST\r",  // bad UTF-8 BOM value
  };

  for (size_t i = 0; i < arraysize(kBadSignatures); ++i) {
    const std::string bad = kBadSignatures[i];
    EXPECT_FALSE(ParseManifest(url, bad.c_str(), bad.length(), manifest));
  }

  const std::string kGoodSignatures[] = {
    "CACHE MANIFEST",
    "CACHE MANIFEST ",
    "CACHE MANIFEST\r",
    "CACHE MANIFEST\n",
    "CACHE MANIFEST\r\n",
    "CACHE MANIFEST\t# ignore me\r",
    "CACHE MANIFEST ignore\r\n",
    "\xEF\xBB\xBF" "CACHE MANIFEST \r\n",   // BOM present
  };

  for (size_t i = 0; i < arraysize(kGoodSignatures); ++i) {
    const std::string good = kGoodSignatures[i];
    EXPECT_TRUE(ParseManifest(url, good.c_str(), good.length(), manifest));
  }
}

TEST(ManifestParserTest, NoManifestUrl) {
  Manifest manifest;
  const std::string kData("CACHE MANIFEST\r"
    "relative/tobase.com\r"
    "http://absolute.com/addme.com");
  const GURL kUrl;
  EXPECT_TRUE(ParseManifest(kUrl, kData.c_str(), kData.length(), manifest));
  EXPECT_TRUE(manifest.explicit_urls.empty());
  EXPECT_TRUE(manifest.fallback_namespaces.empty());
  EXPECT_TRUE(manifest.online_whitelist_namespaces.empty());
  EXPECT_FALSE(manifest.online_whitelist_all);
}

TEST(ManifestParserTest, ExplicitUrls) {
  Manifest manifest;
  const GURL kUrl("http://www.foo.com");
  const std::string kData("CACHE MANIFEST\r"
    "relative/one\r"
    "# some comment\r"
    "http://www.foo.com/two#strip\r\n"
    "NETWORK:\r"
    "  \t CACHE:\r"
    "HTTP://www.diff.com/three\r"
    "FALLBACK:\r"
    " \t # another comment with leading whitespace\n"
    "IGNORE:\r"
    "http://www.foo.com/ignore\r"
    "CACHE: \r"
    "garbage:#!@\r"
    "https://www.foo.com/diffscheme \t \r"
    "  \t relative/four#stripme\n\r"
    "*\r");

  EXPECT_TRUE(ParseManifest(kUrl, kData.c_str(), kData.length(), manifest));
  EXPECT_TRUE(manifest.fallback_namespaces.empty());
  EXPECT_TRUE(manifest.online_whitelist_namespaces.empty());
  EXPECT_FALSE(manifest.online_whitelist_all);

  base::hash_set<std::string> urls = manifest.explicit_urls;
  const size_t kExpected = 5;
  ASSERT_EQ(kExpected, urls.size());
  EXPECT_TRUE(urls.find("http://www.foo.com/relative/one") != urls.end());
  EXPECT_TRUE(urls.find("http://www.foo.com/two") != urls.end());
  EXPECT_TRUE(urls.find("http://www.diff.com/three") != urls.end());
  EXPECT_TRUE(urls.find("http://www.foo.com/relative/four") != urls.end());

  // Wildcard is treated as a relative URL in explicit section.
  EXPECT_TRUE(urls.find("http://www.foo.com/*") != urls.end());
}

TEST(ManifestParserTest, WhitelistUrls) {
  Manifest manifest;
  const GURL kUrl("http://www.bar.com");
  const std::string kData("CACHE MANIFEST\r"
    "NETWORK:\r"
    "relative/one\r"
    "# a comment\r"
    "http://www.bar.com/two\r"
    "HTTP://www.diff.com/three#strip\n\r"
    "FALLBACK:\r"
    "garbage\r"
    "UNKNOWN:\r"
    "http://www.bar.com/ignore\r"
    "CACHE:\r"
    "NETWORK:\r"
    "https://www.wrongscheme.com\n"
    "relative/four#stripref \t \r"
    "http://www.five.com\r\n"
    "*foo\r");

  EXPECT_TRUE(ParseManifest(kUrl, kData.c_str(), kData.length(), manifest));
  EXPECT_TRUE(manifest.explicit_urls.empty());
  EXPECT_TRUE(manifest.fallback_namespaces.empty());
  EXPECT_FALSE(manifest.online_whitelist_all);

  std::vector<GURL> online = manifest.online_whitelist_namespaces;
  const size_t kExpected = 6;
  ASSERT_EQ(kExpected, online.size());
  EXPECT_EQ(GURL("http://www.bar.com/relative/one"), online[0]);
  EXPECT_EQ(GURL("http://www.bar.com/two"), online[1]);
  EXPECT_EQ(GURL("http://www.diff.com/three"), online[2]);
  EXPECT_EQ(GURL("http://www.bar.com/relative/four"), online[3]);
  EXPECT_EQ(GURL("http://www.five.com"), online[4]);
  EXPECT_EQ(GURL("http://www.bar.com/*foo"), online[5]);
}

TEST(ManifestParserTest, FallbackUrls) {
  Manifest manifest;
  const GURL kUrl("http://glorp.com");
  const std::string kData("CACHE MANIFEST\r"
    "# a comment\r"
    "CACHE:\r"
    "NETWORK:\r"
    "UNKNOWN:\r"
    "FALLBACK:\r"
    "relative/one \t \t http://glorp.com/onefb  \t \r"
    "*\r"
    "https://glorp.com/wrong http://glorp.com/wrongfb\r"
    "http://glorp.com/two#strip relative/twofb\r"
    "HTTP://glorp.com/three relative/threefb#strip\n"
    "http://glorp.com/three http://glorp.com/three-dup\r"
    "http://glorp.com/solo \t \r\n"
    "http://diff.com/ignore http://glorp.com/wronghost\r"
    "http://glorp.com/wronghost http://diff.com/ohwell\r"
    "relative/badscheme ftp://glorp.com/ignored\r"
    "garbage\r\n"
    "CACHE:\r"
    "# only fallback urls in this test\r"
    "FALLBACK:\n"
    "relative/four#strip relative/fourfb#strip\r"
    "http://www.glorp.com/notsame relative/skipped\r");

  EXPECT_TRUE(ParseManifest(kUrl, kData.c_str(), kData.length(), manifest));
  EXPECT_TRUE(manifest.explicit_urls.empty());
  EXPECT_TRUE(manifest.online_whitelist_namespaces.empty());
  EXPECT_FALSE(manifest.online_whitelist_all);

  std::vector<FallbackNamespace> fallbacks = manifest.fallback_namespaces;
  const size_t kExpected = 5;
  ASSERT_EQ(kExpected, fallbacks.size());
  EXPECT_EQ(GURL("http://glorp.com/relative/one"),
            fallbacks[0].first);
  EXPECT_EQ(GURL("http://glorp.com/onefb"),
            fallbacks[0].second);
  EXPECT_EQ(GURL("http://glorp.com/two"),
            fallbacks[1].first);
  EXPECT_EQ(GURL("http://glorp.com/relative/twofb"),
            fallbacks[1].second);
  EXPECT_EQ(GURL("http://glorp.com/three"),
            fallbacks[2].first);
  EXPECT_EQ(GURL("http://glorp.com/relative/threefb"),
            fallbacks[2].second);
  EXPECT_EQ(GURL("http://glorp.com/three"),       // duplicates are stored
            fallbacks[3].first);
  EXPECT_EQ(GURL("http://glorp.com/three-dup"),
            fallbacks[3].second);
  EXPECT_EQ(GURL("http://glorp.com/relative/four"),
            fallbacks[4].first);
  EXPECT_EQ(GURL("http://glorp.com/relative/fourfb"),
            fallbacks[4].second);
}

TEST(ManifestParserTest, FallbackUrlsWithPort) {
  Manifest manifest;
  const GURL kUrl("http://www.portme.com:1234");
  const std::string kData("CACHE MANIFEST\r"
    "FALLBACK:\r"
    "http://www.portme.com:1234/one relative/onefb\r"
    "HTTP://www.portme.com:9876/wrong http://www.portme.com:1234/ignore\r"
    "http://www.portme.com:1234/stillwrong http://www.portme.com:42/boo\r"
    "relative/two relative/twofb\r"
    "http://www.portme.com:1234/three HTTP://www.portme.com:1234/threefb\r"
    "http://www.portme.com/noport http://www.portme.com:1234/skipped\r"
    "http://www.portme.com:1234/skipme http://www.portme.com/noport\r");

  EXPECT_TRUE(ParseManifest(kUrl, kData.c_str(), kData.length(), manifest));
  EXPECT_TRUE(manifest.explicit_urls.empty());
  EXPECT_TRUE(manifest.online_whitelist_namespaces.empty());
  EXPECT_FALSE(manifest.online_whitelist_all);

  std::vector<FallbackNamespace> fallbacks = manifest.fallback_namespaces;
  const size_t kExpected = 3;
  ASSERT_EQ(kExpected, fallbacks.size());
  EXPECT_EQ(GURL("http://www.portme.com:1234/one"),
            fallbacks[0].first);
  EXPECT_EQ(GURL("http://www.portme.com:1234/relative/onefb"),
            fallbacks[0].second);
  EXPECT_EQ(GURL("http://www.portme.com:1234/relative/two"),
            fallbacks[1].first);
  EXPECT_EQ(GURL("http://www.portme.com:1234/relative/twofb"),
            fallbacks[1].second);
  EXPECT_EQ(GURL("http://www.portme.com:1234/three"),
            fallbacks[2].first);
  EXPECT_EQ(GURL("http://www.portme.com:1234/threefb"),
            fallbacks[2].second);
}

TEST(ManifestParserTest, ComboUrls) {
  Manifest manifest;
  const GURL kUrl("http://combo.com:42");
  const std::string kData("CACHE MANIFEST\r"
    "relative/explicit-1\r"
    "# some comment\r"
    "http://combo.com:99/explicit-2#strip\r"
    "NETWORK:\r"
    "http://combo.com/whitelist-1\r"
    "HTTP://www.diff.com/whitelist-2#strip\r"
    "*\r"
    "CACHE:\n\r"
    "http://www.diff.com/explicit-3\r"
    "FALLBACK:\r"
    "http://combo.com:42/fallback-1 http://combo.com:42/fallback-1b\r"
    "relative/fallback-2 relative/fallback-2b\r"
    "UNKNOWN:\r\n"
    "http://combo.com/ignoreme\r"
    "relative/still-ignored\r"
    "NETWORK:\r\n"
    "relative/whitelist-3#strip\r"
    "http://combo.com:99/whitelist-4\r");
  EXPECT_TRUE(ParseManifest(kUrl, kData.c_str(), kData.length(), manifest));
  EXPECT_TRUE(manifest.online_whitelist_all);

  base::hash_set<std::string> urls = manifest.explicit_urls;
  size_t expected = 3;
  ASSERT_EQ(expected, urls.size());
  EXPECT_TRUE(urls.find("http://combo.com:42/relative/explicit-1") !=
              urls.end());
  EXPECT_TRUE(urls.find("http://combo.com:99/explicit-2") != urls.end());
  EXPECT_TRUE(urls.find("http://www.diff.com/explicit-3") != urls.end());

  std::vector<GURL> online = manifest.online_whitelist_namespaces;
  expected = 4;
  ASSERT_EQ(expected, online.size());
  EXPECT_EQ(GURL("http://combo.com/whitelist-1"), online[0]);
  EXPECT_EQ(GURL("http://www.diff.com/whitelist-2"), online[1]);
  EXPECT_EQ(GURL("http://combo.com:42/relative/whitelist-3"), online[2]);
  EXPECT_EQ(GURL("http://combo.com:99/whitelist-4"), online[3]);

  std::vector<FallbackNamespace> fallbacks = manifest.fallback_namespaces;
  expected = 2;
  ASSERT_EQ(expected, fallbacks.size());
  EXPECT_EQ(GURL("http://combo.com:42/fallback-1"),
            fallbacks[0].first);
  EXPECT_EQ(GURL("http://combo.com:42/fallback-1b"),
            fallbacks[0].second);
  EXPECT_EQ(GURL("http://combo.com:42/relative/fallback-2"),
            fallbacks[1].first);
  EXPECT_EQ(GURL("http://combo.com:42/relative/fallback-2b"),
            fallbacks[1].second);
}

TEST(ManifestParserTest, UnusualUtf8) {
  Manifest manifest;
  const GURL kUrl("http://bad.com");
  const std::string kData("CACHE MANIFEST\r"
    "\xC0" "invalidutf8\r"
    "nonbmp" "\xF1\x84\xAB\xBC\r");
  EXPECT_TRUE(ParseManifest(kUrl, kData.c_str(), kData.length(), manifest));

  base::hash_set<std::string> urls = manifest.explicit_urls;
  EXPECT_TRUE(urls.find("http://bad.com/%EF%BF%BDinvalidutf8") != urls.end());
  EXPECT_TRUE(urls.find("http://bad.com/nonbmp%F1%84%AB%BC") != urls.end());
}

TEST(ManifestParserTest, IgnoreAfterSpace) {
  Manifest manifest;
  const GURL kUrl("http://smorg.borg");
  const std::string kData(
    "CACHE MANIFEST\r"
    "resource.txt this stuff after the white space should be ignored\r");
  EXPECT_TRUE(ParseManifest(kUrl, kData.c_str(), kData.length(), manifest));

  base::hash_set<std::string> urls = manifest.explicit_urls;
  EXPECT_TRUE(urls.find("http://smorg.borg/resource.txt") != urls.end());
}

}  // namespace appcache


text:
var MongoPipeApi = require('../index');
var PromisePipe = require('promise-pipe')();
var expect = require('chai').expect;

PromisePipe.use('db', MongoPipeApi('test', ['coll']));

var dropPipe = PromisePipe().db.drop.coll();
var insertPipe = PromisePipe().db.insert.coll();
var findPipe = PromisePipe().db.find.coll();
var findOnePipe = PromisePipe().db.findOne.coll();
var findAndModifyPipe = PromisePipe().db.findAndModify.coll();
var removePipe = PromisePipe().db.remove.coll();

var mockData = {
  a: "testA"
}
describe("MongoPipeApi", function(){
  before(function(done){
    dropPipe().then(done)
  })
  describe('can insert item to collection', function(){
    var saveResult;
    before(function(done){
      insertPipe(mockData).then(function(resp){
        saveResult = resp;
        done();
      })
    })
    it('should have ID',function(){
      expect(saveResult).to.have.property("_id");
    });
    it('should return mockData',function(){
      expect(saveResult).to.have.property('a', mockData.a);
    });
    describe('can get it from collection', function(){
      var findResult;
      before(function(done){
        findPipe({a: "testA"}).then(function(resp){
          findResult = resp[0];
          done();
        })
      })
      it('shoul be same as post', function(){
        expect(findResult).to.deep.equal(saveResult);
      })
      describe('can remove it from collection', function(){
        var removeCount;
        before(function(done){
          removePipe({_id:findResult._id}).then(function(count){
            removeCount = count;
            done();
          });
        })
        it('it should remove one item', function(){
          expect(removeCount.n).to.equal(1);
        })
      })
    });
    describe('can get one from collection', function(){
      var findOneResult, saveOneResult;
      before(function(done){
        insertPipe(mockData).then(function(resp){
        saveOneResult = resp;
          findOnePipe({a: "testA"}).then(function(resp){
            findOneResult = resp[0];
            done();
          })
        })
      })
      it('shoul be same as post', function(){
        expect(findOneResult).to.deep.equal(saveOneResult);
      })
			describe('can modify item in collection', function(){
				var updateResult;
				before(function(done){
					findAndModifyPipe({query:{_id:findOneResult._id}, update:{$set:{a:"Mock"}}}).then(function(resp){
	          findOnePipe({_id: findOneResult._id}).then(function(resp){
							updateResult = resp[0];
	            done();
	          })
	        })
	      })
				it('shoul update the item', function(){
	        expect(updateResult).to.have.property("a","Mock");
	      })

			})
    });

  })

})


text:
/*
* WebTemplate 1.0
* Luca Vercelli 2017
* Released under MIT license
*/
package com.example.myapp.crud.entity;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;

/**
 * In order to display an Entity on a grid, or to export it to an Excel sheet,
 * it's a good idea to declare entities and columns in the tables Grid and
 * GridColumn. Columns can refer to HQL (SQL?) functions, or to other tables,
 * thanks to JPA's relations.
 *
 * @author luca vercelli
 *
 */
@Entity
@Table(name = "APP_GRID")
@XmlRootElement
public class Grid {

	private Long id;
	private String entity;
	private String description;
	private List<GridColumn> columns = new ArrayList<>();

	public Grid() {
	}

	/**
	 * Full constructor
	 */
	public Grid(String entity, String description) {
		this.entity = entity;
		this.description = description;
	}

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "ID")
	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	@Column(name = "ENTITY", nullable = false)
	public String getEntity() {
		return entity;
	}

	public void setEntity(String entity) {
		this.entity = entity;
	}

	@Column(name = "DESCRIPTION")
	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	@OneToMany(mappedBy = "grid", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
	@XmlTransient // FIXME should not be
	public List<GridColumn> getColumns() {
		return columns;
	}

	public void setColumns(List<GridColumn> columns) {
		this.columns = columns;
	}

	@Override
	public String toString() {
		return "Grid #" + description + " for " + entity;
	}

	@Override
	public int hashCode() {
		return ("" + id).hashCode();
	}

	@Override
	public boolean equals(Object o2) {
		if (o2 == null || !(o2 instanceof Grid))
			return false;
		Grid r2 = (Grid) o2;
		if (r2.id == null || this.id == null)
			return false;
		return r2.id.equals(this.id);
	}
}


text:
package ie.dit;

public class Spider implements Comparable<Spider>
{
	private String species;
	private String colour;
	private int numEyes;

	public Spider(String species, String colour, int numEyes)
	{
		this.species = species;
		this.colour = colour;
		this.numEyes = numEyes;
	}

	public String getSpecies() {
		return species;
	}
	public void setSpecies(String species) {
		this.species = species;
	}
	public String getColour() {
		return colour;
	}
	public void setColour(String colour) {
		this.colour = colour;
	}
	public int getNumEyes() {
		return numEyes;
	}
	@Override
	public String toString() {
		return "Spider [species=" + species + ", colour=" + colour
				+ ", numEyes=" + numEyes + "]";
	}
	public void setNumEyes(int numEyes) {
		this.numEyes = numEyes;
	}

	public int compareTo(Spider other) {
		//return other.numEyes - this.numEyes;
		return other.getSpecies().compareTo(this.getSpecies());
	}
}


text:
struct FT_LibraryRec_;
struct FT_FaceRec_;
typedef struct FT_LibraryRec_* FT_Library;
typedef struct FT_FaceRec_* FT_Face;

namespace flex
{
	class DirectoryWatcher;
	struct JSONField;
	struct JSONObject;
	struct LoadedMesh;
	struct FontMetaData;
	class BitmapFont;
	struct FontMetric;
	struct Texture;
	class Mesh;
	struct MeshInfo;
	struct MaterialCreateInfo;
	struct PrefabInfo;
	class StringBuilder;

	class ResourceManager
	{
	public:
		ResourceManager();
		~ResourceManager();

		void Initialize();
		void PostInitialize();
		void Update();
		void Destroy();
		void DestroyAllLoadedMeshes();

		void PreSceneChange();
		void OnSceneChanged();

		// Returns true if found and *loadedMesh was set
		bool FindPreLoadedMesh(const std::string& relativeFilePath, LoadedMesh** loadedMesh);
		LoadedMesh* FindOrLoadMesh(const std::string& relativeFilePath);

		bool MeshFileNameConforms(const std::string& fileName);

		void DiscoverMeshes();
		void DiscoverPrefabs();
		void DiscoverAudioFiles();
		void DiscoverTextures();

		void ParseMeshJSON(i32 sceneFileVersion, GameObject* parent, const JSONObject& meshObj, const std::vector<MaterialID>& materialIDs);

		void ParseFontFile();
		void SerializeFontFile();

		void ParseMaterialsFile();
		bool SerializeMaterialFile() const;

		void ParseDebugOverlayNamesFile();

		JSONField SerializeMesh(Mesh* mesh);

		void SetRenderedSDFFilePath(FontMetaData& metaData);

		bool LoadFontMetrics(const std::vector<char>& fileMemory,
			FT_Library& ft,
			FontMetaData& metaData,
			std::map<i32, FontMetric*>* outCharacters,
			std::array<glm::vec2i, 4>* outMaxPositions,
			FT_Face* outFace);

		void LoadFonts(bool bForceRender);

		void DrawImGuiWindows();
		void DrawImGuiMeshList(i32* selectedMeshIndex, ImGuiTextFilter* meshFilter);
		// Expects to be called from within an ImGui menu
		void DrawImGuiMenuItemizableItems();
		bool DrawAudioSourceIDImGui(const char* label, StringID& audioSourceSID);

		// Returns a pointer into loadedTextures if a texture has been loaded from that file path, otherwise returns nullptr
		Texture* FindLoadedTextureWithPath(const std::string& filePath);
		Texture* FindLoadedTextureWithName(const std::string& fileName);
		Texture* GetLoadedTexture(TextureID textureID);
		TextureID GetOrLoadTexture(const std::string& textureFilePath);
		bool RemoveLoadedTexture(TextureID textureID, bool bDestroy);
		bool RemoveLoadedTexture(Texture* texture, bool bDestroy);
		TextureID GetOrLoadIcon(StringID gameObjectTypeID);

		TextureID GetNextAvailableTextureID();
		TextureID AddLoadedTexture(Texture* texture);

		MaterialCreateInfo* GetMaterialInfo(const char* materialName);
		// DEPRECATED (see cpp)
		GameObject* GetPrefabTemplate(const char* prefabName) const;
		// DEPRECATED (see cpp)
		PrefabID GetPrefabID(const char* prefabName) const;
		GameObject* GetPrefabTemplate(const PrefabID& prefabID) const;
		std::string GetPrefabFileName(const PrefabID& prefabID) const;
		bool IsPrefabDirty(const PrefabID& prefabID) const;
		void SetPrefabDirty(const PrefabID& prefabID);
		void SetAllPrefabsDirty(bool bDirty);
		void UpdatePrefabData(GameObject* prefabTemplate, const PrefabID& prefabID);
		PrefabID AddNewPrefab(GameObject* prefabTemplate, const char* fileName = nullptr);
		bool IsPrefabIDValid(const PrefabID& prefabID);

		void RemovePrefabTemplate(const PrefabID& prefabID);

		bool PrefabTemplateContainsChild(const PrefabID& prefabID, GameObject* child) const;

		AudioSourceID GetAudioID(StringID audioFileSID);
		AudioSourceID GetOrLoadAudioID(StringID audioFileSID);
		void LoadAudioFile(StringID audioFileSID, StringBuilder* errorStringBuilder);

		bool bShowEditorMaterials = false;

		std::map<StringID, FontMetaData> fontMetaData;
		// TODO: Separate fonts from font buffers
		std::vector<BitmapFont*> fontsScreenSpace;
		std::vector<BitmapFont*> fontsWorldSpace;

		std::vector<Texture*> loadedTextures;
		std::vector<std::string> discoveredTextures; // Stores relative file paths to all textures in textures directory
		// Pair of (GameObjectTypeID, (Relative file path, texture ID))
		// texture ID will be invalid until texture is loaded
		std::vector<Pair<StringID, Pair<std::string, TextureID>>> icons;
		TextureID tofuIconID = InvalidTextureID;

		std::vector<MaterialCreateInfo> parsedMaterialInfos;

		struct PrefabTemplatePair
		{
			PrefabTemplatePair(GameObject* templateObject, const PrefabID& prefabID, const std::string& fileName, bool bDirty) :
				templateObject(templateObject),
				prefabID(prefabID),
				fileName(fileName),
				bDirty(bDirty)
			{
			}

			GameObject* templateObject = nullptr;
			PrefabID prefabID = InvalidPrefabID;
			std::string fileName;
			bool bDirty = false;
		};
		std::vector<PrefabTemplatePair> prefabTemplates;

		// Relative file path (e.g. MESH_DIRECTORY "cube.glb") -> LoadedMesh
		std::map<std::string, LoadedMesh*> loadedMeshes;
		std::vector<std::string> discoveredMeshes;

		struct AudioFileMetaData
		{
			AudioFileMetaData()	{}

			explicit AudioFileMetaData(std::string name, AudioSourceID sourceID = InvalidShaderID) :
				name(name),
				sourceID(sourceID)
			{
			}

			std::string name;
			AudioSourceID sourceID = InvalidAudioSourceID;
			bool bInvalid = false;

			// Editor-only
			Date fileModifiedDate;
		};
		std::map<StringID, AudioFileMetaData> discoveredAudioFiles;

		static const char* s_SupportedTextureFormats[];

		std::vector<std::string> debugOverlayNames;

	private:
		void WritePrefabToDisk(PrefabTemplatePair& prefabTemplatePair, const PrefabID& prefabID);
		bool PrefabTemplateContainsChildRecursive(GameObject* prefabTemplate, GameObject* child) const;

		UIContainer* ParseUIConfig(const char* filePath);
		bool SerializeUIConfig(const char* filePath, UIContainer* uiContainer);

		std::string m_FontsFilePathAbs;
		std::string m_FontImageExtension = ".png";

		DirectoryWatcher* m_AudioDirectoryWatcher = nullptr;
		i32 m_AudioRefreshFrameCountdown = -1; // When non-negative, counts down each frame until refresh is applied

	};
} // namespace flex


text:
import React, { useCallback, useMemo, useRef } from 'react';
import { useDispatch } from 'react-redux';
import { css, t, useTheme } from '@superset-ui/core';
import { setDirectPathToChild } from 'src/dashboard/actions/dashboardState';
import Icons from 'src/components/Icons';
import {
  DependencyItem,
  Row,
  RowLabel,
  RowTruncationCount,
  RowValue,
  TooltipList,
} from './Styles';
import { useFilterDependencies } from './useFilterDependencies';
import { useTruncation } from './useTruncation';
import { DependencyValueProps, FilterCardRowProps } from './types';
import { TooltipWithTruncation } from './TooltipWithTruncation';

const DependencyValue = ({
  dependency,
  hasSeparator,
}: DependencyValueProps) => {
  const dispatch = useDispatch();
  const handleClick = useCallback(() => {
    dispatch(setDirectPathToChild([dependency.id]));
  }, [dependency.id, dispatch]);
  return (

      {hasSeparator && , }
      <DependencyItem role="button" onClick={handleClick} tabIndex={0}>
        {dependency.name}
      </DependencyItem>

  );
};

export const DependenciesRow = React.memo(({ filter }: FilterCardRowProps) => {
  const dependencies = useFilterDependencies(filter);
  const dependenciesRef = useRef<HTMLDivElement>(null);
  const [elementsTruncated, hasHiddenElements] = useTruncation(dependenciesRef);
  const theme = useTheme();

  const tooltipText = useMemo(
    () =>
      elementsTruncated > 0 && dependencies ? (
        <TooltipList>
          {dependencies.map(dependency => (

              <DependencyValue dependency={dependency} />

          ))}
        </TooltipList>
      ) : null,
    [elementsTruncated, dependencies],
  );

  if (!Array.isArray(dependencies) || dependencies.length === 0) {
    return null;
  }
  return (
    <Row>
      <RowLabel
        css={css`
          display: inline-flex;
          align-items: center;
        `}
      >
        {t('Dependent on')}{' '}
        <TooltipWithTruncation
          title={t(
            'Filter only displays values relevant to selections made in other filters.',
          )}
        >
          <Icons.Info
            iconSize="m"
            iconColor={theme.colors.grayscale.light1}
            css={css`
              margin-left: ${theme.gridUnit}px;
            `}
          />
        </TooltipWithTruncation>
      </RowLabel>
      <TooltipWithTruncation title={tooltipText}>
        <RowValue ref={dependenciesRef}>
          {dependencies.map((dependency, index) => (
            <DependencyValue
              dependency={dependency}
              hasSeparator={index !== 0}
            />
          ))}
        </RowValue>
        {hasHiddenElements && (
          <RowTruncationCount>+{elementsTruncated}</RowTruncationCount>
        )}
      </TooltipWithTruncation>
    </Row>
  );
});


text:
namespace base {
template <typename Type>
struct DefaultSingletonTraits;
}  // namespace base

namespace content {

class PowerTracingAgent : public base::trace_event::TracingAgent,
                          public battor::BattOrAgent::Listener {
 public:
  // Retrieve the singleton instance.
  static PowerTracingAgent* GetInstance();

  void StartAgentTracing(const base::trace_event::TraceConfig& trace_config,
                         const StartAgentTracingCallback& callback) override;
  void StopAgentTracing(const StopAgentTracingCallback& callback) override;
  void RecordClockSyncMarker(
      const std::string& sync_id,
      const RecordClockSyncMarkerCallback& callback) override;

  bool SupportsExplicitClockSync() override;

  // base::trace_event::TracingAgent implementation.
  std::string GetTracingAgentName() override;
  std::string GetTraceEventLabel() override;

  // BattOrAgent::Listener implementation.
  void OnStartTracingComplete(battor::BattOrError error) override;
  void OnStopTracingComplete(const std::string& trace,
                             battor::BattOrError error) override;
  void OnRecordClockSyncMarkerComplete(battor::BattOrError error) override;
  void OnGetFirmwareGitHashComplete(const std::string& version,
                                    battor::BattOrError error) override;

 private:
  // This allows constructor and destructor to be private and usable only
  // by the Singleton class.
  friend struct base::DefaultSingletonTraits<PowerTracingAgent>;

  PowerTracingAgent();
  ~PowerTracingAgent() override;

  void FindBattOrOnFileThread(const StartAgentTracingCallback& callback);
  void StartAgentTracingOnIOThread(const std::string& path,
                                   const StartAgentTracingCallback& callback);
  void StopAgentTracingOnIOThread(const StopAgentTracingCallback& callback);
  void RecordClockSyncMarkerOnIOThread(
      const std::string& sync_id,
      const RecordClockSyncMarkerCallback& callback);

  // Returns the path of a BattOr (e.g. /dev/ttyUSB0), or an empty string if
  // none are found.
  std::string GetBattOrPath();

  // All interactions with the BattOrAgent (after construction) must happen on
  // the IO thread.
  std::unique_ptr<battor::BattOrAgent, BrowserThread::DeleteOnIOThread>
      battor_agent_;

  StartAgentTracingCallback start_tracing_callback_;
  StopAgentTracingCallback stop_tracing_callback_;
  std::string record_clock_sync_marker_sync_id_;
  base::TimeTicks record_clock_sync_marker_start_time_;
  RecordClockSyncMarkerCallback record_clock_sync_marker_callback_;

  DISALLOW_COPY_AND_ASSIGN(PowerTracingAgent);
};

}  // namespace content

#endif  // CONTENT_BROWSER_TRACING_POWER_TRACING_AGENT_H_


text:
package com.android.manifmerger;

import com.android.annotations.NonNull;
import com.android.annotations.Nullable;
import com.android.ide.common.blame.SourcePosition;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Replaces all placeholders of the form ${name} with a tool invocation provided value
 */
public class PlaceholderHandler {

    // interesting placeholders names that are documented to be automatically provided.
    public static final String INSTRUMENTATION_RUNNER = "instrumentationRunner";
    public static final String PACKAGE_NAME = "packageName";
    public static final String APPLICATION_ID = "applicationId";

    // regular expression to recognize placeholders like ${name}, potentially surrounded by a
    // prefix and suffix string. this will split in 3 groups, the prefix, the placeholder name, and
    // the suffix.
    static final Pattern PATTERN = Pattern.compile("([^\\$]*)\\$\\{([^\\}]*)\\}(.*)");

    /**
     * Interface to provide a value for a placeholder key.
     * @param <T> the key type
     */
    public interface KeyBasedValueResolver<T> {

        /**
         * Returns a placeholder value for the placeholder key or null if none exists.
         */
        @Nullable
        String getValue(@NonNull T key);
    }

    /**
     * Returns true if the passed string is a placeholder value, false otherwise.
     */
    public static boolean isPlaceHolder(@NonNull String string) {
        return PATTERN.matcher(string).matches();
    }

    /**
     * Visits a document's entire tree and check each attribute for a placeholder existence.
     * If one is found, delegate to the provided {@link KeyBasedValueResolver} to provide a value
     * for the placeholder.
     * <p>
     * If no value is provided, an error will be generated.
     *
     * @param xmlDocument the xml document to visit
     * @param valueProvider the placeholder value provider.
     * @param mergingReportBuilder to report errors and log actions.
     */
    public void visit(
            @NonNull ManifestMerger2.MergeType mergeType,
            @NonNull XmlDocument xmlDocument,
            @NonNull KeyBasedValueResolver<String> valueProvider,
            @NonNull MergingReport.Builder mergingReportBuilder) {

        visit(mergeType, xmlDocument.getRootNode(), valueProvider, mergingReportBuilder);
    }

    private void visit(
            @NonNull ManifestMerger2.MergeType mergeType,
            @NonNull XmlElement xmlElement,
            @NonNull KeyBasedValueResolver<String> valueProvider,
            @NonNull MergingReport.Builder mergingReportBuilder) {

        for (XmlAttribute xmlAttribute : xmlElement.getAttributes()) {

            StringBuilder resultString = new StringBuilder();
            String inputString = xmlAttribute.getValue();
            Matcher matcher = PATTERN.matcher(inputString);
            if (matcher.matches()) {
                while (matcher.matches()) {
                    String placeholderValue = valueProvider.getValue(matcher.group(2));
                    // whatever precedes the placeholder key is added back to the string.
                    resultString.append(matcher.group(1));
                    if (placeholderValue == null) {
                        // if this is a library, ignore the failure
                        MergingReport.Record.Severity severity =
                                mergeType == ManifestMerger2.MergeType.LIBRARY
                                        ? MergingReport.Record.Severity.INFO
                                        : MergingReport.Record.Severity.ERROR;

                        xmlAttribute.addMessage(mergingReportBuilder, severity,
                                String.format(
                                        "Attribute %1$s at %2$s requires a placeholder substitution"
                                                + " but no value for <%3$s> is provided.",
                                        xmlAttribute.getId(),
                                        xmlAttribute.printPosition(),
                                        matcher.group(2)
                                ));
                        // we add back the placeholder key, since this is not an error for libraries
                        resultString.append("${");
                        resultString.append(matcher.group(2));
                        resultString.append("}");
                    } else {
                        // record the attribute set
                        mergingReportBuilder.getActionRecorder().recordAttributeAction(
                                xmlAttribute,
                                SourcePosition.UNKNOWN,
                                Actions.ActionType.INJECTED,
                                null /* attributeOperationType */);

                        // substitute the placeholder key with its value.
                        resultString.append(placeholderValue);
                    }
                    // the new input string is the tail of the previous match, as it may contain
                    // more placeholders to substitute.
                    inputString = matcher.group(3);
                    // reset the pattern matching with that new string to test for more placeholders
                    matcher = PATTERN.matcher(inputString);
                }
                // append the last remainder (without placeholders) in the result string.
                resultString.append(inputString);
                xmlAttribute.getXml().setValue(resultString.toString());
            }
        }
        for (XmlElement childElement : xmlElement.getMergeableElements()) {
            visit(mergeType, childElement, valueProvider, mergingReportBuilder);
        }
    }
}


text:
iCloud4j is a Java port of the [PyiCloud](https://github.com/picklepete/pyicloud) library. It provides a means for Java applications to use iCloud web services.
It is licenced under the Apache 2.0 licence.

#Authentication

When the account isn't protected using two-factor authentication, authentication can be down by supplying a simple
username/password pair:

	ICloudService iCloud = new ICloudService("client-id");
	iCloud.authenticate("user@example.com", "password".toCharArray());

#Persistent sessions

An authenticated session can be serialized, stored and re-used. Authenticate requesting an
extendedLogin session and serialize/store the ICloudSession:

	ICloudService iCloud = new ICloudService("client-id");
	iCloud.authenticate("user@example.com", "password".toCharArray(), true);
	ICloudSession session = iCloud.getSession();

Later the same session can be loaded and re-used without password authentication:

	ICloudService iCloud = new ICloudService(session);

#Devices

A list of devices linked to the iCloud account can be retrieved via the 'FindMyIPhoneService':

	FindMyIPhoneService findMyIPhoneService = new FindMyIPhoneService(iCloudService);
	List<AppleDevice> devices = findMyIPhoneService.getDevices();

#Ubiquity (File Storage)

The iCloud Ubiquity file storage can be browsed by creating a new instance of the 'UbiquityService', and then calling
methods on each node from there:

	UbiquityService ubiquityService = new UbiquityService(iCloudService);
	UbiquityNode rootNode = ubiquityService.getRoot();
	List<UbiquityNode> childrenNode = root.getChildren();

File data can be streamed into an output stream:

	OutputStream outputStream;
	UbiquityNode child = folder.getChildren().get(0);
	if ("file".equals(child.getType()) {
		child.downloadFileData(outputStream);
	}

#Drive (iCloud Drive)

The iCloud Drive contents can be browsed like so:

	DriveService driveService = new DriveService(iCloud);
	DriveNode root = driveService.getRoot();
	for(DriveNode node : root.getChildren()) {
		...
	}

#CKDatabase (CloudKit database)

The CloudKit databases can be queried like so:

	String query = "{\"query\":{\"recordType\":\"CPLAssetAndMasterByAssetDateWithoutHiddenOrDeleted\"},\"zoneID\":{\"zoneName\":\"PrimarySync\"},\"desiredKeys\":[\"filenameEnc\"],\"resultsLimit\":20}";

	CKDatabaseService photosDatabase = new CKDatabaseService(iCloud, CKDatabaseService.ENDPOINT_PHOTOS);
	CKResponse response = photosDatabase.query(query);
	for(CKRecord record : response.getRecords()) {
		String fileName = record.getString("filenameEnc");
		...
	}


text:
package org.elasticsearch.xpack.core.enrich.action;

import org.elasticsearch.action.ActionRequestValidationException;
import org.elasticsearch.action.ActionResponse;
import org.elasticsearch.action.ActionType;
import org.elasticsearch.action.support.master.MasterNodeReadRequest;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.xcontent.ToXContentObject;
import org.elasticsearch.xcontent.XContentBuilder;
import org.elasticsearch.xpack.core.enrich.EnrichPolicy;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class GetEnrichPolicyAction extends ActionType<GetEnrichPolicyAction.Response> {

    public static final GetEnrichPolicyAction INSTANCE = new GetEnrichPolicyAction();
    public static final String NAME = "cluster:admin/xpack/enrich/get";

    private GetEnrichPolicyAction() {
        super(NAME, Response::new);
    }

    public static class Request extends MasterNodeReadRequest<Request> {

        private final List<String> names;

        public Request() {
            this.names = new ArrayList<>();
        }

        public Request(String[] names) {
            this.names = Arrays.asList(names);
        }

        public Request(StreamInput in) throws IOException {
            super(in);
            this.names = in.readStringList();
        }

        @Override
        public ActionRequestValidationException validate() {
            return null;
        }

        public List<String> getNames() {
            return names;
        }

        @Override
        public void writeTo(StreamOutput out) throws IOException {
            super.writeTo(out);
            out.writeStringCollection(names);
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Request request = (Request) o;
            return Objects.equals(names, request.names);
        }

        @Override
        public int hashCode() {
            return Objects.hash(names);
        }
    }

    public static class Response extends ActionResponse implements ToXContentObject {

        private final List<EnrichPolicy.NamedPolicy> policies;

        public Response(Map<String, EnrichPolicy> policies) {
            Objects.requireNonNull(policies, "policies cannot be null");
            // use a treemap to guarantee ordering in the set, then transform it to the list of named policies
            this.policies = new TreeMap<>(policies).entrySet()
                .stream()
                .map(entry -> new EnrichPolicy.NamedPolicy(entry.getKey(), entry.getValue()))
                .collect(Collectors.toList());
        }

        public Response(StreamInput in) throws IOException {
            policies = in.readList(EnrichPolicy.NamedPolicy::new);
        }

        @Override
        public void writeTo(StreamOutput out) throws IOException {
            out.writeList(policies);
        }

        @Override
        public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
            builder.startObject();
            {
                builder.startArray("policies");
                {
                    for (EnrichPolicy.NamedPolicy policy : policies) {
                        builder.startObject();
                        {
                            builder.startObject("config");
                            {
                                policy.toXContent(builder, params);
                            }
                            builder.endObject();
                        }
                        builder.endObject();
                    }
                }
                builder.endArray();
            }
            builder.endObject();

            return builder;
        }

        public List<EnrichPolicy.NamedPolicy> getPolicies() {
            return policies;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Response response = (Response) o;
            return policies.equals(response.policies);
        }

        @Override
        public int hashCode() {
            return Objects.hash(policies);
        }
    }
}


text:
package ru.lanwen.raml.rarc.api.ra;

import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterSpec;
import ru.lanwen.raml.rarc.api.Method;

import javax.lang.model.element.Modifier;

/**
 * @author lanwen (Merkushev Kirill)
 */
public class Constructors {

    public static Method defaultConstructor(ReqSpecField req, RespSpecField resp) {
        return () -> MethodSpec.constructorBuilder()
                .addStatement("this.$N = new $T()", req.name(), req.fieldSpec().type)
                .addStatement("this.$N = new $T()", resp.name(), resp.fieldSpec().type)
                .addModifiers(Modifier.PUBLIC).build();
    }

    public static Method specsConstructor(ReqSpecField req, RespSpecField resp) {
        return () -> MethodSpec.constructorBuilder()
                .addModifiers(Modifier.PUBLIC)
                .addParameter(ParameterSpec.builder(req.fieldSpec().type, req.name()).build())
                .addStatement("this.$N = $N", req.name(), req.name())
                .addStatement("this.$N = new $T()", resp.name(), resp.fieldSpec().type)
                .build();
    }
}


text:
/* **********************************************************
** Importador NoEscape 1.0
** Curso de Experto en Desarrollo de Videojuegos
** Escuela Superior de Informatica - Univ. Castilla-La Mancha
** Carlos Gonzalez Morcillo - David Vallejo Fernandez
************************************************************/

#include <GraphVertex.h>

GraphVertex::GraphVertex
(GraphNode& data)
:_data(data)
{
}

GraphVertex::~GraphVertex()
{
	std::vector<GraphEdge*>::iterator itEdge;
	for (itEdge = _edges.begin();
		itEdge != _edges.end();
		++itEdge)
		delete *itEdge;

	_edges.clear();
}

std::vector<GraphVertex*>
GraphVertex::adjacents() const
{
	std::vector<GraphVertex*> result;
	std::vector<GraphEdge*>::const_iterator it;

	for (it = _edges.begin();
		it != _edges.end();
		++it)
		result.push_back((*it)->getDestination());

	return result;
}

GraphVertex* GraphVertex::nextVertx(Direcction direction, GraphVertex* actualVertx)
{
	GraphVertex *nextVertex = NULL;
	if (actualVertx){
		for (GraphEdge* e : actualVertx->getEdges())
		{
			if (!checkVertex(e->getDestination(), "CageDoor"))
			{
				switch (direction)
				{

				case Direcction::UP:

					if (actualVertx->getData().getPosition().z < e->getDestination()->getData().getPosition().z)
					{
						nextVertex = e->getDestination();
					}

					break;
				case Direcction::DOWN:
					if (actualVertx->getData().getPosition().z > e->getDestination()->getData().getPosition().z)
					{
						nextVertex = e->getDestination();
					}

					break;
				case Direcction::RIGHT:

					if (actualVertx->getData().getPosition().x < e->getDestination()->getData().getPosition().x)
					{
						nextVertex = e->getDestination();
					}

					break;
				case Direcction::LEFT:
					if (actualVertx->getData().getPosition().x > e->getDestination()->getData().getPosition().x)
					{
						nextVertex = e->getDestination();
					}
					break;
				}
			}
		}
	}
	return nextVertex;
}

bool  GraphVertex::checkVertex(GraphVertex* actualVertx, std::string type)
{
	bool result = false;
	if (actualVertx)
	{
		result = actualVertx->getData().getType() == type;
	}
	return result;
}


text:
import unittest

from rx import Observable
from rx.testing import TestScheduler, ReactiveTest, is_prime, MockDisposable
from rx.disposables import Disposable, SerialDisposable

on_next = ReactiveTest.on_next
on_completed = ReactiveTest.on_completed
on_error = ReactiveTest.on_error
subscribe = ReactiveTest.subscribe
subscribed = ReactiveTest.subscribed
disposed = ReactiveTest.disposed
created = ReactiveTest.created

class TestIsEmpty(unittest.TestCase):
    def test_is_empty_empty(self):
        scheduler = TestScheduler()
        xs = scheduler.create_hot_observable(on_next(150, 1), on_completed(250))

        def create():
            return xs.is_empty()

        res = scheduler.start(create=create).messages
        res.assert_equal(on_next(250, True), on_completed(250))
        xs.subscriptions.assert_equal(subscribe(200, 250))

    def test_is_empty_return(self):
        scheduler = TestScheduler()
        xs = scheduler.create_hot_observable(on_next(150, 1), on_next(210, 2), on_completed(250))

        def create():
            return xs.is_empty()
        res = scheduler.start(create=create).messages
        res.assert_equal(on_next(210, False), on_completed(210))
        xs.subscriptions.assert_equal(subscribe(200, 210))

    def test_is_empty_throw(self):
        ex = 'ex'
        scheduler = TestScheduler()
        xs = scheduler.create_hot_observable(on_next(150, 1), on_error(210, ex))

        def create():
            return xs.is_empty()
        res = scheduler.start(create=create).messages
        res.assert_equal(on_error(210, ex))
        xs.subscriptions.assert_equal(subscribe(200, 210))

    def test_is_empty_never(self):
        scheduler = TestScheduler()
        xs = scheduler.create_hot_observable(on_next(150, 1))
        def create():
            return xs.is_empty()
        res = scheduler.start(create=create).messages
        res.assert_equal()
        xs.subscriptions.assert_equal(subscribe(200, 1000))