text:
package ru.org.linux.group;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import ru.org.linux.auth.AccessViolationException;
import ru.org.linux.site.Template;

import javax.servlet.ServletRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
public class GroupModificationController {
  @Autowired
  private GroupDao groupDao;

  @Autowired
  private GroupInfoPrepareService prepareService;

  @RequestMapping(value="/groupmod.jsp", method = RequestMethod.GET)
  public ModelAndView showForm(@RequestParam("group") int id, ServletRequest request) throws Exception {
    Template tmpl = Template.getTemplate(request);

    if (!tmpl.isModeratorSession()) {
      throw new AccessViolationException("Not moderator");
    }

    Group group = groupDao.getGroup(id);

    ModelAndView mv = new ModelAndView("groupmod", "group", group);

    mv.getModel().put("groupInfo", prepareService.prepareGroupInfo(group, request.isSecure()));

    return mv;
  }

  @RequestMapping(value="/groupmod.jsp", method = RequestMethod.POST)
  public ModelAndView modifyGroup(
    @RequestParam("group") int id,
    @RequestParam("title") String title,
    @RequestParam("info") String info,
    @RequestParam("urlName") String urlName,
    @RequestParam("longinfo") String longInfo,
    @RequestParam(value = "preview", required = false) String preview,
    @RequestParam(value = "resolvable", required = false) String resolvable,
    ServletRequest request
  ) throws Exception {
    Template tmpl = Template.getTemplate(request);

    if (!tmpl.isModeratorSession()) {
      throw new AccessViolationException("Not moderator");
    }

    Group group = groupDao.getGroup(id);

    if (preview != null) {
      group.setTitle(title);
      group.setInfo(info);
      group.setLongInfo(longInfo);

      Map<String, Object> params = new HashMap<>();
      params.put("group", group);
      params.put("groupInfo", prepareService.prepareGroupInfo(group, request.isSecure()));
      params.put("preview", true);

      return new ModelAndView("groupmod", params);
    }

    groupDao.setParams(group, title, info, longInfo, resolvable!=null, urlName);

    return new ModelAndView("action-done", "message", "Параметры изменены");
  }
}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.fcduarte.todoapp.MainFragment" >

    <ListView
        android:id="@+id/lvItems"
        android:layout_width="match_parent"
        android:layout_height="380dp"
        android:layout_above="@+id/btnAddItem"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:transcriptMode="normal" >

    </ListView>

    <EditText
        android:id="@+id/etNewItem"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:ems="10"
        android:hint="@string/new_item_hint" >

    </EditText>

    <Button
        android:id="@+id/btnAddItem"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:text="@string/add_button_label" />

</RelativeLayout>

redpajama_set_name: RedPajamaGithub


text:
package org.apache.tinkerpop.gremlin.tinkergraph.structure;

import org.apache.commons.configuration.BaseConfiguration;
import org.apache.commons.configuration.Configuration;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.util.Arrays;
import java.util.UUID;

import static org.junit.Assert.assertEquals;

/**
 * @author Stephen Mallette (http://stephen.genoprime.com)
 */
@RunWith(Enclosed.class)
public class TinkerGraphIdManagerTest {

    @RunWith(Parameterized.class)
    public static class NumberIdManagerTest {
        private static final Configuration longIdManagerConfig = new BaseConfiguration();
        private static final Configuration integerIdManagerConfig = new BaseConfiguration();

        @Parameterized.Parameters(name = "{0}")
        public static Iterable<Object[]> data() {
            return Arrays.asList(new Object[][]{
                    {"coerceLong", 100l, 200l, 300l},
                    {"coerceInt", 100, 200, 300},
                    {"coerceDouble", 100d, 200d, 300d},
                    {"coerceFloat", 100f, 200f, 300f},
                    {"coerceString", "100", "200", "300"}});
        }

        @Parameterized.Parameter(value = 0)
        public String name;

        @Parameterized.Parameter(value = 1)
        public Object vertexIdValue;

        @Parameterized.Parameter(value = 2)
        public Object edgeIdValue;

        @Parameterized.Parameter(value = 3)
        public Object vertexPropertyIdValue;

        @BeforeClass
        public static void setup() {
            longIdManagerConfig.addProperty(TinkerGraph.GREMLIN_TINKERGRAPH_EDGE_ID_MANAGER, TinkerGraph.DefaultIdManager.LONG.name());
            longIdManagerConfig.addProperty(TinkerGraph.GREMLIN_TINKERGRAPH_VERTEX_ID_MANAGER, TinkerGraph.DefaultIdManager.LONG.name());
            longIdManagerConfig.addProperty(TinkerGraph.GREMLIN_TINKERGRAPH_VERTEX_PROPERTY_ID_MANAGER, TinkerGraph.DefaultIdManager.LONG.name());

            integerIdManagerConfig.addProperty(TinkerGraph.GREMLIN_TINKERGRAPH_EDGE_ID_MANAGER, TinkerGraph.DefaultIdManager.INTEGER.name());
            integerIdManagerConfig.addProperty(TinkerGraph.GREMLIN_TINKERGRAPH_VERTEX_ID_MANAGER, TinkerGraph.DefaultIdManager.INTEGER.name());
            integerIdManagerConfig.addProperty(TinkerGraph.GREMLIN_TINKERGRAPH_VERTEX_PROPERTY_ID_MANAGER, TinkerGraph.DefaultIdManager.INTEGER.name());
        }

        @Test
        public void shouldUseLongIdManagerToCoerceTypes() {
            final Graph graph = TinkerGraph.open(longIdManagerConfig);
            final Vertex v = graph.addVertex(T.id, vertexIdValue);
            final VertexProperty vp = v.property(VertexProperty.Cardinality.single, "test", "value", T.id, vertexPropertyIdValue);
            final Edge e = v.addEdge("self", v, T.id, edgeIdValue);

            assertEquals(100l, v.id());
            assertEquals(200l, e.id());
            assertEquals(300l, vp.id());
        }

        @Test
        public void shouldUseIntegerIdManagerToCoerceTypes() {
            final Graph graph = TinkerGraph.open(integerIdManagerConfig);
            final Vertex v = graph.addVertex(T.id, vertexIdValue);
            final VertexProperty vp = v.property(VertexProperty.Cardinality.single, "test", "value", T.id, vertexPropertyIdValue);
            final Edge e = v.addEdge("self", v, T.id, edgeIdValue);

            assertEquals(100, v.id());
            assertEquals(200, e.id());
            assertEquals(300, vp.id());
        }
    }

    @RunWith(Parameterized.class)
    public static class UuidIdManagerTest {
        private static final Configuration idManagerConfig = new BaseConfiguration();

        private static final UUID vertexId = UUID.fromString("0E939658-ADD2-4598-A722-2FC178E9B741");
        private static final UUID edgeId = UUID.fromString("748179AA-E319-8C36-41AE-F3576B73E05C");
        private static final UUID vertexPropertyId = UUID.fromString("EC27384C-39A0-923D-9410-271B585683B6");

        @Parameterized.Parameters(name = "{0}")
        public static Iterable<Object[]> data() {
            return Arrays.asList(new Object[][]{
                    {"coerceUuid", vertexId, edgeId, vertexPropertyId},
                    {"coerceString", vertexId.toString(), edgeId.toString(), vertexPropertyId.toString()}});
        }

        @Parameterized.Parameter(value = 0)
        public String name;

        @Parameterized.Parameter(value = 1)
        public Object vertexIdValue;

        @Parameterized.Parameter(value = 2)
        public Object edgeIdValue;

        @Parameterized.Parameter(value = 3)
        public Object vertexPropertyIdValue;

        @BeforeClass
        public static void setup() {
            idManagerConfig.addProperty(TinkerGraph.GREMLIN_TINKERGRAPH_EDGE_ID_MANAGER, TinkerGraph.DefaultIdManager.UUID.name());
            idManagerConfig.addProperty(TinkerGraph.GREMLIN_TINKERGRAPH_VERTEX_ID_MANAGER, TinkerGraph.DefaultIdManager.UUID.name());
            idManagerConfig.addProperty(TinkerGraph.GREMLIN_TINKERGRAPH_VERTEX_PROPERTY_ID_MANAGER, TinkerGraph.DefaultIdManager.UUID.name());
        }

        @Test
        public void shouldUseIdManagerToCoerceTypes() {
            final Graph graph = TinkerGraph.open(idManagerConfig);
            final Vertex v = graph.addVertex(T.id, vertexIdValue);
            final VertexProperty vp = v.property(VertexProperty.Cardinality.single, "test", "value", T.id, vertexPropertyIdValue);
            final Edge e = v.addEdge("self", v, T.id, edgeIdValue);

            assertEquals(vertexId, v.id());
            assertEquals(edgeId, e.id());
            assertEquals(vertexPropertyId, vp.id());
        }
    }
}


text:
// With Play Scala

object DependencyInjection {
  //#dependency-injection
  import javax.inject._
  import play.api.Configuration

  class MyController @Inject() (config: Configuration) {
    // ...
  }
  //#dependency-injection
}


text:
package com.alibaba.jstorm.transactional.spout;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.jstorm.client.spout.IAckValueSpout;
import com.alibaba.jstorm.client.spout.IFailValueSpout;
import com.alibaba.jstorm.task.TaskBaseMetric;
import com.alibaba.jstorm.transactional.utils.AckPendingBatchTracker;

import backtype.storm.spout.SpoutOutputCollector;
import backtype.storm.spout.SpoutOutputCollectorCb;
import backtype.storm.task.ICollectorCallback;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.IRichSpout;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.utils.Utils;

/**
 * This spout was created to provide compatibility with the ACK mechanism of Storm
 */
public class AckTransactionSpout implements ITransactionSpoutExecutor {
    private static final long serialVersionUID = -6561817670963028414L;

    private static Logger LOG = LoggerFactory.getLogger(AckTransactionSpout.class);

    private IRichSpout spoutExecutor;
    private boolean isCacheTuple;
    private TaskBaseMetric taskStats;

    private volatile long currBatchId = -1;
    // Map<BatchId, Map<StreamId, Map<MsgId, Value>>>
    private AckPendingBatchTracker<Map<Object, List<Object>>> tracker;

    private Random random;

    private class AckSpoutOutputCollector extends SpoutOutputCollectorCb {
        private SpoutOutputCollectorCb delegate;

        public AckSpoutOutputCollector (SpoutOutputCollectorCb delegate) {
            this.delegate = delegate;
        }

        @Override
        public List<Integer> emit(String streamId, List<Object> tuple, Object messageId) {
            if (messageId != null) {
                addPendingTuple(currBatchId, streamId, messageId, tuple);
                tuple.add(Utils.generateId(random));
            } else {
                // for non-anchor tuples, use 0 as default rootId
                tuple.add(0l);
            }
            return delegate.emit(streamId, tuple, null);
        }

        @Override
        public void emitDirect(int taskId, String streamId, List<Object> tuple, Object messageId) {
            delegate.emitDirect(taskId, streamId, tuple, null);
        }

        @Override
        public List<Integer> emit(String streamId, List<Object> tuple, Object messageId, ICollectorCallback callback) {
            if (messageId != null) {
                addPendingTuple(currBatchId, streamId, messageId, tuple);
                tuple.add(Utils.generateId(random));
            } else {
                // for non-anchor tuples, use 0 as default rootId
                tuple.add(0l);
            }
            return delegate.emit(streamId, tuple, null, callback);
        }

        @Override
        public void emitDirect(int taskId, String streamId, List<Object> tuple, Object messageId, ICollectorCallback callback) {
            if (messageId != null) {
                addPendingTuple(currBatchId, streamId, messageId, tuple);
                tuple.add(Utils.generateId(random));
            } else {
                tuple.add(0l);
            }
            delegate.emitDirect(taskId, streamId, tuple, null, callback);
        }

