text:
package com.nutiteq.advancedmap.activity;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.webkit.WebView;
import android.widget.RelativeLayout;
import android.widget.ZoomControls;

import com.nutiteq.MapView;
import com.nutiteq.advancedmap.R;
import com.nutiteq.components.Components;
import com.nutiteq.components.MapPos;
import com.nutiteq.components.Options;
import com.nutiteq.datasources.raster.MBOnlineRasterDataSource;
import com.nutiteq.geometry.Marker;
import com.nutiteq.layers.raster.UTFGridRasterLayer;
import com.nutiteq.layers.raster.deprecated.UtfGridLayerInterface;
import com.nutiteq.log.Log;
import com.nutiteq.projections.EPSG3857;
import com.nutiteq.style.MarkerStyle;
import com.nutiteq.ui.Label;
import com.nutiteq.ui.ViewLabel;
import com.nutiteq.utils.NetUtils;
import com.nutiteq.utils.UiUtils;
import com.nutiteq.utils.UnscaledBitmapLoader;
import com.nutiteq.vectorlayers.MarkerLayer;
import com.nutiteq.advancedmap.maplisteners.UtfGridLayerEventListener;

/**
 * Demonstrates usage of MapBoxMapLayer - online tile-based map source
 *
 * It is almost like basic tile-based source, with some important additions:
 * a) load metadata as json, here map legend HTML and template for map popup is loaded from this
 * b) load UTFGrid tiles as json in addition to map graphics. This enables tooltip on map click,
 *  even through it is raster data source
 *  Note that from SDK point of view the grid tooltip is an invisible Marker in MarkerLayer, which has open Label.
 *
 *  jMoustache library is required to resolve popup templates.
 *
 * @author jaak
 *
 */
public class MapBoxMapActivity extends Activity {

    // Please configure your ID and account here
    private static final String MAPBOX_MAPID = "geography-class";
    private static final String MAPBOX_ACCOUNT = "nutiteq";

    /**
     * Asynchronous task for loading metadata.
     */
    public class LoadMetadataTask extends AsyncTask<Void, Void, JSONObject> {

        private UtfGridLayerEventListener mapListener;
        private String account;
        private String map;

        public LoadMetadataTask(UtfGridLayerEventListener mapListener, String account, String map){
            this.mapListener = mapListener;
            this.account = account;
            this.map = map;
        }

        protected JSONObject doInBackground(Void... v) {
            try {
                String url = "http://api.tiles.mapbox.com/v3/"+account+"."+map+".json";
                String json = NetUtils.downloadUrl(url, null, true, "UTF-8");
                if(json == null)
                    return null;
                JSONObject metaData = new JSONObject(json);
                Log.debug("metadata loaded: "+metaData.toString());
                return metaData;

            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        protected void onPostExecute(JSONObject metaData) {
            if(metaData == null){
                Log.error("no metadata found");
                return;
            }
            String template = metaData.optString("template");
            this.mapListener.setTemplate(template);

            String legend = metaData.optString("legend");
            if(legend != null && !legend.equals("")){
                Log.debug("legend: "+legend);
                UiUtils.addWebView((RelativeLayout) findViewById(R.id.mainView), MapBoxMapActivity.this, legend, 320, 300);
            }else{
                Log.debug("no legend found");
            }

        }
    }

    private MapView mapView;

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

        setContentView(R.layout.main);

        // enable logging for troubleshooting - optional
        Log.enableAll();
        Log.setTag("mapbox");

        // 1. Get the MapView from the Layout xml - mandatory
        mapView = (MapView) findViewById(R.id.mapView);

        // Optional, but very useful: restore map state during device rotation,
        // it is saved in onRetainNonConfigurationInstance() below
        Components retainObject = (Components) getLastNonConfigurationInstance();
        if (retainObject != null) {
            // just restore configuration, skip other initializations
            mapView.setComponents(retainObject);
            // recreate listener
            UtfGridLayerEventListener oldListener = (UtfGridLayerEventListener ) mapView.getOptions().getMapListener();
            UtfGridLayerEventListener mapListener = new UtfGridLayerEventListener(this, mapView, oldListener.getLayer(), oldListener.getClickMarker());
            mapView.getOptions().setMapListener(mapListener);
            mapView.getOptions().setMapListener(null);

            LoadMetadataTask task = new LoadMetadataTask(mapListener, MAPBOX_ACCOUNT, MAPBOX_MAPID);
            task.execute();
            return;
        } else {
            // 2. create and set MapView components - mandatory
            Components components = new Components();
            mapView.setComponents(components);
        }

        // 3. Define map layer for basemap - mandatory.

        // MapBox Streets
        //		final MapBoxMapLayer mapLayer = new MapBoxMapLayer(new EPSG3857(), 0, 19, 333,
        //				MAPBOX_ACCOUNT, "map-j6a1wkx0");

        // MapBox Satellite
        MBOnlineRasterDataSource dataSource = new MBOnlineRasterDataSource(new EPSG3857(), 0, 19, MAPBOX_ACCOUNT, MAPBOX_MAPID);
        UTFGridRasterLayer mapLayer = new UTFGridRasterLayer(dataSource, dataSource, 334);

        mapView.getLayers().setBaseLayer(mapLayer);

        // add a layer and marker for click labels
        // define small invisible Marker, as Label requires some Marker
        Bitmap pointMarker = UnscaledBitmapLoader.decodeResource(getResources(), R.drawable.point);
        MarkerStyle markerStyle = MarkerStyle.builder().setBitmap(pointMarker).setSize(0.01f).setColor(0).build();

        //  define label as WebView to show HTML
        WebView labelView = new WebView(this);
        // It is important to set size, exception will come otherwise
        labelView.layout(0, 0, 150, 150);
        Label label = new ViewLabel("", labelView, new Handler());

        Marker clickMarker = new Marker(new MapPos(0,0), label, markerStyle, null);

        MarkerLayer clickMarkerLayer = new MarkerLayer(new EPSG3857());
        clickMarkerLayer.add(clickMarker);
        mapView.getLayers().addLayer(clickMarkerLayer);

        // set initial map view camera - optional. "World view" is default
        // Location: Estonia
        //mapView.setFocusPoint(mapView.getLayers().getBaseLayer().getProjection().fromWgs84(24.5f, 58.3f));
        mapView.setFocusPoint(new MapPos(2745202.3f, 8269676.0f));
        // rotation - 0 = north-up
        mapView.setMapRotation(0f);
        // zoom - 0 = world, like on most web maps
        mapView.setZoom(5.0f);
        // tilt means perspective view. Default is 90 degrees for "normal" 2D map view, minimum allowed is 30 degrees.
        mapView.setTilt(90.0f);

        // Activate some mapview options to make it smoother - optional
        mapView.getOptions().setPreloading(false);
        mapView.getOptions().setSeamlessHorizontalPan(true);
        mapView.getOptions().setTileFading(true);
        mapView.getOptions().setKineticPanning(true);
        mapView.getOptions().setDoubleClickZoomIn(true);
        mapView.getOptions().setDualClickZoomOut(true);

        // mapView.getConstraints().setTiltRange(new Range(90,90));

        // set sky bitmap - optional, default - white
        mapView.getOptions().setSkyDrawMode(Options.DRAW_BITMAP);
        mapView.getOptions().setSkyOffset(4.86f);
        mapView.getOptions().setSkyBitmap(
                UnscaledBitmapLoader.decodeResource(getResources(),
                        R.drawable.sky_small));

        // Map background, visible if no map tiles loaded - optional, default - white
        mapView.getOptions().setBackgroundPlaneDrawMode(Options.DRAW_BITMAP);
        mapView.getOptions().setBackgroundPlaneBitmap(
                UnscaledBitmapLoader.decodeResource(getResources(),
                        R.drawable.background_plane));
        mapView.getOptions().setClearColor(Color.WHITE);

        // configure texture caching - optional, suggested
        mapView.getOptions().setTextureMemoryCacheSize(20 * 1024 * 1024);
        mapView.getOptions().setCompressedMemoryCacheSize(8 * 1024 * 1024);

        // define online map persistent caching - optional, suggested. Default - no caching
        // FIXME jaakl: currently disabled caching to enforce loading utfgrid. there is no utfgrid cache yet
        //        mapView.getOptions().setPersistentCachePath(this.getDatabasePath("mapcache_mapbox").getPath());
        // set persistent raster cache limit to 100MB
        mapView.getOptions().setPersistentCacheSize(100 * 1024 * 1024);

        // 4. zoom buttons using Android widgets - optional
        // get the zoomcontrols that was defined in main.xml
        ZoomControls zoomControls = (ZoomControls) findViewById(R.id.zoomcontrols);
        // set zoomcontrols listeners to enable zooming
        zoomControls.setOnZoomInClickListener(new View.OnClickListener() {
            public void onClick(final View v) {
                mapView.zoomIn();
            }
        });
        zoomControls.setOnZoomOutClickListener(new View.OnClickListener() {
            public void onClick(final View v) {
                mapView.zoomOut();
            }
        });

    }

    @Override
    protected void onStart() {
        mapView.startMapping();
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mapView.stopMapping();
    }

    public MapView getMapView() {
        return mapView;
    }

}


text:
"""Example implementation of the 2nd order Moving Average (MA2) model."""

from functools import partial

import numpy as np
import scipy.stats as ss

import elfi

def MA2(t1, t2, n_obs=100, batch_size=1, random_state=None):
    r"""Generate a sequence of samples from the MA2 model.

    The sequence is a moving average

        x_i = w_i + \theta_1 w_{i-1} + \theta_2 w_{i-2}

    where w_i are white noise ~ N(0,1).

    Parameters
    ----------
    t1 : float, array_like
    t2 : float, array_like
    n_obs : int, optional
    batch_size : int, optional
    random_state : RandomState, optional

    """
    # Make inputs 2d arrays for broadcasting with w
    t1 = np.asanyarray(t1).reshape((-1, 1))
    t2 = np.asanyarray(t2).reshape((-1, 1))
    random_state = random_state or np.random

    # i.i.d. sequence ~ N(0,1)
    w = random_state.randn(batch_size, n_obs + 2)
    x = w[:, 2:] + t1 * w[:, 1:-1] + t2 * w[:, :-2]
    return x

def autocov(x, lag=1):
    """Return the autocovariance.

    Assumes a (weak) univariate stationary process with mean 0.
    Realizations are in rows.

    Parameters
    ----------
    x : np.array of size (n, m)
    lag : int, optional

    Returns
    -------
    C : np.array of size (n,)

    """
    x = np.atleast_2d(x)
    # In R this is normalized with x.shape[1]
    C = np.mean(x[:, lag:] * x[:, :-lag], axis=1)
    return C

def get_model(n_obs=100, true_params=None, seed_obs=None):
    """Return a complete MA2 model in inference task.

    Parameters
    ----------
    n_obs : int, optional
        observation length of the MA2 process
    true_params : list, optional
        parameters with which the observed data is generated
    seed_obs : int, optional
        seed for the observed data generation

    Returns
    -------
    m : elfi.ElfiModel

    """
    if true_params is None:
        true_params = [.6, .2]

    y = MA2(*true_params, n_obs=n_obs, random_state=np.random.RandomState(seed_obs))
    sim_fn = partial(MA2, n_obs=n_obs)

