text:
package org.apache.accumulo.core.client.impl;

import static com.google.common.base.Preconditions.checkArgument;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;

import org.apache.accumulo.core.client.AccumuloException;
import org.apache.accumulo.core.client.AccumuloSecurityException;
import org.apache.accumulo.core.client.Instance;
import org.apache.accumulo.core.client.TableNotFoundException;
import org.apache.accumulo.core.data.Mutation;
import org.apache.accumulo.core.data.Range;
import org.apache.accumulo.core.data.impl.KeyExtent;
import org.apache.accumulo.core.metadata.MetadataLocationObtainer;
import org.apache.accumulo.core.metadata.MetadataTable;
import org.apache.accumulo.core.metadata.RootTable;
import org.apache.hadoop.io.Text;

public abstract class TabletLocator {

  /**
   * Flipped false on call to {@link #clearLocators}. Checked by client classes that locally cache Locators.
   */
  private volatile boolean isValid = true;

  boolean isValid() {
    return isValid;
  }

  public abstract TabletLocation locateTablet(ClientContext context, Text row, boolean skipRow, boolean retry) throws AccumuloException,
      AccumuloSecurityException, TableNotFoundException;

  public abstract <T extends Mutation> void binMutations(ClientContext context, List<T> mutations, Map<String,TabletServerMutations<T>> binnedMutations,
      List<T> failures) throws AccumuloException, AccumuloSecurityException, TableNotFoundException;

  public abstract List<Range> binRanges(ClientContext context, List<Range> ranges, Map<String,Map<KeyExtent,List<Range>>> binnedRanges)
      throws AccumuloException, AccumuloSecurityException, TableNotFoundException;

  public abstract void invalidateCache(KeyExtent failedExtent);

  public abstract void invalidateCache(Collection<KeyExtent> keySet);

  /**
   * Invalidate entire cache
   */
  public abstract void invalidateCache();

  /**
   * Invalidate all metadata entries that point to server
   */
  public abstract void invalidateCache(Instance instance, String server);

  private static class LocatorKey {
    String instanceId;
    String tableName;

    LocatorKey(String instanceId, String table) {
      this.instanceId = instanceId;
      this.tableName = table;
    }

    @Override
    public int hashCode() {
      return instanceId.hashCode() + tableName.hashCode();
    }

    @Override
    public boolean equals(Object o) {
      if (o instanceof LocatorKey)
        return equals((LocatorKey) o);
      return false;
    }

    public boolean equals(LocatorKey lk) {
      return instanceId.equals(lk.instanceId) && tableName.equals(lk.tableName);
    }

  }

  private static HashMap<LocatorKey,TabletLocator> locators = new HashMap<LocatorKey,TabletLocator>();

  public static synchronized void clearLocators() {
    for (TabletLocator locator : locators.values()) {
      locator.isValid = false;
    }
    locators.clear();
  }

  public static synchronized TabletLocator getLocator(ClientContext context, String tableId) {
    Instance instance = context.getInstance();
    LocatorKey key = new LocatorKey(instance.getInstanceID(), tableId);
    TabletLocator tl = locators.get(key);
    if (tl == null) {
      MetadataLocationObtainer mlo = new MetadataLocationObtainer();

      if (RootTable.ID.equals(tableId)) {
        tl = new RootTabletLocator(new ZookeeperLockChecker(instance));
      } else if (MetadataTable.ID.equals(tableId)) {
        tl = new TabletLocatorImpl(MetadataTable.ID, getLocator(context, RootTable.ID), mlo, new ZookeeperLockChecker(instance));
      } else {
        tl = new TabletLocatorImpl(tableId, getLocator(context, MetadataTable.ID), mlo, new ZookeeperLockChecker(instance));
      }
      locators.put(key, tl);
    }

    return tl;
  }

  public static class TabletLocations {

    private final List<TabletLocation> locations;
    private final List<KeyExtent> locationless;

    public TabletLocations(List<TabletLocation> locations, List<KeyExtent> locationless) {
      this.locations = locations;
      this.locationless = locationless;
    }

    public List<TabletLocation> getLocations() {
      return locations;
    }

    public List<KeyExtent> getLocationless() {
      return locationless;
    }
  }

  public static class TabletLocation implements Comparable<TabletLocation> {
    private static final WeakHashMap<String,WeakReference<String>> tabletLocs = new WeakHashMap<String,WeakReference<String>>();

    private static String dedupeLocation(String tabletLoc) {
      synchronized (tabletLocs) {
        WeakReference<String> lref = tabletLocs.get(tabletLoc);
        if (lref != null) {
          String loc = lref.get();
          if (loc != null) {
            return loc;
          }
        }

        tabletLocs.put(tabletLoc, new WeakReference<String>(tabletLoc));
        return tabletLoc;
      }
    }

    public final KeyExtent tablet_extent;
    public final String tablet_location;
    public final String tablet_session;

    public TabletLocation(KeyExtent tablet_extent, String tablet_location, String session) {
      checkArgument(tablet_extent != null, "tablet_extent is null");
      checkArgument(tablet_location != null, "tablet_location is null");
      checkArgument(session != null, "session is null");
      this.tablet_extent = tablet_extent;
      this.tablet_location = dedupeLocation(tablet_location);
      this.tablet_session = dedupeLocation(session);
    }

    @Override
    public boolean equals(Object o) {
      if (o instanceof TabletLocation) {
        TabletLocation otl = (TabletLocation) o;
        return tablet_extent.equals(otl.tablet_extent) && tablet_location.equals(otl.tablet_location) && tablet_session.equals(otl.tablet_session);
      }
      return false;
    }

    @Override
    public int hashCode() {
      throw new UnsupportedOperationException("hashcode is not implemented for class " + this.getClass().toString());
    }

    @Override
    public String toString() {
      return "(" + tablet_extent + "," + tablet_location + "," + tablet_session + ")";
    }

    @Override
    public int compareTo(TabletLocation o) {
      int result = tablet_extent.compareTo(o.tablet_extent);
      if (result == 0) {
        result = tablet_location.compareTo(o.tablet_location);
        if (result == 0)
          result = tablet_session.compareTo(o.tablet_session);
      }
      return result;
    }
  }

  public static class TabletServerMutations<T extends Mutation> {
    private Map<KeyExtent,List<T>> mutations;
    private String tserverSession;

    public TabletServerMutations(String tserverSession) {
      this.tserverSession = tserverSession;
      this.mutations = new HashMap<KeyExtent,List<T>>();
    }

    public void addMutation(KeyExtent ke, T m) {
      List<T> mutList = mutations.get(ke);
      if (mutList == null) {
        mutList = new ArrayList<T>();
        mutations.put(ke, mutList);
      }

      mutList.add(m);
    }

    public Map<KeyExtent,List<T>> getMutations() {
      return mutations;
    }

    final String getSession() {
      return tserverSession;
    }
  }
}


text:
package com.bmc.preset;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

import com.baidubce.services.media.model.GetPresetResponse;
import com.bmc.R;
import com.bmc.setting.CurrentConf;

public class PresetDetailActivity extends Activity
        implements OnPresetFragmentInteractionListener {

    private GetPresetResponse preset;

    private boolean editable = false;

    public static void start(Context context, String presetName) {
        Intent intent = new Intent(context, PresetDetailActivity.class);
        intent.putExtra("presetName", presetName);
        context.startActivity(intent);
    }

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

        Intent intent = getIntent();
        String presetName = intent.getStringExtra("presetName");
        editable = intent.getBooleanExtra("editable", false);

        if (presetName == null) {
            preset = new GetPresetResponse();
        } else {
            preset = CurrentConf.getMediaClient().getPreset(presetName);
            if (editable && presetName.startsWith("bce.")) {
                // user copy system preset, remove system prefix
                preset.setPresetName(presetName.substring(4));
            }
        }

        setContentView(R.layout.activity_preset_detail);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_preset_detail, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public GetPresetResponse getPreset() {
        return preset;
    }

    @Override
    public Boolean editable() {
        return editable;
    }
}

redpajama_set_name: RedPajamaGithub


text:
import { Command } from 'substance'

class IncreaseHeadingLevelCommand extends Command {

  getCommandState(params) {
    let doc = params.editorSession.getDocument()
    let sel = params.selection
    let isBlurred = params.editorSession.isBlurred()

    let commandState = {
      disabled: false
    }

    if (sel.isPropertySelection() && !isBlurred) {
      let path = sel.getPath()
      let node = doc.get(path[0])
      if (node
        && node.isBlock()
        && node.type === 'heading') {
        commandState.active = true
      } else {
        commandState.disabled = true
      }
    } else {
      commandState.disabled = true
    }

    return commandState
  }

  execute(params) {
    let sel = params.selection
    let editorSession = params.editorSession
    let doc = editorSession.getDocument()
    let path = sel.getPath()
    let node = doc.get(path[0])
    if(node.getAttribute('level') < 3) {
      editorSession.transaction((txDoc) => {
        let node = txDoc.get(path[0])
        node.setAttribute('level', String(parseInt(node.level, 10) + 1))
      })
    }
  }
}

export default IncreaseHeadingLevelCommand


text:
/*global
    msos: false,
    jQuery: false,
    jquery: false
*/

// Adapted for use thru MobileSiteOS. This works without worrying about load order because
// 'jquery.ui.js' includes ui core, widget, mouse, position, draggable, effect.core already bundled.

msos.provide("jquery.ui.touch");

jquery.ui.touch.version = new msos.set_version(15, 12, 15);

(function ($) {

    "use strict";

    if (!msos.config.browser.touch) {
        msos.console.warn('jquery.ui.touch -> browser does not support touch!');
        return;
    }

    var temp_utv = 'jquery.ui.touch',
        mouseProto = $.ui.mouse.prototype,
        _mouseInit = mouseProto._mouseInit,
		_mouseDestroy = mouseProto._mouseDestroy,
        dbug_txt = '',
        touchHandled;

    function simulateMouseEvent(event, simulatedType) {

        // Ignore multi-touch events
        if (event.originalEvent.touches.length > 1) {
            return;
        }

        msos.do_nothing(event);

        if (msos.debug) {
			dbug_txt = msos.debug.event_text(event, temp_utv + ' - simulateMouseEvent -> called, type: ' + simulatedType);
            msos.debug.event(event, dbug_txt);
        }

        var touch = event.originalEvent.changedTouches[0],
            simulatedEvent = document.createEvent('MouseEvents');

        // Initialize the simulated mouse event using the touch event's coordinates
        simulatedEvent.initMouseEvent(
            simulatedType, // type
            true, // bubbles
            true, // cancelable
            window, // view
            1, // detail
            touch.screenX, // screenX
            touch.screenY, // screenY
            touch.clientX, // clientX
            touch.clientY, // clientY
            false, // ctrlKey
            false, // altKey
            false, // shiftKey
            false, // metaKey
            0, // button
            null // relatedTarget
        );

        // Dispatch the simulated event to the target element
        event.target.dispatchEvent(simulatedEvent);
    }

    mouseProto._touchStart = function (event) {

        var self = this;

        // Ignore the event if another widget is already being handled
        if (touchHandled || !self._mouseCapture(event.originalEvent.changedTouches[0])) {
            return;
        }

        // Set the flag to prevent other widgets from inheriting the touch event
        touchHandled = true;

        // Track movement to determine if interaction was a click
        self._touchMoved = false;

        // Simulate the mouseover event
        simulateMouseEvent(event, 'mouseover');

        // Simulate the mousemove event
        simulateMouseEvent(event, 'mousemove');

        // Simulate the mousedown event
        simulateMouseEvent(event, 'mousedown');
    };

    mouseProto._touchMove = function (event) {

        // Ignore event if not handled
        if (!touchHandled) {
            return;
        }

        // Interaction was not a click
        this._touchMoved = true;

        // Simulate the mousemove event
        simulateMouseEvent(event, 'mousemove');
    };

    mouseProto._touchEnd = function (event) {

        // Ignore event if not handled
        if (!touchHandled) {
            return;
        }

        // Simulate the mouseup event
        simulateMouseEvent(event, 'mouseup');

        // Simulate the mouseout event
        simulateMouseEvent(event, 'mouseout');

        // If the touch interaction did not move, it should trigger a click
        if (!this._touchMoved) {

            // Simulate the click event
            simulateMouseEvent(event, 'click');
        }

        // Unset the flag to allow other widgets to inherit the touch event
        touchHandled = false;
    };

    mouseProto._mouseInit = function () {

        var self = this;

		// Delegate the touch handlers to the widget's element
		self.element.bind({
			touchstart: $.proxy(self, '_touchStart'),
			touchmove: $.proxy(self, '_touchMove'),
			touchend: $.proxy(self, '_touchEnd')
		});

        // Call the original $.ui.mouse init method
        _mouseInit.call(self);
    };

	mouseProto._mouseDestroy = function () {

		var self = this;

		// Delegate the touch handlers to the widget's element
		self.element.unbind({
			touchstart: $.proxy(self, '_touchStart'),
			touchmove: $.proxy(self, '_touchMove'),
			touchend: $.proxy(self, '_touchEnd')
		});

		// Call the original $.ui.mouse destroy method
		_mouseDestroy.call(self);
	};

}(jQuery));