        @Override
        public void reportError(Throwable error) {
            delegate.reportError(error);
        }

        @Override
        public void flush(){
            delegate.flush();
        }

        @Override
        public void emitDirectCtrl(int taskId, String streamId, List<Object> tuple, Object messageId) {
            delegate.emitDirectCtrl(taskId, streamId, tuple, messageId);
        }

        @Override
        public List<Integer> emitCtrl(String streamId, List<Object> tuple, Object messageId) {
            return delegate.emitCtrl(streamId, tuple, messageId);
        }
    }

    public AckTransactionSpout(IRichSpout spout) {
        this.spoutExecutor = spout;
        if (spoutExecutor instanceof IAckValueSpout || spoutExecutor instanceof IFailValueSpout)
            isCacheTuple = true;
        else
            isCacheTuple = false;
    }

    @Override
    public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) {
        SpoutOutputCollectorCb ackOutput = new AckSpoutOutputCollector(collector.getDelegate());
        spoutExecutor.open(conf, context, new SpoutOutputCollector(ackOutput));
        tracker = new AckPendingBatchTracker<>();
        taskStats = new TaskBaseMetric(context.getTopologyId(), context.getThisComponentId(), context.getThisTaskId());
        random = new Random(Utils.secureRandomLong());
    }

    @Override
    public void close() {
        spoutExecutor.close();
    }

    @Override
    public void activate() {
        spoutExecutor.activate();
    }

    @Override
    public void deactivate() {
        spoutExecutor.deactivate();
    }

    @Override
    public void nextTuple() {
        spoutExecutor.nextTuple();
    }

    @Override
    public void ack(Object msgId) {
        spoutExecutor.ack(msgId);
    }

    @Override
    public void fail(Object msgId) {
        spoutExecutor.fail(msgId);
    }

    public void ack(Object msgId, List<Object> values) {
        ((IAckValueSpout) spoutExecutor).ack(msgId, values);
    }

    public void fail(Object msgId, List<Object> values) {
        ((IFailValueSpout) spoutExecutor).fail(msgId, values);
    }

    @Override
    public void declareOutputFields(OutputFieldsDeclarer declarer) {
        spoutExecutor.declareOutputFields(declarer);
    }

    @Override
    public Map<String, Object> getComponentConfiguration() {
        return spoutExecutor.getComponentConfiguration();
    }

    @Override
    public void initState(Object userState) {
        if (userState != null) {
            currBatchId = (Long) userState;
        } else {
            currBatchId = 1;
        }
    }

    @Override
    public Object finishBatch(long batchId) {
        currBatchId++;
        return null;
    }

    @Override
    public Object commit(long batchId, Object state) {
        return batchId;
    }

    @Override
    public void rollBack(Object userState) {
        if (userState != null) {
            currBatchId = (Long) userState;
        } else {
            currBatchId = 1;
        }

        removeObsoleteBatches(currBatchId);
        for (Long batchId : tracker.getBatchIds())
            ackOrFailBatch(batchId, false);
    }

    @Override
    public void ackCommit(long batchId, long timeStamp) {
        ackOrFailBatch(batchId, true);
        removeObsoleteBatches(batchId);
    }

    private void ackOrFailBatch(long batchId, boolean isAck) {
        for (String streamId : tracker.getStreamIds(batchId)) {
            Map<Object, List<Object>> pendingBatch = tracker.getPendingBatch(batchId, streamId);
            if (pendingBatch == null)
                continue;

            for (Entry<Object, List<Object>> entry : pendingBatch.entrySet()) {
                ackOrFailTuple(entry.getKey(), entry.getValue(), isAck);
            }
            if (isAck)
                taskStats.spoutAckedTuple(streamId, pendingBatch.size());
            else
                taskStats.spoutFailedTuple(streamId, pendingBatch.size());
        }
    }

    private void ackOrFailTuple(Object msgId, List<Object> value, boolean isAck) {
        if (isAck) {
            if (spoutExecutor instanceof IAckValueSpout)
                ack(msgId, value);
            else
                ack(msgId);
        } else {
            if (spoutExecutor instanceof IFailValueSpout)
                fail(msgId, value);
            else
                fail(msgId);
        }
    }

    private void addPendingTuple(long batchId, String streamId, Object msgId, List<Object> value) {
        Map<Object, List<Object>> pendingBatch = tracker.getPendingBatch(batchId, streamId);
        if (pendingBatch == null) {
            pendingBatch = new HashMap<>();
        }
        List<Object> cacheValue = isCacheTuple ? value : null;
        pendingBatch.put(msgId, cacheValue);
    }

    private void removeObsoleteBatches(long commitBatchId) {
        TreeSet<Long> totalBatches = new TreeSet<Long>(tracker.getBatchIds());
        Set<Long> obsoleteBatches = totalBatches.headSet(commitBatchId);
        if (obsoleteBatches != null && obsoleteBatches.size() > 0) {
            LOG.info("Remove obsolete batches: {}", obsoleteBatches);
            for (Long batchId : obsoleteBatches) {
                tracker.removeBatch(batchId);
            }
        }
    }
}


text:
package com.newsblur.activity;

import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import butterknife.ButterKnife;
import butterknife.Bind;

import com.newsblur.R;
import com.newsblur.fragment.ItemSetFragment;
import com.newsblur.fragment.ReadFilterDialogFragment;
import com.newsblur.fragment.StoryOrderDialogFragment;
import com.newsblur.fragment.TextSizeDialogFragment;
import com.newsblur.service.NBSyncService;
import com.newsblur.util.AppConstants;
import com.newsblur.util.FeedSet;
import com.newsblur.util.FeedUtils;
import com.newsblur.util.PrefConstants.ThemeValue;
import com.newsblur.util.PrefsUtils;
import com.newsblur.util.ReadFilter;
import com.newsblur.util.ReadFilterChangedListener;
import com.newsblur.util.StateFilter;
import com.newsblur.util.StoryListStyle;
import com.newsblur.util.StoryOrder;
import com.newsblur.util.StoryOrderChangedListener;
import com.newsblur.util.UIUtils;

public abstract class ItemsList extends NbActivity implements StoryOrderChangedListener, ReadFilterChangedListener, OnSeekBarChangeListener {

    public static final String EXTRA_FEED_SET = "feed_set";

	private static final String STORY_ORDER = "storyOrder";
	private static final String READ_FILTER = "readFilter";
    private static final String DEFAULT_FEED_VIEW = "defaultFeedView";
    private static final String BUNDLE_ACTIVE_SEARCH_QUERY = "activeSearchQuery";

	protected ItemSetFragment itemSetFragment;
    @Bind(R.id.itemlist_sync_status) TextView overlayStatusText;
    @Bind(R.id.itemlist_search_query) EditText searchQueryInput;
	protected StateFilter intelState;

    protected FeedSet fs;

