text:
package org.apache.ignite.internal.processors.cache;

import org.apache.ignite.internal.*;
import org.apache.ignite.internal.processors.affinity.*;
import org.apache.ignite.internal.processors.cache.version.*;
import org.apache.ignite.internal.util.future.*;
import org.apache.ignite.internal.util.tostring.*;
import org.apache.ignite.internal.util.typedef.*;
import org.apache.ignite.internal.util.typedef.internal.*;
import org.jetbrains.annotations.*;

import java.util.*;
import java.util.concurrent.locks.*;

/**
 * Collection of near local locks acquired by a thread on one topology version.
 */
public class GridCacheExplicitLockSpan extends ReentrantLock {
    /** */
    private static final long serialVersionUID = 0L;

    /** Topology snapshot. */
    @GridToStringInclude
    private final AffinityTopologyVersion topVer;

    /** Pending candidates. */
    @GridToStringInclude
    private final Map<KeyCacheObject, Deque<GridCacheMvccCandidate>> cands = new HashMap<>();

    /** Span lock release future. */
    @GridToStringExclude
    private final GridFutureAdapter<Object> releaseFut = new GridFutureAdapter<>();

    /**
     * @param topVer Topology version.
     * @param cand Candidate.
     */
    public GridCacheExplicitLockSpan(AffinityTopologyVersion topVer, GridCacheMvccCandidate cand) {
        this.topVer = topVer;

        ensureDeque(cand.key()).addFirst(cand);
    }

    /**
     * Adds candidate to a lock span.
     *
     * @param topVer Topology snapshot for which candidate is added.
     * @param cand Candidate to add.
     * @return {@code True} if candidate was added, {@code false} if this span is empty and
     *      new span should be created.
     */
    public boolean addCandidate(AffinityTopologyVersion topVer, GridCacheMvccCandidate cand) {
        lock();

        try {
            if (cands.isEmpty())
                return false;

            assert this.topVer.equals(this.topVer);

            Deque<GridCacheMvccCandidate> deque = ensureDeque(cand.key());

            GridCacheMvccCandidate old = F.first(deque);

            deque.add(cand);

            if (old != null && old.owner())
                cand.setOwner();

            return true;
        }
        finally {
            unlock();
        }
    }

    /**
     * Removes candidate from this lock span.
     *
     * @param cand Candidate to remove.
     * @return {@code True} if span is empty and should be removed, {@code false} otherwise.
     */
    public boolean removeCandidate(GridCacheMvccCandidate cand) {
        lock();

        try {
            Deque<GridCacheMvccCandidate> deque = cands.get(cand.key());

            if (deque != null) {
                assert !deque.isEmpty();

                if (deque.peekFirst().equals(cand)) {
                    deque.removeFirst();

                    if (deque.isEmpty())
                        cands.remove(cand.key());
                }
            }

            boolean empty = cands.isEmpty();

            if (empty)
                releaseFut.onDone();

            return empty;
        }
        finally {
            unlock();
        }
    }

    /**
     * Removes lock by key and optional version.
     *
     * @param key Key.
     * @param ver Version (or {@code null} if any candidate should be removed.)
     * @return Removed candidate if matches given parameters.
     */
    public GridCacheMvccCandidate removeCandidate(KeyCacheObject key, @Nullable GridCacheVersion ver) {
        lock();

        try {
            Deque<GridCacheMvccCandidate> deque = cands.get(key);

            GridCacheMvccCandidate cand = null;

            if (deque != null) {
                assert !deque.isEmpty();

                if (ver == null || deque.peekFirst().version().equals(ver)) {
                    cand = deque.removeFirst();

                    if (deque.isEmpty())
                        cands.remove(cand.key());
                }
            }

            boolean empty = cands.isEmpty();

            if (empty)
                releaseFut.onDone();

            return cand;
        }
        finally {
            unlock();
        }
    }

    /**
     * @return {@code True} if span is empty and candidates cannot be added anymore.
     */
    public boolean isEmpty() {
        lock();

        try {
            return cands.isEmpty();
        }
        finally {
            unlock();
        }
    }

    /**
     * Marks all candidates added for given key as owned.
     *
     * @param key Key.
     */
    public void markOwned(KeyCacheObject key) {
        lock();

        try {
            Deque<GridCacheMvccCandidate> deque = cands.get(key);

            assert deque != null;

            for (GridCacheMvccCandidate cand : deque)
                cand.setOwner();
        }
        finally {
            unlock();
        }
    }

    /**
     * Gets explicit lock candidate for given key.
     *
     * @param key Key to lookup.
     * @param ver Version to lookup (if {@code null} - return any).
     * @return Last added explicit lock candidate, if any, or {@code null}.
     */
    @Nullable public GridCacheMvccCandidate candidate(KeyCacheObject key, @Nullable final GridCacheVersion ver) {
        lock();

        try {
            Deque<GridCacheMvccCandidate> deque = cands.get(key);

            if (deque != null) {
                assert !deque.isEmpty();

                return ver == null ? deque.peekFirst() : F.find(deque, null, new P1<GridCacheMvccCandidate>() {
                    @Override public boolean apply(GridCacheMvccCandidate cand) {
                        return cand.version().equals(ver);
                    }
                });
            }

            return null;
        }
        finally {
            unlock();
        }
    }

    /**
     * Gets actual topology snapshot for thread lock span.
     *
     * @return Topology snapshot or {@code null} if candidate list is empty.
     */
    @Nullable public AffinityTopologyVersion topologyVersion() {
        return releaseFut.isDone() ? null : topVer;
    }

    /**
     * Gets span release future. Future is completed when last lock is released.
     *
     * @return Release future.
     */
    public IgniteInternalFuture<Object> releaseFuture() {
        return releaseFut;
    }

    /**
     * Gets deque from candidate map and adds it if it does not exist.
     *
     * @param key Key to look up.
     * @return Deque.
     */
    private Deque<GridCacheMvccCandidate> ensureDeque(KeyCacheObject key) {
        Deque<GridCacheMvccCandidate> deque = cands.get(key);

        if (deque == null) {
            deque = new LinkedList<>();

            cands.put(key, deque);
        }

        return deque;
    }

    /** {@inheritDoc} */
    @Override public String toString() {
        lock();

        try {
            return S.toString(GridCacheExplicitLockSpan.class, this);
        }
        finally {
            unlock();
        }
    }
}


text:
package me.chromuim.cinematic.data.local;

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

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
import me.chromuim.cinematic.core.MoviesDataSource;
import me.chromuim.cinematic.core.api.MovieReview;
import me.chromuim.cinematic.core.api.MovieVideo;
import me.chromuim.cinematic.data.Movie;
import me.chromuim.cinematic.data.local.MoviesContract.MoviesEntry;

/**
 * Created by chromuim on 17.05.17.
 */

public class MoviesLocalDataSource implements MoviesDataSource {

  private static final String TAG = "MoviesLocalDataSource";

  private static MoviesLocalDataSource INSTANCE;
  private final MoviesDbHelper mDbHelper;

  private SQLiteDatabase mDb;

  private MoviesLocalDataSource(@NonNull Context context) {
    checkNotNull(context);
    mDbHelper = new MoviesDbHelper(context);
    mDb = mDbHelper.getWritableDatabase();
  }

  public static MoviesLocalDataSource getInstance(@NonNull Context context) {
    if (INSTANCE == null) {
      INSTANCE = new MoviesLocalDataSource(context);
    }
    return INSTANCE;
  }

  @Nullable
  @Override
  public List<Movie> getMovies(String sortType, int pageNo) {
    List<Movie> movieList = new ArrayList<>();

    try {
      Cursor cursor = mDb.query(MoviesEntry.TABLE_NAME, null, null, null, null, null, null, null);
      if (cursor != null && cursor.getCount() > 0) {
        while (cursor.moveToNext()) {
          int movieId = cursor.getInt(cursor.getColumnIndexOrThrow(MoviesEntry.COLUMN_MOVIE_ID));
          String title = cursor.getString(cursor.getColumnIndexOrThrow(MoviesEntry.COLUMN_MOVIE_TITLE));
          String overview = cursor.getString(cursor.getColumnIndexOrThrow(MoviesEntry.COLUMN_MOVIE_OVERVIEW));
          String posterPath = cursor.getString(cursor.getColumnIndexOrThrow(MoviesEntry.COLUMN_MOVIE_POSTER_PATH));
          String backDropPath = cursor.getString(cursor.getColumnIndexOrThrow(MoviesEntry.COLUMN_MOVIE_BACKDROP_PATH));
          float average = cursor.getFloat(cursor.getColumnIndexOrThrow(MoviesEntry.COLUMN_MOVIE_AVERAGE));
          String releaseDate = cursor.getString(cursor.getColumnIndexOrThrow(MoviesEntry.COLUMN_MOVIE_RELEASE_DATE));

          Movie movie = new Movie(movieId, title, overview, posterPath, backDropPath, average, releaseDate);
          movieList.add(movie);
        }
      }
      if (cursor != null) {
        cursor.close();
      }
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
      Log.e(TAG, "getMovies: ", e);
    }

    return movieList;
  }

  @Nullable
  @Override
  public Movie getMovie(int movieId) {
    String selection = MoviesEntry.COLUMN_MOVIE_ID + " = ?";
    String[] selectionArgs = new String[]{String.valueOf(movieId)};

    Movie movie = null;
    try {
      Cursor cursor = mDb.query(MoviesEntry.TABLE_NAME, null, selection, selectionArgs, null, null, null, null);
      movie = null;
      if (cursor != null && cursor.getCount() > 0) {
        cursor.moveToFirst();
        int id = cursor.getInt(cursor.getColumnIndexOrThrow(MoviesEntry.COLUMN_MOVIE_ID));
        String title = cursor.getString(cursor.getColumnIndexOrThrow(MoviesEntry.COLUMN_MOVIE_TITLE));
        String overview = cursor.getString(cursor.getColumnIndexOrThrow(MoviesEntry.COLUMN_MOVIE_OVERVIEW));
        String posterPath = cursor.getString(cursor.getColumnIndexOrThrow(MoviesEntry.COLUMN_MOVIE_POSTER_PATH));
        String backDropPath = cursor.getString(cursor.getColumnIndexOrThrow(MoviesEntry.COLUMN_MOVIE_BACKDROP_PATH));
        float average = cursor.getFloat(cursor.getColumnIndexOrThrow(MoviesEntry.COLUMN_MOVIE_AVERAGE));
        String releaseDate = cursor.getString(cursor.getColumnIndexOrThrow(MoviesEntry.COLUMN_MOVIE_RELEASE_DATE));

        movie = new Movie(id, title, overview, posterPath, backDropPath, average, releaseDate);
      }

      if (cursor != null) {
        cursor.close();
      }
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
      Log.e(TAG, "getMovie: ", e);
    }

    return movie;
  }

  @Nullable
  @Override
  public List<MovieVideo> getMovieVideos(int movieId) {
    // empty for now , since i'm not saving videos in Db
    return null;
  }

  @Nullable
  @Override
  public List<MovieReview> getMovieReviews(int movieId) {
    // nothing yet
    return null;
  }

  @Override
  public void save(@NonNull Movie movie) {
    checkNotNull(movie);

    try {
      ContentValues values = new ContentValues();
      values.put(MoviesEntry.COLUMN_MOVIE_ID, movie.getId());
      values.put(MoviesEntry.COLUMN_MOVIE_TITLE, movie.getTitle());
      values.put(MoviesEntry.COLUMN_MOVIE_OVERVIEW, movie.getOverview());
      values.put(MoviesEntry.COLUMN_MOVIE_POSTER_PATH, movie.getPosterPath());
      values.put(MoviesEntry.COLUMN_MOVIE_BACKDROP_PATH, movie.getBackdropPath());
      values.put(MoviesEntry.COLUMN_MOVIE_AVERAGE, movie.getAverage());
      values.put(MoviesEntry.COLUMN_MOVIE_RELEASE_DATE, movie.getReleaseDate());

      mDb.insert(MoviesEntry.TABLE_NAME, null, values);
    } catch (Exception e) {
      e.printStackTrace();
      Log.e(TAG, "save: ", e);
    }
  }

  @Override
  public void deleteAll() {
    try {
      mDb.delete(MoviesEntry.TABLE_NAME, null, null);
    } catch (Exception e) {
      e.printStackTrace();
      Log.e(TAG, "deleteAll: ", e);
    }
  }

  @Override
  public void refreshAll() {
    // no need
  }
}

redpajama_set_name: RedPajamaGithub