text:
package gossip

import (
	"fmt"
	"math"
	"reflect"
	"sort"
	"sync"
	"testing"
	"time"

	"github.com/cockroachdb/cockroach/roachpb"
	"github.com/cockroachdb/cockroach/util"
	"github.com/cockroachdb/cockroach/util/leaktest"
	"github.com/gogo/protobuf/proto"
)

var emptyAddr = util.MakeUnresolvedAddr("test", "<test-addr>")

// TestZeroDuration verifies that specifying a zero duration sets
// TTLStamp to max int64.
func TestZeroDuration(t *testing.T) {
	defer leaktest.AfterTest(t)
	is := newInfoStore(1, emptyAddr)
	info := is.newInfo(nil, 0)
	if info.TTLStamp != math.MaxInt64 {
		t.Errorf("expected zero duration to get max TTLStamp: %d", info.TTLStamp)
	}
}

// TestNewInfo creates new info objects. Verify sequence increments.
func TestNewInfo(t *testing.T) {
	defer leaktest.AfterTest(t)
	is := newInfoStore(1, emptyAddr)
	info1 := is.newInfo(nil, time.Second)
	info2 := is.newInfo(nil, time.Second)
	if info1.seq != info2.seq-1 {
		t.Errorf("sequence numbers should increment %d, %d", info1.seq, info2.seq)
	}
}

// TestInfoStoreGetInfo adds an info, and makes sure it can be fetched
// via getInfo. Also, verifies a non-existent info can't be fetched.
func TestInfoStoreGetInfo(t *testing.T) {
	defer leaktest.AfterTest(t)
	is := newInfoStore(1, emptyAddr)
	i := is.newInfo(nil, time.Second)
	if err := is.addInfo("a", i); err != nil {
		t.Error(err)
	}
	if infoCount := len(is.Infos); infoCount != 1 {
		t.Errorf("infostore count incorrect %d != 1", infoCount)
	}
	if is.MaxSeq != i.seq {
		t.Error("max seq value wasn't updated")
	}
	if is.getInfo("a") != i {
		t.Error("unable to get info")
	}
	if is.getInfo("b") != nil {
		t.Error("erroneously produced non-existent info for key b")
	}
}

// Verify TTL is respected on info fetched by key.
func TestInfoStoreGetInfoTTL(t *testing.T) {
	defer leaktest.AfterTest(t)
	is := newInfoStore(1, emptyAddr)
	i := is.newInfo(nil, time.Nanosecond)
	if err := is.addInfo("a", i); err != nil {
		t.Error(err)
	}
	time.Sleep(time.Nanosecond)
	if is.getInfo("a") != nil {
		t.Error("shouldn't be able to get info with short TTL")
	}
}

// Add infos using same key, same and lesser timestamp; verify no
// replacement.
func TestAddInfoSameKeyLessThanEqualTimestamp(t *testing.T) {
	defer leaktest.AfterTest(t)
	is := newInfoStore(1, emptyAddr)
	info1 := is.newInfo(nil, time.Second)
	if err := is.addInfo("a", info1); err != nil {
		t.Error(err)
	}
	info2 := is.newInfo(nil, time.Second)
	info2.Value.Timestamp.WallTime = info1.Value.Timestamp.WallTime
	if err := is.addInfo("a", info2); err == nil {
		t.Error("able to add info2 with same timestamp")
	}
	info2.Value.Timestamp.WallTime--
	if err := is.addInfo("a", info2); err == nil {
		t.Error("able to add info2 with lesser timestamp")
	}
	// Verify info2 did not replace info1.
	if is.getInfo("a") != info1 {
		t.Error("info1 was replaced, despite same timestamp")
	}
}

// Add infos using same key, same timestamp; verify no replacement.
func TestAddInfoSameKeyGreaterTimestamp(t *testing.T) {
	defer leaktest.AfterTest(t)
	is := newInfoStore(1, emptyAddr)
	info1 := is.newInfo(nil, time.Second)
	info2 := is.newInfo(nil, time.Second)
	if err1, err2 := is.addInfo("a", info1), is.addInfo("a", info2); err1 != nil || err2 != nil {
		t.Error(err1, err2)
	}
}

// Verify that adding two infos with different hops but same keys
// always chooses the minimum hops.
func TestAddInfoSameKeyDifferentHops(t *testing.T) {
	defer leaktest.AfterTest(t)
	is := newInfoStore(1, emptyAddr)
	info1 := is.newInfo(nil, time.Second)
	info1.Hops = 1
	info2 := is.newInfo(nil, time.Second)
	info2.Value.Timestamp.WallTime = info1.Value.Timestamp.WallTime
	info2.Hops = 2
	if err := is.addInfo("a", info1); err != nil {
		t.Errorf("failed insert: %s", err)
	}
	if err := is.addInfo("a", info2); err == nil {
		t.Errorf("shouldn't have inserted info 2: %s", err)
	}

	i := is.getInfo("a")
	if i.Hops != info1.Hops || !proto.Equal(i, info1) {
		t.Error("failed to properly combine hops and value", i)
	}

	// Try yet another info, with lower hops yet (0).
	info3 := is.newInfo(nil, time.Second)
	if err := is.addInfo("a", info3); err != nil {
		t.Error(err)
	}
	i = is.getInfo("a")
	if i.Hops != info3.Hops || !proto.Equal(i, info3) {
		t.Error("failed to properly combine hops and value", i)
	}
}

// Helper method creates an infostore with 10 infos.
func createTestInfoStore(t *testing.T) infoStore {
	is := newInfoStore(1, emptyAddr)

	for i := 0; i < 10; i++ {
		infoA := is.newInfo(nil, time.Second)
		if err := is.addInfo(fmt.Sprintf("a.%d", i), infoA); err != nil {
			t.Fatal(err)
		}

		infoB := is.newInfo(nil, time.Second)
		if err := is.addInfo(fmt.Sprintf("b.%d", i), infoB); err != nil {
			t.Fatal(err)
		}

		infoC := is.newInfo(nil, time.Second)
		if err := is.addInfo(fmt.Sprintf("c.%d", i), infoC); err != nil {
			t.Fatal(err)
		}
	}

	return is
}

// Check infostore delta based on info sequence numbers.
func TestInfoStoreDelta(t *testing.T) {
	defer leaktest.AfterTest(t)
	is := createTestInfoStore(t)

	// Verify deltas with successive sequence numbers.
	for i := 0; i < 10; i++ {
		infos := is.delta(2, int64(i*3))

		for j := 0; j < 10-i; j++ {
			if _, ok := infos[fmt.Sprintf("c.%d", j+i)]; !ok {
				t.Errorf("unable to fetch info %d", j+i)
			}
			if i > 0 {
				if _, ok := infos[fmt.Sprintf("c.%d", 0)]; ok {
					t.Errorf("erroneously fetched info %d", j+i+1)
				}
			}
		}
	}

	if infos := is.delta(2, int64(30)); len(infos) != 0 {
		t.Error("fetching delta of infostore at maximum sequence number should return nil")
	}
}

// TestInfoStoreDistant verifies selection of infos from store with
// Hops > maxHops.
func TestInfoStoreDistant(t *testing.T) {
	defer leaktest.AfterTest(t)
	nodes := []roachpb.NodeID{
		roachpb.NodeID(1),
		roachpb.NodeID(2),
		roachpb.NodeID(3),
	}
	is := newInfoStore(1, emptyAddr)
	// Add info from each address, with hop count equal to index+1.
	for i := 0; i < len(nodes); i++ {
		inf := is.newInfo(nil, time.Second)
		inf.Hops = uint32(i + 1)
		inf.NodeID = nodes[i]
		if err := is.addInfo(fmt.Sprintf("b.%d", i), inf); err != nil {
			t.Fatal(err)
		}
	}

	for i := 0; i < len(nodes); i++ {
		nodesLen := is.distant(uint32(i)).len()
		if nodesLen != 3-i {
			t.Errorf("%d nodes (not %d) should be over maxHops = %d", 3-i, nodesLen, i)
		}
	}
}

// TestLeastUseful verifies that the least-contributing peer node
// can be determined.
func TestLeastUseful(t *testing.T) {
	defer leaktest.AfterTest(t)
	nodes := []roachpb.NodeID{
		roachpb.NodeID(1),
		roachpb.NodeID(2),
	}
	is := newInfoStore(1, emptyAddr)

	set := makeNodeSet(3)
	if is.leastUseful(set) != 0 {
		t.Error("not expecting a node from an empty set")
	}

	inf1 := is.newInfo(nil, time.Second)
	inf1.peerID = 1
	if err := is.addInfo("a1", inf1); err != nil {
		t.Fatal(err)
	}
	if is.leastUseful(set) != 0 {
		t.Error("not expecting a node from an empty set")
	}

	set.addNode(nodes[0])
	if is.leastUseful(set) != nodes[0] {
		t.Error("expecting nodes[0] as least useful")
	}

	inf2 := is.newInfo(nil, time.Second)
	inf2.peerID = 1
	if err := is.addInfo("a2", inf2); err != nil {
		t.Fatal(err)
	}
	if is.leastUseful(set) != nodes[0] {
		t.Error("expecting nodes[0] as least useful")
	}

	set.addNode(nodes[1])
	if is.leastUseful(set) != nodes[1] {
		t.Error("expecting nodes[1] as least useful")
	}

	inf3 := is.newInfo(nil, time.Second)
	inf3.peerID = 2
	if err := is.addInfo("a3", inf3); err != nil {
		t.Fatal(err)
	}
	if is.leastUseful(set) != nodes[1] {
		t.Error("expecting nodes[1] as least useful")
	}
}

type callbackRecord struct {
	keys []string
	wg   *sync.WaitGroup
	sync.Mutex
}