	@Override
    protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);

        overridePendingTransition(R.anim.slide_in_from_right, R.anim.slide_out_to_left);

		fs = (FeedSet) getIntent().getSerializableExtra(EXTRA_FEED_SET);
		intelState = PrefsUtils.getStateFilter(this);

        // this is not strictly necessary, since our first refresh with the fs will swap in
        // the correct session, but that can be delayed by sync backup, so we try here to
        // reduce UI lag, or in case somehow we got redisplayed in a zero-story state
        FeedUtils.prepareReadingSession(fs, false);

        if (PrefsUtils.isAutoOpenFirstUnread(this)) {
            if (FeedUtils.dbHelper.getUnreadCount(fs, intelState) > 0) {
                UIUtils.startReadingActivity(fs, Reading.FIND_FIRST_UNREAD, this);
            }
        }

        getWindow().setBackgroundDrawableResource(android.R.color.transparent);

		setContentView(R.layout.activity_itemslist);
        ButterKnife.bind(this);

		FragmentManager fragmentManager = getSupportFragmentManager();
		itemSetFragment = (ItemSetFragment) fragmentManager.findFragmentByTag(ItemSetFragment.class.getName());
		if (itemSetFragment == null) {
            itemSetFragment = ItemSetFragment.newInstance();
			itemSetFragment.setRetainInstance(true);
			FragmentTransaction transaction = fragmentManager.beginTransaction();
			transaction.add(R.id.activity_itemlist_container, itemSetFragment, ItemSetFragment.class.getName());
			transaction.commit();
		}

        if (bundle != null) {
            String activeSearchQuery = bundle.getString(BUNDLE_ACTIVE_SEARCH_QUERY);
            if (activeSearchQuery != null) {
                searchQueryInput.setText(activeSearchQuery);
                searchQueryInput.setVisibility(View.VISIBLE);
                fs.setSearchQuery(activeSearchQuery);
            }
        }
        searchQueryInput.setOnKeyListener(new OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if ((keyCode == KeyEvent.KEYCODE_BACK) && (event.getAction() == KeyEvent.ACTION_DOWN)) {
                    searchQueryInput.setVisibility(View.GONE);
                    searchQueryInput.setText("");
                    checkSearchQuery();
                    return true;
                }
                if ((keyCode == KeyEvent.KEYCODE_ENTER) && (event.getAction() == KeyEvent.ACTION_DOWN)) {
                    checkSearchQuery();
                    return true;
                }
                return false;
            }
        });
	}

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (searchQueryInput != null) {
            String q = searchQueryInput.getText().toString().trim();
            if (q.length() > 0) {
                outState.putString(BUNDLE_ACTIVE_SEARCH_QUERY, q);
            }
        }
    }

    public FeedSet getFeedSet() {
        return this.fs;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (NBSyncService.isHousekeepingRunning()) finish();
        updateStatusIndicators();
        // Reading activities almost certainly changed the read/unread state of some stories. Ensure
        // we reflect those changes promptly.
        itemSetFragment.hasUpdated();
    }

    @Override
    protected void onPause() {
        super.onPause();
        NBSyncService.addRecountCandidates(fs);
    }

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.itemslist, menu);

        if (fs.isGlobalShared() ||
            fs.isAllSocial() ||
            fs.isFilterSaved() ||
            fs.isAllSaved() ||
            fs.isSingleSavedTag() ||
            fs.isInfrequent() ||
            fs.isAllRead() ) {
            menu.findItem(R.id.menu_mark_all_as_read).setVisible(false);
        }

        if (fs.isGlobalShared() ||
            fs.isAllSocial() ||
            fs.isAllRead() ) {
            menu.findItem(R.id.menu_story_order).setVisible(false);
        }

        if (fs.isGlobalShared() ||
            fs.isFilterSaved() ||
            fs.isAllSaved() ||
            fs.isSingleSavedTag() ||
            fs.isInfrequent() ||
            fs.isAllRead() ) {
            menu.findItem(R.id.menu_read_filter).setVisible(false);
        }

        if (fs.isGlobalShared() ||
            fs.isAllSocial() ||
            fs.isInfrequent() ||
            fs.isAllRead() ) {
            menu.findItem(R.id.menu_search_stories).setVisible(false);
        }

        if ((!fs.isSingleNormal()) || fs.isFilterSaved()) {
            menu.findItem(R.id.menu_notifications).setVisible(false);
            menu.findItem(R.id.menu_delete_feed).setVisible(false);
            menu.findItem(R.id.menu_instafetch_feed).setVisible(false);
            menu.findItem(R.id.menu_intel).setVisible(false);
            menu.findItem(R.id.menu_rename_feed).setVisible(false);
        }

        if (!fs.isInfrequent()) {
            menu.findItem(R.id.menu_infrequent_cutoff).setVisible(false);
        }

		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		super.onPrepareOptionsMenu(menu);

        StoryListStyle listStyle = PrefsUtils.getStoryListStyle(this, fs);
        if (listStyle == StoryListStyle.GRID_F) {
             menu.findItem(R.id.menu_list_style_grid_f).setChecked(true);
        } else if (listStyle == StoryListStyle.GRID_M) {
             menu.findItem(R.id.menu_list_style_grid_m).setChecked(true);
        } else if (listStyle == StoryListStyle.GRID_C) {
             menu.findItem(R.id.menu_list_style_grid_c).setChecked(true);
        } else {
            menu.findItem(R.id.menu_list_style_list).setChecked(true);
        }

        ThemeValue themeValue = PrefsUtils.getSelectedTheme(this);
        if (themeValue == ThemeValue.LIGHT) {
            menu.findItem(R.id.menu_theme_light).setChecked(true);
        } else if (themeValue == ThemeValue.DARK) {
            menu.findItem(R.id.menu_theme_dark).setChecked(true);
        } else if (themeValue == ThemeValue.BLACK) {
            menu.findItem(R.id.menu_theme_black).setChecked(true);
        }

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == android.R.id.home) {
			finish();
			return true;
		} else if (item.getItemId() == R.id.menu_mark_all_as_read) {
            FeedUtils.markRead(this, fs, null, null, R.array.mark_all_read_options, true);
			return true;
		} else if (item.getItemId() == R.id.menu_story_order) {
            StoryOrder currentValue = getStoryOrder();
            StoryOrderDialogFragment storyOrder = StoryOrderDialogFragment.newInstance(currentValue);
            storyOrder.show(getSupportFragmentManager(), STORY_ORDER);
            return true;
        } else if (item.getItemId() == R.id.menu_read_filter) {
            ReadFilter currentValue = getReadFilter();
            ReadFilterDialogFragment readFilter = ReadFilterDialogFragment.newInstance(currentValue);
            readFilter.show(getSupportFragmentManager(), READ_FILTER);
            return true;
		} else if (item.getItemId() == R.id.menu_textsize) {
			TextSizeDialogFragment textSize = TextSizeDialogFragment.newInstance(PrefsUtils.getListTextSize(this), TextSizeDialogFragment.TextSizeType.ListText);
			textSize.show(getSupportFragmentManager(), TextSizeDialogFragment.class.getName());
			return true;
        } else if (item.getItemId() == R.id.menu_search_stories) {
            if (searchQueryInput.getVisibility() != View.VISIBLE) {
                searchQueryInput.setVisibility(View.VISIBLE);
                searchQueryInput.requestFocus();
            } else {
                searchQueryInput.setVisibility(View.GONE);
                checkSearchQuery();
            }
        } else if (item.getItemId() == R.id.menu_theme_light) {
            PrefsUtils.setSelectedTheme(this, ThemeValue.LIGHT);
            UIUtils.restartActivity(this);
        } else if (item.getItemId() == R.id.menu_theme_dark) {
            PrefsUtils.setSelectedTheme(this, ThemeValue.DARK);
            UIUtils.restartActivity(this);
        } else if (item.getItemId() == R.id.menu_theme_black) {
            PrefsUtils.setSelectedTheme(this, ThemeValue.BLACK);
            UIUtils.restartActivity(this);
        } else if (item.getItemId() == R.id.menu_list_style_list) {
            PrefsUtils.updateStoryListStyle(this, fs, StoryListStyle.LIST);
            itemSetFragment.updateStyle();
        } else if (item.getItemId() == R.id.menu_list_style_grid_f) {
            PrefsUtils.updateStoryListStyle(this, fs, StoryListStyle.GRID_F);
            itemSetFragment.updateStyle();
        } else if (item.getItemId() == R.id.menu_list_style_grid_m) {
            PrefsUtils.updateStoryListStyle(this, fs, StoryListStyle.GRID_M);
            itemSetFragment.updateStyle();
        } else if (item.getItemId() == R.id.menu_list_style_grid_c) {
            PrefsUtils.updateStoryListStyle(this, fs, StoryListStyle.GRID_C);
            itemSetFragment.updateStyle();
        }

		return false;
	}

	public StoryOrder getStoryOrder() {
        return PrefsUtils.getStoryOrder(this, fs);
    }

	private void updateStoryOrderPreference(StoryOrder newOrder) {
        PrefsUtils.updateStoryOrder(this, fs, newOrder);
    }

	private ReadFilter getReadFilter() {
        return PrefsUtils.getReadFilter(this, fs);
    }

    private void updateReadFilterPreference(ReadFilter newValue) {
        PrefsUtils.updateReadFilter(this, fs, newValue);
    }

    @Override
	public void handleUpdate(int updateType) {
        if ((updateType & UPDATE_REBUILD) != 0) {
            finish();
        }
        if ((updateType & UPDATE_STATUS) != 0) {
            updateStatusIndicators();
        }
		if ((updateType & UPDATE_STORY) != 0) {
            if (itemSetFragment != null) {
			    itemSetFragment.hasUpdated();
            }
        }
    }

    private void updateStatusIndicators() {
        if (overlayStatusText != null) {
            String syncStatus = NBSyncService.getSyncStatusMessage(this, true);
            if (syncStatus != null)  {
                if (AppConstants.VERBOSE_LOG) {
                    syncStatus = syncStatus + UIUtils.getMemoryUsageDebug(this);
                }
                overlayStatusText.setText(syncStatus);
                overlayStatusText.setVisibility(View.VISIBLE);
            } else {
                overlayStatusText.setVisibility(View.GONE);
            }
        }
    }

    private void checkSearchQuery() {
        String oldQuery = fs.getSearchQuery();
        String q = searchQueryInput.getText().toString().trim();
        if (q.length() < 1) {
            q = null;
        }
        fs.setSearchQuery(q);
        if (!TextUtils.equals(q, oldQuery)) {
            FeedUtils.prepareReadingSession(fs, true);
            triggerSync();
            itemSetFragment.resetEmptyState();
            itemSetFragment.hasUpdated();
            itemSetFragment.scrollToTop();
        }
    }

	@Override
    public void storyOrderChanged(StoryOrder newValue) {
        updateStoryOrderPreference(newValue);
        restartReadingSession();
    }

    @Override
    public void readFilterChanged(ReadFilter newValue) {
        updateReadFilterPreference(newValue);
        restartReadingSession();
    }

    protected void restartReadingSession() {
        NBSyncService.resetFetchState(fs);
        FeedUtils.prepareReadingSession(fs, true);
        triggerSync();
        itemSetFragment.resetEmptyState();
        itemSetFragment.hasUpdated();
        itemSetFragment.scrollToTop();
    }

    // NB: this callback is for the text size slider
	@Override
	public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        float size = AppConstants.LIST_FONT_SIZE[progress];
	    PrefsUtils.setListTextSize(this, size);
        if (itemSetFragment != null) itemSetFragment.setTextSize(size);
	}

    // unused OnSeekBarChangeListener method
	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
	}

    // unused OnSeekBarChangeListener method
	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
	}

    @Override
    public void finish() {
        super.finish();
        /*
         * Animate out the list by sliding it to the right and the Main activity in from
         * the left.  Do this when going back to Main as a subtle hint to the swipe gesture,
         * to make the gesture feel more natural, and to override the really ugly transition
         * used in some of the newer platforms.
         */
        overridePendingTransition(R.anim.slide_in_from_left, R.anim.slide_out_to_right);
    }
}


text:
namespace DentalSoft.Data.Models
{
    using System;

    public interface IAuditInfo
    {
        DateTime CreatedOn { get; set; }

        bool PreserveCreatedOn { get; set; }

        DateTime? ModifiedOn { get; set; }
    }
}


text:
package org.broad.igv.ui.panel;

import org.broad.igv.PreferenceManager;
import org.broad.igv.feature.Locus;
import org.broad.igv.lists.GeneList;
import org.broad.igv.track.RegionScoreType;
import org.broad.igv.track.Track;
import org.broad.igv.ui.IGV;
import org.broad.igv.ui.action.SearchCommand;
import org.broad.igv.ui.util.MessageUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @author jrobinso
 * @date Sep 10, 2010
 */
public class FrameManager {

    private static List<ReferenceFrame> frames = new ArrayList();
    private static ReferenceFrame defaultFrame;

    public static final String DEFAULT_FRAME_NAME = "genome";

    static {
        frames.add(getDefaultFrame());
    }

    public synchronized static ReferenceFrame getDefaultFrame() {
        if (defaultFrame == null) {
            defaultFrame = new ReferenceFrame(DEFAULT_FRAME_NAME);
        }
        return defaultFrame;
    }

    public static List<ReferenceFrame> getFrames() {
        return frames;
    }

    public static ReferenceFrame getFrame(String frameName){
        for(ReferenceFrame frame: frames){
            if(frame.getName().equals(frameName)){
                return frame;
            }
        }
        return null;
    }

    public static void setFrames(List<ReferenceFrame> f) {
        frames = f;
    }

    public static boolean isGeneListMode() {
        return frames.size() > 1;
    }

    public static int getStateHash() {
        if(isGeneListMode()) {
            String hs = "";
            for(ReferenceFrame frame : frames) {
                hs = hs + frame.getStateHash();
            }
            return hs.hashCode();
        }
        else {
            return defaultFrame.getStateHash();
        }
    }

    public static void setToDefaultFrame(String searchString) {
        frames.clear();
        if (searchString != null) {
            Locus locus = getLocus(searchString, 0);
            if (locus != null) {
                getDefaultFrame().jumpTo(locus);
            }
        }
        frames.add(getDefaultFrame());
        getDefaultFrame().recordHistory();
    }

    private static boolean addNewFrame(String searchString){
        boolean locusAdded = false;
        Locus locus = getLocus(searchString);
        if (locus != null) {
            ReferenceFrame referenceFrame = new ReferenceFrame(searchString);
            referenceFrame.jumpTo(locus);
            locusAdded = frames.add(referenceFrame);
        }
        return locusAdded;
    }

    public static void resetFrames(GeneList gl) {

        frames.clear();

        if (gl == null) {
            frames.add(getDefaultFrame());
        } else {
            List<String> lociNotFound = new ArrayList();
            List<String> loci = gl.getLoci();
            if (loci.size() == 1) {
                Locus locus = getLocus(loci.get(0));
                if (locus == null) {
                    lociNotFound.add(loci.get(0));
                } else {
                    IGV.getInstance().getSession().setCurrentGeneList(null);
                    getDefaultFrame().jumpTo(locus.getChr(), locus.getStart(), locus.getEnd());
                }
            } else {
                for (String searchString : gl.getLoci()) {
                    if(!addNewFrame(searchString)){
                        lociNotFound.add(searchString);
                    }
                }
            }

            if (lociNotFound.size() > 1) {
                StringBuffer message = new StringBuffer();
                message.append("<html>The following loci could not be found in the currently loaded annotation sets: <br>");
                for (String s : lociNotFound) {
                    message.append(s + " ");
                }
                MessageUtils.showMessage(message.toString());

            }
        }
    }

    /**
     * @return The minimum scale among all active frames
     *         TODO -- track this with "rescale" events, rather than compute on the fly
     */
    public static double getMinimumScale() {
        double minScale = Double.MAX_VALUE;
        for (ReferenceFrame frame : frames) {
            minScale = Math.min(minScale, frame.getScale());
        }
        return minScale;
    }

    /**
     * Uses default flanking region with
     * {@link #getLocus(String, int)}
     * @param searchString
     * @return
     */
    public static Locus getLocus(String searchString) {
        int flankingRegion = PreferenceManager.getInstance().getAsInt(PreferenceManager.FLANKING_REGION);
        return getLocus(searchString, flankingRegion);
    }