    m = elfi.ElfiModel()
    elfi.Prior(CustomPrior1, 2, model=m, name='t1')
    elfi.Prior(CustomPrior2, m['t1'], 1, name='t2')
    elfi.Simulator(sim_fn, m['t1'], m['t2'], observed=y, name='MA2')
    elfi.Summary(autocov, m['MA2'], name='S1')
    elfi.Summary(autocov, m['MA2'], 2, name='S2')
    elfi.Distance('euclidean', m['S1'], m['S2'], name='d')
    return m

# Define prior t1 as in Marin et al., 2012 with t1 in range [-b, b]
class CustomPrior1(elfi.Distribution):
    """Define prior for t1 in range [-a, a].

    As in Marin et al., 2012.
    """

    @classmethod
    def rvs(cls, b, size=1, random_state=None):
        """Get random variates.

        Parameters
        ----------
        b : float
        size : int or tuple, optional
        random_state : RandomState, optional

        Returns
        -------
        arraylike

        """
        u = ss.uniform.rvs(loc=0, scale=1, size=size, random_state=random_state)
        t1 = np.where(u < 0.5, np.sqrt(2. * u) * b - b, -np.sqrt(2. * (1. - u)) * b + b)
        return t1

    @classmethod
    def pdf(cls, x, b):
        """Return density at `x`.

        Parameters
        ----------
        x : float or arraylike
        b : float

        Returns
        -------
        arraylike

        """
        p = 1. / b - np.abs(x) / (b * b)
        # set values outside of [-b, b] to zero
        p = np.where(p < 0., 0., p)
        return p

class CustomPrior2(elfi.Distribution):
    """Define prior for t2 conditionally on t1 in range [-a, a].

    As in Marin et al., 2012.
    """

    @classmethod
    def rvs(cls, t1, a, size=1, random_state=None):
        """Get random variates.

        Parameters
        ----------
        t1 : float or arraylike
        a : float
        size : int or tuple, optional
        random_state : RandomState, optional

        Returns
        -------
        arraylike

        """
        locs = np.maximum(-a - t1, -a + t1)
        scales = a - locs
        t2 = ss.uniform.rvs(loc=locs, scale=scales, size=size, random_state=random_state)
        return t2

    @classmethod
    def pdf(cls, x, t1, a):
        """Return density at `x`.

        Parameters
        ----------
        x : float or arraylike
        t1 : float or arraylike
        a : float

        Returns
        -------
        arraylike

        """
        locs = np.maximum(-a - t1, -a + t1)
        scales = a - locs
        p = (x >= locs) * (x <= locs + scales) * 1 / np.where(scales > 0, scales, 1)
        return p

redpajama_set_name: RedPajamaGithub


text:
namespace hiberlite{

template<class AV>
void KillChildren::notifyInitWalk(AV& av)
{
	rowId=std::stack<sqlid_t>();
	rowId.push(av.getRootId());
}

template<class AV>
void KillChildren::notifyDoneWalk(AV& av)
{
}

template<class AV, class E, class S>
void KillChildren::act(AV& av, collection_nvp<E,S> nvp )
{
	av.diveTable(nvp.name);
		std::string tab=av.getScope().table();
		std::vector<sqlid_t> children=Database::dbSelectChildIds(av.getConnection(), tab, rowId.top());
		for(size_t i=0;i<children.size();i++){
			E* entry;
			construct(av,&entry,static_cast<unsigned int>(0));
				rowId.push(children[i]);
					sql_nvp<E> el("item",*entry);
					av & el;
				rowId.pop();
			destroy(*this, entry, static_cast<unsigned int>(0));
		}
	av.pop();

	Database::dbDeleteRows(av.getConnection(),tab,HIBERLITE_PARENTID_COLUMN,rowId.top());
}

template<class C>
void ChildKiller::killChildren(bean_key key, C& bean)
{
	startWalk(bean, key);
}

} //namespace hiberlite

#endif // BEANUPDATER_IMPL_HPP_INCLUDED


text:
<!DOCTYPE html>

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

    <title>Vivian Mo- Projects</title>

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

    <link href="css/3-col-portfolio.css" rel="stylesheet">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,700,300italic,400italic,700italic" rel="stylesheet" type="text/css">

                        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                            Toggle navigation

                        </button>
                        Vivian Mo

                                About

                                Projects

                                Gif Portfolio

                                Contact

Technical Projects

                            Mini-Med

A device that collects and displays real-time biomedical data on a website that can then be viewed by a doctor to provide a remote diagnosis

                            Remy

Interdisciplinary project that applied the sociological framework of gender scripts and used a SCOT analysis to study the technology and marketing behind fashionable wearables

                            PANDA

A remotely-programmable smart pillbox that notifies patients when it's time to take medication

                            Happy Wagon

Android app based on Stargirl's happy wagon from Jerry Spinelli's 2000 novel Stargirl

                        Scotty

An Android app that displays data from and communicates with a Bluetooth Low-Energy transceiver in real time for remote access

                        VEX Robotics

Robots, both autonomous and manually controlled, designed, built, and programmed for the VEX Robotics Competition

                        crazychipmunk

tumblr blog dedicated to gifs and graphics on which original posts have garnered 2 million reblogs and likes

                        Exploring Methods to Develop Cross-Platform Mobile Apps

Research paper exploring different methods for cross platform app development: native, hybrid, and web apps

Copyright © Vivian Mo 2015


text:
<?php

namespace app\models;

use app\models\query\EventQuery;
use app\modules\admin\models\EventLang;
use Yii;
use yii\behaviors\TimestampBehavior;

/**
 * This is the model class for table "event".
 *
 * @property integer $id
 * @property string $title
 * @property string $date
 * @property integer $status
 * @property integer $created_at
 * @property integer $updated_at
 */
class Event extends Root
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'event';
    }

    /**
     * @return \app\models\query\EventQuery|\yii\db\ActiveQuery
     */
    public static function find()
    {
        return new EventQuery(get_called_class());
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title', 'date', 'status'], 'required'],
            [['status', 'created_at', 'updated_at'], 'integer'],
            [['title', 'date'], 'string', 'max' => 255]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'title' => Yii::t('app', 'Назва'),
            'date' => Yii::t('app', 'Дата проведення'),
            'status' => Yii::t('app', 'Опубліковано'),
            'created_at' => Yii::t('app', 'Створено'),
            'updated_at' => Yii::t('app', 'Оновлено'),
        ];
    }

    /**
     * @param null $lang_id
     *
     * @return static
     */
    public function getContent($lang_id = null)
    {
        $lang_id = ($lang_id === null)? Lang::getCurrent()->id : $lang_id;
        // Для перевірки наявності перекладу поточною мовою
        $is_translate = EventLang::find()->where(['event_id' => $this->id, 'lang_id' => $lang_id ])->one();
        // Якщо немає перекладу для поточної мови - отримуємо дані для мови, встановленої по замовчуванню
        if(!$is_translate){
            $result = $this->hasOne(EventLang::className(), ['event_id' => 'id'])->where('lang_id = :lang_id', [':lang_id' => Lang::getDefaultLang()->id]);
        }else{
            // Якщо є переклад - виводимо його
            $result = $this->hasOne(EventLang::className(), ['event_id' => 'id'])->where('lang_id = :lang_id', [':lang_id' => $lang_id]);
        }
        return $result;
    }
}


text:
package com.intellij.refactoring.introduceParameterObject;

import com.intellij.openapi.options.ConfigurationException;
import com.intellij.psi.PsiNamedElement;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.changeSignature.ParameterInfo;
import com.intellij.refactoring.ui.RefactoringDialog;
import com.intellij.refactoring.util.AbstractParameterTablePanel;
import com.intellij.refactoring.util.AbstractVariableData;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;
import java.util.List;

public abstract class AbstractIntroduceParameterObjectDialog<M extends PsiNamedElement,
                                                             P extends ParameterInfo,
                                                             C extends IntroduceParameterObjectClassDescriptor<M, P>,
                                                             V extends AbstractVariableData> extends RefactoringDialog {
  protected M mySourceMethod;
  private JPanel myWholePanel;
  private JTextField mySourceMethodTextField;
  protected JCheckBox myDelegateCheckBox;
  private JPanel myParamsPanel;
  private JPanel myParameterClassPanel;

  protected AbstractParameterTablePanel<V> myParameterTablePanel;

  protected abstract String getSourceMethodPresentation();
  protected abstract JPanel createParameterClassPanel();
  protected abstract AbstractParameterTablePanel<V> createParametersPanel();

  protected abstract C createClassDescriptor();

  protected boolean isDelegateCheckboxVisible() {
    return true;
  }

  public AbstractIntroduceParameterObjectDialog(M method) {
    super(method.getProject(), true);
    mySourceMethod = method;
    setTitle(RefactoringBundle.message("refactoring.introduce.parameter.object.title"));
  }

  @Override
  protected void doAction() {
    final IntroduceParameterObjectDelegate<M, P, C> delegate = IntroduceParameterObjectDelegate.findDelegate(mySourceMethod);
    final List<P> allMethodParameters = delegate.getAllMethodParameters(mySourceMethod);
    invokeRefactoring(new IntroduceParameterObjectProcessor<M, P, C>(mySourceMethod, createClassDescriptor(), allMethodParameters, keepMethodAsDelegate()));
  }

  @Override
  protected void canRun() throws ConfigurationException {
    if (!hasParametersToExtract()) {
      throw new ConfigurationException("Nothing found to extract");
    }
  }

  @Nullable
  @Override
  protected JComponent createCenterPanel() {
    mySourceMethodTextField.setText(getSourceMethodPresentation());
    mySourceMethodTextField.setEditable(false);

    myDelegateCheckBox.setVisible(isDelegateCheckboxVisible());

    myParameterTablePanel = createParametersPanel();
    myParamsPanel.add(myParameterTablePanel, BorderLayout.CENTER);

    myParameterClassPanel.add(createParameterClassPanel(), BorderLayout.CENTER);
    return myWholePanel;
  }

  protected boolean keepMethodAsDelegate() {
    return myDelegateCheckBox.isSelected();
  }

  public boolean hasParametersToExtract() {
    for (AbstractVariableData info : myParameterTablePanel.getVariableData()) {
      if (info.passAsParameter) {
        return true;
      }
    }
    return false;
  }
}


text:
package ua.com.fielden.platform.security.tokens.attachment;

import static java.lang.String.format;

import ua.com.fielden.platform.attachment.Attachment;
import ua.com.fielden.platform.reflection.TitlesDescsGetter;
import ua.com.fielden.platform.security.ISecurityToken;
import ua.com.fielden.platform.security.tokens.Template;

/**
 * Attachment save/upload token.
 *
 * @author TG Team
 *
 */
public class Attachment_CanSave_Token implements ISecurityToken {
    private static final String ENTITY_TITLE = TitlesDescsGetter.getEntityTitleAndDesc(Attachment.class).getKey();
    public static final String TITLE = format(Template.SAVE.forTitle(), ENTITY_TITLE);
    public static final String DESC = format(Template.SAVE.forDesc(), ENTITY_TITLE);
}


text:
/* stdint.h */
typedef int uint32_t;
typedef long long uint64_t;

#if _DEBUG
#endif

#include "../mumble_plugin_win32.h"