text:
.formset_inputs label {
    float: left;
    margin-right: 5px;
}
span.formset_inputs input[type=text] {
    float: left;
}
.formset_inputs select {
    float: left;
    margin-left: 5px;
}
span.formset_inputs input[type=checkbox]{
    float: left;
    margin-top: 8px;
}


text:
password="testtest"

if [ $OS == "ubuntu" ]; then
	# Check if mysql is installed and store
	# the return code. (0 -> installed).
	type "mysql" >/dev/null 2>&1
	installed=$?

	# Make sure mysql is not installed before trying to install it.
	if [ $installed != 0 ]; then
		# Check if the refs have been updated by a previous module
		# and update the refs only if needed. (Fast bootstrap -> Happy developer)
		if [ -z $refs_updated ]; then
			apt-get update
			refs_updated=true
		fi

		# Set the mysql password to $password. (I hope your not using this script in production... right?).
		debconf-set-selections <<< "mysql-server-5.5 mysql-server/root_password password $password"
		debconf-set-selections <<< "mysql-server-5.5 mysql-server/root_password_again password $password"

		# Install the program we have all been waiting for
		# forefully with the -y flag.
		apt-get -y install mysql-server-5.5
	fi
elif [ $OS == "centos" ]; then
	# Check if mysql is installed and store
	# the return code. (0 -> installed).
	yum list installed mysql &>/dev/null
	installed=$?

	# Make sure httpd is not installed before trying to install it.
	if [ $installed != 0 ]; then
		# Install the mysql server.
		yum -y install mysql-server

		# Set the mysql server to run at boot.
		chkconfig mysqld on

		# Start mysql to set the password.
		service mysqld start &>/dev/null
		mysqladmin -u root password 'testtest'
	fi
fi


text:
struct ComponentOpStruct
{
  int32_t      operationID;
  const char * operationCode;
  const char * operationName;
  const bool   isRootRoleOp;
  const bool   isAdminOp;
  const bool   isDMLOp;
  const bool   isPublicOp;
};

// The ComponentListStruct describes the relationship between a component UID,
// its name, the number of operations for the component, and a pointer to the
// list of operations.
//   componentUID  - the UID for the component
//   componentName - the component name
//   numOps        - the number of operations in the component
//   componentOps  - pointer the ComponentOpStruct describing the operations
struct ComponentListStruct
{
   int64_t                   componentUID;
   const char              * componentName;
   int32_t                   numOps;
   const ComponentOpStruct * componentOps;
};

// UID's for system component
// USER_COMPONENT_START_UID begins user defined components
enum ComponentOp{ INVALID_COMPONENT_UID        = 0,
                  SQL_OPERATIONS_COMPONENT_UID = 1,
                  DBMGR_COMPONENT_UID          = 2,
                  WMS_COMPONENT_UID            = 3,
                  USER_COMPONENT_START_UID     = 1000};

// List of components
#define SQL_OPERATIONS_NAME "SQL_OPERATIONS"
#define DBMGR_NAME          "DBMGR"
#define WMS_NAME            "WMS"

// Defines component operations for SQL_OPERATIONS:
//  to add a new operation, add an entry to this list (in alphebetic order)
//  and add a corresponding entry to the sqlOpList.
enum class SQLOperation {
   ALTER = 2,
   ALTER_LIBRARY,
   ALTER_ROUTINE,
   ALTER_ROUTINE_ACTION,
   ALTER_SCHEMA,
   ALTER_SEQUENCE,
   ALTER_SYNONYM,
   ALTER_TABLE,
   ALTER_TRIGGER,
   ALTER_VIEW,
   CREATE,
   CREATE_CATALOG,
   CREATE_INDEX,
   CREATE_LIBRARY,
   CREATE_PROCEDURE,
   CREATE_ROUTINE,
   CREATE_ROUTINE_ACTION,
   CREATE_SCHEMA,
   CREATE_SEQUENCE,
   CREATE_SYNONYM,
   CREATE_TABLE,
   CREATE_TRIGGER,
   CREATE_VIEW,
   DML_DELETE,
   DML_EXECUTE,
   DML_INSERT,
   DML_REFERENCES,
   DML_SELECT,
   DML_SELECT_METADATA,
   DML_UPDATE,
   DML_USAGE,
   DROP,
   DROP_CATALOG,
   DROP_INDEX,
   DROP_LIBRARY,
   DROP_PROCEDURE,
   DROP_ROUTINE,
   DROP_ROUTINE_ACTION,
   DROP_SCHEMA,
   DROP_SEQUENCE,
   DROP_SYNONYM,
   DROP_TABLE,
   DROP_TRIGGER,
   DROP_VIEW,
   MANAGE,
   MANAGE_COMPONENTS,
   MANAGE_LIBRARY,
   MANAGE_LOAD,
   MANAGE_PRIVILEGES,
   MANAGE_ROLES,
   MANAGE_STATISTICS,
   MANAGE_TENANTS,
   MANAGE_USERS,
   QUERY_ACTIVATE,
   QUERY_CANCEL,
   QUERY_SUSPEND,
   REGISTER_HIVE_OBJECT,
   REMAP_USER,
   SHOW,
   UNREGISTER_HIVE_OBJECT,
   USE_ALTERNATE_SCHEMA,
   FIRST_OPERATION = ALTER,
   LAST_OPERATION = USE_ALTERNATE_SCHEMA,
   NUMBER_OF_OPERATIONS = LAST_OPERATION - FIRST_OPERATION + 1,
   UNKNOWN,
   FIRST_DML_PRIV = DML_DELETE,
   LAST_DML_PRIV = DML_USAGE
};

// Assign initial privileges for SQL_OPERATIONS (based on ComponentOpStruct):
//    recommend that DB__ROOTROLE granted all non DML privileges
//    recommend that DB__ADMIN and DB__ADMINROLE granted all non DML privileges
//    recommend that PUBLIC granted only a small subset of privileges
static const ComponentOpStruct sqlOpList[] =
{
 {(int32_t)SQLOperation::ALTER,               "A0","ALTER",true,true,false,false},
 {(int32_t)SQLOperation::ALTER_LIBRARY,       "AL","ALTER_LIBRARY",true,false,false,false},
 {(int32_t)SQLOperation::ALTER_ROUTINE,       "AR","ALTER_ROUTINE",true,false,false,false},
 {(int32_t)SQLOperation::ALTER_ROUTINE_ACTION,"AA","ALTER_ROUTINE_ACTION",true,false,false,false},
 {(int32_t)SQLOperation::ALTER_SCHEMA,        "AH","ALTER_SCHEMA",true,false,false,false},
 {(int32_t)SQLOperation::ALTER_SEQUENCE,      "AQ","ALTER_SEQUENCE",true,false,false,false},
 {(int32_t)SQLOperation::ALTER_SYNONYM,       "AY","ALTER_SYNONYM",true,false,false,false},
 {(int32_t)SQLOperation::ALTER_TABLE,         "AT","ALTER_TABLE",true,false,false,false},
 {(int32_t)SQLOperation::ALTER_TRIGGER,       "AG","ALTER_TRIGGER",true,false,false,false},
 {(int32_t)SQLOperation::ALTER_VIEW,          "AV","ALTER_VIEW",true,false,false,false},

 {(int32_t)SQLOperation::CREATE,              "C0","CREATE",true,true,false,false },
 {(int32_t)SQLOperation::CREATE_CATALOG,      "CC","CREATE_CATALOG",true,false,false,false},
 {(int32_t)SQLOperation::CREATE_INDEX,        "CI","CREATE_INDEX",true,false,false,false},
 {(int32_t)SQLOperation::CREATE_LIBRARY,      "CL","CREATE_LIBRARY",true,false,false,false},
 {(int32_t)SQLOperation::CREATE_PROCEDURE,    "CP","CREATE_PROCEDURE",true,false,false,false},
 {(int32_t)SQLOperation::CREATE_ROUTINE,      "CR","CREATE_ROUTINE",true,false,false,false},
 {(int32_t)SQLOperation::CREATE_ROUTINE_ACTION,"CA","CREATE_ROUTINE_ACTION",true,false,false,false},
 {(int32_t)SQLOperation::CREATE_SCHEMA,       "CH","CREATE_SCHEMA",true,false,false,true},
 {(int32_t)SQLOperation::CREATE_SEQUENCE,     "CQ","CREATE_SEQUENCE",true,false,false,false},
 {(int32_t)SQLOperation::CREATE_SYNONYM,      "CY","CREATE_SYNONYM",true,false,false,false},
 {(int32_t)SQLOperation::CREATE_TABLE,        "CT","CREATE_TABLE",true,false,false,false},
 {(int32_t)SQLOperation::CREATE_TRIGGER,      "CG","CREATE_TRIGGER",true,false,false,false},
 {(int32_t)SQLOperation::CREATE_VIEW,         "CV","CREATE_VIEW",true,false,false,false},

 {(int32_t)SQLOperation::DML_DELETE,     "PD","DML_DELETE",false,false,true,false},
 {(int32_t)SQLOperation::DML_EXECUTE,    "PE","DML_EXECUTE",false,false,true,false},
 {(int32_t)SQLOperation::DML_INSERT,     "PI","DML_INSERT",false,false,true,false},
 {(int32_t)SQLOperation::DML_REFERENCES, "PR","DML_REFERENCES",false,false,true,false},
 {(int32_t)SQLOperation::DML_SELECT,     "PS","DML_SELECT",false,false,true,false},
 {(int32_t)SQLOperation::DML_SELECT_METADATA,"PM","DML_SELECT_METADATA",true,true,true,false},
 {(int32_t)SQLOperation::DML_UPDATE,     "PU","DML_UPDATE",false,false,true,false},
 {(int32_t)SQLOperation::DML_USAGE,      "PG","DML_USAGE",false,false,true,false},

 {(int32_t)SQLOperation::DROP,               "D0","DROP",true,true,false,false },
 {(int32_t)SQLOperation::DROP_CATALOG,       "DC","DROP_CATALOG",true,false,false,false},
 {(int32_t)SQLOperation::DROP_INDEX,         "DI","DROP_INDEX",true,false,false,false},
 {(int32_t)SQLOperation::DROP_LIBRARY,       "DL","DROP_LIBRARY",true,false,false,false},
 {(int32_t)SQLOperation::DROP_PROCEDURE,     "DP","DROP_PROCEDURE",true,false,false,false},
 {(int32_t)SQLOperation::DROP_ROUTINE,       "DR","DROP_ROUTINE",true,false,false,false},
 {(int32_t)SQLOperation::DROP_ROUTINE_ACTION,"DA","DROP_ROUTINE_ACTION",true,false,false,false},
 {(int32_t)SQLOperation::DROP_SCHEMA,        "DH","DROP_SCHEMA",true,false,false,false},
 {(int32_t)SQLOperation::DROP_SEQUENCE,      "DQ","DROP_SEQUENCE",true,false,false,false},
 {(int32_t)SQLOperation::DROP_SYNONYM,       "DY","DROP_SYNONYM",true,false,false,false},
 {(int32_t)SQLOperation::DROP_TABLE,         "DT","DROP_TABLE",true,false,false,false},
 {(int32_t)SQLOperation::DROP_TRIGGER,       "DG","DROP_TRIGGER",true,false,false,false},
 {(int32_t)SQLOperation::DROP_VIEW,          "DV","DROP_VIEW",true,false,false,false},

 {(int32_t)SQLOperation::MANAGE,            "M0","MANAGE",true,true,false,false},
 {(int32_t)SQLOperation::MANAGE_COMPONENTS, "MC","MANAGE_COMPONENTS",true,false,false,false},
 {(int32_t)SQLOperation::MANAGE_LIBRARY,    "ML","MANAGE_LIBRARY",true,false,false,false},
 {(int32_t)SQLOperation::MANAGE_LOAD,       "MT","MANAGE_LOAD",true,false,false,false},
 {(int32_t)SQLOperation::MANAGE_PRIVILEGES, "MP","MANAGE_PRIVILEGES",true,false,false,false},
 {(int32_t)SQLOperation::MANAGE_ROLES,      "MR","MANAGE_ROLES",true,false,false,false},
 {(int32_t)SQLOperation::MANAGE_STATISTICS, "MS","MANAGE_STATISTICS",true,false,false,false},
 {(int32_t)SQLOperation::MANAGE_TENANTS,    "MX","MANAGE_TENANTS",true,false,false,false},
 {(int32_t)SQLOperation::MANAGE_USERS,      "MU","MANAGE_USERS",true,false,false,false},

 {(int32_t)SQLOperation::QUERY_ACTIVATE, "QA","QUERY_ACTIVATE",true,true,false,false},
 {(int32_t)SQLOperation::QUERY_CANCEL,   "QC","QUERY_CANCEL",true,true,false,false},
 {(int32_t)SQLOperation::QUERY_SUSPEND,  "QS","QUERY_SUSPEND",true,true,false,false},
 {(int32_t)SQLOperation::REGISTER_HIVE_OBJECT,  "RH","REGISTER_HIVE_OBJECT",true,true,false,false},

 {(int32_t)SQLOperation::REMAP_USER,           "RU","REMAP_USER",true,true,false,false},
 {(int32_t)SQLOperation::SHOW,                 "SW","SHOW",true,true,false,false},
 {(int32_t)SQLOperation::UNREGISTER_HIVE_OBJECT,  "UH","UNREGISTER_HIVE_OBJECT",true,true,false,false},
 {(int32_t)SQLOperation::USE_ALTERNATE_SCHEMA, "UA","USE_ALTERNATE_SCHEMA",true,true,false,false}
};