    /**
     * Runs a search for the specified string, and returns a locus
     * of the given region with additional space on each side.
     * Note: We DO NOT add the flanking region if the {@code searchString}
     * is a locus (e.g. chr1:50-100), only if it's a gene or feature name (or something else)
     *
     * @param searchString
     * @param flankingRegion
     * @return The found locus, null if not found
     */
    public static Locus getLocus(String searchString, int flankingRegion) {
        SearchCommand cmd = new SearchCommand(getDefaultFrame(), searchString);
        List<SearchCommand.SearchResult> results = cmd.runSearch(searchString);
        Locus locus = null;
        for (SearchCommand.SearchResult result : results) {
            if (result.getType() != SearchCommand.ResultType.ERROR) {
                int delta = 0;

                if (result.getType() != SearchCommand.ResultType.LOCUS) {
                    if (flankingRegion < 0) {
                        delta = (-flankingRegion * (result.getEnd() - result.getStart())) / 100;
                    } else {
                        delta = flankingRegion;
                    }
                }

                int start = result.getStart() - delta;
                //Don't allow flanking region to extend past origin
                //There are some circumstances in which we render before origin (e.g. soft-clips)
                //so we are conservative
                if (start < 0 && result.getStart() >= -1) {
                    start = 0;
                }
                locus = new Locus(
                        result.getChr(),
                        start,
                        result.getEnd() + delta);
                //We just take the first result
                break;
            }
        }
        return locus;
    }

    public static void removeFrame(ReferenceFrame frame) {
        frames.remove(frame);
    }

    public static void sortFrames(final Track t) {

        Collections.sort(frames, new Comparator<ReferenceFrame>() {
            @Override
            public int compare(ReferenceFrame o1, ReferenceFrame o2) {
                float s1 = t.getRegionScore(o1.getChromosome().getName(), (int) o1.getOrigin(), (int) o1.getEnd(),
                        o1.getZoom(), RegionScoreType.SCORE, o1.getName());
                float s2 = t.getRegionScore(o2.getChromosome().getName(), (int) o2.getOrigin(), (int) o2.getEnd(),
                        o2.getZoom(), RegionScoreType.SCORE, o2.getName());
                return (s1 == s2 ? 0 : (s1 > s2) ? -1 : 1);
            }
        });

    }

    /**
     * Increment the zoom level of the visibile frame(s). Supports batch commands zoomIn and zoomOut
     *
     * @param zoom the zoom level increment, usually -1 or 1
     */
    public static void incrementZoom(int zoom) {

        if(isGeneListMode()) {
            for(ReferenceFrame frame : getFrames()) {
                frame.doZoomIncrement(zoom);
            }
        }
        else {
            getDefaultFrame().doZoomIncrement(zoom);
        }
    }

}


text:
package picocli;

import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.ProvideSystemProperty;
import org.junit.contrib.java.lang.system.RestoreSystemProperties;
import org.junit.rules.TestRule;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
import picocli.CommandLine.UnmatchedArgumentException;
import picocli.test.Execution;
import picocli.test.Supplier;

import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;

import static java.lang.String.format;
import static org.junit.Assert.*;

public class UnmatchedArgumentExceptionTest {

    // allows tests to set any kind of properties they like, without having to individually roll them back
    @Rule
    public final TestRule restoreSystemProperties = new RestoreSystemProperties();

    @Rule
    public final ProvideSystemProperty ansiOFF = new ProvideSystemProperty("picocli.ansi", "false");

    @Command
    static class Example {
    }

    @Test(expected = NullPointerException.class)
    public void testConstructorRejectsNullList() {
        new UnmatchedArgumentException(new CommandLine(new Example()), (List<String>) null);
    }

    @Test
    public void testConstructorNonNullList() {
        List<String> args = Arrays.asList("a", "b", "c");
        UnmatchedArgumentException ex = new UnmatchedArgumentException(new CommandLine(new Example()), args);
        assertEquals(args, ex.getUnmatched());
        assertNotSame(args, ex.getUnmatched());
    }
    @Test
    @SuppressWarnings("deprecation")
    public void testUnmatchedArgumentSuggestsOptions() {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        CommandLine cmd = new CommandLine(new Demo.GitCommit());
        cmd.parseWithHandler(((CommandLine.IParseResultHandler)null), new PrintStream(baos), new String[]{"-fi"});
        String expected = format("" +
                "Unknown option: '-fi'%n" +
                "Possible solutions: --fixup, --file%n");
        assertEquals(expected, baos.toString());
    }
    @Test
    @SuppressWarnings("deprecation")
    public void testUnmatchedArgumentDoesNotSuggestOptionsIfNoMatch() {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        CommandLine cmd = new CommandLine(new Demo.GitCommit());
        cmd.parseWithHandler(((CommandLine.IParseResultHandler)null), new PrintStream(baos), new String[]{"-x"});
        String actual = baos.toString();
        assertTrue(actual, actual.startsWith("Unknown option: '-x'"));
        assertTrue(actual, actual.contains("Usage:"));
        assertFalse(actual, actual.contains("Possible solutions:"));
    }
    @Test
    @SuppressWarnings("deprecation")
    public void testUnmatchedArgumentSuggestsSubcommands() {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Demo.mainCommand().parseWithHandler(((CommandLine.IParseResultHandler)null), new PrintStream(baos), new String[]{"chekcout"});
        String expected = format("" +
                "Unmatched argument at index 0: 'chekcout'%n" +
                "Did you mean: checkout or help or branch?%n");
        assertEquals(expected, baos.toString());
    }
    @Test
    @SuppressWarnings("deprecation")
    public void testUnmatchedArgumentSuggestsSubcommands2() {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Demo.mainCommand().parseWithHandler(((CommandLine.IParseResultHandler)null), new PrintStream(baos), new String[]{"me"});
        String expected = format("" +
                "Unmatched argument at index 0: 'me'%n" +
                "Did you mean: merge?%n");
        assertEquals(expected, baos.toString());
    }

    @Test
    public void testPrintSuggestionsPrintStream() {
        CommandLine cmd = new CommandLine(new Demo.GitCommit());
        UnmatchedArgumentException ex = new UnmatchedArgumentException(cmd, Arrays.asList("-fi"));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        UnmatchedArgumentException.printSuggestions(ex, new PrintStream(baos));
        String expected = format("" +
                "Possible solutions: --fixup, --file%n");
        assertEquals(expected, baos.toString());
    }

    @Test
    public void testPrintSuggestionsPrintStreamAutoFlushes() {
        CommandLine cmd = new CommandLine(new Demo.GitCommit());
        UnmatchedArgumentException ex = new UnmatchedArgumentException(cmd, Arrays.asList("-fi"));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        UnmatchedArgumentException.printSuggestions(ex, new PrintStream(new BufferedOutputStream(baos)));
        String expected = format("" +
                "Possible solutions: --fixup, --file%n");
        assertEquals(expected, baos.toString());
    }

    @Test
    public void testPrintSuggestionsPrintWriter() {
        CommandLine cmd = new CommandLine(new Demo.GitCommit());
        UnmatchedArgumentException ex = new UnmatchedArgumentException(cmd, Arrays.asList("-fi"));
        StringWriter sw = new StringWriter();
        UnmatchedArgumentException.printSuggestions(ex, new PrintWriter(sw));
        String expected = format("" +
                "Possible solutions: --fixup, --file%n");
        assertEquals(expected, sw.toString());
    }

    @Test
    public void testPrintSuggestionsPrintWriterAutoFlushes() {
        CommandLine cmd = new CommandLine(new Demo.GitCommit());
        UnmatchedArgumentException ex = new UnmatchedArgumentException(cmd, Arrays.asList("-fi"));
        StringWriter sw = new StringWriter();
        UnmatchedArgumentException.printSuggestions(ex, new PrintWriter(new BufferedWriter(sw)));
        String expected = format("" +
                "Possible solutions: --fixup, --file%n");
        assertEquals(expected, sw.toString());
    }

    @Test
    public void testUnmatchedListWithNullElements() {
        CommandLine cmd = new CommandLine(new Demo.GitCommit());
        UnmatchedArgumentException ex = new UnmatchedArgumentException(cmd, Arrays.asList("-fi", null));
        StringWriter sw = new StringWriter();
        UnmatchedArgumentException.printSuggestions(ex, new PrintWriter(sw));
        String expected = format("" +
                "Possible solutions: --fixup, --file%n");
        assertEquals(expected, sw.toString());
    }

    //https://github.com/remkop/picocli/issues/887
    @Test
    public void testHiddenOptionsNotSuggested() {
        class MyApp {
            @Option(names = "--aaa", hidden = true) int a;
            @Option(names = "--apples", hidden = false) int apples;
            @Option(names = "--bbb", hidden = false) int b;
        }
        CommandLine cmd = new CommandLine(new MyApp());
        UnmatchedArgumentException ex = new UnmatchedArgumentException(cmd, Arrays.asList("--a", null));
        StringWriter sw = new StringWriter();
        UnmatchedArgumentException.printSuggestions(ex, new PrintWriter(sw));
        String expected = format("" +
                "Possible solutions: --apples%n");
        assertEquals(expected, sw.toString());
    }

    //https://github.com/remkop/picocli/issues/887
    @Test
    public void testHiddenCommandsNotSuggested() {

        @Command(name="Completion", subcommands = { picocli.AutoComplete.GenerateCompletion.class } )
        class CompletionSubcommandDemo implements Runnable {
            public void run() { }
        }
        Supplier<CommandLine> supplier = new Supplier<CommandLine>() {
            public CommandLine get() {
                CommandLine cmd = new CommandLine(new CompletionSubcommandDemo());
                CommandLine gen = cmd.getSubcommands().get("generate-completion");
                gen.getCommandSpec().usageMessage().hidden(true);
                return cmd;
            }
        };

        Execution execution = Execution.builder(supplier).execute("ge");
        execution.assertSystemErr("" +
                "Unmatched argument at index 0: 'ge'%n" +
                "Usage: Completion [COMMAND]%n");
    }

    @Test
    public void testUnmatchedExceptionStringConstructor() {
        UnmatchedArgumentException ex = new UnmatchedArgumentException(new CommandLine(CommandLine.Model.CommandSpec.create()), "aa");
        assertNotNull(ex.getUnmatched());
        assertTrue(ex.getUnmatched().isEmpty());
        assertTrue(ex.getSuggestions().isEmpty());
    }

    @Test
    public void testUnmatchedExceptionListConstructor() {
        UnmatchedArgumentException ex = new UnmatchedArgumentException(new CommandLine(CommandLine.Model.CommandSpec.create()), new ArrayList<String>());
        assertNotNull(ex.getUnmatched());
        assertTrue(ex.getUnmatched().isEmpty());
        assertTrue(ex.getSuggestions().isEmpty());

        ex = new UnmatchedArgumentException(new CommandLine(CommandLine.Model.CommandSpec.create()), Arrays.asList("a", "b"));
        assertEquals(Arrays.asList("a", "b"), ex.getUnmatched());
    }

    @Test
    public void testUnmatchedExceptionStackConstructor() {
        UnmatchedArgumentException ex = new UnmatchedArgumentException(new CommandLine(CommandLine.Model.CommandSpec.create()), new Stack<String>());
        assertNotNull(ex.getUnmatched());
        assertTrue(ex.getUnmatched().isEmpty());
        assertTrue(ex.getSuggestions().isEmpty());

        Stack<String> stack = new Stack<String>();
        stack.push("x");
        stack.push("y");
        stack.push("z");
        ex = new UnmatchedArgumentException(new CommandLine(CommandLine.Model.CommandSpec.create()), stack);
        assertEquals(Arrays.asList("z", "y", "x"), ex.getUnmatched());
    }

    @Test
    public void testUnmatchedExceptionIsUnknownOption() {
        CommandLine cmd = new CommandLine(CommandLine.Model.CommandSpec.create());

        assertFalse("unmatch list is null", new UnmatchedArgumentException(cmd, "").isUnknownOption());
        assertFalse("unmatch list is empty", new UnmatchedArgumentException(cmd, new ArrayList<String>()).isUnknownOption());

        List<String> likeAnOption = Arrays.asList("-x");
        assertTrue("first unmatched resembles option", new UnmatchedArgumentException(cmd, likeAnOption).isUnknownOption());

        List<String> unlikeOption = Arrays.asList("xxx");
        assertFalse("first unmatched doesn't resembles option", new UnmatchedArgumentException(cmd, unlikeOption).isUnknownOption());
    }
}