struct guid {
	uint64_t first;
	uint64_t second;
};

uint32_t p_playerBase;
guid g_playerGUID;

/*
 * To update visit http://www.ownedcore.com/forums/world-of-warcraft/world-of-warcraft-bots-programs/wow-memory-editing
 * and look for a thread called [WoW][TheVersion] Info Dump Thread.
 *
 * Where possible, I have included in the comments the different names some posters
 * call each value, to ease in upgrading. "[_]" means the value name may or may not
 * have an underscore in it depending on who's posting the offset.
 */
static uint32_t ptr_ClientConnection=0xED5C90; // ClientConnection or CurMgrPointer
static uint32_t off_ObjectManager=0x62C; // objectManager or CurMgrOffset
static uint32_t ptr_WorldFrame=0xD93E30; // Camera[_]Pointer, CameraStruct
static uint32_t off_CameraOffset=0x7610; // Camera[_]Offset
static uint32_t ptr_PlayerName=0xED5CD0; // PlayerName
static uint32_t ptr_RealmName=0xED5E7E; // RealmName

static uint32_t off_localGUID = 0xF8; // localGUID
static uint32_t off_firstObject = 0xD8; // firstObject
static uint32_t off_nextObject = 0x3C; // nextObject
static uint32_t off_objectGUID = 0x28;

uint32_t getInt32(uint32_t ptr) {
	uint32_t result;
	SIZE_T r;
	BOOL ok=ReadProcessMemory(hProcess, (void *)ptr, &result, sizeof(uint32_t), &r);
	if (ok && (r == sizeof(uint32_t))) {
		return result;
	} else {
		return 0xffffffff;
	}
}

uint64_t getInt64(uint32_t ptr) {
	uint64_t result;
	SIZE_T r;
	BOOL ok=ReadProcessMemory(hProcess, (void *)ptr, &result, sizeof(uint64_t), &r);
	if (ok && (r == sizeof(uint64_t))) {
		return result;
	} else {
		return 0xffffffffffffffff;
	}
}

float getFloat(uint32_t ptr) {
	float result;
	SIZE_T r;
	BOOL ok=ReadProcessMemory(hProcess, (void *)ptr, &result, sizeof(float), &r);
	if (ok && (r == sizeof(float))) {
		return result;
	} else {
		return (float)0xffffffff;
	}
}

int getCStringN(uint32_t ptr, char *buffer, size_t buffersize) {
	SIZE_T r;
	BOOL ok = ReadProcessMemory(hProcess, (void *)ptr, buffer, buffersize, &r);

	/* safety net, just in case we didn't get a string back at all */
	buffer[buffersize-1] = '\0';

	if (ok && (r == buffersize)) {
		return static_cast<int>(strlen(buffer));
	} else {
		return 0;
	}
}

int getString(uint32_t ptr, std::string &buffer) {
	char buf[1024];
	int bufLength;

	bufLength = getCStringN(ptr, buf, sizeof(buf));
	buffer = buf;

	return bufLength;
}

int getWString(uint32_t ptr, std::wstring &buffer) {
	char buf[1024];
	int bufLength;
	wchar_t wbuf[1024];
	int wbufLength;

	bufLength = getCStringN(ptr, buf, sizeof(buf));
	wbufLength = MultiByteToWideChar(CP_UTF8, 0,
	                                 buf, bufLength,
	                                 wbuf, 1024);
	buffer.assign(wbuf, wbufLength);

	return wbufLength;
}

#ifdef _DEBUG
void getDebug16(uint32_t ptr) {
	unsigned char buf[16];
	SIZE_T r;
	BOOL ok=ReadProcessMemory(hProcess, (void *)ptr, &buf, sizeof(buf), &r);
	if (ok && (r == sizeof(buf))) {
		printf("%08x: %02x%02x%02x%02x %02x%02x%02x%02x %02x%02x%02x%02x %02x%02x%02x%02x\n",
		       ptr,
		       buf[0], buf[1], buf[2], buf[3],
		       buf[4], buf[5], buf[6], buf[7],
		       buf[8], buf[9], buf[10], buf[11],
		       buf[12], buf[13], buf[14], buf[15]
		      );
	}
}

void stringDebug(std::string &theString) {
	std::cout << "String length=" << theString.length() << " content=\"" << theString << "\" debug=";
	for (size_t i=0; i<theString.length(); i++) {
		if (i>0) {
			std::cout << " ";
		}
		std::cout << (unsigned int)theString[i];
	}
	std::cout << std::endl;
}
#endif

uint32_t getPlayerBase() {
	uint32_t gClientConnection;
	uint32_t sCurMgr;
	uint32_t curObj;
	guid playerGUID;
	uint32_t playerBase;

	uint32_t nextObj;
	guid GUID;

	playerBase=0;

	gClientConnection=getInt32((uint32_t)pModule + ptr_ClientConnection);
	sCurMgr=getInt32(gClientConnection + off_ObjectManager);
	if (sCurMgr != 0) {
		playerGUID.first=getInt64(sCurMgr+off_localGUID);
		playerGUID.second=getInt64(sCurMgr+off_localGUID + 0x8);
		if (playerGUID.second != 0) {
			g_playerGUID.first = playerGUID.first;
			g_playerGUID.second = playerGUID.second;

			curObj=getInt32(sCurMgr+off_firstObject); // firstObject
			while (curObj != 0) {
				nextObj=getInt32(curObj + off_nextObject); // nextObject
				GUID.first=getInt64(curObj + off_objectGUID);
				GUID.second=getInt64(curObj + off_objectGUID + 0x8);
				if (playerGUID.first == GUID.first && playerGUID.second == GUID.second) {
					playerBase = curObj;
					break;
				} else if (curObj == nextObj) {
					break;
				} else {
					curObj = nextObj;
				}
			}
		}
	}

	return playerBase;
}

void getPlayerName(std::wstring &identity) {
	std::wstring playerName, realmName;

	getWString((uint32_t)pModule + ptr_PlayerName, playerName);
	getWString((uint32_t)pModule + ptr_RealmName, realmName);

	identity = playerName + L"-" + realmName;
	//printf("Name: %ls\n", identity.data());
	return;
}

void getCamera(float camera_pos[3], float camera_front[3], float camera_top[3]) {
	uint32_t ptr1, ptr2;
	float buf[4][3];

	ptr1 = getInt32((uint32_t)pModule + ptr_WorldFrame);
	ptr2 = getInt32(ptr1+off_CameraOffset);

	peekProc((BYTE *) ptr2+0x08, buf, sizeof(buf));

	/* camera postition */
	camera_pos[0] = -buf[0][1];
	camera_pos[1] =  buf[0][2];
	camera_pos[2] =  buf[0][0];

	/* camera front vector */
	camera_front[0] = -buf[1][1];
	camera_front[1] =  buf[1][2];
	camera_front[2] =  buf[1][0];

	/* camera right vector */
#if 0 /* gets calculated in mumble client */
	camera_right[0] = -buf[2][1];
	camera_right[1] =  buf[2][2];
	camera_right[2] =  buf[2][0];
#endif

	/* camera top vector */
	camera_top[0] = -buf[3][1];
	camera_top[1] =  buf[3][2];
	camera_top[2] =  buf[3][0];
}

typedef class WowData {
		std::wstring nameAvatar;
		bool nameAvatarValid;

		guid playerGUID;
		uint32_t pointerPlayerObject;

	public:
		WowData::WowData() {
			refresh();
		}

		void WowData::updateAvatarName() {
			getPlayerName(nameAvatar);
			if (!nameAvatar.empty()) {
				nameAvatarValid = true;
			} else {
				nameAvatarValid = false;
			}
		}

		std::wstring getNameAvatar() {
			if (!nameAvatarValid) {
				updateAvatarName();
			}

			return nameAvatar;
		}

		void refresh() {
			nameAvatarValid = false;
		}
} WowData_t;

WowData_t wow;

static int fetch(float *avatar_pos, float *avatar_front, float *avatar_top, float *camera_pos, float *camera_front, float *camera_top, std::string &context, std::wstring &identity) {
	/* clear position */
	for (int i=0; i<3; i++) {
		avatar_pos[i]=avatar_front[i]=avatar_top[i]=camera_pos[i]=camera_front[i]=camera_top[i]=0.0;
	}

	/* are we still looking at the right object? */
	guid peekGUID, tempGUID;
	peekGUID.first=getInt64(p_playerBase+0x30);
	peekGUID.second=getInt64(p_playerBase+0x30+0x8);
	if (g_playerGUID.first != peekGUID.first || g_playerGUID.second != peekGUID.second) {
		/* no? Try to resynch to the new address. Happens when walking through portals quickly (aka no or short loading screen) */
		tempGUID.first = g_playerGUID.first;
		tempGUID.second = g_playerGUID.second;
		p_playerBase=getPlayerBase();
		if (tempGUID.first != g_playerGUID.first || tempGUID.first != g_playerGUID.first) {
			/* GUID of actor changed, likely a character and/or realm change */
			wow.refresh();
		}
		peekGUID.first=getInt64(p_playerBase+0x28);
		peekGUID.second=getInt64(p_playerBase+0x28+0x8);
		if (g_playerGUID.first != peekGUID.first || g_playerGUID.second != peekGUID.second) {
			/* no? we are still getting the expected GUID for our avatar, but we don't have it's current position */
			return true;
		}
	}

	context.clear();
	std::wstringstream identityStream;
	identityStream << wow.getNameAvatar();
	identity = identityStream.str();

	BOOL ok = true;

	// Wow stores as
	// North/South (+ North)
	// East/West (+ West)
	// Up/Down (+Up)
	// ... which isn't a right-hand coordinate system.

	float pos[3];
	ok = ok && peekProc((BYTE *) p_playerBase + 0xA50, pos, sizeof(float)*3);
	if (! ok) {
		if (g_playerGUID.second == 0xffffffffffffffff) {
			return false;
		} else if (g_playerGUID.second == 0) {
			return true;
		} else {
			/* FIXME need a better way to mark PlayerBase invalid */
			g_playerGUID.first=0;
			g_playerGUID.second=0;
			return true; /* we got a good reference for an avatar, but no good position */
		}
	}

	/* convert wow -> right hand coordinate system */
	avatar_pos[0] = -pos[1];
	avatar_pos[1] = pos[2];
	avatar_pos[2] = pos[0];

	float heading=0.0;
	ok = ok && peekProc((BYTE *) p_playerBase + 0xA60, &heading, sizeof(heading));
	if (! ok)
		return false;

	float pitch=0.0;
	ok = ok && peekProc((BYTE *) p_playerBase + 0xA70, &pitch, sizeof(pitch));
	if (! ok)
		return false;

	/* TODO use yaw (heading) and pitch angles */
	/* FIXME sin/cos (heading) is right from the numbers, but (-heading) is right from the sound position */
	avatar_front[0]=-sin(heading);
	avatar_front[1]=0.0;
	avatar_front[2]=cos(heading);

	// Dummy top vector, can't tilt your head sideways in wow.
	avatar_top[0]= 0.0;
	avatar_top[1]= 1.0;
	avatar_top[2]= 0.0;

	getCamera(camera_pos, camera_front, camera_top);

	if (! ok)
		return false;

	//printf("P %f %f %f -- %f %f %f \n", avatar_pos[0], avatar_pos[1], avatar_pos[2], avatar_front[0], avatar_front[1], avatar_front[2]);
	//printf("C %f %f %f -- %f %f %f \n", camera_pos[0], camera_pos[1], camera_pos[2], camera_front[0], camera_front[1], camera_front[2]);

	// is it a unit length vector?
	if (fabs((avatar_front[0]*avatar_front[0]+avatar_front[1]*avatar_front[1]+avatar_front[2]*avatar_front[2])-1.0)>0.5) {
		//		printf("F %f %f %f\n", front[0], front[1], front[2]);
		return false;
	}

	// are we around 0/0/0
	if ((fabs(avatar_pos[0])<0.1) && (fabs(avatar_pos[1])<0.1) && (fabs(avatar_pos[2])<0.1)) {
		//		printf("P %f %f %f\n", avatar_pos[0], avatar_pos[1], avatar_pos[2]);
		return false;
	}

	return true;
}