// Defines the component operations for DBMGR:
//   add an entry to this list for new DBMGR operations(in alphabetic order)
//   and to the corresponding dbmgrOpList
enum class DBMGROperation {
   MANAGE_ALERTS = 2,
   MANAGE_SESSIONS,
   SHOW_ACTIVE_QUERIES,
   SHOW_EVENT_LOGS,
   SHOW_REPOS_QUERIES
};

// Assign initial privileges for DBMGROperation (based on ComponentOpStruct):
static const ComponentOpStruct dbmgrOpList[] =
{
 {(int32_t)DBMGROperation::MANAGE_ALERTS,       "MA","MANAGE_ALERTS",true,true,false,false},
 {(int32_t)DBMGROperation::MANAGE_SESSIONS,     "MS","MANAGE_SESSIONS",true,true,false,false},
 {(int32_t)DBMGROperation::SHOW_ACTIVE_QUERIES, "AQ","SHOW_ACTIVE_QUERIES",true,true,false,false},
 {(int32_t)DBMGROperation::SHOW_EVENT_LOGS,     "EL","SHOW_EVENT_LOGS",true,true,false,false},
 {(int32_t)DBMGROperation::SHOW_REPOS_QUERIES,  "RQ","SHOW_REPOS_QUERIES",true,true,false,false}
};

// Defines the component operations for WMS:
//   add an entry to this list for new WMS operations (in alphabetic order)
//   and to the corresponding wmsOpList
enum class WMSOperation {
   MANAGE_WMS = 2
};

// Assign initial privileges for DBMGROperation (based on ComponentOpStruct):
static const ComponentOpStruct wmsOpList[] =
{
 {(int32_t)WMSOperation::MANAGE_WMS,       "MW","MANAGE_WMS",true,true,false,false},
};

// List of components
static const ComponentListStruct componentList[]
{ { (int64_t)SQL_OPERATIONS_COMPONENT_UID, SQL_OPERATIONS_NAME, sizeof(sqlOpList)/sizeof(ComponentOpStruct), (ComponentOpStruct *)&sqlOpList },
  { (int64_t)DBMGR_COMPONENT_UID, DBMGR_NAME, sizeof(dbmgrOpList)/sizeof(ComponentOpStruct), (ComponentOpStruct *)&dbmgrOpList },
  { (int64_t)WMS_COMPONENT_UID, WMS_NAME, sizeof(wmsOpList)/sizeof(ComponentOpStruct), (ComponentOpStruct *)&wmsOpList } };

#endif


text:
/**
 *
 * $Id$
 */
package subkdm.kdmObjects.validation;

import org.eclipse.emf.common.util.EList;

import subkdm.kdmObjects.AbstractCodeElement;

/**
 * A sample validator interface for {@link subkdm.kdmObjects.Module}.
 * This doesn't really do anything, and it's not a real EMF artifact.
 * It was generated by the org.eclipse.emf.examples.generator.validator plug-in to illustrate how EMF's code generator can be extended.
 * This can be disabled with -vmargs -Dorg.eclipse.emf.examples.generator.validator=false.
 */
public interface ModuleValidator {
	boolean validate();

	boolean validateCodeElement(EList<AbstractCodeElement> value);
}


text:
.. _marvin-utils-maskbit:

=====================================================
Maskbit (:mod:`marvin.utils.general.maskbit.Maskbit`)
=====================================================

.. _marvin-utils-maskbit-intro:

Introduction
------------
:mod:`~marvin.utils.general.maskbit.Maskbit` contains the schema for a MaNGA flag (e.g., ``MANGA_DAPPIXMASK``) and provides convenience functions for translating amongst mask values, bits, and labels.

.. _marvin-utils-maskbit-getting-started:

Getting Started
---------------

:mod:`~marvin.utils.general.maskbit.Maskbit` is most frequently encountered as an attribute on a :ref:`marvin-tools` object (e.g., :attr:`marvin.tools.quantities.Map.pixmask` is an instance of :mod:`~marvin.utils.general.maskbit.Maskbit`).

.. code-block:: python

    from marvin.tools.maps import Maps
    maps = Maps(plateifu='8485-1901')
    ha = maps['gflux ha']

    ha.pixmask
    # <Maskbit 'MANGA_DAPPIXMASK'
    #
    #     bit         label                                        description
    # 0     0         NOCOV                         No coverage in this spaxel
    # 1     1        LOWCOV                        Low coverage in this spaxel
    # 2     2     DEADFIBER                   Major contributing fiber is dead
    # 3     3      FORESTAR                                    Foreground star
    # 4     4       NOVALUE  Spaxel was not fit because it did not meet sel...
    # 5     5    UNRELIABLE  Value is deemed unreliable; see TRM for defini...
    # 6     6     MATHERROR              Mathematical error in computing value
    # 7     7     FITFAILED                  Attempted fit for property failed
    # 8     8     NEARBOUND  Fitted value is too near an imposed boundary; ...
    # 9     9  NOCORRECTION               Appropriate correction not available
    # 10   10     MULTICOMP          Multi-component velocity features present
    # 11   30      DONOTUSE                 Do not use this spaxel for science>

It is also possible to initialize a :mod:`~marvin.utils.general.maskbit.Maskbit` instance without a :ref:`marvin-tools` object:

.. code-block:: python

    from marvin.utils.general.maskbit import Maskbit
    mngtarg1 = Maskbit('MANGA_TARGET1')

    mngtarg1.schema
    #     bit                  label                     description
    # 0     0                   NONE
    # 1     1       PRIMARY_PLUS_COM        March 2014 commissioning
    # 2     2          SECONDARY_COM        March 2014 commissioning
    # 3     3     COLOR_ENHANCED_COM        March 2014 commissioning
    # 4     4         PRIMARY_v1_1_0   First tag, August 2014 plates
    # 5     5       SECONDARY_v1_1_0   First tag, August 2014 plates
    # 6     6  COLOR_ENHANCED_v1_1_0   First tag, August 2014 plates
    # 7     7           PRIMARY_COM2         July 2014 commissioning
    # 8     8         SECONDARY_COM2         July 2014 commissioning
    # 9     9    COLOR_ENHANCED_COM2         July 2014 commissioning
    # 10   10         PRIMARY_v1_2_0
    # 11   11       SECONDARY_v1_2_0
    # 12   12  COLOR_ENHANCED_v1_2_0
    # 13   13                 FILLER                  Filler targets
    # 14   14                RETIRED            Bit retired from use>

.. _marvin-utils-maskbit-using:

Using :mod:`~marvin.utils.general.maskbit.Maskbit`
--------------------------------------------------

Maskbit Schema
``````````````

:mod:`~marvin.utils.general.maskbit.Maskbit` makes properly applying masks easy by providing the schema for a flag:

.. code-block:: python

    from marvin.tools.maps import Maps
    maps = Maps(plateifu='8485-1901')
    ha = maps['gflux ha']

    ha.manga_target1.description
    # 'Targeting bits for all galaxy targets.'

    ha.manga_target1.schema
    #     bit                  label                     description
    # 0     0                   NONE
    # 1     1       PRIMARY_PLUS_COM        March 2014 commissioning
    # 2     2          SECONDARY_COM        March 2014 commissioning
    # 3     3     COLOR_ENHANCED_COM        March 2014 commissioning
    # 4     4         PRIMARY_v1_1_0   First tag, August 2014 plates
    # 5     5       SECONDARY_v1_1_0   First tag, August 2014 plates
    # 6     6  COLOR_ENHANCED_v1_1_0   First tag, August 2014 plates
    # 7     7           PRIMARY_COM2         July 2014 commissioning
    # 8     8         SECONDARY_COM2         July 2014 commissioning
    # 9     9    COLOR_ENHANCED_COM2         July 2014 commissioning
    # 10   10         PRIMARY_v1_2_0
    # 11   11       SECONDARY_v1_2_0
    # 12   12  COLOR_ENHANCED_v1_2_0
    # 13   13                 FILLER                  Filler targets
    # 14   14                RETIRED            Bit retired from use

Mask, Bits, and Labels
``````````````````````

It also contains the mask value, the corresponding bits, and the corresponding labels for the :ref:`marvin-tools` object:

.. code-block:: python

    ha.manga_target1.mask    # 2336
    ha.manga_target1.bits    # [5, 8, 11]
    ha.manga_target1.labels  # ['SECONDARY_v1_1_0', 'SECONDARY_COM2', 'SECONDARY_v1_2_0']

Array of Mask Values
````````````````````

Let's look at a flag with a mask that is an array and not just a single integer:

.. code-block:: python

    ha.pixmask
    # <Maskbit 'MANGA_DAPPIXMASK'
    #
    #     bit         label                                        description
    # 0     0         NOCOV                         No coverage in this spaxel
    # 1     1        LOWCOV                        Low coverage in this spaxel
    # 2     2     DEADFIBER                   Major contributing fiber is dead
    # 3     3      FORESTAR                                    Foreground star
    # 4     4       NOVALUE  Spaxel was not fit because it did not meet sel...
    # 5     5    UNRELIABLE  Value is deemed unreliable; see TRM for defini...
    # 6     6     MATHERROR              Mathematical error in computing value
    # 7     7     FITFAILED                  Attempted fit for property failed
    # 8     8     NEARBOUND  Fitted value is too near an imposed boundary; ...
    # 9     9  NOCORRECTION               Appropriate correction not available
    # 10   10     MULTICOMP          Multi-component velocity features present
    # 11   30      DONOTUSE                 Do not use this spaxel for science>

    ha.pixmask.mask  # == ha.mask
    # array([[1073741843, 1073741843, 1073741843, ..., 1073741843, 1073741843,
    #     1073741843],
    #    ...,
    #    [1073741843, 1073741843, 1073741843, ..., 1073741843, 1073741843,
    #     1073741843]])

    ha.pixmask.bits
    # [[[0, 1, 4, 30],
    #   ...,
    # [0, 1, 4, 30]]]

    ha.pixmask.labels
    # [[['NOCOV', 'LOWCOV', 'NOVALUE', 'DONOTUSE'],
    #   ...,
    # ['NOCOV', 'LOWCOV', 'NOVALUE', 'DONOTUSE']]]

    ha.pixmask.mask[17, 32]    # 1073741843
    ha.pixmask.bits[17][32]    # [0, 1, 4, 30]
    ha.pixmask.labels[17][32]  # ['NOCOV', 'LOWCOV', 'NOVALUE', 'DONOTUSE']