text:
'use strict';

let mongoose = require('mongoose');
let Schema = mongoose.Schema;

let presetSchema = new Schema({
  name: {type: String, required: [true, "Name is required"], minlength: 3, maxlength: 100},
  order: {type: Number},
  color: {type: Number},
  userId: {type: String, required: true}
});

presetSchema.index({name: 1, userId: 1}, {unique: true});

// validate that category name is unique per user
presetSchema.path('name').validate(function (value, done) {
  console.log(this);
  this.model('Presets').count({
    name: value,
    userId: this.userId
  }, function (err, count) {
    if (err) {
      return done(err);
    }
    // If `count` is greater than zero, "invalidate"
    done(!count);
  });
}, 'Category name exists');

let PresetModel = mongoose.model('Presets', presetSchema);

module.exports = {

  /**
   *
   * @param {string} name
   * @param {int} order
   * @param {int} color
   * @param {string} userId
   * @returns {Model|*|Aggregate}
   */
  create(name, order, color, userId){
    let preset = new PresetModel({
      name: name,
      order: order,
      color: color,
      userId: userId
    });
    return preset.save();
  },

  /**
   *
   * @param {string} presetId
   * @returns {*|Query}
   */
  findById(presetId){
    return PresetModel.findOne({'_id': presetId});
  },

  /**
   *
   * @param userId
   * @returns {Query}
   */
  findByUser(userId){
    return PresetModel.find({'userId': userId}).sort({order: 1});
  },

  /**
   *
   * @param {string} presetId
   * @param {string} userId
   * @param {string} name
   * @param {number} color
   * @returns {Promise}
   */
  update(presetId, userId, name, color){
    if (color == undefined){
      color = 0;
    }
    return PresetModel.findOneAndUpdate({
      _id: presetId,
      userId: userId
    }, {name: name, color: color})
  },

  /**
   *
   * @param {array} presets
   * @param {string} userId
   */
  reOder(presets, userId){
    presets.forEach(function (presetId, order) {
      PresetModel.findOneAndUpdate({
        _id: presetId,
        userId: userId
      }, {order: order + 1})
        .catch(function (e) {
          console.log(e);
        });
    });
  },

  /**
   *
   * @param {string} presetId
   * @param {string} userId
   * @returns {Promise}
   */
  delete(presetId, userId){
    return PresetModel.remove({_id: presetId, userId: userId});
  }
};


text:
/*---------------------------------------------------------------------------

    (c) 2004 Scorpio Software
        19 Wittama Drive
        Glenmore Park
        Sydney NSW 2745
        Australia

-----------------------------------------------------------------------------

    $Workfile::                                                           $
    $Revision::                                                           $
        $Date::                                                           $
      $Author::                                                           $

---------------------------------------------------------------------------*/
//---------------------------------------------------------------------------
#ifndef ZXImporterH
#define ZXImporterH
//---------------------------------------------------------------------------
#include "..\ZXImageInterface.h"
//---------------------------------------------------------------------------
class ZXImporter
{
private:

protected:
    ZXImageManager*             m_pImageManager;
    String                      m_sPaletteSignature;
    String                      m_sError;

            int     __fastcall  AddImage(const String& sType, const String& sName, int iWidth, int iHeight, bool bMasked, ZXImage** pImage = NULL);

public:
                    __fastcall  ZXImporter();
    virtual         __fastcall ~ZXImporter();

    virtual bool    __fastcall  ChoosePalette(TStrings* sFiles, TStrings* pPalettes) = 0;
    virtual bool    __fastcall  Import(TStrings* sFiles) = 0;

    __property  String          PaletteSignature    = { read = m_sPaletteSignature  , write = m_sPaletteSignature   };
    __property  ZXImageManager* ImageManager        = { read = m_pImageManager      , write = m_pImageManager       };
    __property  String          Error               = { read = m_sError                                             };
};
//---------------------------------------------------------------------------
#endif


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Bot',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=255, unique=True)),
                ('mu', models.FloatField(default=25.0)),
                ('sigma', models.FloatField(default=8.33333)),
                ('enabled', models.BooleanField(default=True)),
            ],
        ),
        migrations.CreateModel(
            name='Match',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('date', models.DateTimeField()),
                ('replay', models.FileField(upload_to='hlt/')),
                ('seed', models.CharField(max_length=255)),
                ('width', models.IntegerField()),
                ('height', models.IntegerField()),
            ],
            options={
                'verbose_name_plural': 'matches',
            },
        ),
        migrations.CreateModel(
            name='MatchResult',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('rank', models.IntegerField()),
                ('mu', models.FloatField()),
                ('sigma', models.FloatField()),
                ('last_frame_alive', models.IntegerField()),
                ('bot', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='matches', to='tournament.Bot')),
                ('match', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='results', to='tournament.Match')),
            ],
        ),
    ]


text:
'use strict';

angular.module('myApp.sliders', ['ngRoute'])

  .config(['$routeProvider', function ($routeProvider) {
    $routeProvider.when('/sliders', {
      templateUrl: 'sliders/sliders.html',
      controller: 'SlidersController'
    });
  }])

  /**
   * The sliders controller handles the sliders for the /sliders page and allows users full control over the ranges
   * of the perceptual features.
   */
  .controller('SlidersController', ['$scope', 'ResourcesService', 'SongRequestService', 'angularPlayer', 'SlidersService','$timeout',
    function ($scope, ResourcesService, SongRequestService, angularPlayer, SlidersService, $timeout) {
      const ERROR_DURATION = 3000;
      var activeErrors = 0;

      /**
       * Shows the "No songs found"-error
       * @param duration The duration to show the error for
       */
      var showNoSongsFoundError = function (duration) {
        $scope.showError = true;
        activeErrors++;
        var thisError = activeErrors;
        $timeout(function () {
          if (thisError === activeErrors) { // No new errors have been added during the timeout
            $scope.showError = false;
            activeErrors = 0;
          }
        }, duration);
      };

      /**
       * Callback function which gets called when songs are to be added
       * @param res The added songs
       */
      var addedSongs = function (res) {
        if (res.length === 0) {
          showNoSongsFoundError(ERROR_DURATION);
        }
      };

      /**
       * Sets the location of the error
       * @param sliderId The id of the slider used
       */
      var setErrorLocation = function(sliderId){
        var slider = $('.'+sliderId);
        $scope.errorLeft = slider.offset().left+slider.width()/6;
        $scope.errorTop = slider.offset().top+35;
      };

      /**
       * Sends a request to play songs matching the features selected in the sliders
       */
      $scope.sendRequestForClosest = function (sliderId) {
        setErrorLocation(sliderId);
        SlidersService.saveSliders($scope.featureList);
        SongRequestService.playMatchingSongs($scope.featureList,addedSongs,"Closest");
        SlidersService.setLastRequestNumber(SongRequestService.getLastRequestNumber());
      };

      /**
       * Resets all the sliders to the original settings
       */
      $scope.resetSliders = function(){
        for(var i = 0; i < $scope.featureList.length; i++){
          $scope.featureList[i].minValue = 0;
          $scope.featureList[i].maxValue = 100;
        }
        SlidersService.saveSliders($scope.featureList);
        SongRequestService.playMatchingSongs($scope.featureList,addedSongs,"Closest");
        SlidersService.setLastRequestNumber(SongRequestService.getLastRequestNumber());
      };

      /**
       * Loads existing values
       */
      var loadValues = function () {
        $scope.featureList = SlidersService.getSavedValues().features;
        // Check if another request has been done on another page, if so, reset the sliders
        if(SlidersService.getLastRequestNumber() !== SongRequestService.getLastRequestNumber()){
          $scope.resetSliders();
        }
      };

      /**
       * Sets that the page has fully loaded after 200 ms
       */
      var setPageLoaded = function() {
        $timeout(function () {
          $scope.pageLoaded = true;
        }, 200);
      };

      /* Controller body starts here */

      $scope.featureList = [];

      if(SlidersService.hasTransferred()){ // Check if user has copied values to the sliders page
        ResourcesService.Features.query().$promise.then(function (data) {
          $scope.featureList = SlidersService.getTransferredValues();
          for (var i = 0; i < data.length; i++){
            $scope.featureList[i].low = data[i].low;
            $scope.featureList[i].high = data[i].high;
          }
          SlidersService.clearTransferredValues();
          SlidersService.saveSliders($scope.featureList);
          setPageLoaded();
        }, function (err) {
          throw "No features were returned by query: " + err;
        });
      }
      else if (!SlidersService.getSavedValues().features) { // Import saved values if possible
        ResourcesService.Features.query().$promise.then(function (data) {
          $scope.featureList = data;
          for (var i = 0; i < $scope.featureList.length; i++) {
            $scope.featureList[i].minValue = 0;
            $scope.featureList[i].maxValue = 100;
          }
          setPageLoaded();
        }, function (err) {
          throw "No features were returned by query: " + err;
        });
      }
      else { // No transferred or saved values exist, build the list ourselves
        loadValues();
        setPageLoaded();
      }

    }]);


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
		android:orientation="vertical" android:layout_width="match_parent"
		android:paddingTop="10dp"
		android:layout_height="match_parent">
	<android.support.v7.widget.AppCompatEditText
			android:id="@+id/et_1"
			android:layout_marginLeft="15dp"
			android:layout_marginRight="15dp"
			style="@style/dialogutil_md_innput"
			android:layout_width="match_parent"
			android:layout_height="wrap_content" />
	<android.support.v7.widget.AppCompatEditText
			android:id="@+id/et_2"
			android:layout_marginLeft="15dp"
			android:layout_marginRight="15dp"
			style="@style/dialogutil_md_innput"
			android:layout_width="match_parent"
			android:layout_height="wrap_content" />

</LinearLayout>


text:
package com.vmware.vim25;

/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/

public enum HostDisconnectedEventReasonCode {
  sslThumbprintVerifyFailed ("sslThumbprintVerifyFailed"),
  licenseExpired ("licenseExpired"),
  agentUpgrade ("agentUpgrade"),
  userRequest ("userRequest"),
  insufficientLicenses ("insufficientLicenses"),
  agentOutOfDate ("agentOutOfDate"),
  passwordDecryptFailure ("passwordDecryptFailure"),
  unknown ("unknown"),
  vcVRAMCapacityExceeded ("vcVRAMCapacityExceeded");

  @SuppressWarnings("unused")
  private final String val;
  private HostDisconnectedEventReasonCode(String val)
  {
    this.val = val;
  }
}


text:
/*	$OpenBSD: rpc.c,v 1.10 1998/02/23 20:32:30 niklas Exp $	*/
/*	$NetBSD: rpc.c,v 1.16 1996/10/13 02:29:06 christos Exp $	*/

/*
 * Copyright (c) 1992 Regents of the University of California.
 * All rights reserved.
 *
 * This software was developed by the Computer Systems Engineering group
 * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
 * contributed to Berkeley.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Lawrence Berkeley Laboratory and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * @(#) Header: rpc.c,v 1.12 93/09/28 08:31:56 leres Exp  (LBL)
 */

/*
 * RPC functions used by NFS and bootparams.
 * Note that bootparams requires the ability to find out the
 * address of the server from which its response has come.
 * This is supported by keeping the IP/UDP headers in the
 * buffer space provided by the caller.  (See rpc_fromaddr)
 */

#include <sys/param.h>
#include <sys/socket.h>

#include <netinet/in.h>
#include <netinet/in_systm.h>

#include <nfs/rpcv2.h>

#include "stand.h"
#include "net.h"
#include "netif.h"
#include "rpc.h"

struct auth_info {
	int32_t 	authtype;	/* auth type */
	u_int32_t	authlen;	/* auth length */
};