func (cr *callbackRecord) Add(key string, _ []byte) {
	cr.Lock()
	defer cr.Unlock()
	cr.keys = append(cr.keys, key)
	cr.wg.Done()
}

func (cr *callbackRecord) Keys() []string {
	cr.Lock()
	defer cr.Unlock()
	return append([]string(nil), cr.keys...)
}

func TestCallbacks(t *testing.T) {
	defer leaktest.AfterTest(t)
	is := newInfoStore(1, emptyAddr)
	wg := &sync.WaitGroup{}
	cb1 := callbackRecord{wg: wg}
	cb2 := callbackRecord{wg: wg}
	cbAll := callbackRecord{wg: wg}

	is.registerCallback("key1", cb1.Add)
	is.registerCallback("key2", cb2.Add)
	is.registerCallback("key.*", cbAll.Add)

	i1 := is.newInfo(nil, time.Second)
	i2 := is.newInfo(nil, time.Second)
	i3 := is.newInfo(nil, time.Second)

	// Add infos twice and verify callbacks aren't called for same timestamps.
	wg.Add(5)
	for i := 0; i < 2; i++ {
		if err := is.addInfo("key1", i1); err != nil {
			if i == 0 {
				t.Error(err)
			}
		} else {
			if i != 0 {
				t.Errorf("expected error on run #%d, but didn't get one", i)
			}
		}
		if err := is.addInfo("key2", i2); err != nil {
			if i == 0 {
				t.Error(err)
			}
		} else {
			if i != 0 {
				t.Errorf("expected error on run #%d, but didn't get one", i)
			}
		}
		if err := is.addInfo("key3", i3); err != nil {
			if i == 0 {
				t.Error(err)
			}
		} else {
			if i != 0 {
				t.Errorf("expected error on run #%d, but didn't get one", i)
			}
		}
		wg.Wait()

		if expKeys := []string{"key1"}; !reflect.DeepEqual(cb1.Keys(), expKeys) {
			t.Errorf("expected %v, got %v", expKeys, cb1.Keys())
		}
		if expKeys := []string{"key2"}; !reflect.DeepEqual(cb2.Keys(), expKeys) {
			t.Errorf("expected %v, got %v", expKeys, cb2.Keys())
		}
		keys := cbAll.Keys()
		sort.Strings(keys)
		if expKeys := []string{"key1", "key2", "key3"}; !reflect.DeepEqual(keys, expKeys) {
			t.Errorf("expected %v, got %v", expKeys, keys)
		}
	}

	// Update an info.
	{
		i1 := is.newInfo([]byte("a"), time.Second)
		wg.Add(2)
		if err := is.addInfo("key1", i1); err != nil {
			t.Error(err)
		}
		wg.Wait()

		if expKeys := []string{"key1", "key1"}; !reflect.DeepEqual(cb1.Keys(), expKeys) {
			t.Errorf("expected %v, got %v", expKeys, cb1.Keys())
		}
		if expKeys := []string{"key2"}; !reflect.DeepEqual(cb2.Keys(), expKeys) {
			t.Errorf("expected %v, got %v", expKeys, cb2.Keys())
		}
		keys := cbAll.Keys()
		sort.Strings(keys)
		if expKeys := []string{"key1", "key1", "key2", "key3"}; !reflect.DeepEqual(keys, expKeys) {
			t.Errorf("expected %v, got %v", expKeys, keys)
		}
	}

	// Register another callback with same pattern and verify it is
	// invoked for all three keys.
	wg.Add(3)
	is.registerCallback("key.*", cbAll.Add)
	wg.Wait()

	expKeys := []string{"key1", "key2", "key3", "key1", "key1", "key2", "key3"}
	sort.Strings(expKeys)
	keys := cbAll.Keys()
	sort.Strings(keys)
	if !reflect.DeepEqual(keys, expKeys) {
		t.Errorf("expected %v, got %v", expKeys, keys)
	}
}

// TestRegisterCallback verifies that a callback is invoked when
// registered if there are items which match its regexp in the
// infostore.
func TestRegisterCallback(t *testing.T) {
	defer leaktest.AfterTest(t)
	is := newInfoStore(1, emptyAddr)
	wg := &sync.WaitGroup{}
	cb := callbackRecord{wg: wg}

	i1 := is.newInfo(nil, time.Second)
	i2 := is.newInfo(nil, time.Second)
	if err := is.addInfo("key1", i1); err != nil {
		t.Fatal(err)
	}
	if err := is.addInfo("key2", i2); err != nil {
		t.Fatal(err)
	}

	wg.Add(2)
	is.registerCallback("key.*", cb.Add)
	wg.Wait()
	actKeys := cb.Keys()
	sort.Strings(actKeys)
	if expKeys := []string{"key1", "key2"}; !reflect.DeepEqual(actKeys, expKeys) {
		t.Errorf("expected %v, got %v", expKeys, cb.Keys())
	}
}


text:
module Commentable
  include DataMapper::Resource

  is :remixable,
    :suffix => "comment"

  property :id,         Integer, :key => true, :serial => true
  property :comment,    String
  property :created_at, DateTime

end


text:
package com.unb.matriculeme.dao;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Token {
    @Id
    @GeneratedValue
    private int id;

    @Column(nullable = false, length = 32)
    private String token;

    @Column(nullable = false)
    private boolean valid;

    @Column(nullable = false)
    private long time;

    public int getId() {
        return id;
    }

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

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public boolean getValid() {
        return valid;
    }

    public void setValid(boolean valid) {
        this.valid = valid;
    }

    public long getTime() {
        return time;
    }

    public void setTime(long time) {
        this.time = time;
    }
}


text:
require 'vk/api/types'

module Vk
  module API
    class Ads < Vk::Schema::Namespace
      # Object type
      ObjectType = API::Types::Coercible::String.enum('ad', 'campaign', 'client', 'office')
    end
  end
end


text:
import m from 'mithril'
import moment from 'moment'
import _ from 'underscore'
import h from '../../../h'
import { RewardDetails } from '../../../entities/reward-details'
import { RewardDetailsStream, ToggleStream, StreamType } from '../../../entities/reward-details-stream'
import rewardVM from '../../../vms/reward-vm'
import dashboardRewardCard from '../../dashboard-reward-card'
import editRewardCard from '../../edit-reward-card'
import userVM from '../../../vms/user-vm'
import { ProjectDetails } from '../../../entities/project-details'
import { RewardsEditListCard } from './rewards-edit-list-card'

type ExtendedWindow = {
    $(...params: any[]): any
    I18n: {
        locale: string
        t(path: string, ...params: any[])
    }
}

const { $, I18n } = window as any as ExtendedWindow;
const jQuery = $
const I18nScope = _.partial(h.i18nScope, 'projects.reward_fields');
const prop = h.RedrawStream as <T>(data?: T, onUpdate?: (data: T) => void) => (newData?: T) => T

export type RewardsEditListAttrs = {
    class: string
    project_id: number
    user_id: number
    project: StreamType<ProjectDetails>
    error: StreamType<boolean>
    errors: StreamType<string>
    showSuccess: StreamType<boolean>
    loading: StreamType<boolean>
}

export type RewardsEditListState = {
    rewards: StreamType<StreamType<RewardDetailsStream>[]>
    newReward(): RewardDetailsStream
    user: StreamType<{}>
    setSorting(localVnode: m.VnodeDOM<{}, {}>): void
    showImageToUpload(reward: any, imageFileToUpload: any, imageInputElementFile: any): void
    deleteImage(reward: any, projectId: any, rewardId: any): Promise<any>
    uploadImage(reward: any, imageFileToUpload: any, projectId: any, rewardId: any): Promise<any>
}

export class RewardsEditList implements m.Component {

    oninit({ attrs, state }: m.Vnode<RewardsEditListAttrs, RewardsEditListState>) {
        const rewards = prop<StreamType<RewardDetailsStream>[]>([])
        const loading = attrs.loading
        const error = attrs.error
        const errors = attrs.errors
        const showSuccess = attrs.showSuccess
        function newReward(): RewardDetailsStream {
            return {
                id: prop(null),
                minimum_value: prop(null),
                title: prop(''),
                shipping_options: prop('free'),
                edit: h.toggleProp(true, false) as any as ToggleStream<boolean>,
                deliver_at: prop(moment().date(1).format()),
                description: prop(''),
                paid_count: prop(0),
                waiting_payment_count: prop(0),
                limited: h.toggleProp(false, true) as any as ToggleStream<boolean>,
                maximum_contributions: prop(null),
                run_out: h.toggleProp(false, true) as any as ToggleStream<boolean>,
                newReward: true,
                uploaded_image: prop(null),
                row_order: prop(999999999 + (rewards().length * 20)) // we need large and spaced apart numbers
            };
        }

        const updateRewardSortPosition = (rewardId, position) => m.request({
            method: 'POST',
            url: `/${I18n.locale}/projects/${attrs.project_id}/rewards/${rewardId}/sort?reward[row_order_position]=${position}`,
            config: (xhr) => {
                if (h.authenticityToken()) {
                    xhr.setRequestHeader('X-CSRF-Token', h.authenticityToken());
                    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
                }
            }
        });

        function setSorting(localVnode: m.VnodeDOM) {
            if (jQuery) {
                jQuery(localVnode.dom).sortable({
                    update(event, ui) {
                        const rewardId = ui.item[0].id
                        updateRewardSortPosition(rewardId, ui.item.index())
                    }
                })
            }
        }

        async function loadRewards() {

            await rewardVM.fetchRewards(attrs.project_id)

            rewards([]);

            for (const reward of rewardVM.rewards()) {

                const limited = reward.maximum_contributions !== null && !reward.run_out;
                const rewardDataStreams: RewardDetailsStream = {
                    id: prop(reward.id),
                    deliver_at: prop(reward.deliver_at),
                    description: prop(reward.description),
                    run_out: h.toggleProp(reward.run_out, !reward.run_out) as any as ToggleStream<boolean>,
                    maximum_contributions: prop(reward.maximum_contributions),
                    minimum_value: prop(reward.minimum_value),
                    edit: h.toggleProp(false, true) as any as ToggleStream<boolean>,
                    limited: h.toggleProp(limited, !limited) as any as ToggleStream<boolean>,
                    paid_count: prop(reward.paid_count),
                    row_order: prop(reward.row_order),
                    shipping_options: prop(reward.shipping_options),
                    title: prop(reward.title),
                    uploaded_image: prop(reward.uploaded_image),
                    waiting_payment_count: prop(reward.waiting_payment_count),
                    newReward: false,
                }

                const rewardDataStreamProp = prop<RewardDetailsStream>(rewardDataStreams)
                rewards(rewards().concat([rewardDataStreamProp]));
            }

            if (rewardVM.rewards().length === 0) {
                rewards([prop(newReward())]);
            }

            h.redraw();
        }

        const uploadImage = (reward, imageFileToUpload, projectId, rewardId) => {
            if (imageFileToUpload()) {
                return rewardVM
                    .uploadImage(projectId, rewardId, imageFileToUpload())
                    .then(r => {
                        if (r) {
                            reward.uploaded_image(r.uploaded_image);
                        }
                        return r;
                    })
                    .catch(err => {
                        error(true);
                        errors('Erro ao fazer upload da imagem da recompensa. Favor tentar novamente.');
                    });
            } else {
                return Promise.resolve();
            }
        };

        const deleteImage = (reward, projectId, rewardId) => {
            return rewardVM.deleteImage(projectId, rewardId)
                .then(r => {
                    if (r) {
                        reward.uploaded_image(r.uploaded_image);
                    }
                    return r;
                })
                .catch(err => {
                    error(true);
                    errors('Erro ao deletar a imagem da recompensa. Favor tentar novamente.');
                });
        };

        const showImageToUpload = (reward, imageFileToUpload, imageInputElementFile) => {
            const reader = new FileReader();
            reader.onload = function () {
                imageFileToUpload(imageInputElementFile);
                var dataURL = reader.result;
                reward.uploaded_image(dataURL);
                m.redraw();
            };
            reader.readAsDataURL(imageInputElementFile);
        };

        loadRewards()

        state.rewards = rewards
        state.user = userVM.fetchUser(attrs.user_id) as StreamType<{}>
        state.newReward = newReward
        state.setSorting = setSorting
        state.showImageToUpload = showImageToUpload
        state.deleteImage = deleteImage
        state.uploadImage = uploadImage
    }