static int trylock(const std::multimap<std::wstring, unsigned long long int> &pids) {
	if (! initialize(pids, L"Wow.exe"))
		return false;

	p_playerBase=getPlayerBase();
	if (p_playerBase != 0) {
		float apos[3], afront[3], atop[3], cpos[3], cfront[3], ctop[3];
		std::string context;
		std::wstring identity;
		if (fetch(apos, afront, atop, cpos, cfront, ctop, context, identity))
			return true;
	}

	generic_unlock();
	return false;
}

static const std::wstring longdesc() {
	return std::wstring(L"Supports World of Warcraft 6.0.3 (19103), with identity support.");
}

static std::wstring description(L"World of Warcraft 6.0.3 (19103)");

static std::wstring shortname(L"World of Warcraft");

static int trylock1() {
	return trylock(std::multimap<std::wstring, unsigned long long int>());
}

static MumblePlugin wowplug = {
	MUMBLE_PLUGIN_MAGIC,
	description,
	shortname,
	NULL,
	NULL,
	trylock1,
	generic_unlock,
	longdesc,
	fetch
};

static MumblePlugin2 wowplug2 = {
	MUMBLE_PLUGIN_MAGIC_2,
	MUMBLE_PLUGIN_VERSION,
	trylock
};

extern "C" __declspec(dllexport) MumblePlugin *getMumblePlugin() {
	return &wowplug;
}

extern "C" __declspec(dllexport) MumblePlugin2 *getMumblePlugin2() {
	return &wowplug2;
}


text:
@interface SKMopidyArtist : SKMopidyModel

@end


text:
/**
 * SDC Configuration module.
 */

angular
  .module('dataCollectorApp.sdcConfiguration')
  .config(['$routeProvider', function ($routeProvider) {
    $routeProvider.when('/collector/configuration',
      {
        templateUrl: 'common/administration/sdcConfiguration/sdcConfiguration.tpl.html',
        controller: 'SDCConfigurationController',
        resolve: {
          myVar: function(authService) {
            return authService.init();
          }
        },
        data: {
          authorizedRoles: ['admin', 'creator', 'manager']
        }
      }
    );
  }])
  .controller('SDCConfigurationController', function ($scope, $rootScope, $q, Analytics, configuration, _) {

    angular.extend($scope, {
      initDefer: undefined,
      configKeys: [],
      sdcConfiguration: {}
    });

    console.log('inside method SDCConfigurationController');

    $scope.initDefer = $q.all([configuration.init()]).then(function() {
      console.log('inside method SDCConfigurationController after init');
      if(configuration.isAnalyticsEnabled()) {
        Analytics.trackPage('/collector/configuration');
      }

      $scope.sdcConfiguration = configuration.getConfiguration();
      $scope.configKeys = _.keys($scope.sdcConfiguration);
      $scope.configKeys.sort();
    });

  });


text:
void full_random_alignment_benchmark(const size_t u_n, const size_t v_n, const size_t iterations) {
    time_t seed = time(NULL);
    srand(seed);
    double time_accumulator_1 = 0;
    double time_accumulator_2 = 0;
    for (size_t j = 0; j < iterations; j++) {
        const stream_t* u = stream_create(u_n);
        float* u_data = u->data;
        const stream_t* v = stream_create(v_n);
        float* v_data = v->data;
        for (size_t i = 0; i < u_n; ++i) {
            u_data[2*i] = (float) (sqrtf(i) * 1.0 * rand() / RAND_MAX);
            u_data[2*i+1] = (float) (sqrtf(i) * 1.0 * rand() / RAND_MAX);
        }
        for (size_t i = 0; i < v_n; ++i) {
            v_data[2*i] = (float) (sqrtf(i) * 1.0 * rand() / RAND_MAX);
            v_data[2*i+1] = (float) (sqrtf(i) * 1.0 * rand() / RAND_MAX);
        }

        clock_t start, end;
        start = clock();
        warp_summary_t* warp_summary = full_warp_summary_create(u, v);
        end = clock();
        time_accumulator_1 += ((double) (end - start)) / CLOCKS_PER_SEC;
        start = clock();
        float warp_cost = full_dtw_cost(u, v);
        end = clock();
        time_accumulator_2 += ((double) (end - start)) / CLOCKS_PER_SEC;
        //printf("%f\n", warp_summary->cost);
        //printf("%f\n", warp_cost);
        //assert(warp_cost == warp_summary->cost);
        warp_summary_destroy(warp_summary);
        stream_destroy(u);
        stream_destroy(v);
    }
    printf("%zu iterations of %zu by %zu full time warp took %f millis with path, %f millis without, averages=%f, %f\n",
           iterations, u_n, v_n,
           1000.0*time_accumulator_1,
           1000.0*time_accumulator_2,
           (1000.0*time_accumulator_1) / iterations,
           (1000.0*time_accumulator_2) / iterations);

}

void fast_random_alignment_benchmark(const size_t u_n, const size_t v_n, const size_t radius, const size_t iterations) {
    time_t seed = time(NULL);
    srand(seed);
    double time_accumulator = 0;
    for (size_t j = 0; j < iterations; j++) {
        const stream_t* u = stream_create(u_n);
        float* u_data = u->data;
        const stream_t* v = stream_create(v_n);
        float* v_data = v->data;
        for (size_t i = 0; i < u_n; ++i) {
            u_data[2*i] = (float) (sqrtf(i) * 1.0 * rand() / RAND_MAX);
            u_data[2*i+1] = (float) (sqrtf(i) * 1.0 * rand() / RAND_MAX);
        }
        for (size_t i = 0; i < v_n; ++i) {
            v_data[2*i] = (float) (sqrtf(i) * 1.0 * rand() / RAND_MAX);
            v_data[2*i+1] = (float) (sqrtf(i) * 1.0 * rand() / RAND_MAX);
        }

        clock_t start, end;
        start = clock();
        warp_summary_t* warp_summary = fast_warp_summary_create(u, v, radius); // Don't care about the results here; just the computation.
        end = clock();
        //printf("Warp summary: %zu points, %f cost\n", warp_summary->path_length, warp_summary->cost);
        warp_summary_destroy(warp_summary);
        time_accumulator += ((double) (end - start)) / CLOCKS_PER_SEC;

        stream_destroy(u);
        stream_destroy(v);
    }
    printf("%zu iterations of %zu by %zu fast time warp (radius %zu) with path took %f millis, average=%f\n",
           iterations, u_n, v_n, radius,
           1000.0*time_accumulator,
           (1000.0*time_accumulator) / iterations);
}

void accuracy_benchmark(const size_t u_n, const size_t v_n, const size_t radius_max) {
    time_t seed = time(NULL);
    srand(seed);
    const stream_t* u = stream_create(u_n);
    float* u_data = u->data;
    const stream_t* v = stream_create(v_n);
    float* v_data = v->data;

    clock_t start, end;
    for (size_t i = 0; i < u_n; ++i) {
        u_data[2*i] = (float) (i * 1.0 * rand() / RAND_MAX);
        u_data[2*i+1] = (float) (i * 1.0 * rand() / RAND_MAX);
    }
    for (size_t i = 0; i < v_n; ++i) {
        v_data[2*i] = (float) (i * 1.0 * rand() / RAND_MAX);
        v_data[2*i+1] = (float) (i * 1.0 * rand() / RAND_MAX);
    }
    double full_millis;
    double fast_millis;

    start = clock();
    const warp_summary_t* full_warp_summary = full_warp_summary_create(u, v);
    end = clock();
    full_millis = 1000.0*((double) (end - start)) / CLOCKS_PER_SEC;

    for (size_t radius = 0; radius <= radius_max; radius++) {
        start = clock();
        const warp_summary_t* fast_warp_summary = fast_warp_summary_create(u, v, radius);
        end = clock();
        fast_millis = 1000.0*((double) (end - start)) / CLOCKS_PER_SEC;
        printf("%zu rows\t%zu cols\t%zu radius\t%f full cost\t%f ms_full\t%f fast cost\t%f ms_fast\t%f error\n",
               u_n, v_n, radius,
               full_warp_summary->cost,
               full_millis,
               fast_warp_summary->cost,
               fast_millis,
               (fast_warp_summary->cost - full_warp_summary->cost) / full_warp_summary->cost);
        warp_summary_destroy(fast_warp_summary);
    }
    warp_summary_destroy(full_warp_summary);
    stream_destroy(u);
    stream_destroy(v);
}

void medoid_real_data_benchmark() {
    char filename[1024];
    size_t bddl = strlen(BENCHMARK_DATA_DIR);
    strcpy(filename, BENCHMARK_DATA_DIR);
    strcpy(filename + bddl, "segments/oldlahondas.json");

    const stream_collection_t *streams_from_json = read_streams_from_json(filename);
    if (!streams_from_json) {
        printf("Unable to load streams from file '%s'\n", filename);
        return;
    }
    int approximate = 0;
    size_t index;
    printf("Computing medoid consensus with approximate = %d \n", approximate);
    //TIMEIT(
            index = medoid_consensus(streams_from_json, approximate);
    //);
    printf("Index of optimal stream with approximate = %d  is %zu\n", approximate, index);

    approximate = 1;
    printf("Computing medoid consensus with approximate = %d \n", approximate);
    //TIMEIT(
            index = medoid_consensus(streams_from_json, approximate);
    //);

    printf("Index of optimal stream with approximate = %d  is %zu\n", approximate, index);
    stream_collection_destroy(streams_from_json);
}

void medoid_real_data_reduced_benchmark() {
    char filename[1024];
    size_t bddl = strlen(BENCHMARK_DATA_DIR);
    strcpy(filename, BENCHMARK_DATA_DIR);
    strcpy(filename + bddl, "segments/oldlahondas.json");

    const stream_collection_t *streams_from_json = read_streams_from_json(filename);
    if (!streams_from_json) {
        printf("Unable to load streams from file '%s'\n", filename);
        return;
    }

    for (size_t index = 0; index < streams_from_json->n; ++index) {
        //printf("Downsampling a stream.\n");

        stream_t* s = streams_from_json->data[index];
        stream_geojson_printf(s);
        printf("start length: %zu\n", s->n);
        downsample_rdp(s, 0.00005);
        stream_geojson_printf(s);
        printf("new length: %zu\n", s->n);
    }

    stream_collection_destroy(streams_from_json);
}