struct auth_unix {
	int32_t   ua_time;
	int32_t   ua_hostname;	/* null */
	int32_t   ua_uid;
	int32_t   ua_gid;
	int32_t   ua_gidlist;	/* null */
};

struct rpc_call {
	u_int32_t	rp_xid;		/* request transaction id */
	int32_t 	rp_direction;	/* call direction (0) */
	u_int32_t	rp_rpcvers;	/* rpc version (2) */
	u_int32_t	rp_prog;	/* program */
	u_int32_t	rp_vers;	/* version */
	u_int32_t	rp_proc;	/* procedure */
};

struct rpc_reply {
	u_int32_t	rp_xid;		/* request transaction id */
	int32_t 	rp_direction;	/* call direction (1) */
	int32_t 	rp_astatus;	/* accept status (0: accepted) */
	union {
		u_int32_t	rpu_errno;
		struct {
			struct auth_info rok_auth;
			u_int32_t	rok_status;
		} rpu_rok;
	} rp_u;
};

/* Local forwards */
static	ssize_t recvrpc __P((struct iodesc *, void *, size_t, time_t));
static	int rpc_getport __P((struct iodesc *, n_long, n_long));

int rpc_xid;
int rpc_port = 0x400;	/* predecrement */

/*
 * Make a rpc call; return length of answer
 * Note: Caller must leave room for headers.
 */
ssize_t
rpc_call(d, prog, vers, proc, sdata, slen, rdata, rlen)
	register struct iodesc *d;
	register n_long prog, vers, proc;
	register void *sdata;
	register size_t slen;
	register void *rdata;
	register size_t rlen;
{
	register ssize_t cc;
	struct auth_info *auth;
	struct rpc_call *call;
	struct rpc_reply *reply;
	char *send_head, *send_tail;
	char *recv_head, *recv_tail;
	n_long x;
	int port;	/* host order */

#ifdef RPC_DEBUG
	if (debug)
		printf("rpc_call: prog=0x%x vers=%d proc=%d\n",
		    prog, vers, proc);
#endif

	port = rpc_getport(d, prog, vers);
	if (port == -1)
		return (-1);

	d->destport = htons(port);

	/*
	 * Prepend authorization stuff and headers.
	 * Note, must prepend things in reverse order.
	 */
	send_head = sdata;
	send_tail = (char *)sdata + slen;

	/* Auth verifier is always auth_null */
	send_head -= sizeof(*auth);
	auth = (struct auth_info *)send_head;
	auth->authtype = htonl(RPCAUTH_NULL);
	auth->authlen = 0;

#if 1
	/* Auth credentials: always auth unix (as root) */
	send_head -= sizeof(struct auth_unix);
	bzero(send_head, sizeof(struct auth_unix));
	send_head -= sizeof(*auth);
	auth = (struct auth_info *)send_head;
	auth->authtype = htonl(RPCAUTH_UNIX);
	auth->authlen = htonl(sizeof(struct auth_unix));
#else
	/* Auth credentials: always auth_null (XXX OK?) */
	send_head -= sizeof(*auth);
	auth = send_head;
	auth->authtype = htonl(RPCAUTH_NULL);
	auth->authlen = 0;
#endif

	/* RPC call structure. */
	send_head -= sizeof(*call);
	call = (struct rpc_call *)send_head;
	rpc_xid++;
	call->rp_xid       = htonl(rpc_xid);
	call->rp_direction = htonl(RPC_CALL);
	call->rp_rpcvers   = htonl(RPC_VER2);
	call->rp_prog = htonl(prog);
	call->rp_vers = htonl(vers);
	call->rp_proc = htonl(proc);

	/* Make room for the rpc_reply header. */
	recv_head = rdata;
	recv_tail = (char *)rdata + rlen;
	recv_head -= sizeof(*reply);

	cc = sendrecv(d,
	    sendudp, send_head, send_tail - send_head,
	    recvrpc, recv_head, recv_tail - recv_head);

#ifdef RPC_DEBUG
	if (debug)
		printf("callrpc: cc=%d rlen=%d\n", cc, rlen);
#endif
	if (cc < -1)
		return (-1);

	if ((size_t)cc <= sizeof(*reply)) {
		errno = EBADRPC;
		return (-1);
	}

	recv_tail = recv_head + cc;

	/*
	 * Check the RPC reply status.
	 * The xid, dir, astatus were already checked.
	 */
	reply = (struct rpc_reply *)recv_head;
	auth = &reply->rp_u.rpu_rok.rok_auth;
	x = ntohl(auth->authlen);
	if (x != 0) {
#ifdef RPC_DEBUG
		if (debug)
			printf("callrpc: reply auth != NULL\n");
#endif
		errno = EBADRPC;
		return(-1);
	}
	x = ntohl(reply->rp_u.rpu_rok.rok_status);
	if (x != 0) {
		printf("callrpc: error = %d\n", x);
		errno = EBADRPC;
		return(-1);
	}
	recv_head += sizeof(*reply);

	return (ssize_t)(recv_tail - recv_head);
}

/*
 * Returns true if packet is the one we're waiting for.
 * This just checks the XID, direction, acceptance.
 * Remaining checks are done by callrpc
 */
static ssize_t
recvrpc(d, pkt, len, tleft)
	register struct iodesc *d;
	register void *pkt;
	register size_t len;
	time_t tleft;
{
	register struct rpc_reply *reply;
	ssize_t	n;
	int	x;

	errno = 0;
#ifdef RPC_DEBUG
	if (debug)
		printf("recvrpc: called len=%d\n", len);
#endif

	n = readudp(d, pkt, len, tleft);
	if (n <= (4 * 4))
		return -1;

	reply = (struct rpc_reply *)pkt;

	x = ntohl(reply->rp_xid);
	if (x != rpc_xid) {
#ifdef RPC_DEBUG
		if (debug)
			printf("recvrpc: rp_xid %d != xid %d\n", x, rpc_xid);
#endif
		return -1;
	}

	x = ntohl(reply->rp_direction);
	if (x != RPC_REPLY) {
#ifdef RPC_DEBUG
		if (debug)
			printf("recvrpc: rp_direction %d != REPLY\n", x);
#endif
		return -1;
	}

	x = ntohl(reply->rp_astatus);
	if (x != RPC_MSGACCEPTED) {
		errno = ntohl(reply->rp_u.rpu_errno);
		printf("recvrpc: reject, astat=%d, errno=%d\n", x, errno);
		return -1;
	}

	/* Return data count (thus indicating success) */
	return (n);
}

/*
 * Given a pointer to a reply just received,
 * dig out the IP address/port from the headers.
 */
void
rpc_fromaddr(pkt, addr, port)
	void		*pkt;
	struct in_addr	*addr;
	u_short		*port;
{
	struct hackhdr {
		/* Tail of IP header: just IP addresses */
		n_long ip_src;
		n_long ip_dst;
		/* UDP header: */
		u_int16_t uh_sport;		/* source port */
		u_int16_t uh_dport;		/* destination port */
		int16_t	  uh_ulen;		/* udp length */
		u_int16_t uh_sum;		/* udp checksum */
		/* RPC reply header: */
		struct rpc_reply rpc;
	} *hhdr;

	hhdr = ((struct hackhdr *)pkt) - 1;
	addr->s_addr = hhdr->ip_src;
	*port = hhdr->uh_sport;
}

/*
 * RPC Portmapper cache
 */
#define PMAP_NUM 8			/* need at most 5 pmap entries */

int rpc_pmap_num;
struct pmap_list {
	struct in_addr	addr;	/* server, net order */
	u_int	prog;		/* host order */
	u_int	vers;		/* host order */
	int 	port;		/* host order */
} rpc_pmap_list[PMAP_NUM];

/* return port number in host order, or -1 */
int
rpc_pmap_getcache(addr, prog, vers)
	struct in_addr	addr;	/* server, net order */
	u_int		prog;	/* host order */
	u_int		vers;	/* host order */
{
	struct pmap_list *pl;

	for (pl = rpc_pmap_list; pl < &rpc_pmap_list[rpc_pmap_num]; pl++) {
		if (pl->addr.s_addr == addr.s_addr &&
			pl->prog == prog && pl->vers == vers )
		{
			return (pl->port);
		}
	}
	return (-1);
}

void
rpc_pmap_putcache(addr, prog, vers, port)
	struct in_addr	addr;	/* server, net order */
	u_int		prog;	/* host order */
	u_int		vers;	/* host order */
	int 		port;	/* host order */
{
	struct pmap_list *pl;

	/* Don't overflow cache... */
	if (rpc_pmap_num >= PMAP_NUM) {
		/* ... just re-use the last entry. */
		rpc_pmap_num = PMAP_NUM - 1;
#ifdef	RPC_DEBUG
		printf("rpc_pmap_putcache: cache overflow\n");
#endif
	}

	pl = &rpc_pmap_list[rpc_pmap_num];
	rpc_pmap_num++;

	/* Cache answer */
	pl->addr = addr;
	pl->prog = prog;
	pl->vers = vers;
	pl->port = port;
}

/*
 * Request a port number from the port mapper.
 * Returns the port in host order.
 */
int
rpc_getport(d, prog, vers)
	register struct iodesc *d;
	n_long prog;	/* host order */
	n_long vers;	/* host order */
{
	struct args {
		n_long	prog;		/* call program */
		n_long	vers;		/* call version */
		n_long	proto;		/* call protocol */
		n_long	port;		/* call port (unused) */
	} *args;
	struct res {
		n_long port;
	} *res;
	struct {
		n_long	h[RPC_HEADER_WORDS];
		struct args d;
	} sdata;
	struct {
		n_long	h[RPC_HEADER_WORDS];
		struct res d;
		n_long  pad;
	} rdata;
	ssize_t cc;
	int port;

#ifdef RPC_DEBUG
	if (debug)
		printf("getport: prog=0x%x vers=%d\n", prog, vers);
#endif

	/* This one is fixed forever. */
	if (prog == PMAPPROG)
		return (PMAPPORT);

	/* Try for cached answer first */
	port = rpc_pmap_getcache(d->destip, prog, vers);
	if (port != -1)
		return (port);

	args = &sdata.d;
	args->prog = htonl(prog);
	args->vers = htonl(vers);
	args->proto = htonl(IPPROTO_UDP);
	args->port = 0;
	res = &rdata.d;

	cc = rpc_call(d, PMAPPROG, PMAPVERS, PMAPPROC_GETPORT,
		args, sizeof(*args), res, sizeof(*res));
	if (cc < 0 || (size_t)cc < sizeof(*res)) {
		printf("getport: %s", strerror(errno));
		errno = EBADRPC;
		return (-1);
	}
	port = (int)ntohl(res->port);

	rpc_pmap_putcache(d->destip, prog, vers, port);

	return (port);
}


text:
#ifndef FPP_PPB_OPENGLES2_H
#define FPP_PPB_OPENGLES2_H

#include <GLES2/gl2.h>
#include <ppapi/c/ppb_opengles2.h>

void
ppb_opengles2_ActiveTexture(PP_Resource context, GLenum texture);

void
ppb_opengles2_AttachShader(PP_Resource context, GLuint program, GLuint shader);

void
ppb_opengles2_BindAttribLocation(PP_Resource context, GLuint program, GLuint index,
                                 const char *name);

void
ppb_opengles2_BindBuffer(PP_Resource context, GLenum target, GLuint buffer);

void
ppb_opengles2_BindFramebuffer(PP_Resource context, GLenum target, GLuint framebuffer);

void
ppb_opengles2_BindRenderbuffer(PP_Resource context, GLenum target, GLuint renderbuffer);

void
ppb_opengles2_BindTexture(PP_Resource context, GLenum target, GLuint texture);

void
ppb_opengles2_BlendColor(PP_Resource context, GLclampf red, GLclampf green, GLclampf blue,
                         GLclampf alpha);