    view({ attrs, state }: m.Vnode<RewardsEditListAttrs, RewardsEditListState>) {

        const loading = attrs.loading
        const error = attrs.error
        const errors = attrs.errors
        const showSuccess = attrs.showSuccess
        const project = attrs.project
        const showImageToUpload = state.showImageToUpload
        const deleteImage = state.deleteImage
        const uploadImage = state.uploadImage
        const project_id = attrs.project_id
        const sortedRewards = _.sortBy(state.rewards(), reward => Number(reward().row_order()))
        const hasRewards = state.rewards().length > 0
        const shouldShowAddRewardButton = rewardVM.canAdd(project().state, state.user())

        return (
            <>

                    {
                        hasRewards &&

                            {sortedRewards.map((reward, index) =>
                                <RewardsEditListCard
                                    reward={reward}
                                    index={index}
                                    project={project}
                                    error={error}
                                    errors={errors}
                                    user={state.user}
                                    showSuccess={showSuccess}
                                    loading={loading}
                                    showImageToUpload={showImageToUpload}
                                    deleteImage={deleteImage}
                                    uploadImage={uploadImage}
                                    class={attrs.class}
                                    project_id={project_id}
                                />
                            )}

                    }

                <AddRewardButton
                    shouldDisplayButton={shouldShowAddRewardButton}
                    onclick={() => {
                        state.rewards().push(prop(state.newReward()));
                        h.redraw();
                    }} />
            </>
        )
    }
}

type AddRewardButtonAttrs = {
    shouldDisplayButton: boolean
    onclick(event: Event): void
}

class AddRewardButton implements m.Component {
    view({attrs} : m.Vnode<AddRewardButtonAttrs>) {
        const shouldDisplayButton = attrs.shouldDisplayButton
        const onclick = attrs.onclick

        return (
            shouldDisplayButton &&
            <button class='btn btn-large btn-message show_reward_form new_reward_button add_fields'
            onclick={onclick}>
                {I18n.t('add_reward', I18nScope())}
            </button>
        )
    }
}


text:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { DrawRequestItemComponent } from './draw-request-item.component';

describe('DrawRequestItemComponent', () => {
  let component: DrawRequestItemComponent;
  let fixture: ComponentFixture<DrawRequestItemComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ DrawRequestItemComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(DrawRequestItemComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should be created', () => {
    expect(component).toBeTruthy();
  });
});


text:
Harvester
=========

The harvester is OVAL's low-level module which takes
care of the actual OAI-PMH communication. Users of the
validator should normally not have to use it directly.

.. module:: oval.harvester

Harvester Module
----------------

.. autofunction:: oval.harvester.get_protocol_version

.. autofunction:: oval.harvester.normalize_params

.. autofunction:: oval.harvester.fetch_data

.. autofunction:: oval.harvester.configure_request

.. autofunction:: oval.harvester.configure_record_iterator


text:
package by.istin.android.xcore.benchmark.transformer;

import android.content.ContentValues;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;

import by.istin.android.xcore.annotations.Config;
import by.istin.android.xcore.annotations.converter.IConverter;
import by.istin.android.xcore.annotations.converter.gson.GsonConverter;
import by.istin.android.xcore.utils.StringUtil;

/**
 * Created by uladzimir_klyshevich on 7/18/15.
 */
public class TagsTransformer extends Config.AbstractTransformer<GsonConverter.Meta> {

    public static final IConverter<GsonConverter.Meta> CONVERTER = new IConverter<GsonConverter.Meta>() {
        @Override
        public void convert(ContentValues contentValues, String fieldValue, Object parent, GsonConverter.Meta meta) {
            JsonElement jsonElement = meta.getJsonElement();
            if (jsonElement.isJsonNull()) {
                return;
            }
            StringBuilder tagsBuilder = new StringBuilder();
            JsonArray jsonArray = jsonElement.getAsJsonArray();
            int size = jsonArray.size();
            if (size > 0) {
                for (int i = 0; i < size; i++) {
                    JsonElement item = jsonArray.get(i);
                    tagsBuilder.append(item.getAsString());
                    if (i != size - 1) {
                        tagsBuilder.append(", ");
                    }
                }
                String result = tagsBuilder.toString();
                contentValues.put(fieldValue, result);
            }
        }
    };

    @Override
    public IConverter<GsonConverter.Meta> converter() {
        return CONVERTER;
    }

}


text:
package main

import (
	"testing"

	. "gopkg.in/check.v1"
)

type PluginManagerTest struct {
}

func Test(t *testing.T) { TestingT(t) }

var _ = Suite(&PluginManagerTest{})

func (t *PluginManagerTest) SetUpTest(c *C) {
}

func (t *PluginManagerTest) TearDownTest(c *C) {
}

func (t *PluginManagerTest) TestStandard(c *C) {
	install("github.com/myitcv/neovim/example")
}


text:
% ==============================================================================
%
%                                M I S S I O N
%
% ==============================================================================
\chapter{Mission} % ---------------------------------------------------------- %
\label{ch:mission}
% ---------------------------------------------------------------------------- %
% ==============================================================================
%
%                                OVERVIEW
%
% ==============================================================================

Moving from the theoretical domain  to the practical, the overarching question
becomes
\begin{center}
    \emph{What do  we intend to do, why, and how?}
\end{center}
To answer that question is the  purpose of this chapter. A general overview of
the STEMlab hardware is presented first  to give the reader a broad impression
of what  the hardware  component of  the project actually  is.  Based  on that
information, the  objectives of this project  are defined. Possible approaches
to  reach those  objectives are  presented and  evaluated, and  a decision  is
reached  on  how  to  achieve  this  project's  goals. The  project's  problem
statement is included in Appendix~\ref{app:ch:task}.

% ==============================================================================
%
%                         S T E M L A B   1 2 5 - 1 4
%
% ==============================================================================
\section{The Red Pitaya STEMlab 125-14} % <<< -------------------------------- %
\label{sec:stl125}
% ---------------------------------------------------------------------------- %

In order to have a rough idea of what sort of device this project is based on,
some key information of the STEMlab is given first. With that in mind, some of
the  shortcomings  of  its  stock configuration  are  discussed,  which  leads
directly to the main objective of this project.

% ==============================================================================
%
%       S T E M L A B   1 2 5 - 1 4:   H A R D W A R E   O V E R V I E W
%
% ==============================================================================
\subsection{Hardware Overview} %<<< ------------------------------------------ %
\label{subsec:stl125:hardware_overview}
% ---------------------------------------------------------------------------- %

The  device on  which this  project  is based  is the  Pitaya STEMlab  125-14,
pictured  in Figure~\ref{fig:stl125:photo}. STEMlab  is a  compact measurement
instrument (it fits into the palm of  a hand) which can replace more expensive
devices like  oscilloscopes by using  a computer for data  storage, processing
and presentation.

Some of its key specifications relevant to us are:
\begin{itemize}\tightlist
    \item
        two high-speed analog inputs and outputs via coaxial connectors
    \item
        Uses  a  Linear Technology  LTC2145-14  converter~\cite{lt:ltc2145-14}
        on      those      inputs:      \num{14}\,bits      resolution      at
        \num{125}\,MS$\cdot$s\textsuperscript{-1} per channel.
    \item
        Xilinx SoC  with an FPGA component  for data processing on  the device
        itself and two ARM Cortex9 cores for general-purpose tasks
    \item
        Ethernet and USB physical interfacing  chips for data transmission and
        device control
    \item
        Has its own operating system, a GNU/Linux distribution (Ubuntu is used
        in our project), running on the ARM cores.
    \item
        The software used is open-source and available under \cite{pita:github}.
\end{itemize}
More  comprehensive documentation  can be  found at~\cite{pita:readthedocs}. A
block   diagram   with    the   system's   key   components    is   shown   in
Figure~\ref{fig:stl125:block_diagram}.

\begin{figure}
    \centering
    \includegraphics[width=0.67\textwidth]{images/stl125/stemlab125-14-photo.png}
    \caption[STEMlab Photo]
        {Photo of the STEMlab~\cite{pita:elektor:starterkit}}
    \label{fig:stl125:photo}
\end{figure}

\begin{figure}
    \centering
    \includegraphics[width=\textwidth]{images/stl125/stemlab125.png}
    \caption[STEMlab Block Diagram]
        {Block diagram of the Red Pitaya STEMlab~\cite{pita:ossmann}}
    \label{fig:stl125:block_diagram}
\end{figure}

%>>> STEMLAB HARDWARE OVERVIEW
% ==============================================================================
%
%            S T E M L A B   1 2 5 - 1 4:   D O W N S A M P L I N G
%
% ==============================================================================
\subsection{Downsampling on the STEMlab With Stock Configuration} %<<< ------- %
\label{subsec:stl125:ds_default}
% ---------------------------------------------------------------------------- %

The  STEMlab  enables   downsampling  by  powers  of  \num{2}   in  its  stock
configuration, in a range  between $1 = 2^0$ and $65536  = 2^{16}$.  The exact
manner in which this downsampling process is performed is not easily deducible
from  public information;  the  documentation  on the  internals  of the  FPGA
codebase  is  rather  sparse. However,  work  conducted  by  our  predecessors
has  shown  that  the  STEMlab  uses   a  moving  averaging  filter  for  this
process~\cite{bucher:kuery}.

The moving averager's transfer function is
\begin{equation}
    \label{eq:moving_averager}
    H(z) = \frac{1}{N+1}\sum_{k = 0}^{N} z^{-k}.
\end{equation}
A high degree of similarity is immediately recognizable when comparing this to
the  transfer  function  of  a CIC  filter  in  Equation~\ref{eq:cic:complete}
(page~\pageref{eq:cic:complete}). Indeed, a cascade  of moving averagers would
almost yield a CIC  filter, save for the gain, which  could be easily adjusted
after the fact if needed.

A moving averager as a decimation filter is relatively cheap to implement when
using only  decimation rates of powers  of two, as  is the case for  the stock
software of the  STEMlab. The weight for each coefficient of  $z^{-k}$ will be
$\frac{1}{N+1}  =  \frac{1}{R} =  2^{-m},  m  \in \mathbb{N}_0$,  meaning  the
computations can  be performed without  multipliers by performing  a bit-shift
operation to the right. The primary disadvantage which results from these rate
reduction  factors  is that  the  resulting  reduced  sampling rates  are  not
very  ``nice'' numbers,  so  to speak,  since the  incoming  sampling rate  is
\SI{125}{\MHz}, and therefore not a power of \num{2}.