int main() {
    full_random_alignment_benchmark(4000, 4000, 20);
    fast_random_alignment_benchmark(4000, 4000, 8, 100);
    accuracy_benchmark(24000, 24000, 20);
    medoid_real_data_benchmark();
    medoid_real_data_reduced_benchmark();
}


text:
var Plotly = require('@lib/core');
var ohlc = require('@lib/ohlc');
var candlestick = require('@lib/candlestick');

var d3 = require('d3');
var createGraphDiv = require('../assets/create_graph_div');
var destroyGraphDiv = require('../assets/destroy_graph_div');

describe('Bundle with finance trace type', function() {
    'use strict';

    Plotly.register([ohlc, candlestick]);

    var mock = require('@mocks/finance_style.json');

    it('should register the correct trace modules for the generated traces', function() {
        var transformModules = Object.keys(Plotly.Plots.transformsRegistry);

        expect(transformModules).toEqual(['ohlc', 'candlestick']);
    });

    it('should register the correct trace modules for the generated traces', function() {
        var traceModules = Object.keys(Plotly.Plots.modules);

        expect(traceModules).toEqual(['scatter', 'box', 'ohlc', 'candlestick']);
    });

    it('should graph ohlc and candlestick traces', function(done) {

        Plotly.plot(createGraphDiv(), mock.data, mock.layout).then(function() {
            var gSubplot = d3.select('g.cartesianlayer');

            expect(gSubplot.selectAll('g.trace.scatter').size()).toEqual(2);
            expect(gSubplot.selectAll('g.trace.boxes').size()).toEqual(2);

            destroyGraphDiv();
            done();
        });

    });
});


text:
import * as types from '../constants/ActionTypes.js';

const initialState = {
  user: {
    id: null,
    avatar: 'http://www.carderator.com/assets/avatar_placeholder_small.png',
    displayName: 'First Last'
  },
  recipesCreated: [],
  recipesFollowed: [],
  recipesLiked: [],
};

export default function profile(state = initialState, action) {
  switch (action.type) {
    case types.SET_PROFILE_USER:
      return Object.assign({}, state, { user: action.user });
    case types.SET_PROFILE_RECIPES_CREATED:
      return Object.assign({}, state, { recipesCreated: action.recipesCreated });
    case types.SET_PROFILE_RECIPES_FOLLOWED:
      return Object.assign({}, state, { recipesFollowed: action.recipesFollowed });
    case types.SET_PROFILE_RECIPES_LIKED:
      return Object.assign({}, state, { recipesLiked: action.recipesLiked });
    default:
      return state;
  }
};


text:
default['basetomcat']['connector_port'] = '8180'
default['basetomcat']['webapps_dir']    = '/usr/share/tomcat/webapps'

default['basetomcat']['packages'] = {
  'rhel' => ['epel-release', 'tomcat', 'tomcat-admin-webapps']
}


text:
namespace {
BASE_FEATURE(kNavigationLatencyAblation,
             "NavigationLatencyAblation",
             base::FEATURE_DISABLED_BY_DEFAULT);

// The amount of time to stall before resuming loading.
const base::FeatureParam<base::TimeDelta> kNavigationLatencyAblationDuration{
    &kNavigationLatencyAblation, "duration", base::Milliseconds(250)};

// Whether default search Search queries should be ablated.
const base::FeatureParam<bool> kShouldAblateDefaultSearchQueries{
    &kNavigationLatencyAblation, "ablate_default_search_queries", true};

// Whether default search navigations to any of the related hosts should be
// ablated.
const base::FeatureParam<bool> kShouldAblateDefaultSearchHost{
    &kNavigationLatencyAblation, "ablate_default_search_host", true};

// Whether the corpus of URLs that are not part of the default search host
// corpus should be ablated.
const base::FeatureParam<bool> kShouldAblateNonDefaultSearchHost{
    &kNavigationLatencyAblation, "ablate_non_default_search_host", true};

// Different URLs re grouped into ablation types, which can be configured to be
// ablated or not.
enum class AblationType {
  kDefaultSearchQuery = 0,
  kDefaultSearchHost = 1,
  kNonDefaultSearchHost = 2,
};

// The name of the throttle for logging purposes.
constexpr char kNavigationAblationThrottleName[] = "NavigationAblationThrottle";

// Return the type of navigation based on whether `navigation_url` is a search
// query or related to the user's default search provider.
AblationType GetAblationType(const GURL& navigation_url,
                             content::BrowserContext* browser_context) {
  auto* template_url_service = TemplateURLServiceFactory::GetForProfile(
      Profile::FromBrowserContext(browser_context));
  if (!template_url_service)
    return AblationType::kNonDefaultSearchHost;

  auto* default_search = template_url_service->GetDefaultSearchProvider();
  if (!default_search)
    return AblationType::kNonDefaultSearchHost;

  if (default_search->IsSearchURL(navigation_url,
                                  template_url_service->search_terms_data())) {
    return AblationType::kDefaultSearchQuery;
  }

  for (auto url_ref : default_search->url_refs()) {
    if (url::Origin::Create(navigation_url) ==
        url::Origin::Create(GURL(url_ref.GetURL()))) {
      return AblationType::kDefaultSearchHost;
    }
  }

  return AblationType::kNonDefaultSearchHost;
}

bool ShouldCreateThrottle(content::NavigationHandle* navigation) {
  if (!base::FeatureList::IsEnabled(kNavigationLatencyAblation)) {
    return false;
  }

  // Exclude navigations for prerender or other MPArch.
  if (!navigation->IsInPrimaryMainFrame())
    return false;

  // Don't slow down activations from prerender or BFCache.
  if (navigation->IsPageActivation())
    return false;

  // Avoid ablating pages that likely are served from HTTP Cache.
  if (navigation->GetPageTransition() & ui::PAGE_TRANSITION_FORWARD_BACK) {
    return false;
  }

  // Avoid ablataing client redirects as they may be part of a chain for a
  // single navigation.
  if (navigation->GetPageTransition() & ui::PAGE_TRANSITION_CLIENT_REDIRECT) {
    return false;
  }

  // Ignore navigations that are not HTTP(S).
  if (!navigation->GetURL().SchemeIsHTTPOrHTTPS()) {
    return false;
  }

  // Ignore navigations to IP addresses as these may be local network.
  if (navigation->GetURL().HostIsIPAddress()) {
    return false;
  }

  auto ablation_type = GetAblationType(
      navigation->GetURL(), navigation->GetWebContents()->GetBrowserContext());
  switch (ablation_type) {
    case AblationType::kDefaultSearchQuery:
      return kShouldAblateDefaultSearchQueries.Get();
    case AblationType::kDefaultSearchHost:
      return kShouldAblateDefaultSearchHost.Get();
    case AblationType::kNonDefaultSearchHost:
      return kShouldAblateNonDefaultSearchHost.Get();
  }
}

// A navigation throttle that deferes during WillStartRequest and resumes after
// a fixed duration.
class NavigationAblationThrottle : public content::NavigationThrottle {
 public:
  explicit NavigationAblationThrottle(content::NavigationHandle* navigation)
      : content::NavigationThrottle(navigation) {}
  ~NavigationAblationThrottle() override = default;

 private:
  const char* GetNameForLogging() override {
    return kNavigationAblationThrottleName;
  }

  ThrottleCheckResult WillStartRequest() override {
    timer_.Start(
        FROM_HERE, kNavigationLatencyAblationDuration.Get(),
        base::BindOnce(&NavigationAblationThrottle::ResumeLoading,
                       base::Unretained(this), base::TimeTicks::Now()));
    return content::NavigationThrottle::DEFER;
  }

  void ResumeLoading(base::TimeTicks start_time) {
    // Measure the actual wait time to make sure we are near the expected wait
    // time for the experiment arm.
    auto wait_time = base::TimeTicks::Now() - start_time;
    auto excess_wait_time =
        wait_time - kNavigationLatencyAblationDuration.Get();

    // Record the time spent waiting beyond what was configured.
    base::UmaHistogramTimes("Navigation.LatencyAblation.ExcessWaitTime",
                            excess_wait_time);

    Resume();
  }

  // A timer that resumes the loading after a fixed duration. The timer ensures
  // that if |this| is deleted the callback does not run and cause a UAF.
  base::OneShotTimer timer_;
};

}  // namespace

// static
std::unique_ptr<content::NavigationThrottle>
MaybeCreateNavigationAblationThrottle(content::NavigationHandle* navigation) {
  DCHECK(navigation);
  if (!ShouldCreateThrottle(navigation)) {
    return nullptr;
  }
  return std::make_unique<NavigationAblationThrottle>(navigation);
}


text:
var EmbeddedDocument = require('../../model/EmbeddedDocument')
  , utils = require('../../utils')
  , mixins = require('./mixins');

/**
 * List and Set container based on Array
 * @param {Array} values
 * @param {String} path
 * @param {Object} doc
 * @param {String} mode (list|set)
 *
 * @constructor
 * @extends {Array}
 * @implements {OrientContainer}
 */
function OrientArray (values, path, doc, mode) {
  var arr = [];
  arr.push.apply(arr, values);
  arr.__proto__ = OrientArray.prototype;

  arr._atomics = {};
  arr.validators = [];
  arr._path = path;
  arr._mode = mode;

  if (doc) {
    arr._parent = doc;
    arr._schema = doc.schema.path(path);
    doc.on('save', arr.notify('save'));
    doc.on('isNew', arr.notify('isNew'));
  }

  return arr;
};

/**
 * Inherit from Array
 */
OrientArray.prototype = new Array;

/**
 * Parent owner document
 *
 * @type {Doc}
 * @public
 */
OrientArray.prototype._parent;

/**
 * Parent owner document
 *
 * @type {String}
 * @public
 */
OrientArray.prototype._path;

/**
 * @type {SchemaType}
 * @public
 */
OrientArray.prototype._schema;

/**
 * Mode (list|set). Set can contain only unique values
 * @type {String}
 */
OrientArray.prototype._mode;

/**
 * Returns the full path to this document. If optional `path` is passed, it is appended to the full path.
 * @param {String|Number} [path]
 *
 * @return {String}
 * @public
 */
OrientArray.prototype.$__fullPath = mixins.fullPath();

/**
 * Get number of items
 *
 * @return {Number}
 * @public
 */
OrientArray.prototype.count = function () {
  return this.length;
};

/**
 * Return the index of `obj` or `-1` if not found.
 *
 * @param {Object} obj the item to look for
 *
 * @return {Number}
 * @public
 */
OrientArray.prototype.indexOf = function indexOf (obj) {
  for (var i = 0, len = this.length; i < len; ++i) {
    if (obj == this[i])
      return i;
  }
  return -1;
};

/**
 * Marks this array as modified.
 *
 * If it bubbles up from an embedded document change, then it takes the following arguments (otherwise, takes 0 arguments)
 *
 * @param {Doc} [elem] the embedded doc that invoked this method on the Array
 * @param {String} [embeddedPath] the path which changed in the embeddedDoc
 *
 * @return {OrientArray}
 * @public
 */
OrientArray.prototype.$__markModified = mixins.markModified();

/**
 * Register an atomic operation with the parent.
 *
 * @param {String} op operation
 * @param {*} val
 *
 * @return {OrientArray}
 * @public
 */