void
ppb_opengles2_BlendEquation(PP_Resource context, GLenum mode);

void
ppb_opengles2_BlendEquationSeparate(PP_Resource context, GLenum modeRGB, GLenum modeAlpha);

void
ppb_opengles2_BlendFunc(PP_Resource context, GLenum sfactor, GLenum dfactor);

void
ppb_opengles2_BlendFuncSeparate(PP_Resource context, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha,
                                GLenum dstAlpha);

void
ppb_opengles2_BufferData(PP_Resource context, GLenum target, GLsizeiptr size, const void *data,
                         GLenum usage);

void
ppb_opengles2_BufferSubData(PP_Resource context, GLenum target, GLintptr offset, GLsizeiptr size,
                            const void *data);

GLenum
ppb_opengles2_CheckFramebufferStatus(PP_Resource context, GLenum target);

void
ppb_opengles2_Clear(PP_Resource context, GLbitfield mask);

void
ppb_opengles2_ClearColor(PP_Resource context, GLclampf red, GLclampf green, GLclampf blue,
                         GLclampf alpha);

void
ppb_opengles2_ClearDepthf(PP_Resource context, GLclampf depth);

void
ppb_opengles2_ClearStencil(PP_Resource context, GLint s);

void
ppb_opengles2_ColorMask(PP_Resource context, GLboolean red, GLboolean green, GLboolean blue,
                        GLboolean alpha);

void
ppb_opengles2_CompileShader(PP_Resource context, GLuint shader);

void
ppb_opengles2_CompressedTexImage2D(PP_Resource context, GLenum target, GLint level,
                                   GLenum internalformat, GLsizei width, GLsizei height,
                                   GLint border, GLsizei imageSize, const void *data);

void
ppb_opengles2_CompressedTexSubImage2D(PP_Resource context, GLenum target, GLint level,
                                      GLint xoffset, GLint yoffset, GLsizei width, GLsizei height,
                                      GLenum format, GLsizei imageSize, const void *data);

void
ppb_opengles2_CopyTexImage2D(PP_Resource context, GLenum target, GLint level, GLenum internalformat,
                             GLint x, GLint y, GLsizei width, GLsizei height, GLint border);

void
ppb_opengles2_CopyTexSubImage2D(PP_Resource context, GLenum target, GLint level, GLint xoffset,
                                GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);

GLuint
ppb_opengles2_CreateProgram(PP_Resource context);

GLuint
ppb_opengles2_CreateShader(PP_Resource context, GLenum type);

void
ppb_opengles2_CullFace(PP_Resource context, GLenum mode);

void
ppb_opengles2_DeleteBuffers(PP_Resource context, GLsizei n, const GLuint *buffers);

void
ppb_opengles2_DeleteFramebuffers(PP_Resource context, GLsizei n, const GLuint *framebuffers);

void
ppb_opengles2_DeleteProgram(PP_Resource context, GLuint program);

void
ppb_opengles2_DeleteRenderbuffers(PP_Resource context, GLsizei n, const GLuint *renderbuffers);

void
ppb_opengles2_DeleteShader(PP_Resource context, GLuint shader);

void
ppb_opengles2_DeleteTextures(PP_Resource context, GLsizei n, const GLuint *textures);

void
ppb_opengles2_DepthFunc(PP_Resource context, GLenum func);

void
ppb_opengles2_DepthMask(PP_Resource context, GLboolean flag);

void
ppb_opengles2_DepthRangef(PP_Resource context, GLclampf zNear, GLclampf zFar);

void
ppb_opengles2_DetachShader(PP_Resource context, GLuint program, GLuint shader);

void
ppb_opengles2_Disable(PP_Resource context, GLenum cap);

void
ppb_opengles2_DisableVertexAttribArray(PP_Resource context, GLuint index);

void
ppb_opengles2_DrawArrays(PP_Resource context, GLenum mode, GLint first, GLsizei count);

void
ppb_opengles2_DrawElements(PP_Resource context, GLenum mode, GLsizei count, GLenum type,
                           const void *indices);

void
ppb_opengles2_Enable(PP_Resource context, GLenum cap);

void
ppb_opengles2_EnableVertexAttribArray(PP_Resource context, GLuint index);

void
ppb_opengles2_Finish(PP_Resource context);

void
ppb_opengles2_Flush(PP_Resource context);

void
ppb_opengles2_FramebufferRenderbuffer(PP_Resource context, GLenum target, GLenum attachment,
                                      GLenum renderbuffertarget, GLuint renderbuffer);

void
ppb_opengles2_FramebufferTexture2D(PP_Resource context, GLenum target, GLenum attachment,
                                   GLenum textarget, GLuint texture, GLint level);

void
ppb_opengles2_FrontFace(PP_Resource context, GLenum mode);

void
ppb_opengles2_GenBuffers(PP_Resource context, GLsizei n, GLuint *buffers);

void
ppb_opengles2_GenerateMipmap(PP_Resource context, GLenum target);

void
ppb_opengles2_GenFramebuffers(PP_Resource context, GLsizei n, GLuint *framebuffers);

void
ppb_opengles2_GenRenderbuffers(PP_Resource context, GLsizei n, GLuint *renderbuffers);

void
ppb_opengles2_GenTextures(PP_Resource context, GLsizei n, GLuint *textures);

void
ppb_opengles2_GetActiveAttrib(PP_Resource context, GLuint program, GLuint index, GLsizei bufsize,
                              GLsizei *length, GLint *size, GLenum *type, char *name);

void
ppb_opengles2_GetActiveUniform(PP_Resource context, GLuint program, GLuint index, GLsizei bufsize,
                               GLsizei *length, GLint *size, GLenum *type, char *name);

void
ppb_opengles2_GetAttachedShaders(PP_Resource context, GLuint program, GLsizei maxcount,
                                 GLsizei *count, GLuint *shaders);

GLint
ppb_opengles2_GetAttribLocation(PP_Resource context, GLuint program, const char *name);

void
ppb_opengles2_GetBooleanv(PP_Resource context, GLenum pname, GLboolean *params);

void
ppb_opengles2_GetBufferParameteriv(PP_Resource context, GLenum target, GLenum pname, GLint *params);

GLenum
ppb_opengles2_GetError(PP_Resource context);

void
ppb_opengles2_GetFloatv(PP_Resource context, GLenum pname, GLfloat *params);

void
ppb_opengles2_GetFramebufferAttachmentParameteriv(PP_Resource context, GLenum target,
                                                  GLenum attachment, GLenum pname, GLint *params);

void
ppb_opengles2_GetIntegerv(PP_Resource context, GLenum pname, GLint *params);

void
ppb_opengles2_GetProgramiv(PP_Resource context, GLuint program, GLenum pname, GLint *params);

void
ppb_opengles2_GetProgramInfoLog(PP_Resource context, GLuint program, GLsizei bufsize,
                                GLsizei *length, char *infolog);

void
ppb_opengles2_GetRenderbufferParameteriv(PP_Resource context, GLenum target, GLenum pname,
                                         GLint *params);

void
ppb_opengles2_GetShaderiv(PP_Resource context, GLuint shader, GLenum pname, GLint *params);

void
ppb_opengles2_GetShaderInfoLog(PP_Resource context, GLuint shader, GLsizei bufsize, GLsizei *length,
                               char *infolog);

void
ppb_opengles2_GetShaderPrecisionFormat(PP_Resource context, GLenum shadertype, GLenum precisiontype,
                                       GLint *range, GLint *precision);

void
ppb_opengles2_GetShaderSource(PP_Resource context, GLuint shader, GLsizei bufsize, GLsizei *length,
                              char *source);

const GLubyte *
ppb_opengles2_GetString(PP_Resource context, GLenum name);

void
ppb_opengles2_GetTexParameterfv(PP_Resource context, GLenum target, GLenum pname, GLfloat *params);

void
ppb_opengles2_GetTexParameteriv(PP_Resource context, GLenum target, GLenum pname, GLint *params);

void
ppb_opengles2_GetUniformfv(PP_Resource context, GLuint program, GLint location, GLfloat *params);

void
ppb_opengles2_GetUniformiv(PP_Resource context, GLuint program, GLint location, GLint *params);

GLint
ppb_opengles2_GetUniformLocation(PP_Resource context, GLuint program, const char *name);

void
ppb_opengles2_GetVertexAttribfv(PP_Resource context, GLuint index, GLenum pname, GLfloat *params);

void
ppb_opengles2_GetVertexAttribiv(PP_Resource context, GLuint index, GLenum pname, GLint *params);

void
ppb_opengles2_GetVertexAttribPointerv(PP_Resource context, GLuint index, GLenum pname,
                                      void **pointer);

void
ppb_opengles2_Hint(PP_Resource context, GLenum target, GLenum mode);

GLboolean
ppb_opengles2_IsBuffer(PP_Resource context, GLuint buffer);

GLboolean
ppb_opengles2_IsEnabled(PP_Resource context, GLenum cap);

GLboolean
ppb_opengles2_IsFramebuffer(PP_Resource context, GLuint framebuffer);

GLboolean
ppb_opengles2_IsProgram(PP_Resource context, GLuint program);

GLboolean
ppb_opengles2_IsRenderbuffer(PP_Resource context, GLuint renderbuffer);

GLboolean
ppb_opengles2_IsShader(PP_Resource context, GLuint shader);

GLboolean
ppb_opengles2_IsTexture(PP_Resource context, GLuint texture);

void
ppb_opengles2_LineWidth(PP_Resource context, GLfloat width);

void
ppb_opengles2_LinkProgram(PP_Resource context, GLuint program);

void
ppb_opengles2_PixelStorei(PP_Resource context, GLenum pname, GLint param);

void
ppb_opengles2_PolygonOffset(PP_Resource context, GLfloat factor, GLfloat units);

void
ppb_opengles2_ReadPixels(PP_Resource context, GLint x, GLint y, GLsizei width, GLsizei height,
                         GLenum format, GLenum type, void *pixels);

void
ppb_opengles2_ReleaseShaderCompiler(PP_Resource context);

void
ppb_opengles2_RenderbufferStorage(PP_Resource context, GLenum target, GLenum internalformat,
                                  GLsizei width, GLsizei height);

void
ppb_opengles2_SampleCoverage(PP_Resource context, GLclampf value, GLboolean invert);

void
ppb_opengles2_Scissor(PP_Resource context, GLint x, GLint y, GLsizei width, GLsizei height);

void
ppb_opengles2_ShaderBinary(PP_Resource context, GLsizei n, const GLuint *shaders,
                           GLenum binaryformat, const void *binary, GLsizei length);

void
ppb_opengles2_ShaderSource(PP_Resource context, GLuint shader, GLsizei count, const char **str,
                           const GLint *length);

void
ppb_opengles2_StencilFunc(PP_Resource context, GLenum func, GLint ref, GLuint mask);

void
ppb_opengles2_StencilFuncSeparate(PP_Resource context, GLenum face, GLenum func, GLint ref,
                                  GLuint mask);

void
ppb_opengles2_StencilMask(PP_Resource context, GLuint mask);

void
ppb_opengles2_StencilMaskSeparate(PP_Resource context, GLenum face, GLuint mask);

void
ppb_opengles2_StencilOp(PP_Resource context, GLenum fail, GLenum zfail, GLenum zpass);

void
ppb_opengles2_StencilOpSeparate(PP_Resource context, GLenum face, GLenum fail, GLenum zfail,
                                GLenum zpass);

void
ppb_opengles2_TexImage2D(PP_Resource context, GLenum target, GLint level, GLint internalformat,
                         GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type,
                         const void *pixels);

void
ppb_opengles2_TexParameterf(PP_Resource context, GLenum target, GLenum pname, GLfloat param);

void
ppb_opengles2_TexParameterfv(PP_Resource context, GLenum target, GLenum pname,
                             const GLfloat *params);