Translating Amongst Mask Values, Bits, and labels
`````````````````````````````````````````````````

With ``MANGA_DAPPIXMASK``, you might want to translate individual mask values, bits, or labels:

.. code-block:: python

    ha.pixmask.values_to_bits(1073741843)  # [0, 1, 4, 30]
    ha.pixmask.values_to_labels(1073741843)  #['NOCOV', 'LOWCOV', 'NOVALUE', 'DONOTUSE']

    # Translate one label
    ha.pixmask.labels_to_value('NOCOV')  # 1
    ha.pixmask.labels_to_bits('NOCOV')   # [0]

    # Translate multiple labels
    ha.pixmask.labels_to_value(['NOCOV', 'UNRELIABLE'])  # 33
    ha.pixmask.labels_to_bits(['NOCOV', 'UNRELIABLE'])  # [0, 5]

Making a Custom Mask
````````````````````

You might want to produce a mask (e.g., to produce a custom mask for plotting):

.. TODO FIX ha.value < 1e-17

.. code-block:: python

    # Mask of regions with no IFU coverage
    nocov = ha.pixmask.get_mask('NOCOV')

    # Mask of regions with low Halpha flux and marked as DONOTUSE
    low_ha = (ha.value < 1e-17) * ha.pixmask.labels_to_value('DONOTUSE')

    # Combine masks using bitwise OR (`|`)
    my_mask = nocov | low_ha

    fig, ax = ha.plot(mask=my_mask)

.. TODO UNCOMMENT
.. .. image:: ../_static/custom_mask.png

See the :doc:`../tutorials/plotting-tutorial` (e.g., :ref:`marvin-plotting-custom-map-axes`) for more about custom masks.

Reference/API
-------------

.. rubric:: Class Inheritance Diagram

.. inheritance-diagram:: marvin.utils.general.maskbit.Maskbit

.. rubric:: Module

.. autosummary:: marvin.utils.general.maskbit.

.. rubric:: Functions

.. autosummary::

    marvin.utils.general.maskbit.Maskbit.get_mask
    marvin.utils.general.maskbit.Maskbit.labels_to_bits
    marvin.utils.general.maskbit.Maskbit.labels_to_value
    marvin.utils.general.maskbit.Maskbit.values_to_labels
    marvin.utils.general.maskbit.Maskbit.values_to_bits


text:
using GalaSoft.MvvmLight.Messaging;
using LightBuzz.Vitruvius.Core;
using Microsoft.Kinect;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using WindowsInput;
using WindowsInput.Native;

//TODO: why not use CanvasExtensions here and move/merge respective functionality to it?
//TODO: why not wrap the parent Grid of Image and Canvas controls' inside a Viewbox and thus avoid manually resizing the Canvas?

namespace LightBuzz.Vitruvius.Controls
{
    /// <summary>
    /// Interaction logic for KinectViewer.xaml
    /// </summary>
    public partial class KinectViewer : UserControl
    {
        #region --- Constants ---

        /// <summary>
        /// A custom tag indicating that the UIElement was drawn with Vitruvius.
        /// </summary>
        protected const string TAG = "LightBuzz.Vitruvius"; //strings are immutable (and a string pool is used) so using static readonly should give no performance benefit

        /// <summary>
        /// The default drawing color.
        /// </summary>
        protected static readonly Color DEFAULT_COLOR = Colors.LightCyan;

        /// <summary>
        /// The default circle radius.
        /// </summary>
        protected const double DEFAULT_ELLIPSE_RADIUS = 20;

        /// <summary>
        /// The default line thickness.
        /// </summary>
        protected const double DEFAULT_BONE_THICKNESS = 8;

        /// <summary>
        /// The default horizontal flipping.
        /// </summary>
        protected const bool DEFAULT_FLIPPED_HORIZONTALLY = false;

        /// <summary>
        /// The default vertical flipping.
        /// </summary>
        protected const bool DEFAULT_FLIPPED_VERTICALLY = false;

        #endregion

        #region --- Fields ---

        protected int _kinectFrameWidth; //=0
        protected int _kinectFrameHeight; //=0

        protected double _ratioX = 1.0;
        protected double _ratioY = 1.0;

        ConcurrentDictionary<Color, VirtualKeyCode> colorToKey = new ConcurrentDictionary<Color, VirtualKeyCode>();

        #endregion

        #region --- Initialization ---

        Ellipse e1, e2, e3, e4;

     //   [DllImport("user32.dll")]
     //   [return: MarshalAs(UnmanagedType.Bool)]
//        static extern bool SetForegroundWindow(IntPtr hWnd);

        public KinectViewer()
        {
            //Process[] processes = Process.GetProcessesByName("chrome"); // GetProcesses();// GetProcessesByName("Google Chrome (32 bit)");
           // Process game1 = processes[0];
           // IntPtr p = game1.MainWindowHandle;
           // SetForegroundWindow(p); //GetProcessesByName("Google Chrome (32 bit)");
            this.InitializeComponent();
            SetValue(RenderTransformOriginProperty, new Point(0.5, 0.5)); //this is needed for FlippedHorizontally and FlippedVertically to work, since they set the RenderTransform property

            e1 = CreateAnEllipse(100, 100, Colors.Red , VirtualKeyCode.LEFT);

            e2 = CreateAnEllipse(100, 100, Colors.RoyalBlue,VirtualKeyCode.RIGHT);

            e3 = CreateAnEllipse(100, 100, Colors.Salmon,VirtualKeyCode.UP);
            e4 = CreateAnEllipse(100, 100, Colors.SeaGreen, VirtualKeyCode.DOWN);

            Canvas.SetLeft(e1, 10);
            Canvas.SetTop(e2, 10);

            Canvas.SetLeft(e2, 10);
            Canvas.SetTop(e2, 150);

            Canvas.SetLeft(e3, 10);
            Canvas.SetTop(e3, 250);

            Canvas.SetLeft(e4, 10);
            Canvas.SetTop(e4, 350);

            canvas2.Children.Add(e1);
            canvas2.Children.Add(e2);

            canvas2.Children.Add(e3);
            canvas2.Children.Add(e4);

            Messenger.Default.Register<bool>(this, ViewsConsts.MessagesTrackingMode, changeSensorMode);
            Messenger.Default.Register<Tuple<Color, VirtualKeyCode>>(this, ViewsConsts.MessagesNewColor, addEllipse);

        }

        private void addEllipse(Tuple<Color, VirtualKeyCode> obj)
        {
           var color = obj.Item1;
           var key = obj.Item2;

            if (colorToKey.Keys.Contains(color))
            {
                return;
            }

            e1 = CreateAnEllipse(100, 100, color, key);
            canvas2.Children.Add(e1);

        }

        bool IsSensorSeated;

        private void changeSensorMode(bool obj)
        {
            IsSensorSeated = obj;
        }

        #endregion

        #region --- Properties ---

        #region CoordinateMapper

        public CoordinateMapper CoordinateMapper
        {
            get { return (CoordinateMapper)GetValue(CoordinateMapperProperty); }
            set { SetValue(CoordinateMapperProperty, value); }
        }

        public static readonly DependencyProperty CoordinateMapperProperty =
            DependencyProperty.Register("CoordinateMapper", typeof(CoordinateMapper), typeof(KinectViewer), new PropertyMetadata(KinectSensor.KinectSensors.Where(s => s.Status == KinectStatus.Connected).FirstOrDefault().CoordinateMapper));

        #endregion

        #region FrameType

        public VisualizationMode FrameType
        {
            get { return (VisualizationMode)GetValue(KinectFrameTypeProperty); }
            set { SetValue(KinectFrameTypeProperty, value); }
        }

        public static readonly DependencyProperty KinectFrameTypeProperty =
            DependencyProperty.Register("FrameType", typeof(VisualizationMode), typeof(KinectViewer), new PropertyMetadata(VisualizationMode.Color));

        #endregion

        #region JointBrush

        public Brush JointBrush
        {
            get { return (Brush)GetValue(JointBrushProperty); }
            set { SetValue(JointBrushProperty, value); }
        }

        public static readonly DependencyProperty JointBrushProperty =
            DependencyProperty.Register("JointBrush", typeof(Brush), typeof(KinectViewer), new PropertyMetadata(new SolidColorBrush(DEFAULT_COLOR)));

        #endregion

        #region BoneBrush

        public Brush BoneBrush
        {
            get { return (Brush)GetValue(BoneBrushProperty); }
            set { SetValue(BoneBrushProperty, value); }
        }

        public static readonly DependencyProperty BoneBrushProperty =
            DependencyProperty.Register("BoneBrush", typeof(Brush), typeof(KinectViewer), new PropertyMetadata(new SolidColorBrush(DEFAULT_COLOR)));

        #endregion

        #region JointRadius

        public double JointRadius
        {
            get { return (double)GetValue(JointRadiusProperty); }
            set { SetValue(JointRadiusProperty, value); }
        }

        public static readonly DependencyProperty JointRadiusProperty =
            DependencyProperty.Register("JointRadius", typeof(double), typeof(KinectViewer), new PropertyMetadata(DEFAULT_ELLIPSE_RADIUS));

        #endregion

        #region BoneThickness

        public double BoneThickness
        {
            get { return (double)GetValue(BoneThicknessProperty); }
            set { SetValue(BoneThicknessProperty, value); }
        }

        public static readonly DependencyProperty BoneThicknessProperty =
            DependencyProperty.Register("BoneThickness", typeof(double), typeof(KinectViewer), new PropertyMetadata(DEFAULT_BONE_THICKNESS));

        #endregion

        #region FlippedHorizontally

        public bool FlippedHorizontally
        {
            get { return (bool)GetValue(FlippedHorizontallyProperty); }
            set { SetValue(FlippedHorizontallyProperty, value); }
        }

        public static readonly DependencyProperty FlippedHorizontallyProperty =
            DependencyProperty.Register("FlippedHorizontally", typeof(bool), typeof(KinectViewer),
                new PropertyMetadata(DEFAULT_FLIPPED_HORIZONTALLY, OnFlippedHorizontallyPropertyChange));

        private static void OnFlippedHorizontallyPropertyChange(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            bool flipped = (bool)e.NewValue;
            KinectViewer viewer = (KinectViewer)d;
            viewer.SetValue(RenderTransformProperty, viewer.FlipTransform);
        }

        #endregion

        #region FlippedVertically

        public bool FlippedVertically
        {
            get { return (bool)GetValue(FlippedVerticallyProperty); }
            set { SetValue(FlippedVerticallyProperty, value); }
        }

        public static readonly DependencyProperty FlippedVerticallyProperty =
            DependencyProperty.Register("FlippedVertically", typeof(bool), typeof(KinectViewer),
                new PropertyMetadata(DEFAULT_FLIPPED_VERTICALLY, OnFlippedVerticallyPropertyChange));

        private static void OnFlippedVerticallyPropertyChange(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            bool flipped = (bool)e.NewValue;
            KinectViewer viewer = (KinectViewer)d;
            viewer.SetValue(RenderTransformProperty, viewer.FlipTransform);
        }

        #endregion

        #region FlipTransform

        public ScaleTransform FlipTransform
        {
            //flips around the center point either horizontally, or vertically or both horizontally and vertically
            get
            {
                return (!FlippedHorizontally && !FlippedVertically) ? null : new ScaleTransform((FlippedHorizontally) ? -1 : 1, (FlippedVertically) ? -1 : 1); //assumes RenderTransformOrigin property has been set to (0.5, 0.5) at constructor, that is the view center
            }
        }

        #endregion

        #endregion

        #region --- Methods ---

        #region Public methods

        public void Clear() //TODO: change this method to be like Canvas.ClearSkeletons extension method and clear only the TAG'ed items?
        {
            canvas.Children.Clear();
        }

        public void DrawJoint(Joint joint, Brush brush, double radius)
        {
            if (joint.TrackingState == JointTrackingState.NotTracked) return;

            Point point = new Point(_ratioX, _ratioY);

            switch (FrameType)
            {
                case VisualizationMode.Color:
                    ColorImagePoint colorPoint = CoordinateMapper.MapSkeletonPointToColorPoint(joint.Position, ColorImageFormat.RgbResolution640x480Fps30);
                    point.X *= float.IsInfinity(colorPoint.X) ? 0.0 : colorPoint.X;
                    point.Y *= float.IsInfinity(colorPoint.Y) ? 0.0 : colorPoint.Y;
                    break;

                case VisualizationMode.Depth:
                case VisualizationMode.Infrared:
                    DepthImagePoint depthPoint = CoordinateMapper.MapSkeletonPointToDepthPoint(joint.Position, DepthImageFormat.Resolution320x240Fps30);
                    point.X *= float.IsInfinity(depthPoint.X) ? 0.0 : depthPoint.X;
                    point.Y *= float.IsInfinity(depthPoint.Y) ? 0.0 : depthPoint.Y;
                    break;

                default:
                    break;
            }

            Ellipse ellipse = new Ellipse
            {
                Tag = TAG,
                Width = radius,
                Height = radius,
                Fill = brush
            };

            Canvas.SetLeft(ellipse, point.X - ellipse.Width / 2);
            Canvas.SetTop(ellipse, point.Y - ellipse.Height / 2);

            canvas.Children.Add(ellipse);

            DoThings(ellipse, point);
        }

        InputSimulator sim = new InputSimulator();

        public async Task<bool> DoThings(Ellipse ellipse, Point point)
        {
            try
            {
                var x2 = point.X;
                var y2 = point.Y;//Canvas.GetTop(ellipse);
                Rect r2 = new Rect(x2, y2, ellipse.ActualWidth, ellipse.ActualHeight);

                //todo add key handling
                foreach (var myellipse in ellipseList) {

                    Color color = (myellipse.Fill as SolidColorBrush).Color;
                    Conflict(r2, myellipse, colorToKey[color]);
                }

            }
            catch (Exception ee)
            {
                Console.WriteLine(ee);
            }
            return true;
        }

        ConcurrentDictionary<VirtualKeyCode, VirtualKeyCode> clicks = new ConcurrentDictionary<VirtualKeyCode, VirtualKeyCode>();

        public async Task Conflict(Rect r2, Ellipse elipse, VirtualKeyCode keycode)
        {

            var x3 = Canvas.GetLeft(elipse);
            var y3 = Canvas.GetTop(elipse);
            //Rect r3 = new Rect(x3, y3, e2.ActualWidth, e2.ActualHeight);

            Rect r3 = new Rect(x3, y3, 100, 100);

            if (r2.IntersectsWith(r3))
            {
                if (clicks.Keys.Contains(keycode))
                {
                    return;
                }

                try
                {
                    //Conflict started
                    // System.Windows.Forms.SendKeys.SendWait("" + System.Windows.Forms.Keys.Left);
                    //System.Windows.Forms.SendKeys.SendWait("{LEFT}{LEFT}{LEFT}");\
                    if(clicks.TryAdd(keycode, keycode))
                    {
                        sim.Keyboard.KeyDown(keycode);
                    }

//                    await Task.Delay(1000);
//                   sim.Keyboard.KeyPress(keycode);

                    //System.Windows.Forms.SendKeys.SendWait("a");
                }
                catch (StackOverflowException ee)
                {
                    System.Windows.Forms.SendKeys.Flush();
                }
                //System.Windows.Forms.SendKeys.SendWait("{LEFT}");
            }
            else
            {
                //Conflict stoped
                if (clicks.Keys.Contains(keycode))
                {
                    sim.Keyboard.KeyPress(keycode);
                    VirtualKeyCode notused;
                    clicks.TryRemove(keycode,out notused);
                }
            }

        }

        public void DrawJoint(Joint joint)
        {
            DrawJoint(joint, JointBrush, DEFAULT_ELLIPSE_RADIUS);
        }

        public void DrawBone(Joint first, Joint second, Brush brush, double thickness)
        {
            if (first.TrackingState == JointTrackingState.NotTracked || second.TrackingState == JointTrackingState.NotTracked) return;

            Point firstPoint = new Point(_ratioX, _ratioY);
            Point secondPoint = new Point(_ratioX, _ratioY);

            switch (FrameType)
            {
                case VisualizationMode.Color:
                    ColorImagePoint colorFirstPoint = CoordinateMapper.MapSkeletonPointToColorPoint(first.Position, ColorImageFormat.RgbResolution640x480Fps30);
                    firstPoint.X *= float.IsInfinity(colorFirstPoint.X) ? 0.0 : colorFirstPoint.X;
                    firstPoint.Y *= float.IsInfinity(colorFirstPoint.Y) ? 0.0 : colorFirstPoint.Y;

                    ColorImagePoint colorSecondPoint = CoordinateMapper.MapSkeletonPointToColorPoint(second.Position, ColorImageFormat.RgbResolution640x480Fps30);
                    secondPoint.X *= float.IsInfinity(colorSecondPoint.X) ? 0.0 : colorSecondPoint.X;
                    secondPoint.Y *= float.IsInfinity(colorSecondPoint.Y) ? 0.0 : colorSecondPoint.Y;
                    break;

                case VisualizationMode.Depth:
                case VisualizationMode.Infrared:
                    DepthImagePoint depthFirstPoint = CoordinateMapper.MapSkeletonPointToDepthPoint(first.Position, DepthImageFormat.Resolution320x240Fps30);
                    firstPoint.X *= float.IsInfinity(depthFirstPoint.X) ? 0.0 : depthFirstPoint.X;
                    firstPoint.Y *= float.IsInfinity(depthFirstPoint.Y) ? 0.0 : depthFirstPoint.Y;

                    DepthImagePoint depthSecondPoint = CoordinateMapper.MapSkeletonPointToDepthPoint(second.Position, DepthImageFormat.Resolution320x240Fps30);
                    secondPoint.X *= float.IsInfinity(depthSecondPoint.X) ? 0.0 : depthSecondPoint.X;
                    secondPoint.Y *= float.IsInfinity(depthSecondPoint.Y) ? 0.0 : depthSecondPoint.Y;
                    break;

                default:
                    break;
            }

            Line line = new Line
            {
                Tag = TAG,
                X1 = firstPoint.X,
                Y1 = firstPoint.Y,
                X2 = secondPoint.X,
                Y2 = secondPoint.Y,
                StrokeThickness = thickness,
                Stroke = brush
            };

            canvas.Children.Add(line);

        }

        public void DrawBone(Joint first, Joint second)
        {
            DrawBone(first, second, BoneBrush, DEFAULT_BONE_THICKNESS);
        }

        List<Ellipse> ellipseList = new List<Ellipse>();

        // Customize your ellipse in this method
        public Ellipse CreateAnEllipse(int height, int width, Color color, VirtualKeyCode key)
        {
            SolidColorBrush fillBrush = new SolidColorBrush() { Color = color };
            SolidColorBrush borderBrush = new SolidColorBrush() { Color = Colors.Black };

            Ellipse ret = new Ellipse()
            {
                Height = height,
                Width = width,
                StrokeThickness = 1,
                Stroke = borderBrush,
                Fill = fillBrush,
                AllowDrop = true
            };

            ret.MouseMove += ellipse_MouseMove;
            ret.DragEnter += ellipse_DragEnter;
            ret.DragLeave += ellipse_DragLeave;
            ret.DragOver += ellipse_DragOver;
            ret.Drop += ellipse_Drop;

            ellipseList.Add(ret);

            colorToKey.TryAdd(color, key);

            return ret;
        }

        private void ellipse_Drop(object sender, DragEventArgs e)
        {
            Ellipse ellipse = sender as Ellipse;
            if (ellipse != null)
            {
                // If the DataObject contains string data, extract it.
                if (e.Data.GetDataPresent(DataFormats.StringFormat))
                {
                    string dataString = (string)e.Data.GetData(DataFormats.StringFormat);

                    // If the string can be converted into a Brush,
                    // convert it and apply it to the ellipse.
                    BrushConverter converter = new BrushConverter();
                    if (converter.IsValid(dataString))
                    {
                        Brush newFill = (Brush)converter.ConvertFromString(dataString);
                        ellipse.Fill = newFill;
                    }
                }
            }
        }

        private void ellipse_DragOver(object sender, DragEventArgs e)
        {
            e.Effects = DragDropEffects.None;

            // If the DataObject contains string data, extract it.
            if (e.Data.GetDataPresent(DataFormats.StringFormat))
            {
                string dataString = (string)e.Data.GetData(DataFormats.StringFormat);

                // If the string can be converted into a Brush, allow copying.
                BrushConverter converter = new BrushConverter();
                if (converter.IsValid(dataString))
                {
                    e.Effects = DragDropEffects.Copy | DragDropEffects.Move;
                }
            }
        }

        private void ellipse_DragLeave(object sender, DragEventArgs e)
        {
            Ellipse ellipse = sender as Ellipse;
            if (ellipse != null)
            {
                ellipse.Fill = _previousFill;
            }
        }

        private Brush _previousFill = null;
        private void ellipse_DragEnter(object sender, DragEventArgs e)
        {
            Ellipse ellipse = sender as Ellipse;
            if (ellipse != null)
            {
                // Save the current Fill brush so that you can revert back to this value in DragLeave.
                _previousFill = ellipse.Fill;

                // If the DataObject contains string data, extract it.
                if (e.Data.GetDataPresent(DataFormats.StringFormat))
                {
                    string dataString = (string)e.Data.GetData(DataFormats.StringFormat);

                    // If the string can be converted into a Brush, convert it.
                    BrushConverter converter = new BrushConverter();
                    if (converter.IsValid(dataString))
                    {
                        Brush newFill = (Brush)converter.ConvertFromString(dataString);
                        ellipse.Fill = newFill;
                    }
                }
            }
        }

        private void ellipse_MouseMove(object sender, MouseEventArgs e)
        {

            Ellipse ellipse = sender as Ellipse;

            if (ellipse != null && e.LeftButton == MouseButtonState.Pressed)
            {
                double firstXPos = e.GetPosition(ellipse).X;
                double firstYPos = e.GetPosition(ellipse).Y;

                //DragDrop.DoDragDrop(
                //                      ellipse,
                //                      ellipse,
                //                      DragDropEffects.All);

                Canvas.SetLeft(ellipse, e.GetPosition(this).X - 50);
                Canvas.SetTop(ellipse, e.GetPosition(this).Y);
                // DragDrop.DoDragDrop( ellipse,
                //                      ellipse,
                //                      DragDropEffects.All);
            }
        }

        public void DrawBody(Skeleton body)
        {
            Clear();
            // canvas.Children.Add(e1);

            // canvas.Children.Add(e2);

            if (body == null || body.TrackingState != SkeletonTrackingState.Tracked) return;

            foreach (Joint joint in body.Joints)
            {

                if (
                IsSensorSeated && (
                joint.JointType == JointType.HipCenter ||
                joint.JointType == JointType.HipLeft ||
                joint.JointType == JointType.HipRight ||
                joint.JointType == JointType.KneeLeft ||
                joint.JointType == JointType.KneeRight ||
                joint.JointType == JointType.AnkleLeft ||
                joint.JointType == JointType.AnkleRight ||
                joint.JointType == JointType.FootRight ||
                joint.JointType == JointType.FootLeft)
                )
                {
                    continue;
                }

                DrawJoint(joint, JointBrush, JointRadius);
            }

            DrawBone(body.Joints[JointType.Head], body.Joints[JointType.ShoulderCenter], BoneBrush, BoneThickness);
            DrawBone(body.Joints[JointType.ShoulderCenter], body.Joints[JointType.ShoulderLeft], BoneBrush, BoneThickness);
            DrawBone(body.Joints[JointType.ShoulderCenter], body.Joints[JointType.ShoulderRight], BoneBrush, BoneThickness);
            DrawBone(body.Joints[JointType.ShoulderCenter], body.Joints[JointType.Spine], BoneBrush, BoneThickness);
            DrawBone(body.Joints[JointType.ShoulderLeft], body.Joints[JointType.ElbowLeft], BoneBrush, BoneThickness);
            DrawBone(body.Joints[JointType.ShoulderRight], body.Joints[JointType.ElbowRight], BoneBrush, BoneThickness);
            DrawBone(body.Joints[JointType.ElbowLeft], body.Joints[JointType.WristLeft], BoneBrush, BoneThickness);
            DrawBone(body.Joints[JointType.ElbowRight], body.Joints[JointType.WristRight], BoneBrush, BoneThickness);
            DrawBone(body.Joints[JointType.WristLeft], body.Joints[JointType.HandLeft], BoneBrush, BoneThickness);
            DrawBone(body.Joints[JointType.WristRight], body.Joints[JointType.HandRight], BoneBrush, BoneThickness);
            DrawBone(body.Joints[JointType.Spine], body.Joints[JointType.HipCenter], BoneBrush, BoneThickness);

            if (IsSensorSeated)
            {
                return;
            }

            DrawBone(body.Joints[JointType.HipCenter], body.Joints[JointType.HipLeft], BoneBrush, BoneThickness);
            DrawBone(body.Joints[JointType.HipCenter], body.Joints[JointType.HipRight], BoneBrush, BoneThickness);
            DrawBone(body.Joints[JointType.HipLeft], body.Joints[JointType.KneeLeft], BoneBrush, BoneThickness);
            DrawBone(body.Joints[JointType.HipRight], body.Joints[JointType.KneeRight], BoneBrush, BoneThickness);
            DrawBone(body.Joints[JointType.KneeLeft], body.Joints[JointType.AnkleLeft], BoneBrush, BoneThickness);
            DrawBone(body.Joints[JointType.KneeRight], body.Joints[JointType.AnkleRight], BoneBrush, BoneThickness);
            DrawBone(body.Joints[JointType.AnkleLeft], body.Joints[JointType.FootLeft], BoneBrush, BoneThickness);
            DrawBone(body.Joints[JointType.AnkleRight], body.Joints[JointType.FootRight], BoneBrush, BoneThickness);
        }

        public void Update(BitmapSource source)
        {
            if (source != null)
                Update(new WriteableBitmap(source));
        }

        public void Update(WriteableBitmap source)
        {
            if (source == null) return;

            camera.Source = source;

            if (_kinectFrameWidth == 0 || _kinectFrameHeight == 0)
            {
                _kinectFrameWidth = source.PixelWidth;
                _kinectFrameHeight = source.PixelHeight;
            }

            if (double.IsNaN(canvas.Width) || double.IsNaN(canvas.Height) || canvas.Width == 0.0 || canvas.Height == 0.0 || double.IsInfinity(canvas.Width) || double.IsInfinity(canvas.Height))
                SetCanvasSize();
        }

        #endregion

        #region Protected methods

        protected void SetCanvasSize()
        {
            canvas.Width = camera.ActualWidth;
            canvas.Height = camera.ActualHeight;

            _ratioX = canvas.Width / _kinectFrameWidth;
            _ratioY = canvas.Height / _kinectFrameHeight;

            canvas2.Width = camera.ActualWidth;
            canvas2.Height = camera.ActualHeight;

        }

        #endregion

        #endregion

        #region --- Events ---

        protected void UserControl_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            _kinectFrameWidth = _kinectFrameHeight = 0;
            canvas.Width = canvas.Height = 0.0; //note: need to clear this too for "SetCanvasSize()" to be called next time Update method is called

            canvas2.Width = canvas2.Height = 0.0;

        }

        #endregion
    }
}


text:
namespace ChilliSource
{
    //----------------------------------------------------------------
    SystemInfo::SystemInfo(const DeviceInfo& deviceInfo, const ScreenInfo& screenInfo, const RenderInfo& renderInfo, const std::string& appVersion) noexcept
        : m_deviceInfo(deviceInfo), m_screenInfo(screenInfo), m_renderInfo(renderInfo), m_appVersion(appVersion)
    {
    }

    //----------------------------------------------------------------
    const DeviceInfo& SystemInfo::GetDeviceInfo() const noexcept
    {
        return m_deviceInfo;
    }

    //----------------------------------------------------------------
    const RenderInfo& SystemInfo::GetRenderInfo() const noexcept
    {
        return m_renderInfo;
    }

    //----------------------------------------------------------------
    const ScreenInfo& SystemInfo::GetScreenInfo() const noexcept
    {
        return m_screenInfo;
    }

    //----------------------------------------------------------------
    const std::string& SystemInfo::GetAppVersion() const noexcept
    {
        return m_appVersion;
    }
}


text:
<?php

namespace PHP_CodeSniffer\Standards\Generic\Sniffs\CodeAnalysis;

use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Util\Tokens;

class UselessOverridingMethodSniff implements Sniff
{

    /**
     * Registers the tokens that this sniff wants to listen for.
     *
     * @return int[]
     */
    public function register()
    {
        return array(T_FUNCTION);

    }//end register()

    /**
     * Processes this test, when one of its tokens is encountered.
     *
     * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned.
     * @param int                         $stackPtr  The position of the current token
     *                                               in the stack passed in $tokens.
     *
     * @return void
     */
    public function process(File $phpcsFile, $stackPtr)
    {
        $tokens = $phpcsFile->getTokens();
        $token  = $tokens[$stackPtr];

        // Skip function without body.
        if (isset($token['scope_opener']) === false) {
            return;
        }

        // Get function name.
        $methodName = $phpcsFile->getDeclarationName($stackPtr);

        // Get all parameters from method signature.
        $signature = array();
        foreach ($phpcsFile->getMethodParameters($stackPtr) as $param) {
            $signature[] = $param['name'];
        }

        $next = ++$token['scope_opener'];
        $end  = --$token['scope_closer'];

        for (; $next <= $end; ++$next) {
            $code = $tokens[$next]['code'];

            if (isset(Tokens::$emptyTokens[$code]) === true) {
                continue;
            } else if ($code === T_RETURN) {
                continue;
            }

            break;
        }

        // Any token except 'parent' indicates correct code.
        if ($tokens[$next]['code'] !== T_PARENT) {
            return;
        }

        // Find next non empty token index, should be double colon.
        $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($next + 1), null, true);

        // Skip for invalid code.
        if ($next === false || $tokens[$next]['code'] !== T_DOUBLE_COLON) {
            return;
        }

        // Find next non empty token index, should be the function name.
        $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($next + 1), null, true);

        // Skip for invalid code or other method.
        if ($next === false || $tokens[$next]['content'] !== $methodName) {
            return;
        }

        // Find next non empty token index, should be the open parenthesis.
        $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($next + 1), null, true);

        // Skip for invalid code.
        if ($next === false || $tokens[$next]['code'] !== T_OPEN_PARENTHESIS) {
            return;
        }

        $parameters       = array('');
        $parenthesisCount = 1;
        $count            = count($tokens);
        for (++$next; $next < $count; ++$next) {
            $code = $tokens[$next]['code'];

            if ($code === T_OPEN_PARENTHESIS) {
                ++$parenthesisCount;
            } else if ($code === T_CLOSE_PARENTHESIS) {
                --$parenthesisCount;
            } else if ($parenthesisCount === 1 && $code === T_COMMA) {
                $parameters[] = '';
            } else if (isset(Tokens::$emptyTokens[$code]) === false) {
                $parameters[(count($parameters) - 1)] .= $tokens[$next]['content'];
            }

            if ($parenthesisCount === 0) {
                break;
            }
        }//end for

        $next = $phpcsFile->findNext(Tokens::$emptyTokens, ($next + 1), null, true);
        if ($next === false || $tokens[$next]['code'] !== T_SEMICOLON) {
            return;
        }

        // Check rest of the scope.
        for (++$next; $next <= $end; ++$next) {
            $code = $tokens[$next]['code'];
            // Skip for any other content.
            if (isset(Tokens::$emptyTokens[$code]) === false) {
                return;
            }
        }

        $parameters = array_map('trim', $parameters);
        $parameters = array_filter($parameters);

        if (count($parameters) === count($signature) && $parameters === $signature) {
            $phpcsFile->addWarning('Possible useless method overriding detected', $stackPtr, 'Found');
        }

    }//end process()

}//end class


text:
<md-content class="md-padding" layout-xs="column" layout="row">

            <md-card ng-repeat="record in group ">
                <md-card-title>
                    <md-card-title-text>
                        {{record.login}}

                            <md-button ng-href="{{record.html_url}}" target="_blank">
                                <md-icon md-svg-src="link" ></md-icon>
                                git link
                            </md-button>

                    </md-card-title-text>
                    <md-card-title-media>

                    </md-card-title-media>
                </md-card-title>
            </md-card>

    </md-content>


text:
using System;

using FluentAssertions;

using Xunit;

namespace ReactiveSearch.UnitTests.Utility.System
{
    public class StringExtensionsFixtures
    {
        [InlineData("batman", true)]
        [InlineData("", false)]
        [InlineData(null, false)]
        [Theory]
        public void HasValueShouldBeExpected(string @string, bool expected)
        {
            var sut = @string.HasValue();

            sut.Should().Be(expected);
        }

        [InlineData("", "", "")]
        [InlineData(null, null, null)]
        [InlineData("batman", null, "batman")]
        [InlineData(null, "batman", "batman")]
        [InlineData("bat cave", null, "bat cave")]
        [InlineData(null, "bat cave", "bat cave")]
        [Theory]
        public void IsNullOrEmptyReturnShouldBeExpected(string @string, string @return, string expected)
        {
            var sut = @string.IsNullOrEmptyReturn(@return);

            sut.Should().Be(expected);
        }

        [InlineData("batman", false)]
        [InlineData("", true)]
        [InlineData(null, true)]
        [Theory]
        public void IsNullOrEmptyShouldBeExpected(string @string, bool expected)
        {
            var sut = @string.IsNullOrEmpty();

            sut.Should().Be(expected);
        }

        [InlineData(null, 10, null)]
        [InlineData("", 10, "")]
        [InlineData("batman", 0, "")]
        [InlineData("batman", 1, "b")]
        [InlineData("batman", 6, "batman")]
        [InlineData("batman and co", 6, "batman")]
        [InlineData("batmanandco", 6, "batman")]
        [Theory]
        public void TruncateShouldBeExpected(string @string, int maxLength, string expected)
        {
            var sut = @string.Truncate(maxLength);

            sut.Should().Be(expected);
        }

        [InlineData(null, 10, null)]
        [InlineData("", 10, "")]
        [InlineData("batman", 0, "...")]
        [InlineData("batman", 1, "...")]
        [InlineData("batman", 6, "batman")]
        [InlineData("batman and co", 6, "bat...")]
        [InlineData("batmanandco", 9, "batman...")]
        [Theory]
        public void TruncateWithEllipsisShouldBeExpected(string @string, int maxLength, string expected)
        {
            var sut = @string.TruncateWithEllipsis(maxLength);

            sut.Should().Be(expected);
        }
    }
}


text:
// -----------------------------------------------------------------------
// Copyright (c) David Kean.
// -----------------------------------------------------------------------
using System;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;
using AudioSwitcher.ApplicationModel;

namespace AudioSwitcher
{
    internal static class Program
    {
        [STAThread]
        public static void Main()
        {
            var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());

            using (CompositionContainer container = new CompositionContainer(catalog))
            {
                IApplication application = container.GetExportedValue<IApplication>();
                application.Start();
            }
        }
    }
}


text:
declare module "winjs" {
    export class Promise {
        static timeout(delay: number): Promise;
    }
}
import WinJS = require('winjs');

// these 3 should be errors
var x = (w1: WinJS) => { };
var y = function (w2: WinJS) { }
function z(w3: WinJS) { }


text:
test_description='detect unwritable repository and fail correctly'

. ./test-lib.sh

test_expect_success setup '

	>file &&
	git add file &&
	test_tick &&
	git commit -m initial &&
	echo >file &&
	git add file

'

test_expect_success POSIXPERM,SANITY 'write-tree should notice unwritable repository' '
	test_when_finished "chmod 775 .git/objects .git/objects/??" &&
	chmod a-w .git/objects .git/objects/?? &&
	test_must_fail git write-tree
'

test_expect_success POSIXPERM,SANITY 'commit should notice unwritable repository' '
	test_when_finished "chmod 775 .git/objects .git/objects/??" &&
	chmod a-w .git/objects .git/objects/?? &&
	test_must_fail git commit -m second
'

test_expect_success POSIXPERM,SANITY 'update-index should notice unwritable repository' '
	test_when_finished "chmod 775 .git/objects .git/objects/??" &&
	echo 6O >file &&
	chmod a-w .git/objects .git/objects/?? &&
	test_must_fail git update-index file
'

test_expect_success POSIXPERM,SANITY 'add should notice unwritable repository' '
	test_when_finished "chmod 775 .git/objects .git/objects/??" &&
	echo b >file &&
	chmod a-w .git/objects .git/objects/?? &&
	test_must_fail git add file
'

test_done


text:
<?php namespace Gckabir\Arty\Commands\Migrate;

use PDOException;
use Gckabir\Arty\Traits\ArtyCommandTrait;
use Gckabir\Arty\Traits\ContainerAwareTrait;
use Gckabir\Arty\Traits\MigrationTrait;
use Illuminate\Database\Console\Migrations\InstallCommand as LaravelInstallCommand;

class InstallCommand extends LaravelInstallCommand
{
    use ContainerAwareTrait, ArtyCommandTrait;
    use MigrationTrait;

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function fire()
    {
        try {
            parent::fire();
        } catch (PDOException $e) {
            if (!isset($e->errorInfo[1]) || $e->errorInfo[1] != 1050) {
                throw $e;
            }

            $this->info('Migration table already exists');
        }

        $this->checkMigrationDirectory();
    }

    protected function checkMigrationDirectory()
    {
        $filesystem = $this->app['files'];
        $migrationPath = $this->getMigrationPath();

        if (!$filesystem->isDirectory($migrationPath)) {
            $this->info('Migration directory does not exist');
            $confirmed = $this->confirm('Do you wish to create it? [y/n]');

            if ($confirmed) {
                if ($filesystem->makeDirectory($migrationPath)) {
                    $this->line('<info>Directory Created:</info> '.$migrationPath);
                } else {
                    $this->error('Error creating directory; please create it manually');
                }
            } else {
                $this->info('Please create a it manually');
            }
        }
    }
}


text:
cask "cityofzion-neon" do
  version "2.12.9"
  sha256 "c938f283f3967ab36826fde6162bf4d46b6e2fc00024bbf08f31c99061c9e242"

  url "https://github.com/CityOfZion/neon-wallet/releases/download/v#{version}/Neon.#{version}.dmg"
  name "Neon Wallet"
  desc "Light wallet for the NEO blockchain"
  homepage "https://github.com/CityOfZion/neon-wallet"

  livecheck do
    url :url
    strategy :github_latest
  end

  app "Neon.app"

  zap trash: [
    "~/Library/Application Support/Neon",
    "~/Library/Preferences/com.electron.neon.helper.plist",
    "~/Library/Preferences/com.electron.neon.plist",
    "~/Library/Saved Application State/com.electron.neon.savedState",
  ]
end


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Input;
using ArmA.Studio.Data.UI.Commands;
using ArmA.Studio.Plugin;

namespace ArmA.Studio.Dialogs
{
    public class DownloadPluginUpdateDialogDataContext : INotifyPropertyChanged, IDialogContext
    {
        private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
        public event PropertyChangedEventHandler PropertyChanged;
        public void RaisePropertyChanged([System.Runtime.CompilerServices.CallerMemberName]string callerName = "") { this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(callerName)); }

        public ICommand CmdOKButtonPressed => new RelayCommand((p) =>
        {
            this.DialogResult = true;
        });
        public ICommand CmdInitialized { get { return new RelayCommandAsync((p) => this.Window_Initialized()); } }

        public bool? DialogResult { get { return this._DialogResult; } set { this._DialogResult = value; this.RaisePropertyChanged(); } }
        private bool? _DialogResult;

        public string WindowHeader => string.Format(Properties.Localization.DownloadingX, this.CurrentPlugin?.Name);
        public string OKButtonText => Properties.Localization.InstallUpdate;

        public bool OKButtonEnabled { get { return this._OKButtonEnabled; } set { this._OKButtonEnabled = value; this.RaisePropertyChanged(); } }
        private bool _OKButtonEnabled;

        public double OverallPluginProgress => this.CurrentPluginToUpdate / (double)this.TotalPluginsToUpdate;
        public int CurrentPluginToUpdate { get { return this._CurrentPluginToUpdate; } set { this._CurrentPluginToUpdate = value; this.RaisePropertyChanged(); this.RaisePropertyChanged(nameof(this.OverallPluginProgress)); } }
        private int _CurrentPluginToUpdate;
        public int TotalPluginsToUpdate { get { return this._TotalPluginsToUpdate; } set { this._TotalPluginsToUpdate = value; this.RaisePropertyChanged(); } }
        private int _TotalPluginsToUpdate;

        public double CurrentPluginProgress => this.CurrentDownloadProgressInKiloBytes / (double)this.FileSizeInKiloBytes;
        public long CurrentDownloadProgressInKiloBytes { get { return this._CurrentDownloadProgressInKiloBytes; } set { this._CurrentDownloadProgressInKiloBytes = value; this.RaisePropertyChanged(); this.RaisePropertyChanged(nameof(this.CurrentPluginProgress)); } }
        private long _CurrentDownloadProgressInKiloBytes;
        public long FileSizeInKiloBytes { get { return this._FileSizeInKiloBytes; } set { this._FileSizeInKiloBytes = value; this.RaisePropertyChanged(); } }
        private long _FileSizeInKiloBytes;

        public IUpdatingPlugin CurrentPlugin { get { return this._CurrentPlugin; } set { this._CurrentPlugin = value; this.RaisePropertyChanged(); this.RaisePropertyChanged(nameof(this.WindowHeader)); } }
        private IUpdatingPlugin _CurrentPlugin;
        private readonly IEnumerable<IUpdatingPlugin> PluginsToUpdate;

        public DownloadPluginUpdateDialogDataContext(IEnumerable<IUpdatingPlugin> pluginsToUpdate)
        {
            this.PluginsToUpdate = pluginsToUpdate;
            this.CurrentPlugin = pluginsToUpdate.FirstOrDefault();
        }

        public async Task Window_Initialized()
        {
            if(!this.PluginsToUpdate.Any())
            {
                Logger.Warn("No plugins to update passed. Exiting Plugin Updater");
                this.DialogResult = false;
                return;
            }
            var list = new List<Tuple<string, string>>();
            foreach(var it in this.PluginsToUpdate)
            {
                Logger.Info($"Updating {it.Name}...");
                this.CurrentPlugin = it;
                string resultPath = await Task.Run(() => it.DownloadUpdate(new Progress<Tuple<long, long>>((t) =>
                {
                    this.CurrentDownloadProgressInKiloBytes = t.Item1;
                    this.FileSizeInKiloBytes = t.Item2;
                })));
                list.Add(new Tuple<string, string>(resultPath, Path.GetFileName(it.GetType().Assembly.Location)));
            }
            Logger.Info($"Done");
            foreach (var it in list)
            {
                var finalPath = Path.Combine(App.PluginsPath, string.Concat(it.Item2, App.CONST_UPDATESUFFIX));
                Logger.Info($"Moving temporary patch file from '{it.Item1}' to '{finalPath}'");
                File.Move(it.Item1, finalPath);
            }
            this.OKButtonEnabled = true;
        }
    }
}


text:
package thin.blog.knowwell;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;

/*
* SurveyList Activity is the main UI Activity of the Application
* This activity contains the Navigation Drawer and takes care of fragment replacement when options of Navigation View are selected
* */
public class SurveyList extends AppCompatActivity implements SurveyListFragment.OnFragmentInteractionListener {
    @Bind(R.id.app_bar)
    Toolbar toolbar;
    @Bind(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    @Bind(R.id.navigation_view)
    NavigationView navigationView;
    SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_survey_list);
        ButterKnife.bind(this);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        sharedPreferences = getSharedPreferences(Constants.SHARED_PREFS_USER_DATA, MODE_PRIVATE);
        View v = navigationView.getHeaderView(0);
        TextView name = (TextView) v.findViewById(R.id.name);
        TextView email = (TextView) v.findViewById(R.id.email);
        CircleImageView profilePhoto = (CircleImageView) v.findViewById(R.id.profile_photo);
        ImageView coverPhoto = (ImageView) v.findViewById(R.id.cover_photo);

        String userName = sharedPreferences.getString(Constants.USER_DATA_NAME, "");
        String userEmail = sharedPreferences.getString(Constants.USER_DATA_EMAIL, "");
        String userProfilePictureUrl = sharedPreferences.getString(Constants.USER_DATA_GOOGLE_PROFILE_PHOTO, "");
        String userCoverPictureUrl = sharedPreferences.getString(Constants.USER_DATA_GOOGLE_COVER_PHOTO, "R.drawable.background_material");
        name.setText(userName);
        email.setText(userEmail);
        if (!userProfilePictureUrl.contentEquals("")) {
            Picasso.with(this).load(userProfilePictureUrl).into(profilePhoto);
        }
        Picasso.with(this).load(userCoverPictureUrl).placeholder(R.drawable.background_material).error(R.drawable.background_material).into(coverPhoto);

        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem item) {
                item.setEnabled(true);
                drawerLayout.closeDrawers();
                switch (item.getItemId()) {
                    case R.id.my_surveys:
                        SurveyListFragment mySurvey = (SurveyListFragment) getSupportFragmentManager().findFragmentByTag("MY_SURVEYS");
                        if (mySurvey == null) {
                            mySurvey = SurveyListFragment.newInstance(2);
                        }
                        getSupportFragmentManager().beginTransaction().replace(R.id.activity_layout, mySurvey, "MY_SURVEYS").commit();
                        break;
                    case R.id.surveys:
                        SurveyListFragment survey = (SurveyListFragment) getSupportFragmentManager().findFragmentByTag("SURVEYS");
                        if (survey == null) {
                            survey = SurveyListFragment.newInstance(1);
                        }
                        getSupportFragmentManager().beginTransaction().replace(R.id.activity_layout, survey, "SURVEYS").commit();
                        break;

                    case R.id.logout:
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        editor.putBoolean(Constants.SUCCESSFUL_LOGIN_HISTORY, false);
                        editor.apply();
                        startActivity(new Intent(SurveyList.this, LoginActivity.class));
                        finish();
                        break;
                }

                return true;
            }
        });

        ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_drawer, R.string.close_drawer);
        drawerLayout.setDrawerListener(drawerToggle);
        drawerToggle.syncState();
        SurveyListFragment survey = (SurveyListFragment) getSupportFragmentManager().findFragmentByTag("SURVEYS");
        if (survey == null) {
            survey = SurveyListFragment.newInstance(1);
        }
        getSupportFragmentManager().beginTransaction().replace(R.id.activity_layout, survey, "SURVEYS").commit();
    }

    @Override
    public void onFragmentInteraction() {
        return;
    }
}


text:
.. _plugins:

#######
Plugins
#######

Plugins allow custom integrations to the internals of the Trainer such as a custom precision or
distributed implementation.

Under the hood, the Lightning Trainer is using plugins in the training routine, added automatically
depending on the provided Trainer arguments. For example:

.. code-block:: python

    # accelerator: GPUAccelerator
    # training type: DDPPlugin
    # precision: NativeMixedPrecisionPlugin
    trainer = Trainer(gpus=4, precision=16)

We expose Accelerators and Plugins mainly for expert users that want to extend Lightning for:

- New hardware (like TPU plugin)
- Distributed backends (e.g. a backend not yet supported by
  `PyTorch <https://pytorch.org/docs/stable/distributed.html#backends>`_ itself)