OrientArray.prototype.$__registerAtomic = function (op, val) {
  if (op === '$set') {
    // $set takes precedence over all other ops.
    // mark entire array modified.
    this._atomics = { $set: val };
    return this;
  }

  var atomics = this._atomics;

  // store whole array in case of atomics combo
  if (this._atomics.$set ||
    Object.keys(atomics).length && !(op in atomics)) {
    // a different op was previously registered.
    // save the entire thing.
    this._atomics = { $set: this };
    return this;
  }

  atomics[op] || (atomics[op] = []);
  atomics[op] = atomics[op].concat(val);

  return this;
};

/**
 * Depopulates stored atomic operation values as necessary for direct insertion to OrientDB.
 *
 * If no atomics exist, we return all container values after conversion.
 *
 * @return {Array}
 * @public
 */
OrientArray.prototype.$__getAtomics = mixins.getAtomics();

/**
 * Returns the number of pending atomic operations to send to the db for this container.
 *
 * @return {Number}
 * @public
 */
OrientArray.prototype.$__hasAtomics = mixins.hasAtomics();

/**
 * Returns a native js Array.
 * @param {Object} options
 *
 * @return {Array}
 * @public
 */
OrientArray.prototype.toObject = function (options) {
  return this.map(function (doc) {
    return doc instanceof EmbeddedDocument
      ? doc.toObject(options)
      : doc
  });
};

/**
 * Helper for console.log
 *
 * @return {String}
 * @public
 */
OrientArray.prototype.inspect = function () {
  if (!this.count()) return '[]';

  return '[' + this.map(function (doc) {
      return ' ' + doc;
    }) + ' ]';
};

/**
 * Resets the internal modified state of subdocuments.
 *
 * @return {OrientArray}
 * @public
 */
OrientArray.prototype.$__reset = mixins.reset();

/**
 * Create an instance of schema entry
 * @param {*} obj
 *
 * @return {*}
 * @public
 */
OrientArray.prototype.create = mixins.create();

/**
 * Creates a fn that notifies all child docs of `event`.
 *
 * @param {String} event
 *
 * @return {Function}
 * @protected
 */
OrientArray.prototype.notify = mixins.notify();

/**
 * Make iteration over each item
 * @param {Function} cb
 * @param {*} [thisArg]
 *
 * @public
 */
OrientArray.prototype.forEach = function (cb, thisArg) {
  var len = this.length;
  for (var i = 0; i < len; ++i) {
    if (thisArg) {
      cb.call(thisArg, this[i], i, this);
    }
    else {
      cb(this[i], i, this);
    }
  }
};

/**
 * Casts a member based on this arrays schema.
 *
 * @param {*} value
 * @param {Number} [id]
 * @param {Array} [array]
 * @param {Boolean} [init]
 *
 * @return {*}
 * @protected
 */
OrientArray.prototype._cast = function (value, id, array, init) {
  return this._schema.getEntry().cast(value, this.$__fullPath(id), this._parent, init, null, this);
};

/**
 * Catches errors that occur during execution of `fn` and stores them in parent Document or rethrow
 *
 * @param {Function} fn function to execute
 * @param {Object} [scope] the scope with which to call fn
 *
 * @return {*}
 * @private
 */
OrientArray.prototype.$__try = function (fn, scope) {
  var res;
  try {
    fn.call(scope);
    res = true;
  }
  catch (e) {
    this.$__error(e);
    res = false;
  }
  return res;
};

/**
 * Registers an error
 *
 * @param {Error} err
 *
 * @return {OrientArray} this
 * @private
 */
OrientArray.prototype.$__error = function (err) {
  if (this._parent) {
    this._parent.$__error(this.$__fullPath(), err);
  }
  else {
    throw err;
  }
  return this;
};

/**
 * Wraps [`Array#push`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push) with proper change tracking.
 *
 * @param {Object} [...]
 *
 * @return {Number} Array length
 * @public
 */
OrientArray.prototype.push = function () {
  var values
    , args = arguments
    , shouldDo;

  if (this._mode === 'set') {
    // only unique values allowed

    shouldDo = this.$__try(function () {
      // we don't need mark modified this instance until we are sure it will be added
      values = [].map.call(args, mixins.castWrapper(this, true), this);
    }, this);

    if (shouldDo) {
      values = values.map(function (v) {
        var found
          , type = v instanceof EmbeddedDocument ? 'doc' :
            v instanceof Date ? 'date' : '';
        switch (type) {
          case 'doc':
            found = this.some(function(doc){ return doc.equals(v) });
            break;

          case 'date':
            var val = +v;
            found = this.some(function(d){ return +d === val });
            break;

          default:
            found = ~this.indexOf(v);
        }

        return found ? undefined : v;
      }, this).filter(function (item) {
        return 'undefined' !== typeof item;
      }).map(function (v) {
        // here we are sure item will be added, so cast it normal way
        return this._cast(utils.clone(v));
      }, this);
    }
  }
  else {
    shouldDo = this.$__try(function () {
      values = [].map.call(args, this._cast, this);
    }, this);
  }

  if (shouldDo && values.length) {
    [].push.apply(this, values);
    this.$__registerAtomic('$add', values);
    this.$__markModified();
  }

  return this.length;
};

/**
 * Wraps [`Array#pop`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/pop) with proper change tracking.
 *
 * ####Note:
 *
 * _marks the entire array as modified which will pass the entire thing to $set potentially overwritting any changes that happen between when you retrieved the object and when you save it._
 *
 * @public
 */
OrientArray.prototype.pop = function () {
  var ret = [].pop.call(this);
  this.$__registerAtomic('$set', this);
  this.$__markModified();
  return ret;
};

/**
 * Wraps [`Array#shift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking.
 *
 * ####Example:
 *
 *     doc.array = [2,3];
 *     var res = doc.array.shift();
 *     console.log(res) // 2
 *     console.log(doc.array) // [3]
 *
 * ####Note:
 *
 * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._
 *
 * @return {*}
 * @public
 */
OrientArray.prototype.shift = function () {
  var ret = [].shift.call(this);
  this.$__registerAtomic('$set', this);
  this.$__markModified();
  return ret;
};

/**
 * Wraps [`Array#unshift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking.
 *
 * ####Note:
 * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._
 *
 * @return {Number} length
 * @public
 */
OrientArray.prototype.unshift = function () {
  var args = arguments
    , values
    , shouldDo = this.$__try(function () {
        values = [].map.call(args, this._cast, this);
      }, this);

  if (shouldDo) {
    [].unshift.apply(this, values);
    this.$__registerAtomic('$set', this);
    this.$__markModified();
  }
  return this.length;
};

/**
 * Wraps [`Array#splice`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice) with proper change tracking and casting.
 *
 * ####Note:
 *
 * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._
 *
 * @return {Array|undefined}
 * @public
 */
OrientArray.prototype.splice = function splice () {
  var ret, vals, i
    , args = arguments;

  if (arguments.length) {
    var shouldDo = this.$__try(function () {
      vals = [];
      for (i = 0; i < args.length; ++i) {
        vals[i] = i < 2
          ? args[i]
          : this._cast(args[i]);
      }
    }, this);

    if (shouldDo) {
      ret = [].splice.apply(this, vals);
      this.$__registerAtomic('$set', this);
      this.$__markModified();
    }
  }

  return ret;
};

/**
 * Wraps [`Array#sort`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort) with proper change tracking.
 *
 * ####NOTE:
 *
 * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._
 *
 * @return {Array}
 * @public
 */
OrientArray.prototype.sort = function () {
  var ret = [].sort.apply(this, arguments);
  this.$__registerAtomic('$set', this);
  this.$__markModified();
  return ret;
};

/**
 * Pulls items from the array atomically.
 *
 * ####Examples:
 *
 *     doc.array.pull(ObjectId)
 *     doc.array.pull({ _id: 'someId' })
 *     doc.array.pull(36)
 *     doc.array.pull('tag 1', 'tag 2')
 *
 * To remove a document from a subdocument array we may pass an object with a matching `_id`.
 *
 *     doc.subdocs.push({ _id: 4815162342 })
 *     doc.subdocs.pull({ _id: 4815162342 }) // removed
 *
 * Or we may passing the _id directly and let mongoose take care of it.
 *
 *     doc.subdocs.push({ _id: 4815162342 })
 *     doc.subdocs.pull(4815162342); // works
 *
 * @param {*} [...]
 *
 * @return {OrientArray}
 * @public
 */
OrientArray.prototype.pull = function () {
  var args = arguments
    , values
    , shouldDo = this.$__try(function () {
        values = [].map.call(args, mixins.castWrapper(this, true), this);
      }, this);

  if (shouldDo) {
    var cur = this._parent.get(this._path)
      , i = cur.length
      , mem
      , modified = false;

    while (i--) {
      mem = cur[i];
      if (mem instanceof EmbeddedDocument) {
        if (values.some(function (v) { return v.equals(mem); } )) {
          [].splice.call(cur, i, 1);
          modified = true;
        }
      }
      else if (~cur.indexOf.call(values, mem)) {
        modified = true;
        [].splice.call(cur, i, 1);
      }
    }

    if (modified) {
      if (values[0] instanceof EmbeddedDocument) {
        // we have to use $set here because of bug in SQL remove with embedded documents
        // causing to remove first item instead of selected
        this.$__registerAtomic('$set', this);
      }
      else {
        this.$__registerAtomic('$remove', values);
      }

      this.$__markModified();
    }
  }

  return this;
};

/**
 * Alias of [push]
 *
 * @see OrientArray#push
 * @return {OrientArray}
 * @public
 */
OrientArray.prototype.add = OrientArray.prototype.push;

/**
 * Alias of [pull]
 *
 * @see OrientArray#pull
 * @return {OrientArray}
 * @public
 */
OrientArray.prototype.remove = OrientArray.prototype.pull;

///**
// * Save sub-documents
// *
// * @return {OrientArray}
// * @public
// */
//OrientArray.prototype.$__save = mixins.save();

module.exports = OrientArray;


text:
// Initialize global variables
// -- for slider ui --
g.globals = {};
g.scale = 1;
g.xaxis_rotate_param = 5;

// initialize ui
function initUI() {
	$(".perspective-enable").click(function(){
		var parent = $(this).parents('.switch');
		if (window.confirm('透視投影に切り替えます。よろしいですか?')) {
			$('.perspective-disable',parent).removeClass('selected');
			$(this).addClass('selected');
			togglePerspective(1);
		} else {
		}
	});
	$(".perspective-disable").click(function(){
		var parent = $(this).parents('.switch');
		if (window.confirm('平行投影に切り替えます。よろしいですか?')) {
			$('.perspective-enable',parent).removeClass('selected');
			$(this).addClass('selected');
			togglePerspective(0);
		} else {
		}
	});
	$('#perspective-disable').removeClass('selected');
	$('#perspective-enable').addClass('selected');
}

// initialize webgl
function initWebGL (c) {
	c.width = 700; c.height = 580;
	// get webgl context
	gl = c.getContext('webgl', { antialias: true }) ||
		c.getContext('experimental-webgl', { antialias: true });
    if (!gl) { alert("Error: failed to get webgl context, sorry :-("); return; }
	// set event listeners
	c.addEventListener("mousedown", handleMouseDown, false);
	c.addEventListener("mousemove", handleMouseMove, false);
	c.addEventListener("mouseup", handleMouseUp, false);

	gl.enable(gl.DEPTH_TEST);
	gl.depthFunc(gl.LEQUAL);
	gl.disable(gl.CULL_FACE);
	gl.disable(gl.BLEND);
	gl.cullFace(gl.FRONT_AND_BACK);
}