void
ppb_opengles2_TexParameteri(PP_Resource context, GLenum target, GLenum pname, GLint param);

void
ppb_opengles2_TexParameteriv(PP_Resource context, GLenum target, GLenum pname, const GLint *params);

void
ppb_opengles2_TexSubImage2D(PP_Resource context, GLenum target, GLint level, GLint xoffset,
                            GLint yoffset, GLsizei width, GLsizei height, GLenum format,
                            GLenum type, const void *pixels);

void
ppb_opengles2_Uniform1f(PP_Resource context, GLint location, GLfloat x);

void
ppb_opengles2_Uniform1fv(PP_Resource context, GLint location, GLsizei count, const GLfloat *v);

void
ppb_opengles2_Uniform1i(PP_Resource context, GLint location, GLint x);

void
ppb_opengles2_Uniform1iv(PP_Resource context, GLint location, GLsizei count, const GLint *v);

void
ppb_opengles2_Uniform2f(PP_Resource context, GLint location, GLfloat x, GLfloat y);

void
ppb_opengles2_Uniform2fv(PP_Resource context, GLint location, GLsizei count, const GLfloat *v);

void
ppb_opengles2_Uniform2i(PP_Resource context, GLint location, GLint x, GLint y);

void
ppb_opengles2_Uniform2iv(PP_Resource context, GLint location, GLsizei count, const GLint *v);

void
ppb_opengles2_Uniform3f(PP_Resource context, GLint location, GLfloat x, GLfloat y, GLfloat z);

void
ppb_opengles2_Uniform3fv(PP_Resource context, GLint location, GLsizei count, const GLfloat *v);

void
ppb_opengles2_Uniform3i(PP_Resource context, GLint location, GLint x, GLint y, GLint z);

void
ppb_opengles2_Uniform3iv(PP_Resource context, GLint location, GLsizei count, const GLint *v);

void
ppb_opengles2_Uniform4f(PP_Resource context, GLint location, GLfloat x, GLfloat y, GLfloat z,
                        GLfloat w);

void
ppb_opengles2_Uniform4fv(PP_Resource context, GLint location, GLsizei count, const GLfloat *v);

void
ppb_opengles2_Uniform4i(PP_Resource context, GLint location, GLint x, GLint y, GLint z, GLint w);

void
ppb_opengles2_Uniform4iv(PP_Resource context, GLint location, GLsizei count, const GLint *v);

void
ppb_opengles2_UniformMatrix2fv(PP_Resource context, GLint location, GLsizei count,
                               GLboolean transpose, const GLfloat *value);

void
ppb_opengles2_UniformMatrix3fv(PP_Resource context, GLint location, GLsizei count,
                               GLboolean transpose, const GLfloat *value);

void
ppb_opengles2_UniformMatrix4fv(PP_Resource context, GLint location, GLsizei count,
                               GLboolean transpose, const GLfloat *value);

void
ppb_opengles2_UseProgram(PP_Resource context, GLuint program);

void
ppb_opengles2_ValidateProgram(PP_Resource context, GLuint program);

void
ppb_opengles2_VertexAttrib1f(PP_Resource context, GLuint indx, GLfloat x);

void
ppb_opengles2_VertexAttrib1fv(PP_Resource context, GLuint indx, const GLfloat *values);

void
ppb_opengles2_VertexAttrib2f(PP_Resource context, GLuint indx, GLfloat x, GLfloat y);

void
ppb_opengles2_VertexAttrib2fv(PP_Resource context, GLuint indx, const GLfloat *values);

void
ppb_opengles2_VertexAttrib3f(PP_Resource context, GLuint indx, GLfloat x, GLfloat y, GLfloat z);

void
ppb_opengles2_VertexAttrib3fv(PP_Resource context, GLuint indx, const GLfloat *values);

void
ppb_opengles2_VertexAttrib4f(PP_Resource context, GLuint indx, GLfloat x, GLfloat y, GLfloat z,
                             GLfloat w);

void
ppb_opengles2_VertexAttrib4fv(PP_Resource context, GLuint indx, const GLfloat *values);

void
ppb_opengles2_VertexAttribPointer(PP_Resource context, GLuint indx, GLint size, GLenum type,
                                  GLboolean normalized, GLsizei stride, const void *ptr);

void
ppb_opengles2_Viewport(PP_Resource context, GLint x, GLint y, GLsizei width, GLsizei height);

GLboolean
ppb_opengles2_chromium_enable_feature_enable_feature_chromium(PP_Resource context,
                                                              const char *feature);

void *
ppb_opengles2_chromium_map_sub_map_buffer_sub_data_chromium(PP_Resource context, GLuint target,
                                                            GLintptr offset, GLsizeiptr size,
                                                            GLenum access);

void
ppb_opengles2_chromium_map_sub_unmap_buffer_sub_data_chromium(PP_Resource context, const void *mem);

void *
ppb_opengles2_chromium_map_sub_map_tex_sub_image_2d_chromium(PP_Resource context, GLenum target,
                                                             GLint level, GLint xoffset,
                                                             GLint yoffset, GLsizei width,
                                                             GLsizei height, GLenum format,
                                                             GLenum type, GLenum access);

void
ppb_opengles2_chromium_map_sub_unmap_tex_sub_image_2d_chromium(PP_Resource context,
                                                               const void *mem);

void
ppb_opengles2_framebuffer_blit_blit_framebuffer_ext(PP_Resource context, GLint srcX0, GLint srcY0,
                                                    GLint srcX1, GLint srcY1, GLint dstX0,
                                                    GLint dstY0, GLint dstX1, GLint dstY1,
                                                    GLbitfield mask, GLenum filter);

void
ppb_opengles2_framebuffer_multisample_renderbuffer_storage_multisample_ext
                    (PP_Resource context, GLenum target, GLsizei samples, GLenum internalformat,
                     GLsizei width, GLsizei height);

void
ppb_opengles2_instanced_arrays_draw_arrays_instanced_angle(PP_Resource context, GLenum mode,
                                                           GLint first, GLsizei count,
                                                           GLsizei primcount);

void
ppb_opengles2_instanced_arrays_draw_elements_instanced_angle(PP_Resource context, GLenum mode,
                                                             GLsizei count, GLenum type,
                                                             const void *indices,GLsizei primcount);

void
ppb_opengles2_instanced_arrays_vertex_attrib_divisor_angle(PP_Resource context, GLuint index,
                                                           GLuint divisor);

void
ppb_opengles2_query_gen_queries_ext(PP_Resource context, GLsizei n, GLuint *queries);

void
ppb_opengles2_query_delete_queries_ext(PP_Resource context, GLsizei n, const GLuint *queries);

GLboolean
ppb_opengles2_query_is_query_ext(PP_Resource context, GLuint id);

void
ppb_opengles2_query_begin_query_ext(PP_Resource context, GLenum target, GLuint id);

void
ppb_opengles2_query_end_query_ext(PP_Resource context, GLenum target);

void
ppb_opengles2_query_get_queryiv_ext(PP_Resource context, GLenum target, GLenum pname,GLint *params);

void
ppb_opengles2_query_get_query_objectuiv_ext(PP_Resource context, GLuint id, GLenum pname,
                                            GLuint *params);

#endif // FPP_PPB_OPENGLES2_H


text:
package ubic.gemma.model.expression.bioAssayData;

import ubic.gemma.model.common.quantitationtype.PrimitiveType;

/**
 * This is used to represent missing value data.
 *
 * @author paul
 *
 */
public class BooleanVectorValueObject extends DataVectorValueObject {
    private static final long serialVersionUID = 1L;
    private boolean[] data;

    public BooleanVectorValueObject( DesignElementDataVector dedv, BioAssayDimensionValueObject badvo ) {
        super( dedv, badvo );
        if ( !dedv.getQuantitationType().getRepresentation().equals( PrimitiveType.BOOLEAN ) ) {
            throw new IllegalArgumentException( "Can only store boolean vectors, got " + dedv.getQuantitationType() );
        }

        this.data = byteArrayConverter.byteArrayToBooleans( dedv.getData() );
    }

    public boolean[] getData() {
        return data;
    }
}


text:
/**
 * Created by nehas on 7/8/2017.
 */
(function (angular) {
    'use strict';

    angular
        .module('mllApp.feedback')
        .directive('feedbackList', feedbackList);

    function feedbackList() {
        return {
            restrict: 'AE',
            replace: true,
            scope: {},
            controller: 'AdminFeedbackController',
            controllerAs: 'ctrl',
            templateUrl: 'feedback-admin-listing.template.html',
            bindToController: {
                userId: '='
            }
        };
    }
})(window.angular);


text:
    <title>My Form</title>

Your form was successfully submitted!

<?php echo anchor('/helpers/validation', 'Try it again!'); ?>


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="stylesheet" href="css/normalize.css">
        <link rel="stylesheet" href="css/bootstrap.min.css">

              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

              </button>
              ICE

About

Hello, Grunt-init ICE

           <canvas id='cv' width='600' height='200'></canvas>
           <input type="button" id="clear" value="Clear">


text:
// Ponyfill
import 'es6-object-assign/auto'
import 'es6-promise/auto'
// Import Vue
import Vue from 'vue'
import VueResource from 'vue-resource'
// Import F7, F7-Vue
import 'framework7'
import Framework7Vue from 'framework7-vue'
// Import F7 iOS Theme Styles
import 'framework7/dist/css/framework7.ios.min.css'
import 'framework7/dist/css/framework7.ios.colors.min.css'
/* OR for Material Theme:
 import Framework7Theme from 'framework7/dist/css/framework7.material.min.css'
 import Framework7ThemeColors from 'framework7/dist/css/framework7.material.colors.min.css'
 */
// Import App Custom Styles
import './assets/styles/framework7-icons.css'
import './assets/fonts/iconfont.css'
import './assets/styles/app.less'
// Import Routes
import Routes from './routes'
// Import App Component
import App from './app'
// Import Vuex store
import store from './store'
// Import language file
import VueI18n from 'vue-i18n'
import StoreCache from './utils/storeCache'
import enUS from './lang/en_us'
import az from './lang/az'
// Laravel Echo
// Carousel framework
import VueCarousel from 'vue-carousel'

// Init Vue Plugin
Vue.use(Framework7Vue)
Vue.use(VueResource)
Vue.use(VueCarousel)

// Vue.http.options.root = 'http://localhost:8000'
Vue.http.options.root = 'http://188.226.148.17'
Vue.http.headers.common['Authorization'] = 'Bearer ' + localStorage.getItem('token')
Vue.http.options.emulateJSON = true

Vue.http.interceptors.push((request, next) => {
  request.headers.set('Authorization', 'Bearer ' + localStorage.getItem('token'))
  request.headers.set('Accept', 'application/json')
  next(function (response) {
    // modify response
    if (response.status === 401) {
      console.log('you have to login to post!!')
      // if expired token exists
      store.dispatch('destroyToken')
    }
    if (response.body.error) {
      window.f7.alert(response.body.message)
    }
  })
})

let cache = new StoreCache('vuex')
Vue.use(VueI18n)
Vue.config.lang = cache.get('lang') || 'en'
Vue.locale('en', enUS)
Vue.locale('az', az)

const EventBus = new Vue()

Object.defineProperties(Vue.prototype, {
  $bus: {
    get: function () {
      return EventBus
    }
  }
})

// Init App
new Vue({
  el: '#app',
  store,
  template: '<app/>',
  // Init Framework7 by passing parameters here
  framework7: {
    root: '#app',
    modalTitle: Vue.t('app.modal.title'),
    modalButtonOk: Vue.t('app.modal.button_ok'),
    modalButtonCancel: Vue.t('app.cancel'),
    smartSelectOpenIn: 'page',
    /* Uncomment to enable Material theme: */
    // material: true,
    routes: Routes
  },
  // Register App Component
  components: {
    app: App
  }
})