- Clusters (e.g. customized access to the cluster's environment interface)

There are two types of Plugins in Lightning with different responsibilities:

TrainingTypePlugin
------------------

- Launching and teardown of training processes (if applicable)
- Setup communication between processes (NCCL, GLOO, MPI, ...)
- Provide a unified communication interface for reduction, broadcast, etc.
- Provide access to the wrapped LightningModule

PrecisionPlugin
---------------

- Perform pre- and post backward/optimizer step operations such as scaling gradients
- Provide context managers for forward, training_step, etc.
- Gradient clipping

Futhermore, for multi-node training Lightning provides cluster environment plugins that allow the advanced user
to configure Lighting to integrate with a :ref:`custom-cluster`.

.. image:: ../_static/images/accelerator/overview.svg

**********************
Create a custom plugin
**********************

Expert users may choose to extend an existing plugin by overriding its methods ...

.. code-block:: python

    from pytorch_lightning.plugins import DDPPlugin

    class CustomDDPPlugin(DDPPlugin):
        def configure_ddp(self):
            self._model = MyCustomDistributedDataParallel(
                self.model,
                device_ids=...,
            )

or by subclassing the base classes :class:`~pytorch_lightning.plugins.training_type.TrainingTypePlugin` or
:class:`~pytorch_lightning.plugins.precision.PrecisionPlugin` to create new ones. These custom plugins
can then be passed into the Trainer directly or via a (custom) accelerator:

.. code-block:: python

    # custom plugins
    trainer = Trainer(plugins=[CustomDDPPlugin(), CustomPrecisionPlugin()])

    # fully custom accelerator and plugins
    accelerator = MyAccelerator(
        precision_plugin=CustomPrecisionPlugin(),
        training_type_plugin=CustomDDPPlugin(),
    )
    trainer = Trainer(accelerator=accelerator)

The full list of built-in plugins is listed below.

.. warning:: The Plugin API is in beta and subject to change.
    For help setting up custom plugins/accelerators, please reach out to us at **support@pytorchlightning.ai**

----------

Training Type Plugins
---------------------

.. currentmodule:: pytorch_lightning.plugins.training_type

.. autosummary::
    :nosignatures:
    :template: classtemplate.rst

    TrainingTypePlugin
    SingleDevicePlugin
    ParallelPlugin
    DataParallelPlugin
    DDPPlugin
    DDP2Plugin
    DDPShardedPlugin
    DDPSpawnShardedPlugin
    DDPSpawnPlugin
    DeepSpeedPlugin
    HorovodPlugin
    SingleTPUPlugin
    TPUSpawnPlugin

Precision Plugins
-----------------

.. currentmodule:: pytorch_lightning.plugins.precision

.. autosummary::
    :nosignatures:
    :template: classtemplate.rst

    PrecisionPlugin
    NativeMixedPrecisionPlugin
    ShardedNativeMixedPrecisionPlugin
    ApexMixedPrecisionPlugin
    DeepSpeedPrecisionPlugin
    TPUHalfPrecisionPlugin
    DoublePrecisionPlugin

Cluster Environments
--------------------

.. currentmodule:: pytorch_lightning.plugins.environments

.. autosummary::
    :nosignatures:
    :template: classtemplate.rst

    ClusterEnvironment
    LightningEnvironment
    LSFEnvironment
    TorchElasticEnvironment
    KubeflowEnvironment
    SLURMEnvironment


text:
<Record>
<Term>Vyvanse</Term>
<SemanticType>Pharmacologic Substance</SemanticType>
<SemanticType>Organic Chemical</SemanticType>
<Synonym>Lisdexamfetamine dimesylate</Synonym>
<Synonym>Vyvanse</Synonym>
<Source>FDA Registry</Source>
</Record>


text:
/***********************************************************************
 * Major and minor VRT API versions.
 *
 * Whenever something is added, increment MINOR version
 * Whenever something is deleted or changed in a way which is not
 * binary/load-time compatible, increment MAJOR version
 *
 *
 * 6.1 (unreleased):
 *	http_CollectHdrSep added
 *	VRT_purge modified (may fail a transaction)
 * 6.0 (2017-03-15):
 *	VRT_hit_for_pass added
 *	VRT_ipcmp added
 *	VRT_Vmod_Init signature changed
 *	VRT_vcl_lookup removed
 *	VRT_vcl_get added
 *	VRT_vcl_rel added
 *	VRT_fail added
 *	WS_Reset and WS_Snapshot signatures changed
 *	WS_Front added
 *	WS_ReserveLumps added
 *	WS_Inside added
 *	WS_Assert_Allocated added
 * 5.0:
 *	Varnish 5.0 release "better safe than sorry" bump
 * 4.0:
 *	VCL_BYTES changed to long long
 *	VRT_CacheReqBody changed signature
 * 3.2:
 *	vrt_backend grew .proxy_header field
 *	vrt_ctx grew .sp field.
 *	vrt_acl type added
 */

#define VRT_MAJOR_VERSION	6U

#define VRT_MINOR_VERSION	1U

/***********************************************************************/

#ifdef __v_printflike
#  define __vrt_printflike(a,b) __v_printflike(a,b)
#else
#  define __vrt_printflike(a,b)
#endif

struct VCL_conf;
struct vrt_acl;
struct busyobj;
struct director;
struct http;
struct req;
struct stevedore;
struct suckaddr;
struct vcl;
struct vmod;
struct vsb;
struct vsl_log;
struct ws;

/***********************************************************************
 * This is the central definition of the mapping from VCL types to
 * C-types.  The python scripts read these from here.
 * (alphabetic order)
 */

typedef const struct vrt_acl *			VCL_ACL;
typedef const struct director *			VCL_BACKEND;
typedef const struct vmod_priv *		VCL_BLOB;
typedef const char *				VCL_BODY;
typedef unsigned				VCL_BOOL;
typedef long long				VCL_BYTES;
typedef double					VCL_DURATION;
typedef const char *				VCL_ENUM;
typedef const struct gethdr_s *			VCL_HEADER;
typedef struct http *				VCL_HTTP;
typedef void					VCL_INSTANCE;
typedef long					VCL_INT;
typedef const struct suckaddr *			VCL_IP;
typedef const struct vrt_backend_probe *	VCL_PROBE;
typedef double					VCL_REAL;
typedef const struct stevedore *		VCL_STEVEDORE;
typedef const char *				VCL_STRING;
typedef double					VCL_TIME;
typedef struct vcl *				VCL_VCL;
typedef void					VCL_VOID;

/***********************************************************************
 * This is the composite argument we pass to compiled VCL and VRT
 * functions.
 */

struct vrt_ctx {
	unsigned			magic;
#define VRT_CTX_MAGIC			0x6bb8f0db

	unsigned			method;
	unsigned			*handling;

	struct vsb			*msg;	// Only in ...init()
	struct vsl_log			*vsl;
	struct vcl			*vcl;
	struct ws			*ws;

	struct sess			*sp;

	struct req			*req;
	struct http			*http_req;
	struct http			*http_req_top;
	struct http			*http_resp;

	struct busyobj			*bo;
	struct http			*http_bereq;
	struct http			*http_beresp;

	double				now;

	/*
	 * method specific argument:
	 *    hash:		struct SHA256Context
	 *    synth+error:	struct vsb *
	 */
	void				*specific;
};

#define VRT_CTX		const struct vrt_ctx *ctx

/***********************************************************************/

struct vmod_data {
	/* The version/id fields must be first, they protect the rest */
	unsigned			vrt_major;
	unsigned			vrt_minor;
	const char			*file_id;

	const char			*name;
	const void			*func;
	int				func_len;
	const char			*proto;
	const char			* const *spec;
	const char			*abi;
};

/***********************************************************************/

enum gethdr_e { HDR_REQ, HDR_REQ_TOP, HDR_RESP, HDR_OBJ, HDR_BEREQ,
		HDR_BERESP };

struct gethdr_s {
	enum gethdr_e	where;
	const char	*what;
};

extern const void * const vrt_magic_string_end;
extern const void * const vrt_magic_string_unset;

/***********************************************************************
 * We want the VCC to spit this structs out as const, but when VMODs
 * come up with them we want to clone them into malloc'ed space which
 * we can free again.
 * We collect all the knowledge here by macroizing the fields and make
 * a macro for handling them all.
 * See also:  cache_backend.h & cache_backend_cfg.c
 * One of those things...
 */

#define VRT_BACKEND_FIELDS(rigid)				\
	rigid char			*vcl_name;		\
	rigid char			*ipv4_addr;		\
	rigid char			*ipv6_addr;		\
	rigid char			*port;			\
	rigid char			*hosthdr;		\
	double				connect_timeout;	\
	double				first_byte_timeout;	\
	double				between_bytes_timeout;	\
	unsigned			max_connections;	\
	unsigned			proxy_header;

#define VRT_BACKEND_HANDLE()			\
	do {					\
		DA(vcl_name);			\
		DA(ipv4_addr);			\
		DA(ipv6_addr);			\
		DA(port);			\
		DA(hosthdr);			\
		DN(connect_timeout);		\
		DN(first_byte_timeout);		\
		DN(between_bytes_timeout);	\
		DN(max_connections);		\
		DN(proxy_header);		\
	} while(0)

struct vrt_backend {
	unsigned			magic;
#define VRT_BACKEND_MAGIC		0x4799ce6b
	VRT_BACKEND_FIELDS(const)
	const struct suckaddr		*ipv4_suckaddr;
	const struct suckaddr		*ipv6_suckaddr;
	const struct vrt_backend_probe	*probe;
};

#define VRT_BACKEND_PROBE_FIELDS(rigid)				\
	double				timeout;		\
	double				interval;		\
	unsigned			exp_status;		\
	unsigned			window;			\
	unsigned			threshold;		\
	unsigned			initial;

#define VRT_BACKEND_PROBE_HANDLE()		\
	do {					\
		DN(timeout);			\
		DN(interval);			\
		DN(exp_status);			\
		DN(window);			\
		DN(threshold);			\
		DN(initial);			\
	} while (0)

struct vrt_backend_probe {
	unsigned			magic;
#define VRT_BACKEND_PROBE_MAGIC		0x84998490
	const char			*url;
	const char			*request;
	VRT_BACKEND_PROBE_FIELDS(const)
};

/***********************************************************************/

/*
 * other stuff.
 * XXX: document when bored
 */

struct vrt_ref {
	unsigned	source;
	unsigned	offset;
	unsigned	line;
	unsigned	pos;
	const char	*token;
};

/* ACL related */
#define VRT_ACL_MAXADDR		16	/* max(IPv4, IPv6) */

typedef int acl_match_f(VRT_CTX, const VCL_IP);

struct vrt_acl {
	unsigned	magic;
#define VRT_ACL_MAGIC	0x78329d96
	acl_match_f	*match;
};

void VRT_acl_log(VRT_CTX, const char *msg);
int VRT_acl_match(VRT_CTX, VCL_ACL, VCL_IP);

/* req related */

VCL_BYTES VRT_CacheReqBody(VRT_CTX, VCL_BYTES maxsize);

/* Regexp related */
void VRT_re_init(void **, const char *);
void VRT_re_fini(void *);
int VRT_re_match(VRT_CTX, const char *, void *re);
const char *VRT_regsub(VRT_CTX, int all, const char *, void *, const char *);

void VRT_ban_string(VRT_CTX, const char *);
void VRT_purge(VRT_CTX, double ttl, double grace, double keep);

void VRT_count(VRT_CTX, unsigned);
void VRT_synth(VRT_CTX, unsigned, const char *);
void VRT_hit_for_pass(VRT_CTX, VCL_DURATION);

struct http *VRT_selecthttp(VRT_CTX, enum gethdr_e);
const char *VRT_GetHdr(VRT_CTX, const struct gethdr_s *);
void VRT_SetHdr(VRT_CTX, const struct gethdr_s *, const char *, ...);
void VRT_handling(VRT_CTX, unsigned hand);
void VRT_fail(VRT_CTX, const char *fmt, ...) __vrt_printflike(2,3);

void VRT_hashdata(VRT_CTX, const char *str, ...);

/* Simple stuff */
int VRT_strcmp(const char *s1, const char *s2);
void VRT_memmove(void *dst, const void *src, unsigned len);
int VRT_ipcmp(const struct suckaddr *sua1, const struct suckaddr *sua2);

void VRT_Rollback(VRT_CTX, const struct http *);

/* Synthetic pages */
void VRT_synth_page(VRT_CTX, const char *, ...);

/* Backend related */
struct director *VRT_new_backend(VRT_CTX, const struct vrt_backend *);
void VRT_delete_backend(VRT_CTX, struct director **);

/* Suckaddr related */
int VRT_VSA_GetPtr(const struct suckaddr *sua, const unsigned char ** dst);

/* VMOD/Modules related */
int VRT_Vmod_Init(VRT_CTX, struct vmod **hdl, void *ptr, int len,
    const char *nm, const char *path, const char *file_id, const char *backup);
void VRT_Vmod_Fini(struct vmod **hdl);

/* VCL program related */
VCL_VCL VRT_vcl_get(VRT_CTX, const char *);
void VRT_vcl_rel(VRT_CTX, VCL_VCL);
void VRT_vcl_select(VRT_CTX, VCL_VCL);

struct vmod_priv;
typedef void vmod_priv_free_f(void *);
struct vmod_priv {
	void			*priv;
	int			len;
	vmod_priv_free_f	*free;
};

#ifdef VCL_RET_MAX
typedef int vmod_event_f(VRT_CTX, struct vmod_priv *, enum vcl_event_e);
#endif

struct vclref;
struct vclref * VRT_ref_vcl(VRT_CTX, const char *);
void VRT_rel_vcl(VRT_CTX, struct vclref **);

void VRT_priv_fini(const struct vmod_priv *p);
struct vmod_priv *VRT_priv_task(VRT_CTX, void *vmod_id);
struct vmod_priv *VRT_priv_top(VRT_CTX, void *vmod_id);

/* Stevedore related functions */
int VRT_Stv(const char *nm);
VCL_STEVEDORE VRT_stevedore(const char *nm);

/* Convert things to string */

char *VRT_IP_string(VRT_CTX, VCL_IP);
char *VRT_INT_string(VRT_CTX, VCL_INT);
char *VRT_REAL_string(VRT_CTX, VCL_REAL);
char *VRT_TIME_string(VRT_CTX, VCL_TIME);
const char *VRT_BOOL_string(VCL_BOOL);
const char *VRT_BACKEND_string(VCL_BACKEND);
const char *VRT_STEVEDORE_string(VCL_STEVEDORE);
const char *VRT_CollectString(VRT_CTX, const char *p, ...);


text:
<!doctype html>

    <meta charset="utf-8">
    <meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>mermaid - Generation of diagrams and flowcharts from text in a similar manner as markdown.</title>
    <link rel="stylesheet" href="fontawesome/css/font-awesome.min.css">

    <link href="stylesheets/screen.css" rel="stylesheet" type="text/css" media="screen"/>
    <link href="stylesheets/print.css" rel="stylesheet" type="text/css" media="print"/>
    <link href="stylesheets/mermaid.forest.css" rel="stylesheet" type="text/css"/>
    <link href="stylesheets/solarized_light.css" rel="stylesheet" type="text/css"/>

        NAV

        shell
        javascript
        html
        css

        <input type="text" class="search" id="input-search" placeholder="Search">

            Star
            Fork
            Download

Documentation Powered by Slate

        {{{contents}}}

            shell
            ruby
            python


text:
class RankingController < ApplicationController

  def ranking
  end

  def have
    # -- type = "Have"を検索してレコードを絞り込み item_idをカウントしグループ化
    best_items_id=Ownership.where(type: "Have").group(:item_id).order('count_item_id desc').limit(10).count(:item_id).keys
    @items=Item.find(best_items_id).sort_by{|v| best_items_id.index(v.id)}
    # -- 生SQLを書いてみました --
    #@items=Item.find_by_sql('select items.id, item_id, title, asin, large_image, type, count(item_id) from ownerships join items on ownerships.item_id = items.id  GROUP BY item_id, items.id, title, asin,large_image, type HAVING type = \'Have\' order by count(item_id) desc limit 10')

    #binding.pry

  end

  def want
    best_items_id=Ownership.where(type: "Want").group(:item_id).order('count_item_id desc').limit(10).count(:item_id).keys
    @items=Item.find(best_items_id).sort_by{|v| best_items_id.index(v.id)}

    # --- 生SQLを書いてみました --
   #@items=Item.find_by_sql('select items.id, item_id, title, asin, large_image, type, count(item_id) from ownerships join items on ownerships.item_id = items.id  GROUP BY item_id, items.id, title, asin,large_image, type HAVING type = \'Want\' order by count(item_id) desc limit 10')
  end

end