Just  like  a  CIC  filter  by  itself,  a  moving  averager  also  makes  for
a  rather   poor  lowpass   filter,  for   two  reasons: Passband   droop  and
poor  stopband   attenuation  (equivalent  to  a   single-stage  CIC  filter).
Figure~\ref{fig:stl125:moving_averager} shows  the frequency response  for the
case of  $R=8$ and  a signal  of \SI{5}{\MHz}. The  incoming sampling  rate is
\SI{125}{\MHz},  the  reduced  sampling  rate  is  $\SI{125}{\MHz}  \div  8  =
\SI{15.625}{\MHz}$. Therefore, anything  above half that frequency  is aliased
back into the region below $\SI{15.625}{\MHz} \div 2 = \SI{7.8125}{\MHz}$.  In
the case of a signal at  \SI{5}{\MHz}, this results in an aliasing attenuation
of a modest \SI{8.06}{\dB}. Combined with the passband droop of \SI{1.48}{\dB}
(a signal  attenuation of  almost \SI{16}{\percent})  at that  frequency, this
makes for a margin of a  mere \SI{6.58}{\dB} between the attenuated signal and
the aliasing attenuation!

\begin{figure}
    \centering
    \input{images/stl125/movingAveragerPBAliasing.tikz}
    \caption[Frequency Response of Moving Averager: Example]{%
        Frequency  response, passband  droop  and aliasing  attenuation for  a
        moving  average  filter  of  order  \num{7}  for  a  decimation  by  a
        factor of \num{8}. The incoming  sampling frequency is \SI{125}{\MHz},
        the  outgoing sampling  frequency is  \SI{15.625}{\MHz}, the  measured
        signal  has   a  frequency   of  \SI{5}{MHz}.%
    }
    \label{fig:stl125:moving_averager}
\end{figure}

As  a benchmark  for  or  own solution,  we  will  use measurements  conducted
by  our  predecessors  with  the  STEMlab's  stock  configuration,  listed  in
Table~\ref{tab:stl125:measurements_bucher_kuery}. The   measurements  do   not
actually  suggest  a very  bad  performance  of  the filter. This  is  because
they   were   conducted   at  specific   harmonic   frequencies. The   primary
issue  with  a   moving  averager  is  less  SNR   for  specific  frequencies,
but  aliasing  when  measuring  a  non-harmonic  signal  which  has  frequency
components above  $f_\mathrm{s,low}/2$. In that case, the  considerations from
Figure~\ref{fig:stl125:moving_averager}  become crucial  to understanding  the
aliasing issue.  This behavior was also confirmed in~\cite{bucher:kuery}.  Our
primary aim  is therefore more  to reduce  these aliasing effects  rather than
purely  trying  to  improve  SNR for  specific  single  frequencies,  although
improving SNR is certainly a goal too.

\begin{table}
    \centering
    \caption[Measurements of STEMlab 125-14 Stock Configuration]{%
        Measurement results  for STEMlab  125-14 from~\cite{bucher:kuery}. SNR
        was  determined for  a  specific harmonic  frequency  signal for  each
        sampling rate.%
    }
    \label{tab:stl125:measurements_bucher_kuery}
    \begin{tabular}{>{$}r<{$}>{$}r<{$}>{$}r<{$}SSS}
        \toprule
        R      &   &       & {$f_\mathrm{s,low}$ (\si{\kHz})} & {$f_\mathrm{signal}$ (\si{\kHz})} & SNR \\
        \midrule
        2^0    & = &     1 & 125000     & 10000   & \SI{62.8}{\dB} \\
        2^3    & = &     8 &  15625     &  5000   & \SI{69.8}{\dB} \\
        2^6    & = &    64 &   1953     &   500   & \SI{76.0}{\dB} \\
        2^{10} & = &  1024 &    122.1   &    40   & \SI{76.4}{\dB} \\
        2^{13} & = &  8192 &     15.26  &     5   & \SI{82.4}{\dB} \\
        2^{16} & = & 65536 &      1.907 &     0.5 & \SI{83.5}{\dB} \\
        \bottomrule
    \end{tabular}
\end{table}

In conclusion, we can formulate three main objectives:
\begin{itemize}\tightlist
    \item
        Reduce  aliasing   of  out-of-range  frequency  components   into  the
        passband.
    \item
        Improve SNR
    \item
        Have a nicer set of reduced sampling rates.
\end{itemize}

%>>> DOWNSAMPLING ON STEMLAB 125-14
%>>> STEMLAB 125-14
% ==============================================================================
%
%                     P O S S I B L E   S O L U T I O N S
%
% ==============================================================================
\section{Possible Solutions} % <<< ------------------------------------------- %
\label{sec:mission:possible_solutions}
% ---------------------------------------------------------------------------- %