// update framerate
function updateFramerates () {
	var nowtime = new Date().getTime();
	var difftime = nowtime - g.rendertime;
	if (difftime == 0) return;
	var f = 1000/difftime;
	g.framerates.push(f);
	if (g.framerates.length>10) g.framerates.shift();
	g.rendertime = nowtime;
}

// display framerate
function displayFramerate () {
	var sum = 0;
	for (var i = 0; i < g.framerates.length; i++)
		sum+= g.framerates[i];
	var f = Math.round(sum/g.framerates.length);
	$('#framerate').text('Framerate: '+f+" fps");
}

// toggle perspective
function togglePerspective(flag) {
	g.view_mode = (flag) ? 1 : 0;
}

// set ui parameters
function setParam(event, ui, obj, name) {
	var id = event.target.id;
	var value = ui.value / 1000;
	if (value < 1) value = 0;
	if (name == 'Scale') {
		if (value < 1) value = 1;
		$('#scale_slider').text($.sprintf(": % 4d", value));
		g.scale = value;
	} else if (name == 'Rotation of around the x-axis') {
		$('#xaxis_rotation_slider').text($.sprintf(": % 4d", value));
		g.xaxis_rotate_param = value;
	}
	obj[id] = value;
}

// get ui values
function getUIValue(obj, id) {
	return obj[id] * 1000;
}

// setup sliders
function setupSlider($, elem, ui, obj) {
	var labelDiv = document.createElement('div');
	labelDiv.appendChild(document.createTextNode(ui.name));
	var sliderDiv = document.createElement('div');
	sliderDiv.id = ui.name;
	elem.appendChild(labelDiv);
	elem.appendChild(sliderDiv);
	$(sliderDiv).slider({
		range: false,
		step: 1,
		max: ui.max * 1000,
		min: ui.min,
		value: getUIValue(obj, ui.name),
		slide: function(event, ui) { setParam(event, ui, obj, sliderDiv.id); }
	});
	$(sliderDiv).css({"margin-bottom" : "6px"});

	if (ui.name == 'Scale') {
		$('#scale_slider').text($.sprintf(": % 4d", ui.value));
		g.scale = ui.value;
	} else if (ui.name == 'Rotation of around the x-axis') {
		$('#xaxis_rotation_slider').text($.sprintf(": % 4d", ui.value));
		g.xaxis_rotate_param = ui.value;
	}
}


text:
/*! \file qle/cashflows/fxlinkedcashflow.hpp
    \brief An FX linked cashflow

        \ingroup cashflows
*/

#ifndef quantext_fx_linked_cashflow_hpp
#define quantext_fx_linked_cashflow_hpp

#include <ql/cashflow.hpp>
#include <ql/handle.hpp>
#include <ql/quote.hpp>
#include <ql/time/date.hpp>
#include <ql/patterns/visitor.hpp>
#include <qle/indexes/fxindex.hpp>

using namespace QuantLib;

namespace QuantExt {

//! FX Linked cash-flow
/*!
 * Cashflow of Domestic currency where the amount is fx linked
 * to some fixed foreign amount.
 *
 * For example: a JPY flow based off 1M USD, if the USDJPY FX rate
 * is 123.45 then the JPY amount is 123.45 M JPY.
 *
 * FXLinkedCashFlow checks the FX fixing date against the eval date
 *
 * For furure fixings (date > eval) this class calcualates the FX Fwd
 * rate (using the provided FX Spot rate and FOR and DOM yield curves)
 *
 * For todays fixing (date = eval) this class converts the foreign
 * amount using the provided FX Spot rate.
 *
 * For previous fixings (date < eval) this class checks the QuantLib
 * IndexManager to get the FX fixing at which the foreign rate should be
 * converted at. The name of the index is a parameter to the constructor.
 *
 * This is not a lazy object.

     \ingroup cashflows
 */
class FXLinkedCashFlow : public CashFlow {
public:
    FXLinkedCashFlow(const Date& cashFlowDate, const Date& fixingDate, Real foreignAmount,
                     boost::shared_ptr<FxIndex> fxIndex, bool invertIndex = false);

    //! \name CashFlow interface
    //@{
    Date date() const { return cashFlowDate_; }
    Real amount() const { return foreignAmount_ * fxRate(); }
    //@}

    Date fxFixingDate() const { return fxFixingDate_; }
    const boost::shared_ptr<FxIndex>& index() const { return fxIndex_; }
    bool invertIndex() const { return invertIndex_; }

    //! \name Visitability
    //@{
    void accept(AcyclicVisitor&);
    //@}

private:
    Date cashFlowDate_;
    Date fxFixingDate_;
    Real foreignAmount_;
    boost::shared_ptr<FxIndex> fxIndex_;
    bool invertIndex_;

    Real fxRate() const;
};

inline void FXLinkedCashFlow::accept(AcyclicVisitor& v) {
    Visitor<FXLinkedCashFlow>* v1 = dynamic_cast<Visitor<FXLinkedCashFlow>*>(&v);
    if (v1 != 0)
        v1->visit(*this);
    else
        CashFlow::accept(v);
}
}

#endif


text:
namespace Google.Cloud.ResourceManager.V3.Snippets
{
    // [START cloudresourcemanager_v3_generated_TagValues_UpdateTagValue_sync_flattened]
    using Google.Cloud.ResourceManager.V3;
    using Google.LongRunning;
    using Google.Protobuf.WellKnownTypes;

    public sealed partial class GeneratedTagValuesClientSnippets
    {
        /// <summary>Snippet for UpdateTagValue</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public void UpdateTagValue()
        {
            // Create client
            TagValuesClient tagValuesClient = TagValuesClient.Create();
            // Initialize request argument(s)
            TagValue tagValue = new TagValue();
            FieldMask updateMask = new FieldMask();
            // Make the request
            Operation<TagValue, UpdateTagValueMetadata> response = tagValuesClient.UpdateTagValue(tagValue, updateMask);

            // Poll until the returned long-running operation is complete
            Operation<TagValue, UpdateTagValueMetadata> completedResponse = response.PollUntilCompleted();
            // Retrieve the operation result
            TagValue result = completedResponse.Result;

            // Or get the name of the operation
            string operationName = response.Name;
            // This name can be stored, then the long-running operation retrieved later by name
            Operation<TagValue, UpdateTagValueMetadata> retrievedResponse = tagValuesClient.PollOnceUpdateTagValue(operationName);
            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // If it has completed, then access the result
                TagValue retrievedResult = retrievedResponse.Result;
            }
        }
    }
    // [END cloudresourcemanager_v3_generated_TagValues_UpdateTagValue_sync_flattened]
}


text:
* enhancements
  * Introduced `DeviseController#set_flash_message!` for conditional flash
    messages setting to reduce complexity.
  * `rails g devise:install` will fail if the app does not have a ORM configured
    (by @arjunsharma)

### 4.0.0.rc1 - 2016-01-02

* Support added to Rails 5 (by @twalpole).
* Devise no longer supports Rails 3.2 and 4.0.
* Devise no longer supports Ruby 1.9 and 2.0.

* deprecations
  * The `devise_parameter_sanitize` API has changed:
    The `for` method was deprecated in favor of `permit`:

    ```ruby
    def configure_permitted_parameters
      devise_parameter_sanitizer.for(:sign_up) << :subscribe_newsletter
      # Should become the following.
      devise_parameter_sanitizer.permit(:sign_up, keys: [:subscribe_newsletter])
    end
    ```

    The customization through instance methods on the sanitizer implementation
    should be done through it's `initialize` method:

    ```ruby
    class User::ParameterSanitizer < Devise::ParameterSanitizer
      def sign_up
        default_params.permit(:username, :email)
      end
    end

    # The `sign_up` method can be a `permit` call on the sanitizer `initialize`.

    class User::ParameterSanitizer < Devise::ParameterSanitizer
      def initialize(*)
        super
        permit(:sign_up, keys: [:username, :email])
      end
    end
    ```

    You can check more examples and explanations on the [README section](/plataformatec/devise#strong-parameters)
    and on the [ParameterSanitizer docs](lib/devise/parameter_sanitizer.rb).

Please check [3-stable](https://github.com/plataformatec/devise/blob/3-stable/CHANGELOG.md)
for previous changes.


text:
"""Media asset management for Invenio."""

def collect_staticroot_removal(app, blueprints):
    """Remove collect's static root folder from list."""
    collect_root = app.extensions["collect"].static_root
    return [
        bp
        for bp in blueprints
        if (bp.has_static_folder and bp.static_folder != collect_root)
    ]


text:
import shortId from 'shortid';
import {
	ADD_TODO, COMPLETE_TODO, EDIT_TODO, REMOVE_TODO,
} from './constants/ActionTypes';

export function addTodo(task, isCompleted = false) {
	return {
		type: ADD_TODO,
		payload: {
			id: shortId.generate(),
			isCompleted,
			task,
		},
	};
}

export function completeTodo(id, isCompleted) {
	return {
		type: COMPLETE_TODO,
		payload: {
			id,
			isCompleted,
		},
	};
}

export function editTodo(id, task) {
	return {
		type: EDIT_TODO,
		payload: {
			id,
			task,
		},
	};
}

export function removeTodo(id) {
	return {
		type: REMOVE_TODO,
		payload: {
			id,
		},
	};
}


text:
package com.github.thomasfischl.aihome.game2048controller.util;

import org.junit.Assert;
import org.junit.Test;

import com.github.thomasfischl.aihome.game2048controller.controller.Direction;
import com.github.thomasfischl.aihome.game2048controller.controller.GameGrid;

public class GameGridConverterTest {

  @Test
  public void test() {
    GameGrid grid = new GameGrid(4);
    grid.setCell(1, 2, 1);
    grid.setCell(2, 2, 1);
    grid.setCell(0, 0, 1);
    grid.setCell(0, 3, 2);
    System.out.println(grid);

    GameGrid result = GameGridUtil.getFutureGrid(grid, Direction.UP);
    Assert.assertEquals(1, result.getCell(0, 0));
    Assert.assertEquals(1, result.getCell(1, 0));
    Assert.assertEquals(1, result.getCell(2, 0));
    Assert.assertEquals(2, result.getCell(0, 1));

    result = GameGridUtil.getFutureGrid(grid, Direction.LEFT);
    Assert.assertEquals(1, result.getCell(3, 0));
    Assert.assertEquals(2, result.getCell(3, 2));
    Assert.assertEquals(2, result.getCell(3, 3));

    result = GameGridUtil.getFutureGrid(grid, Direction.DOWN);
    Assert.assertEquals(1, result.getCell(0, 2));
    Assert.assertEquals(2, result.getCell(0, 3));
    Assert.assertEquals(1, result.getCell(1, 3));
    Assert.assertEquals(1, result.getCell(2, 3));

    result = GameGridUtil.getFutureGrid(grid, Direction.RIGHT);
    Assert.assertEquals(1, result.getCell(0, 0));
    Assert.assertEquals(2, result.getCell(0, 2));
    Assert.assertEquals(2, result.getCell(0, 3));
  }

  @Test
  public void test1() {
    System.out.println("---------------------------------------------------------");
    GameGrid grid = new GameGrid(4);
    grid.setCell(1, 2, 1);
    grid.setCell(2, 2, 1);
    grid.setCell(0, 0, 1);
    grid.setCell(0, 1, 1);
    grid.setCell(0, 3, 2);
    System.out.println(grid);

    double[] result = GameGridConverter.asDirectionWithHintArray(grid);
    for (double val : result) {
      System.out.print(val + ", ");
    }
    System.out.println();

    Assert.assertEquals(0, result[0], 0.0);
    Assert.assertEquals(0, result[1], 0.0);
    Assert.assertEquals(1, result[2], 0.0);
    Assert.assertEquals(0, result[3], 0.0);
    Assert.assertEquals(1, result[4], 0.0);
    Assert.assertEquals(0, result[5], 0.0);
    Assert.assertEquals(0, result[6], 0.0);
    Assert.assertEquals(0, result[7], 0.0);
    Assert.assertEquals(1, result[8], 0.0);
    Assert.assertEquals(1, result[9], 0.0);
    Assert.assertEquals(1, result[10], 0.0);
    Assert.assertEquals(1, result[11], 0.0);
  }

  @Test
  public void test2() {
    System.out.println("---------------------------------------------------------");
    GameGrid grid = new GameGrid(4);
    grid.setCell(1, 2, 1);
    grid.setCell(2, 2, 1);
    System.out.println(grid);

    double[] result = GameGridConverter.asDirectionWithHintArray(grid);
    for (double val : result) {
      System.out.print(val + ", ");
    }
    System.out.println();

    Assert.assertEquals(0, result[0], 0.0);
    Assert.assertEquals(0, result[1], 0.0);
    Assert.assertEquals(1, result[2], 0.0);
    Assert.assertEquals(0, result[3], 0.0);
    Assert.assertEquals(0, result[4], 0.0);
    Assert.assertEquals(0, result[5], 0.0);
    Assert.assertEquals(0, result[6], 0.0);
    Assert.assertEquals(0, result[7], 0.0);
    Assert.assertEquals(1, result[8], 0.0);
    Assert.assertEquals(0, result[9], 0.0);
    Assert.assertEquals(1, result[10], 0.0);
    Assert.assertEquals(0, result[11], 0.0);
  }

  @Test
  public void test3() {
    GameGrid grid = new GameGrid(4);
    grid.setCell(1, 2, 1);
    grid.setCell(2, 2, 1);
    grid.setCell(3, 2, 1);
    System.out.println(grid);

    GameGrid result = GameGridUtil.getFutureGrid(grid, Direction.LEFT);
    System.out.println(result);
    Assert.assertEquals(1, result.getCell(2, 2));
    Assert.assertEquals(2, result.getCell(3, 2));

    result = GameGridUtil.getFutureGrid(grid, Direction.RIGHT);
    Assert.assertEquals(2, result.getCell(0, 2));
    Assert.assertEquals(1, result.getCell(1, 2));
  }

  @Test
  public void test4() {
    GameGrid grid = new GameGrid(4, new int[][] { { 0, 2, 8, 32 }, { 2, 4, 8, 64 }, { 2, 8, 16, 8 }, { 0, 4, 32, 4 } });
    System.out.println(grid);
    System.out.println(GameGridUtil.getFutureGrid(grid, Direction.RIGHT));

    Assert.assertFalse(GameGridUtil.findCluster(GameGridUtil.getFutureGrid(grid, Direction.RIGHT), true));
  }

  @Test
  public void test5() {
    GameGrid grid = new GameGrid(4, new int[][] { { 0, 0, 0, 8 }, { 2, 0, 0, 16 }, { 0, 4, 8, 64 }, { 2, 2, 16, 32 } });
    System.out.println(grid);
    System.out.println(GameGridUtil.getFutureGrid(grid, Direction.RIGHT));

    Assert.assertTrue(GameGridUtil.findCluster(GameGridUtil.getFutureGrid(grid, Direction.RIGHT), true));
    Assert.assertFalse(GameGridUtil.findCluster(GameGridUtil.getFutureGrid(grid, Direction.RIGHT), false));
  }

}


text:
package com.github.blindpirate.gogradle.common;

import org.apache.commons.io.filefilter.WildcardFileFilter;

import java.io.File;
import java.nio.file.Files;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import static com.github.blindpirate.gogradle.common.GoSourceCodeFilter.SourceSetType.PROJECT_BUILD_FILES_ONLY;
import static com.github.blindpirate.gogradle.common.GoSourceCodeFilter.SourceSetType.PROJECT_TEST_FILES_ONLY;
import static com.github.blindpirate.gogradle.core.GolangConfiguration.BUILD;
import static com.github.blindpirate.gogradle.core.dependency.produce.SourceCodeDependencyFactory.TESTDATA_DIRECTORY;
import static com.github.blindpirate.gogradle.core.dependency.produce.VendorDependencyFactory.VENDOR_DIRECTORY;
import static com.github.blindpirate.gogradle.util.IOUtils.filterFilesRecursively;
import static com.github.blindpirate.gogradle.util.IOUtils.isValidDirectory;
import static com.github.blindpirate.gogradle.util.StringUtils.fileNameEqualsAny;
import static com.github.blindpirate.gogradle.util.StringUtils.fileNameStartsWithDotOrUnderline;

/**
 * Filters go source code satisfying a specific predicate. By default, files/directories whose name starts
 * with _ or . and testdata directory will be discarded no matter what the predicate is.
 */
public class GoSourceCodeFilter extends AbstractFileFilter {
    public enum SourceSetType {
        /**
         * All non-test go files in project directory, not including any files in vendor directory
         */
        PROJECT_BUILD_FILES_ONLY(true, false, false),
        /**
         * All *_test.go files in project directory, not including any files in vendor directory
         */
        PROJECT_TEST_FILES_ONLY(false, true, false),

        /**
         * PROJECT_BUILD_FILES_ONLY + PROJECT_TEST_FILES_ONLY
         */
        PROJECT_ALL_FILES_ONLY(true, true, false),

        /**
         * All non-test go files in project directory as well as all non-test go files in vendor directory
         */
        PROJECT_AND_VENDOR_BUILD_FILES(true, false, true),

        /**
         * All *.go files in project directory as well as all non-test go files in vendor directory
         */
        PROJECT_TEST_AND_VENDOR_BUILD_FILES(true, true, true);

        private boolean containsProjectBuildFiles;
        private boolean containsProjectTestFiles;
        private boolean containsVendorBuildFiles;

        SourceSetType(boolean containsProjectBuildFiles,
                      boolean containsProjectTestFiles,
                      boolean containsVendorBuildFiles) {
            this.containsProjectBuildFiles = containsProjectBuildFiles;
            this.containsProjectTestFiles = containsProjectTestFiles;
            this.containsVendorBuildFiles = containsVendorBuildFiles;
        }
    }

    public static Collection<File> filterGoFiles(File projectDir, String configuration) {
        return BUILD.equals(configuration)
                ? filterGoFiles(projectDir, PROJECT_BUILD_FILES_ONLY)
                : filterGoFiles(projectDir, PROJECT_TEST_FILES_ONLY);
    }

    public static Collection<File> filterGoFiles(File projectDir, SourceSetType sourceSetType) {
        Collection<File> projectGoFiles = filterProjectGoFiles(projectDir, sourceSetType);
        if (sourceSetType.containsVendorBuildFiles && isValidDirectory(new File(projectDir, VENDOR_DIRECTORY))) {
            Set<File> result = new HashSet<>(projectGoFiles);
            result.addAll(filterVendorGoFiles(projectDir));
            return result;
        } else {
            return projectGoFiles;
        }
    }

    /**
     * Filters tests files with specific patterns. Wildcards are supported.
     *
     * @param projectDir the project root directory.
     * @param patterns the pattern list
     * @return all files in the project directory (recursively) matching the patterns
     */
    public static Collection<File> filterTestsMatchingPattern(File projectDir, List<String> patterns) {
        WildcardFileFilter wildcardFileFilter = new WildcardFileFilter(patterns);
        return filterGoFiles(projectDir, PROJECT_TEST_FILES_ONLY)
                .stream()
                .filter(wildcardFileFilter::accept)
                .collect(Collectors.toList());
    }

    private static Collection<File> filterVendorGoFiles(File projectDir) {
        Predicate<File> goFilesPredicate = file -> containThisFile(file, true, false);
        return filterFilesRecursively(new File(projectDir, VENDOR_DIRECTORY), new GoSourceCodeFilter(goFilesPredicate));
    }

    private static Collection<File> filterProjectGoFiles(File projectDir, SourceSetType sourceSetType) {
        Predicate<File> notVendorPredicate = dir -> !isVendorDirectoryOfProject(dir, projectDir);
        Predicate<File> projectGoFilesPredicate = file -> containThisFile(file, sourceSetType);

        return filterFilesRecursively(projectDir, new GoSourceCodeFilter(projectGoFilesPredicate, notVendorPredicate));
    }

    private static boolean containThisFile(File file, SourceSetType sourceSetType) {
        return containThisFile(file, sourceSetType.containsProjectBuildFiles, sourceSetType.containsProjectTestFiles);
    }

    private static boolean containThisFile(File file, boolean containsBuildFiles, boolean containsTestFiles) {
        String fileName = file.getName();
        if (!fileName.endsWith(".go")) {
            return false;
        }
        if (fileName.endsWith("_test.go")) {
            return containsTestFiles;
        }
        return containsBuildFiles;
    }

    private static boolean isVendorDirectoryOfProject(File dir, File projectDir) {
        return VENDOR_DIRECTORY.equals(dir.getName()) && projectDir.equals(dir.getParentFile());
    }

    private Predicate<File> filePredicate;
    private Predicate<File> dirPredicate;

    private GoSourceCodeFilter(Predicate<File> filePredicate) {
        this(filePredicate, dir -> true);
    }

    private GoSourceCodeFilter(Predicate<File> filePredicate, Predicate<File> dirPredicate) {
        this.filePredicate = filePredicate;
        this.dirPredicate = dirPredicate;
    }

    @Override
    protected boolean acceptFile(File file) {
        if (fileNameStartsWithDotOrUnderline(file)) {
            return false;
        }
        return filePredicate.test(file);
    }

    @Override
    protected boolean acceptDir(File dir) {
        if (Files.isSymbolicLink(dir.toPath())) {
            return false;
        }
        if (fileNameStartsWithDotOrUnderline(dir)) {
            return false;
        }
        if (fileNameEqualsAny(dir, TESTDATA_DIRECTORY)) {
            return false;
        }
        return dirPredicate.test(dir);
    }
}


text:
<?php

namespace HttpOz\Roles\Tests\Unit;

use HttpOz\Roles\Models\Role;
use HttpOz\Roles\Tests\Stubs\User;
use HttpOz\Roles\Tests\TestCase;

class RoleHasRelationsTraitTest extends TestCase
{
    public function testRoleCanFetchUsers()
    {
        $role = Role::factory()->create();
        User::factory(10)->create()->each(function ($u) use ($role) {
            $u->attachRole($role);
        });

        $this->assertEquals(10, $role->users()->count());
    }
}