Based on the  previous section, it is clear that  the downsampling filter from
the \mbox{STEMlab's} stock  configuration must be replaced  if better aliasing
attenuation is  to be attained. Furthermore,  since a new filtering  system is
being implemented  anyway, one may wish  to change the rate  change factors in
order to achieve  a set of nicer-looking reduced  sampling rates. The question
now becomes: \emph{How}?

Problematic is that  as of spring 2017,  the official code by  Red Pitaya base
has been  split into  two: There is  a new  development branch  bringing major
changes, while  the old code  (which has been  used in the  projects preceding
this one) is no longer being maintained, as explained by one of the developers
in~\cite{pita:github:issue:huesser:jeras}:
\begin{quote}
    Current  development  is done  on  the  \code{mercury} branch  on  the
    FPGA  subproject of  the same  name.  The  code is  still under  heavy
    development and  not stable. All  other FPGA  subprojects will  not be
    developed further.
\end{quote}

Essentially, this presents us with three options on how to proceed:
\begin{itemize}
    \item
        Use  the old  Red Pitaya  codebase,  and implement  our new  filtering
        system based on it.
    \item
        Use the new  Red Pitaya codebase. Due to this  codebase being unstable
        according to the developers themselves as of the time of this project,
        we consider this to be an unviable option.
    \item
        Use an alternative  ecosystem, either by a third party  (if one can be
        found) or developed by ourselves.
\end{itemize}
In   order   to   have   a    somewhat   objective   measure   for   comparing
the   first   and   last   option,    a   decision   matrix   is   used;   see
Table~\ref{tab:decision_matrix:pitaya_vs_own}. In  the  following  paragraphs,
the criteria  and weights in the  table are elaborated upon. The  table uses a
scale of  \num{1} through \num{6},  with \num{1}  being the worst  and \num{6}
being the best score. At the end, totals are tallied and compared.

\paragraph{Reliance  upon others:} Using  the  existing  Red Pitaya  ecosystem
would also  couple us  to any problems  inherent to that  platform and  to the
solutions developed by preceding projects based on it. Any bugs encountered in
the Red Pitaya ecosystem would either  require a bugfix by the manufacturer or
a workaround on our part. Since the old Red Pitaya codebase is no longer being
maintained by  the developers, bugfixes will  not be available, leaving  us to
clean  up  any potential  issues  inherent  to  the  codebase. If we  were  to
implement our  own solution instead, we  would be less reliant  upon others to
fix  any inherent  problems to  the code. These  factors lead  us to  give the
existing codebase a rather weak rating  compared to the choice of pursuing our
own solution.

\paragraph{Flexibility:} Obviously, implementing our own  system would give us
much higher flexibility  than using the existing ecosystem. The  only two true
limitations would  be the  time and  hardware resources  available to  us. The
official codebase would limit us to its capabilities. Adding new functionality
to the existing codebase would be possible, but adapting software for purposes
for which  it was  not originally  intended does tend  to be  a time-consuming
procedure  in our  experience.  Therefore,  the option  of developing  our own
solution wins out again here.

\paragraph{Complexity  of  complete  system:} This  refers  not  just  to  the
complexity  of  the  components  we  work  on,  but  of  the  entire  platform
and   ecosystem. As   anyone   who   bothers  to   peruse   the   Red   Pitaya
codebase~\cite{pita:github}  can deduce,  it is  a large  ecosystem with  many
features and  capabilities, most  of which  are not  relevant to  our needs. A
custom system developed for the specific requirements of this project would be
much leaner and have fewer points of failure.

\paragraph{Labor  costs:} Here  is where  using  the  existing codebase  would
be  beneficial  in our  view. While  understanding  its inner  workings  would
doubtlessly  be  required  and  would   take  a  significant  amount  of  time
(particularly in view of the sparse documentation at this point), developing a
completely new  system from scratch  would be  a much costlier  undertaking in
terms of required man-hours we our estimate.

\paragraph{Chances of success:} Basing our work on the existing codebase would
unburden  us  of  the  legwork  needed  to  get  basic  functionality  up  and
running. We could exchange  the filter components of the  existing system with
our own, but leave most of the remaining system untouched. The challenge would
be to understand the  system well enough to do this.   Building our own system
would require re-implementing more components  of the Red Pitaya platform than
just the filters. As each additional task  increases the risk of failure, this
is not without risk to the project's success. Overall, we consider this factor
to be roughly even between the two choices.

\paragraph{Robustness  of third-party  components:} This criterion  takes into
account our assessment  of the reliability and dependability  of any component
we use which  is not developed by ourselves, along  with its documentation and
manufacturer  support. In the  case of  the  Red Pitaya  codebase, this  would
primarily  comprise the  codebase  itself as  well as  any  components for  it
developed  by other  parties. If  we were  to develop  our  own solution,  the
building blocks would primarily be the  Xilinx toolchain and libraries for the
SoC.

Because the Red Pitaya codebase is  rather large, not well documented, has not
had many years to mature and is no longer being maintained, and the company is
small  and  more  likely to  be  stretched  thin,  we  do not  score  the  Red
Pitaya codebase  highly here. The Xilinx  toolchain and FPGA  libraries, while
undoubtedly not without  bugs, have had a  lot of time to mature  on the other
hand.  Also, Xilinx  is a big company  with vast resources, so  any bugs which
are  encountered in  their products  are more  likely to  be addressed  in our
view. For  these reasons,  we score  developing our  own solution  higher than
using the existing codebase.

\paragraph{Reparability:} If any issues are found in the resulting product, we
are more likely to  be able to fix them if it is  our own codebase rather than
that by a third party.

\paragraph{Long-term viability:} Developing  our own  solution would  allow us
(or anyone  else wishing  to base their  work off of  ours) to  address future
needs relatively  easily. Using the  existing code base  would make  this more
difficult in our view.

\paragraph{Conclusion:} Developing our  own solution does carry  a significant
risk  and is  likely  to require  more  work than  basing  our application  on
existing  work.   But in  light  of  the  mentioned  drawbacks of  the  latter
approach, we still find that it is  the preferable approach and is more likely
to lead to a successful outcome.

\begin{table}
    \centering
    \caption[Decision Matrix of Possible System Design Choices]{%
        Decision   matrix   comparing   the   usage  of   the   existing   Red
        Pitaya   ecosystem  against   building   our   own  data   acquisition
        system. Weighing: Scale  of \num{1}  (worst)  to \num{6}  (best). More
        total points is better.%
    }
    \label{tab:decision_matrix:pitaya_vs_own}
    \begin{tabular}{>{\raggedright}p{80mm}SS}
        \toprule
        & RP & Custom \\
        \midrule
        Reliance on Others &
        2 & 5 \\

        Flexibility &
        2 & 5 \\

        Complexity of Complete System &
        1 & 4 \\

        Labor Costs &
        4 & 2 \\

        Chances of Success &
        4 & 4 \\

        Available Documentation for Used Building Blocks &
        3 & 5 \\

        Robustness of Third-Party Components &
        2 & 5 \\

        Reparability &
        2 & 5 \\

        Long-term Viability&
        2 & 4 \\
        \midrule
        Total & 21 & 37 \\
        \bottomrule
    \end{tabular}
\end{table}

%>>> POSSIBLE SOLUTIONS
% ==============================================================================
%
%                                C O N C E P T
%
% ==============================================================================
\section{Concept} % <<< ------------------------------------------------------ %
\label{sec:mission:concept}
% ---------------------------------------------------------------------------- %

Having concluded that  we shall develop our own solution  from scratch, we can
now devise a concept for how that solution will look.  On the most fundamental
level, it will require the following components:
\begin{itemize}
    \item
        a custom FPGA firmware for data acquisition and filtering
    \item
        a new scope application for data visualization
    \item
        an interfacing layer between the FPGA and the scope
    \item
        optionally, the possibility to connect to other applications like Matlab
\end{itemize}
The   following   sections   elaborate   on   the   general   shape   of   our
solution. Chapters~\ref{ch:fpga}  through~\ref{ch:graphical_front_end} explain
the components  in detail, while Chapter~\ref{ch:filter_design}  documents the
filter design process, which is rather separate from the firmware and software
and therefore a dedicated chapter.

% ==============================================================================
%
%               C O N C E P T :   F P G A   C O M P O N E N T S
%
% ==============================================================================
\subsection{FPGA Components} % <<< ------------------------------------------- %
\label{subsec:concept:fpga_components}
% ---------------------------------------------------------------------------- %

On the most abstract level, the FPGA part of our system will need to be able to
\begin{itemize}\tightlist
    \item
        acquire data from the ADC,
    \item
        decimate and filter it,
    \item
        and pass it on for further processing.
\end{itemize}

Due to the  platform's open nature, there exist some  projects for the STEMlab
by parties other than Red Pitaya  themselves. One of these is \emph{Red Pitaya
Notes} by  Pavel Demin, available  at~\cite{pita:github:pitaya-notes}. As part
of that project, an ADC core for the FPGA which acquires data from the ADC and
passes it on via an AXI4 streaming interface\footnotemark.
\footnotetext{%
    Xilinx's proprietary general-purpose interconnect for moving large amounts
    of data around an FPGA
} has been developed.
Since  this  project  is  open-source   and  has  a  permissive  license  (MIT
license~\cite{licenses:mit},   see   also  Appendix~\ref{sec:mit_license}   on
page~\pageref{sec:mit_license})  and fulfills  our main  technical requirement
(easily to interface  with), it is used  in our project to  interface the FPGA
with the ADC.

For filtering,  one can either  implement custom filter topologies  from basic
FPGA building blocks (adders, multipliers, etc.), write completely custom VHDL
or Verilog code, or use ready-made blocks, if available.  Xilinx provides such
FPGA  blocks for  FIR  and CIC  filters,  both of  which  come with  excellent
documentation~\cite{xilinx:cic-compiler},~\cite{xilinx:fir-compiler}.       In
order to  avoid re-inventing the  wheel and to take  advantage of some  of the
advanced features offered by these two blocks, we use them in our design.

Interfacing  between the  FPGA  and  the outside  world  requires a  component
which  can take  data  from the  filters  and  hand it  off  to the  GNU/Linux
running  on the  ARM cores. Additionally,  the user  must be  able to  trigger
measurements  from  the  operating  system.   Luckily,  such  a  data  logging
core  for   a  Xilinx  FPGA   has  already   been  developed  in   an  earlier
project~\cite{pita:github:huesser:zynq-logger} under a compatible license.  It
comes  with a  kernel  module  to interface  with  GNU/Linux. With some  minor
adaption work, this core should suit our needs nicely.

The  last  component needed  for  the  FPGA is  a  control  logic to  set  the
decimation  rate  and  enable  or  disable specific  components  of  the  data
processing  chain. This  should  be   fairly  straightforward,  and   will  be
implemented by ourselves as a custom block.

In summary, the concept for the FPGA data processing system looks as follows:
\begin{itemize}\tightlist
    \item
        The      ADC      is      accessed     via      the      ADC      core
        from~\cite{pita:github:pitaya-notes}.
    \item
        Filtering the data is conducted with Xilinx's CIC and FIR compilers.
    \item
        For     interfacing     with     GNU/Linux,    the     data     logger
        from~\cite{huess-schnid} is used.
    \item
        A custom control logic configures the data processing chain on-the-fly
        through user input.
\end{itemize}

%>>> CONCEPT: FPGA COMPONENTS
% ==============================================================================
%
%             C O N C E P T :   I N T E R F A C I N G   L A Y E R
%
% ==============================================================================
\subsection{Interfacing Layer} % <<< ----------------------------------------- %
\label{subsec:concept:interfacing_layer}
% ---------------------------------------------------------------------------- %

The interfacing layer is responsible for  sending the data from the STEMlab to
the  user application  running  on  a computer. This  is  done  via a  Gigabit
Ethernet connection. As  is easily apparent,  this connection is far  too slow
for  moving all  data off  the device  which is  generated by  the ADC  (about
\SI{3.7}{\gibi\byte\per\second}), hence  the need for decimation  (among other
reasons).

For the interfacing layer, a server  application to which a client can connect
is run on the STEMlab. The server  takes data from the logger's kernel module,
processes and packages  it as necessary, and sends it  out over Ethernet.  The
application is  documented in  detail in Chapter~\ref{ch:server},  starting on
page~\pageref{ch:server}.

%>>> CONCEPT: INTERFACING LAYER
% ==============================================================================
%
%                         C O N C E P T :   S C O P E
%
% ==============================================================================
\subsection{Oscilloscope} % <<< ---------------------------------------------- %
\label{subsec:concept:scope}
% ---------------------------------------------------------------------------- %

The scope is  the main interface between  the end user and the  STEMlab in our
system. Through it, data  can be visualized and analyzed in  both the time and
frequency domain.  Furthermore,  it is capable of  calculating certain metrics
such as the power  in a given frequency range or SNR  via the autodetection of
signal and noise components.

In  order  to  ensure  maximum   portability,  the  scope  is  implemented  as
a   web   application   rather   than  a   custom   binary. This   allows   it
to   function   on   any   operating   system   with   a   reasonably   modern
browser. A  through  documentation  of  its  capabilities  and  implementation
is   available    in   Chapter~\ref{ch:graphical_front_end},    beginning   on
page~\ref{ch:graphical_front_end}.

%>>> CONCEPT: SCOPE

%>>> CONCEPT

%^^A vim: foldenable foldcolumn=4 foldmethod=marker foldmarker=<<<,>>>


text:
layout: page
permalink: /q10_goodchoices/
---
<iframe src="https://docs.google.com/forms/d/e/1FAIpQLSfWIK6E1v3A9tK1clLditDxTzK52VOXnwKDEsn8dp_zGS-ziA/viewform?embedded=true" width="720" height="1200" frameborder="0" marginheight="0" marginwidth="0">Wird geladen...</iframe>


text:
@class NSArray, NSDictionary;

@protocol WCDBCoding <PBCoding>
+ (id)dummyObject;
+ (const map_7a576766 *)getValueNameIndexMap;
+ (NSArray *)getValueTable;
@property(nonatomic) long long __rowID;

@optional
+ (NSDictionary *)getWCDBTableHelperDictionary;
+ (const map_0e718273 *)getFileValueTagIndexMap;
+ (NSArray *)getFileValueTypeTable;
+ (const map_0e718273 *)getPackedValueTagIndexMap;
+ (NSArray *)getPackedValueTypeTable;
+ (const basic_string_a490aa4c *)getWCDBPrimaryColumnName;
+ (const struct WCDBIndexHelper *)getWCDBIndexArray;
+ (unsigned long long)getWCDBIndexArrayCount;
@end


text:
{-# LANGUAGE PatternGuards, BangPatterns #-}
module Twee.KBO(lessEq, lessIn, lessEqSkolem, Sized(..), Weighted(..)) where

import Twee.Base hiding (lessEq, lessIn, lessEqSkolem)
import Twee.Equation
import Twee.Constraints hiding (lessEq, lessIn, lessEqSkolem)
import qualified Data.Map.Strict as Map
import Data.Map.Strict(Map)
import Data.Maybe
import Control.Monad
import Twee.Utils

lessEqSkolem :: (Function f, Sized f, Weighted f) => Term f -> Term f -> Bool
lessEqSkolem !t !u
  | m < n = True
  | m > n = False
  where
    m = size t
    n = size u
lessEqSkolem (App x Empty) _
  | x == minimal = True
lessEqSkolem _ (App x Empty)
  | x == minimal = False
lessEqSkolem (Var x) (Var y) = x <= y
lessEqSkolem (Var _) _ = True
lessEqSkolem _ (Var _) = False
lessEqSkolem (App (F _ f) ts) (App (F _ g) us) =
  case compare f g of
    LT -> True
    GT -> False
    EQ ->
      let loop Empty Empty = True
          loop (Cons t ts) (Cons u us)
            | t == u = loop ts us
            | otherwise = lessEqSkolem t u
      in loop ts us

-- | Check if one term is less than another in KBO.
{-# SCC lessEq #-}
lessEq :: (Function f, Sized f, Weighted f) => Term f -> Term f -> Bool
lessEq (App f Empty) _ | f == minimal = True
lessEq (Var x) (Var y) | x == y = True
lessEq _ (Var _) = False
lessEq (Var x) t = x `elem` vars t
lessEq t@(App f ts) u@(App g us) =
  (st < su ||
   (st == su && f << g) ||
   (st == su && f == g && lexLess ts us)) &&
  xs `lessVars` ys
  where
    lexLess Empty Empty = True
    lexLess (Cons t ts) (Cons u us)
      | t == u = lexLess ts us
      | otherwise =
        lessEq t u &&
        case unify t u of
          Nothing -> True
          Just sub
            | not (allSubst (\_ (Cons t Empty) -> isMinimal t) sub) -> error "weird term inequality"
            | otherwise -> lexLess (subst sub ts) (subst sub us)
    lexLess _ _ = error "incorrect function arity"
    xs = weightedVars t
    ys = weightedVars u
    st = size t
    su = size u

    [] `lessVars` _ = True
    ((x,k1):xs) `lessVars` ((y,k2):ys)
      | x == y = k1 <= k2 && xs `lessVars` ys
      | x > y  = ((x,k1):xs) `lessVars` ys
    _ `lessVars` _ = False

-- | Check if one term is less than another in a given model.

-- See "notes/kbo under assumptions" for how this works.

{-# SCC lessIn #-}
lessIn :: (Function f, Sized f, Weighted f) => Model f -> Term f -> Term f -> Maybe Strictness
lessIn model t u =
  case sizeLessIn model t u of
    Nothing -> Nothing
    Just Strict -> Just Strict
    Just Nonstrict -> lexLessIn model t u

sizeLessIn :: (Function f, Sized f, Weighted f) => Model f -> Term f -> Term f -> Maybe Strictness
sizeLessIn model t u =
  case minimumIn model m of
    Just l
      | l >  -k -> Just Strict
      | l == -k -> Just Nonstrict
    _ -> Nothing
  where
    (k, m) =
      add 1 u (add (-1) t (0, Map.empty))

    add a (App f ts) (k, m) =
      foldr (add (a * argWeight f)) (k + a * size f, m) (unpack ts)
    add a (Var x) (k, m) = (k, Map.insertWith (+) x a m)

minimumIn :: (Function f, Sized f) => Model f -> Map Var Integer -> Maybe Integer
minimumIn model t =
  liftM2 (+)
    (fmap sum (mapM minGroup (varGroups model)))
    (fmap sum (mapM minOrphan (Map.toList t)))
  where
    minGroup (lo, xs, mhi)
      | all (>= 0) sums = Just (sum coeffs * size lo)
      | otherwise =
        case mhi of
          Nothing -> Nothing
          Just hi ->
            let coeff = negate (minimum coeffs) in
            Just $
              sum coeffs * size lo +
              coeff * (size lo - size hi)
      where
        coeffs = map (\x -> Map.findWithDefault 0 x t) xs
        sums = scanr1 (+) coeffs

    minOrphan (x, k)
      | varInModel model x = Just 0
      | k < 0 = Nothing
      | otherwise = Just k

lexLessIn :: (Function f, Sized f, Weighted f) => Model f -> Term f -> Term f -> Maybe Strictness
lexLessIn _ t u | t == u = Just Nonstrict
lexLessIn cond t u
  | Just a <- fromTerm t,
    Just b <- fromTerm u,
    Just x <- lessEqInModel cond a b = Just x
  | Just a <- fromTerm t,
    any isJust
      [ lessEqInModel cond a b
      | v <- properSubterms u, Just b <- [fromTerm v]] =
        Just Strict
lexLessIn cond (App f ts) (App g us)
  | f == g = loop ts us
  | f << g = Just Strict
  | otherwise = Nothing
  where
    loop Empty Empty = Just Nonstrict
    loop (Cons t ts) (Cons u us)
      | t == u = loop ts us
      | otherwise =
        case lessIn cond t u of
          Nothing -> Nothing
          Just Strict -> Just Strict
          Just Nonstrict ->
            let Just sub = unify t u in
            loop (subst sub ts) (subst sub us)
    loop _ _ = error "incorrect function arity"
lexLessIn _ t _ | isMinimal t = Just Nonstrict
lexLessIn _ _ _ = Nothing

class Sized a where
  -- | Compute the size.
  size  :: a -> Integer

class Weighted f where
  argWeight :: f -> Integer

instance (Weighted f, Labelled f) => Weighted (Fun f) where
  argWeight = argWeight . fun_value

weightedVars :: (Weighted f, Labelled f) => Term f -> [(Var, Integer)]
weightedVars t = collate sum (loop 1 t)
  where
    loop k (Var x) = [(x, k)]
    loop k (App f ts) =
      concatMap (loop (k * argWeight f)) (unpack ts)

instance (Labelled f, Sized f) => Sized (Fun f) where
  size = size . fun_value

instance (Labelled f, Sized f, Weighted f) => Sized (TermList f) where
  size = aux 0
    where
      aux n Empty = n
      aux n (Cons (App f t) u) =
        aux (n + size f + argWeight f * size t) u
      aux n (Cons (Var _) t) = aux (n+1) t

instance (Labelled f, Sized f, Weighted f) => Sized (Term f) where
  size = size . singleton

instance (Labelled f, Sized f, Weighted f) => Sized (Equation f) where
  size (x :=: y) = size x + size y


text:
                            {{field.title}}

                        Toggle

                                Title
                                <input type="text" class="form-control" placeholder="Enter a title" value="{{field.title}}">

                                Command
                                <input type="text" class="form-control" placeholder="Enter a command">

                            <button type="submit" class="btn btn-success btn-block">Update</button>


text:
layout: post
date: 2015-11-21
title: "Pronovias BELUGA Sleeveless Chapel Train Aline/Princess Open Back"
category: Pronovias
tags: [Pronovias,Aline/Princess ,Open Back,V-neck,Chapel Train,Sleeveless,Gauze]
---
### Pronovias BELUGA
Just **$359.99**
###   Sleeveless Chapel Train Aline/Princess  Open Back

BRANDS	Pronovias

Silhouette	Aline/Princess

Trend	Open Back

Neckline	V-neck

Hemline/Train	Chapel Train

Sleeve	Sleeveless

Fabric	Gauze

Buy it: [https://www.readybrides.com/en/pronovias/4293-pronovias-beluga.html](https://www.readybrides.com/en/pronovias/4293-pronovias-beluga.html)


text:
package smarthosting

// EndpointMap Endpoint Data
var EndpointMap map[string]string

// EndpointType regional or central
var EndpointType = "regional"

// GetEndpointMap Get Endpoint Data Map
func GetEndpointMap() map[string]string {
	if EndpointMap == nil {
		EndpointMap = map[string]string{
			"cn-shanghai-internal-test-1": "smarthosting.aliyuncs.com",
			"cn-beijing-gov-1":            "smarthosting.aliyuncs.com",
			"cn-shenzhen-su18-b01":        "smarthosting.aliyuncs.com",
			"cn-beijing":                  "smarthosting.aliyuncs.com",
			"cn-shanghai-inner":           "smarthosting.aliyuncs.com",
			"cn-shenzhen-st4-d01":         "smarthosting.aliyuncs.com",
			"cn-haidian-cm12-c01":         "smarthosting.aliyuncs.com",
			"cn-hangzhou-internal-prod-1": "smarthosting.aliyuncs.com",
			"cn-north-2-gov-1":            "smarthosting.aliyuncs.com",
			"cn-yushanfang":               "smarthosting.aliyuncs.com",
			"cn-qingdao":                  "smarthosting.aliyuncs.com",
			"cn-hongkong-finance-pop":     "smarthosting.aliyuncs.com",
			"cn-shanghai":                 "smarthosting.aliyuncs.com",
			"cn-shanghai-finance-1":       "smarthosting.aliyuncs.com",
			"cn-hongkong":                 "smarthosting.aliyuncs.com",
			"cn-beijing-finance-pop":      "smarthosting.aliyuncs.com",
			"cn-wuhan":                    "smarthosting.aliyuncs.com",
			"us-west-1":                   "smarthosting.aliyuncs.com",
			"cn-shenzhen":                 "smarthosting.aliyuncs.com",
			"cn-zhengzhou-nebula-1":       "smarthosting.aliyuncs.com",
			"rus-west-1-pop":              "smarthosting.aliyuncs.com",
			"cn-shanghai-et15-b01":        "smarthosting.aliyuncs.com",
			"cn-hangzhou-bj-b01":          "smarthosting.aliyuncs.com",
			"cn-hangzhou-internal-test-1": "smarthosting.aliyuncs.com",
			"eu-west-1-oxs":               "smarthosting.aliyuncs.com",
			"cn-zhangbei-na61-b01":        "smarthosting.aliyuncs.com",
			"cn-beijing-finance-1":        "smarthosting.aliyuncs.com",
			"cn-hangzhou-internal-test-3": "smarthosting.aliyuncs.com",
			"cn-hangzhou-internal-test-2": "smarthosting.aliyuncs.com",
			"cn-shenzhen-finance-1":       "smarthosting.aliyuncs.com",
			"cn-hangzhou-test-306":        "smarthosting.aliyuncs.com",
			"cn-huhehaote-nebula-1":       "smarthosting.aliyuncs.com",
			"cn-shanghai-et2-b01":         "smarthosting.aliyuncs.com",
			"cn-hangzhou-finance":         "smarthosting.aliyuncs.com",
			"ap-southeast-1":              "smarthosting.aliyuncs.com",
			"cn-beijing-nu16-b01":         "smarthosting.aliyuncs.com",
			"cn-edge-1":                   "smarthosting.aliyuncs.com",
			"cn-fujian":                   "smarthosting.aliyuncs.com",
			"us-east-1":                   "smarthosting.aliyuncs.com",
			"ap-northeast-2-pop":          "smarthosting.aliyuncs.com",
			"cn-shenzhen-inner":           "smarthosting.aliyuncs.com",
			"cn-zhangjiakou-na62-a01":     "smarthosting.aliyuncs.com",
			"cn-hangzhou":                 "smarthosting.aliyuncs.com",
		}
	}
	return EndpointMap
}

// GetEndpointType Get Endpoint Type Value
func GetEndpointType() string {
	return EndpointType
}


text:
SELECT count(*) FROM table_with_header
--!
34816
--! name: filter with header
SELECT *
FROM table_with_header
WHERE data = 'data'
--!
--! name: simple_scan with footer
SELECT count(*) FROM table_with_footer
--!
34816
--! name: filter with footer
SELECT *
FROM table_with_footer
WHERE data = 'data'
--!
--! name: simple_scan with header and footer
SELECT count(*) FROM table_with_header_and_footer
--!
34816
--! name: filter with header and footer
SELECT *
FROM table_with_header_and_footer
WHERE data = 'data'
--!


text:
require 'opta/opta'

module Opta
  class Api
    include Opta::Response

    attr_accessor :token

    def initialize(token)
      self.token = token
    end

    def squads(tournament)
      response_collection('squads', tmcl: tournament, detailed: 'yes', _pgSz: 1000)
    end

    def match_statistics(match)
      response_member('matchstats', match)
    end

    def match_event(match)
      response_member('matchevent', match)
    end

    def match_list(tournament)
      response_pages('match', tmcl: tournament, live: 'yes')
    end

    def tournament_schedule(tournament)
      response_member('tournamentschedule', tournament)
    end
  end
end


text:
<?php

namespace Oro\Bundle\WorkflowBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

use Doctrine\ORM\EntityManager;
use Doctrine\Common\Persistence\ManagerRegistry;

use Oro\Bundle\WorkflowBundle\Entity\ProcessJob;

class ExecuteProcessJobCommand extends ContainerAwareCommand
{
    const NAME = 'oro:process:execute:job';

    /**
     * @var ManagerRegistry
     */
    protected $registry;

    /**
     * @return ManagerRegistry
     */
    protected function getRegistry()
    {
        if (!$this->registry) {
            $this->registry = $this->getContainer()->get('doctrine');
        }

        return $this->registry;
    }

    /**
     * @inheritdoc
     */
    public function configure()
    {
        $this->setName(self::NAME)
            ->setDescription('Execute process job with specified identifiers')
            ->addOption(
                'id',
                null,
                InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY,
                'Identifiers of the process jobs'
            );
    }

    /**
     * @inheritdoc
     */
    public function execute(InputInterface $input, OutputInterface $output)
    {
        $registry      = $this->getRegistry();
        $processJobIds = $input->getOption('id');
        $processJobs   = $registry->getRepository('OroWorkflowBundle:ProcessJob')->findByIds($processJobIds);

        if (!$processJobs) {
            $output->writeln('<error>Process jobs with passed identifiers do not exist</error>');
            return;
        }

        /** @var EntityManager $entityManager */
        $entityManager = $registry->getManagerForClass('OroWorkflowBundle:ProcessJob');
        $processHandler    = $this->getContainer()->get('oro_workflow.process.process_handler');

        /** @var ProcessJob $processJob */
        foreach ($processJobs as $processJob) {
            $processId = $processJob->getId();
            $entityManager->beginTransaction();
            try {
                $processHandler->handleJob($processJob);
                $entityManager->remove($processJob);
                $entityManager->flush();
                $entityManager->commit();

                $output->writeln(sprintf('<info>Process %s successfully finished</info>', $processId));
            } catch (\Exception $e) {
                $entityManager->rollback();

                $output->writeln(sprintf('<error>Process %s failed: %s</error>', $processId, $e->getMessage()));
            }
        }
    }
}


text:
@class IDEConfigurableDataNode, IDEConfigurableDataSource, NSArray, NSControl, NSMenu, NSOutlineView, NSPasteboard, NSString, NSTableColumn;

@protocol XCEDataRootAdapterP <NSObject>

@optional
- (BOOL)dataSource:(IDEConfigurableDataSource *)arg1 filterDisplayedRootNode:(IDEConfigurableDataNode *)arg2;
- (void)dataSource:(IDEConfigurableDataSource *)arg1 acceptDroppedItems:(NSArray *)arg2 atChildIndex:(long long)arg3;
- (BOOL)dataSource:(IDEConfigurableDataSource *)arg1 canAcceptDroppedItem:(id)arg2 atChildIndex:(long long)arg3;
- (BOOL)useOrganizerStyleDragAndDrop;
- (void)dataSource:(IDEConfigurableDataSource *)arg1 outlineView:(NSOutlineView *)arg2 sortDescriptorsDidChange:(NSArray *)arg3;
- (BOOL)dataSource:(IDEConfigurableDataSource *)arg1 control:(NSControl *)arg2 didFailToFormatString:(NSString *)arg3 errorDescription:(NSString *)arg4;
- (unsigned long long)outlineView:(NSOutlineView *)arg1 validateDrop:(id <NSDraggingInfo>)arg2 proposedItem:(id)arg3 proposedChildIndex:(long long)arg4;
- (BOOL)outlineView:(NSOutlineView *)arg1 acceptDrop:(id <NSDraggingInfo>)arg2 item:(id)arg3 childIndex:(long long)arg4;
- (BOOL)outlineView:(NSOutlineView *)arg1 createItemsFromPasteboard:(NSPasteboard *)arg2;
- (BOOL)outlineView:(NSOutlineView *)arg1 writeItems:(NSArray *)arg2 toPasteboard:(NSPasteboard *)arg3;
- (NSArray *)dataSource:(IDEConfigurableDataSource *)arg1 pasteboardFilenamesForNodes:(NSArray *)arg2;
- (NSMenu *)dataSource:(IDEConfigurableDataSource *)arg1 contextMenuForSelectedNodes:(NSArray *)arg2;
- (void)dataSource:(IDEConfigurableDataSource *)arg1 askToDeleteRootNodes:(NSArray *)arg2 nonRootNodes:(NSArray *)arg3;
- (void)updateAndSaveRoots;
- (void)textDidEndEditing;
- (BOOL)selectDataNode:(IDEConfigurableDataNode *)arg1;
- (BOOL)doubleClickDataNode:(IDEConfigurableDataNode *)arg1 inColumn:(NSTableColumn *)arg2;
- (BOOL)removeRootDataNode:(IDEConfigurableDataNode *)arg1;
- (BOOL)moveDataNodes:(NSArray *)arg1 toRootIndex:(long long)arg2;
- (BOOL)addRootPaths:(NSArray *)arg1 atIndex:(long long)arg2;
@end


text:
<?php

Yii::import('application.modules.comment.events.CommentEvent');
Yii::import('application.modules.notify.NotifyModule');
Yii::import('application.modules.blog.models.Post');
Yii::import('application.modules.blog.models.Blog');

class NotifyNewCommentListener
{
    public static function onNewComment(CommentEvent $event)
    {
        $comment = $event->getComment();

        $module = $event->getModule();

        $parent = $comment->getParent();

        //ответ на комментарий
        if ($comment->hasParent()) {

            if (null !== $parent && $parent->user_id) {

                $notify = NotifySettings::model()->getForUser($parent->user_id);

                if (null !== $notify && $notify->isNeedSendForCommentAnswer()) {

                    Yii::app()->mail->send(
                        $module->email,
                        $parent->email,
                        Yii::t(
                            'NotifyModule.notify',
                            'Reply to your comment on the website "{app}"!',
                            ['{app}' => Chtml::encode(Yii::app()->name)]
                        ),
                        Yii::app()->getController()->renderPartial(
                            'comment-reply-notify-email',
                            ['model' => $comment],
                            true
                        )
                    );
                }
            }
        }

        //нотификация автору поста
        if ('Post' === $comment->model) {

            $post = Post::model()->cache(Yii::app()->getModule('yupe')->coreCacheTime)->with(['createUser'])->get((int)$comment->model_id);

            if (null !== $post) {

                //пропускаем автора поста + если отвечают на комментарий автора поста - он уже получил уведомление выше
                if($comment->user_id != $post->create_user_id) {

                    $notify = NotifySettings::model()->getForUser($post->create_user_id);

                    if (null != $notify && $notify->isNeedSendForNewPostComment()) {

                        Yii::app()->mail->send(
                            $module->email,
                            $post->createUser->email,
                            Yii::t(
                                'NotifyModule.notify',
                                'New comment to your post on website "{app}"!',
                                ['{app}' => Chtml::encode(Yii::app()->name)]
                            ),
                            Yii::app()->getController()->renderPartial(
                                'comment-new-notify-email',
                                ['model' => $comment],
                                true
                            )
                        );
                    }
                }
            }
        }
    }
}


text:
<?php

namespace Axiom\Rivescript\Cortex\Triggers;

use Axiom\Rivescript\Contracts\Trigger as TriggerContract;

abstract class Trigger implements TriggerContract
{
    public function triggerFound()
    {
        return true;
    }

    public function triggerNotFound()
    {
        return false;
    }

    /**
     * Parse the response through the available tags.
     *
     * @param string $response
     *
     * @return string
     */
    protected function parseTags($trigger, $input)
    {
        synapse()->tags->each(function ($tag) use (&$trigger, $input) {
            $class = "\\Axiom\\Rivescript\\Cortex\\Tags\\$tag";
            $tagClass = new $class('trigger');

            $trigger = $tagClass->parse($trigger, $input);
        });

        return mb_strtolower($trigger);
    }
}


text:
/**
 * @fileOverview Provides the Server Side Access API for CrowdLogger remote modules
 * (CLRMs). There are two parts -- the CrowdLogger-side interface (CLI) and
 * the sandbox- side interface (SBI). CRMs communicate with the SBI, which in
 * turn communicates with the CLI, which has access to the CROWDLOGGER
 * object.
 *
 * %%LICENSE%%
 *
 * @author hfeild
 *
 * @version %%VERSION%%
 */

CLRMI.prototype.ServerSideAccess = function(api){
    // Private variables.
    var that = this;

    // Private functions.
    var wrapCallback;

    // Public functions.
    // this.sendData; this.sendPostData; this.sendGetData;

    /**
     * Serves as a wrapper for callback. Given a set of options (e.g., to one
     * of the public methods below), this function will create and register a
     * callback wrapper that can support on_success, on_error, and on_chunk.
     *
     * @param {object} opts  A map of options.
     * OPTIONAL:
     *

     *
{function} on_success  Called if the event field of the object
     *                               passed to the callback is 'on_success'. The
     *                               value of the 'data' field will be passed
     *                               to this function.
     *
{function} on_error    Called if the event field of the object
     *                               passed to the callback is 'on_error'. The
     *                               value of the 'error' field will be passed
     *                               to this function.
     *
{function} on_chunk    Called if the event field of the object
     *                               passed to the callback is 'on_chunk'. The
     *                               value of the 'data' field will be passed
     *                               to this function as well as a 'next' and
     *                               'abort' function.
     *

     * @return The id of the registered callback.
     */
    wrapCallback = function(opts){
        var callbackID;
        var callback = function(params){
            if( params.event === 'on_error' && opts.on_error ){
                opts.on_error(params.error);
            } else if( params.event === 'on_success' && opts.on_success ) {
                opts.on_success(params.data);
            }
            api.base.unregisterCallback(callbackID);
        };

        callbackID = api.base.registerCallback(callback);
        return callbackID;
    };

    // Public function definitions.

    /**
     * Sends data to the given url.
     *
     * @param {object} opts     A map of options:
     * REQUIRED:
     *

     *
{string} url             The URL to send the data to.
     *
{string} method          One of GET or POST.
     *

     * OPTIONAL:
     *

     *
{object|string} data      The data to send.
     *
{boolean} bypassFirewallCheck  If true, then we don't check to
     *                                 see if the internet is accessible.
     *
{string} pingURL         The URL to ping to check if there's an
     *                                 internet connection. This defaults to
     *                                 the CrowdLogger server.
     *
{function} on_success    The function to call on success. Should
     *                                 expect the server response as its only
     *                                 argument.
     *
{function} on_error      Invoked if an error is encountered.
     *

     * @throws CLIException if required options are missing.
     */
    this.sendData = function(opts){
        // This will throw an exception if there are missing arguments.
        api.util.checkArgs(opts, ['url','method'], 'clrmi.ssa.sendData');

        // Pass the data one to the CLI.
        api.base.invokeCLIFunction({
            apiName: 'ssa',
            functionName: 'sendData',
            options: {
                callbackID: wrapCallback(opts),
                data: opts.data,
                url: opts.url,
                method: opts.method,
                bypassFirewallCheck: opts.bypassFirewallCheck,
                pingURL: opts.pingURL
            }
        });

    };

    /**
     * Sends POST data to the given url.
     *
     * @param {object} opts     A map of options:
     * REQUIRED:
     *

     *
{string} url             The URL to send the data to.
     *

     * OPTIONAL:
     *

     *
{object|string} data      The data to send.
     *
{boolean} bypassFirewallCheck  If true, then we don't check to
     *                                 see if the internet is accessible.
     *
{string} pingURL         The URL to ping to check if there's an
     *                                 internet connection. This defaults to
     *                                 the CrowdLogger server.
     *
{function} on_success    The function to call on success. Should
     *                                 expect the server response as its only
     *                                 argument.
     *
{function} on_error      Invoked if an error is encountered.
     *

     * @throws CLIException if required options are missing.
     */
    this.sendPostData = function(opts){
        opts.method = 'POST';
        that.sendData(opts);
    };

    /**
     * Sends GET data to the given url.
     *
     * @param {object} opts     A map of options:
     * REQUIRED:
     *

     *
{string} url             The URL to send the data to.
     *

     * OPTIONAL:
     *

     *
{object|string} data      The data to send.
     *
{boolean} bypassFirewallCheck  If true, then we don't check to
     *                                 see if the internet is accessible.
     *
{string} pingURL         The URL to ping to check if there's an
     *                                 internet connection. This defaults to
     *                                 the CrowdLogger server.
     *
{function} on_success    The function to call on success. Should
     *                                 expect the server response as its only
     *                                 argument.
     *
{function} on_error      Invoked if an error is encountered.
     *

     * @throws CLIException if required options are missing.
     */
    this.sendGetData = function(opts){
        opts.method = 'GET';
        that.sendData(opts);
    };

}


text:
<?php

namespace DCS\OAuthBundle\Event;

use Symfony\Component\EventDispatcher\Event;
use DCS\OAuthBundle\Entity\User;
use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface;

class UserEvent extends Event
{
    /**
     * @var \DCS\OAuthBundle\Entity\User
     */
    private $user;

    /**
     * @var \HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface
     */
    private $userResponse;

    public function __construct(User $user, UserResponseInterface $userResponse)
    {
        $this->user = $user;
        $this->userResponse = $userResponse;
    }

    /**
     * Get user
     *
     * @return \DCS\OAuthBundle\Entity\User
     */
    public function getUser()
    {
        return $this->user;
    }

    /**
     * Get userResponse
     *
     * @return \HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface
     */
    public function getUserResponse()
    {
        return $this->userResponse;
    }

    /**
     * Get name of the provider
     *
     * @return string
     */
    public function getProviderName()
    {
        return $this->userResponse->getResourceOwner()->getName();
    }
}