text:
using Couchbase;
using Couchbase.Core;
using System;
using System.Threading.Tasks;

namespace DevGuide
{
    public class ConnectionConfig
    {
        protected ICluster _cluster;
        protected IBucket _bucket;

        public ConnectionConfig()
        {
            Connect();
        }

        private void Connect()
        {
            _cluster = new Cluster("couchbaseClients/couchbase");
            _bucket = _cluster.OpenBucket();
        }

        private void Disconnect()
        {
            _cluster.CloseBucket(_bucket);
            _bucket.Dispose();
            _bucket = null;
            _cluster.Dispose();
            _cluster = null;
        }

        public virtual async Task ExecuteAsync()
        {
            Console.WriteLine("Connected to bucket '{0}'", _bucket.Name);
        }

        static void Main(string[] args)
        {
            new ConnectionConfig().ExecuteAsync().Wait();
        }

    }
}

redpajama_set_name: RedPajamaGithub


text:
import { Component, Input } from '@angular/core';
import { UntypedFormGroup } from '@angular/forms';
import { FieldDto, JsonFieldPropertiesDto } from '@app/shared';

@Component({
    selector: 'sqx-json-more[field][fieldForm][properties]',
    styleUrls: ['json-more.component.scss'],
    templateUrl: 'json-more.component.html',
})
export class JsonMoreComponent {
    @Input()
    public fieldForm!: UntypedFormGroup;

    @Input()
    public field!: FieldDto;

    @Input()
    public properties!: JsonFieldPropertiesDto;
}


text:
<?php

/**
 * Author: Pavel Petrov <itnelo@gmail.com>
 * Date: 09.02.16 13:54
 */

namespace yii\tools\helpers;

use yii\base\InvalidParamException;

/**
 * All available field formats for formatted database records
 * @package yii\tools\helpers
 */
class FormatHelper
{
    const TYPE_STRING   = 'string';
    const TYPE_NUMBER   = 'number';
    const TYPE_BOOLEAN  = 'boolean';
    const TYPE_LIST     = 'list';
    const TYPE_DATE     = 'date';

    private static $formats = [
        // Type => Formatter's format method
        self::TYPE_STRING   => 'raw',
        self::TYPE_NUMBER   => 'intVal',
        self::TYPE_BOOLEAN  => 'numericBoolean',
        self::TYPE_LIST     => 'raw',
        self::TYPE_DATE     => 'timestamp'
    ];

    public static function typeToFormat($type)
    {
        if (!array_key_exists($type, self::$formats)) {
            throw new InvalidParamException("Invalid type '$type'");
        }

        return self::$formats[$type];
    }
}


text:
package org.apache.skywalking.oap.log.analyzer.provider.log.listener;

/**
 * LogAnalysisListenerFactory implementation creates the listener instance when required.
 * Every LogAnalysisListener could have its own creation factory.
 */
public interface LogAnalysisListenerFactory {

    LogAnalysisListener create();
}


text:
<?php
/**
 * Database connection parameters
 *
 * @author Frederic BAYLE <contact (at) made-in-softland (dot) com>
 * @version 2017-05-12
 */

namespace EDP\Data;

use EDP\EDPObject;
use EDP\Regex;
use EDP\Runtime\Exceptions\Exception;

/**
 * Database connection parameters
 *
 * Theses parameters are extracted from a database connection string as an associative array.
 * Required keys ares Host, Port, DbName, User and Password (Charset is optionnal, utf8 is set by default)
 *
 * @property-read array $ConnectionParameters Database connection parameters
 */
class DbConnectionParameters extends EDPObject
{
    /**
     * Database connection parameters
     *
     * Default values :

     *

     * 01 [
     * 02     'Host'            => 'localhost',
     * 03     'Port'            => '3306',
     * 04     'DbName'          => 'db',
     * 05     'User'            => 'root',
     * 06     'Password'        => 'pwd',
     * 07     'Charset'         => 'utf8',
     * 08     'DateFormat'      => 'Y-m-d',
     * 09     'DateTimeFormat'  => 'Y-m-d H:i:s',
     * 10     'TimeFormat'      => '%H:%I:%S'
     * 11 ]
     *

     *
     * @var array
     */
    protected $_ConnectionParameters;

    /**
     * Class constructor
     *
     * @param string $pConnectionString Databse connection string (format : host=localhost;port=3306;dbname=db;user=root;password=pwd)
     * @throws Exception
     */
    public function __construct($pConnectionString)
    {
        $RxCnxStr = new Regex('\s*([^;]+)\s*=\s*([^;]+)\s*');
        if(!$RxCnxStr->IsMatch($pConnectionString))
        {
            // Bad format
            throw new Exception(\EDP\Str::Format(\EDP\Localization::GetEDPL10n('EDP\Data\DbConnectionParameters::__construct'), $pConnectionString));
        }

        // Initializations
        $this->_ConnectionParameters = [
            'Host'           => 'localhost',
            'Port'           => '3306',
            'DbName'         => 'db',
            'User'           => 'root',
            'Password'       => 'pwd',
            'Charset'        => 'utf8',
            'DateFormat'     => 'Y-m-d',
            'DateTimeFormat' => 'Y-m-d H:i:s',
            'TimeFormat'     => '%H:%I:%S'
        ];

        // Trying to extract parameters from the connection string
        $RxCnxStrResult = $RxCnxStr->Matches($pConnectionString);
        if(count($RxCnxStrResult) > 0)
        {
            // Gets each parameter with its value
            for ($i = 0; $i < count($RxCnxStrResult[1]); $i++)
            {
                $this->_ConnectionParameters[$RxCnxStrResult[1][$i]] = $RxCnxStrResult[2][$i];
            }
        }
    }

    /**
     * Gets the database connection parameters
     *
     * @var array Database connection parameters
     */
    protected function &GetConnectionParameters()
    {
        return $this->_ConnectionParameters;
    }
}


text:
namespace lldb_private {

//----------------------------------------------------------------------
/// @class SymbolContextScope SymbolContextScope.h "lldb/Symbol/SymbolContextScope.h"
/// @brief Inherit from this if your object is part of a symbol context
///        and can reconstruct its symbol context.
///
/// Many objects that are part of a symbol context that have pointers
/// back to parent objects that own them. Any members of a symbol
/// context that, once they are built, will not go away, can inherit
/// from this pure virtual class and can then reconstruct their symbol
/// context without having to keep a complete SymbolContext object in
/// the object.
///
/// Examples of these objects include:
///     @li Module
///     @li CompileUnit
///     @li Function
///     @li Block
///     @li Symbol
///
/// Other objects can store a "SymbolContextScope *" using any pointers
/// to one of the above objects. This allows clients to hold onto a
/// pointer that uniquely will identify a symbol context. Those clients
/// can then always reconstruct the symbol context using the pointer, or
/// use it to uniquely identify a symbol context for an object.
///
/// Example objects include that currently use "SymbolContextScope *"
/// objects include:
///     @li Variable objects that can reconstruct where they are scoped
///         by making sure the SymbolContextScope * comes from the scope
///         in which the variable was declared. If a variable is a global,
///         the appropriate CompileUnit * will be used when creating the
///         variable. A static function variables, can the Block scope
///         in which the variable is defined. Function arguments can use
///         the Function object as their scope. The SymbolFile parsers
///         will set these correctly as the variables are parsed.
///     @li Type objects that know exactly in which scope they
///         originated much like the variables above.
///     @li StackID objects that are able to know that if the CFA
///         (stack pointer at the beginning of a function) and the
///         start PC for the function/symbol and the SymbolContextScope
///         pointer (a unique pointer that identifies a symbol context
///         location) match within the same thread, that the stack
///         frame is the same as the previous stack frame.
///
/// Objects that adhere to this protocol can reconstruct enough of a
/// symbol context to allow functions that take a symbol context to be
/// called. Lists can also be created using a SymbolContextScope* and
/// and object pairs that allow large collections of objects to be
/// passed around with minimal overhead.
//----------------------------------------------------------------------
class SymbolContextScope
{
public:
    virtual
    ~SymbolContextScope () {}

    //------------------------------------------------------------------
    /// Reconstruct the object's symbolc context into \a sc.
    ///
    /// The object should fill in as much of the SymbolContext as it
    /// can so function calls that require a symbol context can be made
    /// for the given object.
    ///
    /// @param[out] sc
    ///     A symbol context object pointer that gets filled in.
    //------------------------------------------------------------------
    virtual void
    CalculateSymbolContext (SymbolContext *sc) = 0;

    virtual lldb::ModuleSP
    CalculateSymbolContextModule ()
    {
        return lldb::ModuleSP();
    }

    virtual CompileUnit *
    CalculateSymbolContextCompileUnit ()
    {
        return NULL;
    }

    virtual Function *
    CalculateSymbolContextFunction ()
    {
        return NULL;
    }

    virtual Block *
    CalculateSymbolContextBlock ()
    {
        return NULL;
    }

    virtual Symbol *
    CalculateSymbolContextSymbol ()
    {
        return NULL;
    }

    //------------------------------------------------------------------
    /// Dump the object's symbolc context to the stream \a s.
    ///
    /// The object should dump its symbol context to the stream \a s.
    /// This function is widely used in the DumpDebug and verbose output
    /// for lldb objets.
    ///
    /// @param[in] s
    ///     The stream to which to dump the object's symbol context.
    //------------------------------------------------------------------
    virtual void
    DumpSymbolContext (Stream *s) = 0;
};

} // namespace lldb_private

#endif  // liblldb_SymbolContextScope_h_


text:
package com.sun.jini.qa.harness;

/**
 * An exception which may be thrown at any time during test setup
 * and execution. May be used to wrap other unexpected exceptions
 * which occur.
 */
public class TestException extends Exception {

    /**
     *Creates a TestException.
     */
    public TestException(){
        super();
    }

    /**
     * Creates a TestException with the given detail message.
     *
     *  @param s the detail message
     */
    public TestException(String s){
        super(s);
    }

    /**
     * Creates a TestException with the given detail message
     * and cause.
     *
     *  @param s the detail message
     *  @param e the cause
     */
    public TestException(String s, Throwable e){
        super(s, e);
    }

    /**
     * Returns the detail message; includes the detail message from
     * the cause if there is one.
     *
     * @return the detail message
     */
    public String getMessage(){
        if (getCause() == null) {
            return super.getMessage();
	} else {
            return super.getMessage() + "; nested exception is: \n\t"
                                      + getCause().getMessage();
	}
    }
}


text:
from main.views import main

__all__ = ['main']


text:
module Nanoc
  # The current Nanoc version.
  VERSION = '4.7.5'.freeze
end


text:
if(DEFINED POLLY_MINGW_CMAKE_)
  return()
else()
  set(POLLY_MINGW_CMAKE_ 1)
endif()

include("${CMAKE_CURRENT_LIST_DIR}/utilities/polly_init.cmake")

polly_init(
    "mingw / gcc / c++11 support / C11"
    "MinGW Makefiles"
)

include("${CMAKE_CURRENT_LIST_DIR}/utilities/polly_common.cmake")

include("${CMAKE_CURRENT_LIST_DIR}/compiler/gcc.cmake")
include("${CMAKE_CURRENT_LIST_DIR}/flags/cxx11.cmake")
include("${CMAKE_CURRENT_LIST_DIR}/flags/c11.cmake")


text:
require 'spec_helper'

describe 'gws_circular_comment_authority', type: :feature, dbscope: :example, js: true do
  let(:site) { gws_site }
  let!(:post) { create(:gws_circular_post, :due_date, site: site, user: user1, member_ids: [user1.id, user2.id, user3.id]) }
  let!(:comment1) { create(:gws_circular_comment, site: site, post: post, user: user2, browsing_authority: 'all') }
  let!(:comment2) do
    create(:gws_circular_comment, site: site, post: post, user: user2, browsing_authority: 'author_or_commenter')
  end
  let(:user1) { create(:gws_user, :gws_user_base) }
  let(:user2) { create(:gws_user, :gws_user_base) }
  let(:user3) { create(:gws_user, :gws_user_base) }
  let(:circular_show_path) { gws_circular_post_path site, post }

  context 'circular author' do
    before do
      login_user user1
      visit circular_show_path
    end

    it do
      within 'div.comments' do
        expect(all('aside.comment').count).to eq 2
        expect(page).to have_content comment1.name
        expect(page).to have_content comment2.name
      end
    end
  end

  context 'commenter' do
    before do
      login_user user2
      visit circular_show_path
    end

    it do
      within 'div.comments' do
        expect(all('aside.comment').count).to eq 2
        expect(page).to have_content comment1.name
        expect(page).to have_content comment2.name
      end
    end
  end

  context 'not circular author and not commenter' do
    before do
      login_user user3
      visit circular_show_path
    end

    it do
      within 'div.comments' do
        expect(all('aside.comment').count).to eq 1
        expect(page).to have_content comment1.name
        expect(page).to have_no_content comment2.name
      end
    end
  end
end


text:
package com.gmail.Lecrayen.Platinum.MMO.DataLibrary;

import java.util.HashSet;
import java.util.UUID;

import org.bukkit.configuration.serialization.SerializableAs;
import org.bukkit.plugin.java.JavaPlugin;

import com.gmail.Lecrayen.Platinum.API.FileStorage;
import com.gmail.Lecrayen.Platinum.MMO.User;

@SerializableAs("User")
public class UserManager {

	private FileStorage file;
	private String section_users = "users";

	private HashSet<User> users;

	public UserManager(JavaPlugin plugin, String filename) {
		file = new FileStorage(plugin, filename);
		importData();
	}

	public HashSet<User> getUsers(){
		return users;
	}

	public boolean isExistingUser(UUID player){
		return getUser(player) != null;
	}

	public User getUser(UUID id){
		for (User u : users){
			if(u.getUUID().equals(id)) return u;
		}
		return null;
	}

	public User getUserByActualName(String name){
		for (User u : users){
			if(u.getActualName().equals(name)) return u;
		}
		return null;
	}

	public void addUser(User u){
		if(users == null) users = new HashSet<User>();
		users.add(u);
	}

	@SuppressWarnings("unchecked")
	private void importData() {
		if (file.getData().get(section_users) != null) {
			users = (HashSet<User>) file.getData().get(section_users);
		} else users = new HashSet<User>();
	}

	public void saveData() {
		file.getData().set(section_users, users);
		file.saveToDisk();
	}
}


text:
package com.fenbi.ytklearn.utils;

/**
 * @author wufan
 */

public class BinarySearch {

    // binary search, return the index of last element that equal or large than target
    public static int findLastEqualOrUpper(float arr[], float target) {
        CheckUtils.check(arr != null && arr.length >= 1, "[GBDT] find last equal or upper error, arr is null or empty");
        if (target > arr[arr.length -1]) {
            return -1;
        }

        int l = 0;
        int u = arr.length - 1;
        while (l <= u) {
            int mid = l + (u-l)/2;
            if (target >= arr[mid]) {
                l = mid + 1;
            } else {
                u = mid - 1;
            }
        }

        u = Math.max(0, u);  // arr[u] <= target, arr[l] > target
        if (arr[u] == target) {
            return u;
        } else {
            return Math.min(arr.length - 1, l);
        }
    }

    // binary search, return the index of first element that equal or large than target
    public static int findFirstEqualOrUpper(double arr[], double target) {
        CheckUtils.check(arr != null && arr.length >= 1, "[GBDT] find first equal or upper error, arr is null or empty");
        if (target > arr[arr.length -1]) {
            return -1;
        }

        int l = 0;
        int u = arr.length - 1;
        while (l <= u) {
            int mid = l + (u-l)/2;
            if (target <= arr[mid]) {
                u = mid - 1;
            } else {
                l = mid + 1;
            }
        }
        return Math.min(arr.length - 1, l);  // arr[l] >= target
    }

    // two number in the arr is treated as an element, key is the second number
    // return the index of first element that equal or large than target
    public static int findFirstEqualOrUpperTuple(double arr[], double target) {
        CheckUtils.check(arr != null && arr.length >= 1, "[GBDT] findFirstEqualOrUpperTuple error, arr is null or empty");
//        CheckUtils.check(target <= arr[arr.length - 1], "[GBDT] findFirstEqualOrUpperTuple error, cant't find element that is no smaller than target(%f)", target);
        if (target > arr[arr.length -1]) {
            return -1;
        }

        int l = 0;
        int u = arr.length/2 - 1;
        while (l <= u) {
            int mid = l + (u-l)/2;
            int index = (mid << 1) + 1;
            if (target <= arr[index]) {
                u = mid - 1;
            } else {
                l = mid + 1;
            }
        }
        return Math.min(arr.length/2 - 1, l); // arr[l] >= target
    }

    public static void main(String[] args) {
        float[] arr = {0, 0, 1, 1, 1, 4, 5, 6, 6, 6, 32};
        float[] target = {0, 0.5f, 1, 1.5f, 3, 4.5f, 6, 7};
        for (int i = 0; i < target.length; i++) {
            int index = findLastEqualOrUpper(arr, target[i]);
            System.out.println(target[i] + ", index:" + index + ", value:" + arr[index] );
//            index = findFirstEqualOrUpper(arr, target[i]);
            System.out.println(target[i] + ", index:" + index + ", value:" + arr[index] );
            System.out.println("==");
        }
    }

}


text:
require 'ffi'

require 'hako/libc'
require 'hako/blas'
require 'hako/lapack'
require 'hako/vector'
require 'hako/matrix'

class Float
  alias old_add +
  alias old_sub -
  alias old_mul *
  alias old_div /
  def +(y)
    return y + self if y.is_a? Matrix or y.is_a? Vector
    old_add(y)
  end
  def -(y)
    return (-y).add!(self) if y.is_a? Matrix or y.is_a? Vector
    old_sub(y)
  end
  def *(y)
    return y*self if y.is_a? Matrix or y.is_a? Vector
    old_mul(y)
  end
  def /(y)
    return y.power_elements(-1).hadamard!(self) if y.is_a? Matrix or y.is_a? Vector
    old_div(y)
  end
end

class Array
  def to_matrix
    Matrix::from_a(self)
  end
  def to_vector
    Vector::from_a(self)
  end
  # Return inverse index Array for index Array.
  def invert_array
    a = Array.new(length)
    each.with_index do |x, i| a[x] = i end
    a
  end
end

# Decompose _A as Q * R * P, and return (Q, R, P).
# Q is $m times \min\{m, n\}$ Matrix which consists of leading columns of
# orthogonal matrix $Q$.
# R is $\min\{m, n\} \times n$ upper triangular Matrix.
# P is represented as column pivot indices Array.
#
# @param _A Matrix.
def decompose_QRP(_A)
  _Acopy = _A.copy
  pivot = FFI::MemoryPointer.new(LAPACK::find_type(:lapack_int), _A.ncols)
  max_rank = [_A.nrows, _A.ncols].min
  tau = Vector.new(max_rank)
  info = LAPACK::dgeqp3(:LAPACK_COL_MAJOR, _A.nrows, _A.ncols, _Acopy.p, _A.nrows, pivot, tau.p)
  raise LAPACK::Info.new(:dgeqp3, info) unless info == 0
  _R = Matrix.new(max_rank, _A.ncols)
  i = 0
  while i < max_rank do
    j = i
    while j < _A.ncols do
      _R[i,j] = _Acopy[i,j]
      j += 1
    end
    i += 1
  end
  info = LAPACK::dorgqr(:LAPACK_COL_MAJOR, _A.nrows, max_rank, max_rank, _Acopy.p, _A.nrows, tau.p)
  [_Acopy.resize(_A.nrows, max_rank), _R, pivot.get_bytes(0, pivot.size).unpack('i*').collect!.with_index do |j, jo| if j == 0 then jo else j - 1 end end]
end

# Return eigen values and corresponding eigen vectors if with_vectors is
# true.
# This assumes that _A is symmetric Matrix for fast computation.
# Eigen vectors are returned in Matrix whose columns are those in order
# indicated by eigen values.
#
# @param _A symmetric Matrix.
# @param with_vectors returns all eigen vectors also if true.
def eigen_system_symmetric(_A, with_vectors: true)
  _Acopy = _A.copy
  lambdas = Vector.new(_A.nrows)
  info = LAPACK::dsyev(:LAPACK_COL_MAJOR, if with_vectors then 'V'.ord else 'N'.ord end, 'U'.ord, _Acopy.ncols, _Acopy.p, _Acopy.nrows, lambdas.p)
  raise LAPACK::Info.new(:dsyev, info) unless info == 0
  if with_vectors then [lambdas, _Acopy] else lambdas end
end
# (see #eigen_system_symmetric)
def eigen_values_symmetric(_A)
  eigen_system_symmetric(_A, with_vectors: false)
end

# Solve the linear equation AX = B.
#
# @param A Matrix.
# @param B Vector or Matrix.
def solve_linear_equation(_A, _B)
  raise '_A must be Matrix' unless _A.is_a? Matrix
  raise '_B must be Vector or Matrix' unless _B.is_a? Vector or _B.is_a? Matrix
  _Acopy, _Bcopy = _A.copy, if _B.is_a? Vector then _B.resize([_A.ncols, _B.length].max) else _B.resize([_A.ncols, _B.nrows].max, _B.ncols) end
  jpvt = FFI::MemoryPointer.new(:int, _A.ncols)
  rcond = 1.0e-05
  rank = FFI::MemoryPointer.new(:int, 1)
  info = LAPACK::dgelsy(:LAPACK_COL_MAJOR, _Acopy.nrows, _Acopy.ncols, if _Bcopy.is_a? Vector then 1 else _Bcopy.ncols end, _Acopy.p, _Acopy.nrows, _Bcopy.p, if _Bcopy.is_a? Vector then _Bcopy.length else _Bcopy.nrows end, jpvt, rcond, rank)
  raise LAPACK::Info.new(:dgelsy, info) unless info == 0
  if _Bcopy.is_a? Vector then _Bcopy.resize(_A.ncols) else _Bcopy.resize(_A.ncols, _Bcopy.ncols) end
end

# Solve the following Weighted Least Squares problem:
#   \min_{\bm{x} \in \mathbb{R}^m} (\bm{y} - A\bm{x})^\top \diag(\bm{w}) (\bm{y} - A\bm{x}),
#     \bm{y} \in \mathbb{R}^m, A: m \times n, \bm{w} \in \mathbb{R}^m
#
# @param y Vector.
# @param _A Matrix.
# @param w weight Vector. If this is omitted, weights are treated as uniform.
def solve_weighted_least_squares(y, _A, w=nil)
  raise "y must be Vector" unless y.is_a? Vector
  raise "_A must be Matrix" unless _A.is_a? Matrix
  raise "length of y and number of rows of A must be equal" unless y.length == _A.nrows
  ycopy, _Acopy = if w then
    raise "w must be Vector" unless w.is_a? Vector
    raise "length of w and y must be equal" unless w.length == y.length
    wsqrt = w.power_elements(0.5)
    [if y.length < _A.ncols then y.hadamard(wsqrt).resize(_A.ncols) else y.hadamard(wsqrt) end, _A.mul_rows(wsqrt)]
  else
    [if y.length < _A.ncols then y.resize(_A.ncols) else y.copy end, _A.copy]
  end
  return solve_linear_equation(_Acopy, ycopy)
end

# Solve the following multiple Weighted Least Squares problem for k = 1,\ldots,K:
#   \min_{\bm{x}_k \in \mathbb{R}^m} (\bm{y}_k - A\bm{x})^\top \diag(\bm{w}_k) (\bm{y}_k - A\bm{x}),
#     Y := (\bm{y}_1,\ldots,\bm{y}_K): m \times K, A: m \times n,
#     W := (\bm{w}_1,\ldots,\bm{w}_K): m \times K
#
# @param _Y Matrix
# @param _A Matrix
# @param _W Matrix if set
def solve_multiple_weighted_least_squares(_Y, _A, _W=nil)
  raise "_Y must be Matrix" unless _Y.is_a? Matrix
  raise "_A must be Matrix" unless _A.is_a? Matrix
  raise "number of rows of _Y and A must be equal" unless _Y.nrows == _A.nrows
  _W ||= Matrix.new(_Y.nrows, _Y.ncols).fill(1.0)
  raise "_W must be Matrix" unless _W.is_a? Matrix
  raise "number of rows of w and y must be equal" unless _W.nrows == _Y.nrows
  raise "number of columns of w and y must be equal" unless _W.ncols == _Y.ncols
  Matrix.new(_A.ncols, _Y.ncols).each.with_index do |x, j|
    x.fill(solve_weighted_least_squares(_Y.slice_columns(j).to_vector, _A, _W.slice_columns(j).to_vector))
  end
end


text:
package com.braisgabin.fbstats;

import java.io.IOException;

import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

public class Api {
	private final OkHttpClient client;
	private final String accessToken;
	private final ObjectMapper mapper;

	public Api(String accessToken) {
		this.accessToken = accessToken;

		this.client = new OkHttpClient();

		this.mapper = new ObjectMapper();
		this.mapper.setVisibility(PropertyAccessor.ALL, Visibility.NONE);
		this.mapper.setVisibility(PropertyAccessor.FIELD, Visibility.NONE);
		this.mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		this.mapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, true);
	}

	public <T> T download(String url, Class<T> clazz) throws JsonParseException, JsonMappingException, IOException {
		Request request = new Request.Builder()
				.url(url)
				.addHeader("Authorization", "OAuth " + accessToken).build();

		Response response = client.newCall(request).execute();
		if (!response.isSuccessful()) {
			throw new RuntimeException(response.body().string());
		}
		return mapper.readValue(response.body().byteStream(), clazz);
	}
}


text:
@import XCTest;

@interface IMGAssetsLibraryTests : XCTestCase

@end

@implementation IMGAssetsLibraryTests

- (void)setUp
{
    [super setUp];
}

- (void)tearDown
{
    [super tearDown];
}

- (void)waitForExpectations
{
    [self waitForExpectationsWithTimeout:901.0 handler:^(NSError *error) {
        if (error) XCTFail(@"Async test timed out");
    }];
}

- (NSData *)inputData
{
    NSData *inputData = [@"Hello, world!" dataUsingEncoding:NSUTF8StringEncoding];
    return inputData;
}

- (void)testThatSaveDataResolvesToAURI
{
    XCTestExpectation *expectation = [self expectationWithDescription:@"Wait for async call to finish"];
    NSData *inputData = [self inputData];

    // Stub out an instance of ALAssetsLibrary
    id library = [OCMockObject partialMockForObject:[[ALAssetsLibrary alloc] init]];
    NSURL *url = [NSURL URLWithString:@"assets-library://path/to/image.jpg"];
    void (^proxyBlock)(NSInvocation *) = ^(NSInvocation *invocation) {
        void (^passedBlock)(NSURL *assetURL, NSError *error);
        [invocation getArgument:&passedBlock atIndex:4];
        passedBlock(url, nil);
    };
    [[[library stub] andDo:proxyBlock] writeImageDataToSavedPhotosAlbum:[OCMArg any]
                                                               metadata:[OCMArg any]
                                                        completionBlock:[OCMArg any]];

    // Stub out [IMGAssetsLibrary assetsLibrary] to return our stub library
    id mock = [OCMockObject mockForClass:[IMGAssetsLibrary class]];
    [[[mock stub] andReturn:library] assetsLibrary];

    // Save data to assets library
    [IMGAssetsLibrary saveData:inputData]
        .then(^(NSString *uri) {
            XCTAssert([uri hasPrefix:@"assets-library://"]);
            [expectation fulfill];
        })
        .catch(^(NSError *error) {
            XCTFail(@"Expected promise to resolve.");
        });
    [self waitForExpectations];
}

//- (void)testThatLoadDataForURILoadsNSData
//{
//    // Save data to assets library (and note the returned URI)
//    // Load data from the saved URI
//}

@end


text:
<?php namespace Shopavel\Orders\Entities;

/**
 * Interface for order entities. An order entity is any model that can be
 * attached to an order, such as products and vouchers.
 *
 * @author  Laurence Roberts <lsjroberts@gmail.com>
 */
interface EntityInterface {

    /**
     * Get the unique key for this entity.
     *
     * @return string
     */
    public function getKey();

}


text:
<?php

namespace PBlondeau\Bundle\WorkBundle\Controller\Album;

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use PBlondeau\Bundle\CommonBundle\Controller\BaseController;
use PBlondeau\Bundle\WorkBundle\Entity\Album;
use PBlondeau\Bundle\WorkBundle\Form\Type\AlbumType;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

/**
 * Album controller.
 *
 * @Route("/admin/albums")
 */
class AdminController extends BaseController
{

    /**
     * @Route("/", name="admin_work_albums")
     * @Method("GET")
     */
    public function indexAction()
    {
        $albums = $this->getPaginator()->paginate(
            $this->getAlbumRepository()->findForAdminList(),
            $this->get('request')->query->get('page', 1),
            self::DEFAULT_ITEMS_PER_PAGE
        );

        return $this->render(
            'PBlondeauWorkBundle:Album/Admin:index.html.twig',
            array(
                'albums' => $albums,
            )
        );
    }

    /**
     * @param Request $request
     * @param Album $album
     *
     * @return \Symfony\Component\HttpFoundation\Response
     *
     * @Route("/create", name="admin_work_albums_create")
     * @Route("/{id}/update", name="admin_work_albums_edit")
     * @Method({"GET", "POST"})
     */
    public function saveAjaxAction(Request $request, Album $album = null)
    {
        if (!$album) {
            $album = new Album();
            $album->setUser($this->getUser());
        }

        $form = $this->buildSaveForm($album);

        if ($request->isMethod('POST')) {
            $form->submit($request);

            if ($form->isValid()) {
                $this->getEntityManager()->persist($album);
                $this->getEntityManager()->flush();

                $context = $album ? 'update' : 'create';
                $message = $this->getSuccessMessageFromContext($context);
                $this->addFlashMessage($message, 'success');

                return $this->redirect($this->generateUrl('admin_work_albums'));
            }
        }

        return $this->render(
            'PBlondeauWorkBundle:Album/Admin:_saveForm.html.twig',
            array(
                'form'  => $form->createView(),
                'album' => $album
            )
        );
    }

    /**
     * @param Request $request
     *
     * @return JsonResponse
     *
     * @Route("/update-position", name="admin_work_albums_update_positions")
     * @Method("POST")
     */
    public function updatePositionAjaxAction(Request $request)
    {
        if (!$request->isXmlHttpRequest()) {
            throw new AccessDeniedException('This path is only accessible in ajax');
        }

        $idWithPositionList = $request->get('idWithPositionList');
        foreach ($idWithPositionList as $idWithPosition) {
            /** @var Album $album */
            $album = $this->getAlbumRepository()->find($idWithPosition['id']);
            if (!$album) {
                throw new NotFoundHttpException();
            }
            $album->setPosition($idWithPosition['position']);
        }

        $this->getEntityManager()->flush();

        return new JsonResponse(
            array(
                'status' => 'success',
                'message' => $this->getTranslator()->trans('form.updatePosition.message', array(), 'adminWorkAlbum')
            )
        );
    }

    /**
     * @param Album $album
     *
     * @return \Symfony\Component\HttpFoundation\RedirectResponseœ
     *
     * @Route("/{id}", name="admin_work_albums_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Album $album)
    {
        $this->getEntityManager()->remove($album);
        $this->getEntityManager()->flush();

        $message = $this->getSuccessMessageFromContext('delete');
        $this->addFlashMessage($message, 'success');

        return $this->redirect($this->generateUrl('admin_work_albums'));
    }

    /**
     * @param Album $album
     *
     * @return \Symfony\Component\Form\Form
     */
    private function buildSaveForm(Album $album)
    {
        if ($album->isNew()) {
            $action = $this->generateUrl('admin_work_albums_create');
            $validationGroups = array('creation');
        } else {
            $action = $this->generateUrl(
                'admin_work_albums_edit',
                array('id' => $album->getId())
            );

            $validationGroups = array('default');
        }

        return $this->createForm(
            new AlbumType(), $album, array(
                'action' => $action,
                'method' => 'POST',
                'attr' => array('class' => 'form form-horizontal'),
                'validation_groups' => $validationGroups
            ),
            $album
        );
    }

    /**
     * @param $context
     *
     * @return string
     */
    private function getSuccessMessageFromContext($context = 'create')
    {
        return $this->getTranslator()->trans('form.' . $context . '.success.message', array(), 'adminWorkAlbum');
    }

}


text:
importScripts("/resources/testharness.js");
importScripts("/html/canvas/resources/canvas-tests.js");

var t = async_test("@font-face fonts should work even if they are not used in the page");
var t_pass = t.done.bind(t);
var t_fail = t.step_func(function(reason) {
    throw reason;
});
t.step(function() {

var canvas = new OffscreenCanvas(100, 50);
var ctx = canvas.getContext('2d');

var f = new FontFace("CanvasTest", "url('/fonts/CanvasTest.ttf')");
let fonts = (self.fonts ? self.fonts : document.fonts);
f.load();
fonts.add(f);
fonts.ready.then(function() {
    ctx.font = '67px CanvasTest';
    ctx.fillStyle = '#f00';
    ctx.fillRect(0, 0, 100, 50);
    ctx.fillStyle = '#0f0';
    ctx.fillText('AA', 0, 50);
    _assertPixelApprox(canvas, 5,5, 0,255,0,255, 2);
    _assertPixelApprox(canvas, 95,5, 0,255,0,255, 2);
    _assertPixelApprox(canvas, 25,25, 0,255,0,255, 2);
    _assertPixelApprox(canvas, 75,25, 0,255,0,255, 2);
  }).then(t_pass, t_fail);

});
done();


text:
var async   = require("async");

var logger = undefined

var init  = function(log){
   logger = log
}

var comparePerms = function(a, b){

   if ( undefined === b && undefined !== a ){
      return false
   }

   for (i in a){
      if (a[i] !== b[i]){
         return false
      }
   }

   for (i in b){
      if (a[i] !== b[i]){
         return false
      }
   }

   return true
}

var propagatePermissions = function(couchbase, dbs, msg, perms){

   var prevComplete     = (undefined !== perms._prev && perms._prev.status === 'propagated')
   var tag              = perms._current._date_created
   var object_updates   = {}
   var objects          = []
   var type_updates_app = {}
   var type_updates_all = {}
   var cloudlet_id      = msg.cloudlet_id;
   var thirdPartyId     = msg.third_party;

   var permsObjects     = perms._current.perms['@objects']
   var permsTypes       = perms._current.perms['@types']

   var prevPermsObjects = (undefined === perms._prev) ? {} : perms._prev.perms['@objects']
   var prevPermsTypes   = (undefined === perms._prev) ? {} : perms._prev.perms['@types']

   for (var i in permsTypes){
      if ( prevComplete ){
         if (permsTypes[i]['@app_level']){
            if ( undefined === prevPermsTypes[i] ||  !comparePerms(permsTypes[i]['@app_level'], prevPermsTypes[i]['@app_level']) ){
               type_updates_app[i] = permsTypes[i]['@app_level']
            }
         }
         if (permsTypes[i]['@cloudlet_level']){
            if ( undefined === prevPermsTypes[i] || !comparePerms(permsTypes[i]['@cloudlet_level'], prevPermsTypes[i]['@cloudlet_level']) ){
               type_updates_all[i] = permsTypes[i]['@cloudlet_level']
            }
         }
      }
      else{
         type_updates_app[i] = permsTypes[i]['@app_level']
         type_updates_all[i] = permsTypes[i]['@cloudlet_level']
      }
   }

   for (var i in permsObjects){
      if ( !prevComplete || !comparePerms(permsObjects[i], prevPermsObjects[i]) ){
         object_updates[i] = permsObjects[i]
         objects.push(i)
      }
   }

   for ( var type_id in type_updates_all ){
      var permissions = type_updates_all[type_id]
      updateObjectPermissionsByType(couchbase, dbs, cloudlet_id, type_id, thirdPartyId, permissions, objects, false)
   }

   for ( var type_id in type_updates_app ){
      var permissions = type_updates_app[type_id]
      updateObjectPermissionsByType(couchbase, dbs, cloudlet_id, type_id, thirdPartyId, permissions, objects, true)
   }

   //not async between 2
   //process objects last

   var funs = {}

   for ( var object_id in object_updates ){
      var permissions = object_updates[object_id]
      funs[i] = function(dbs, cloudlet_id, object_id, thirdPartyId, permissions, applevel){
         return function (callback) {
            updateObjectsPermission(dbs, cloudlet_id, object_id, thirdPartyId, permissions, applevel, callback)
         }
      }(dbs, cloudlet_id, object_id, thirdPartyId, permissions, false)
   }

   async.series(funs, function (err, results) {

      if (err) {
         logger.error(err);
      }
      else{

         dbs['permissions'].get(msg.database, function (err, db_body) {

            if (err && 13 === err.code){
               logger.info("Permissions do not exist: update failed");
            }
            else{
               if ( tag === db_body.value._current._date_created){
                  db_body.value._current.status = "propagated"
               }
               else if ( tag === db_body.value._prev._date_created){
                  db_body.value._prev.status = "propagated"
               }

               dbs['permissions'].replace(msg.database, db_body.value, function (err, result) {
                  logger.info("Permissions have been propogated");
               })
            }
         });
      }
   });
}

var updateObjectPermissionsByType = function(couchbase, dbs, cloudlet_id, type_id, thirdPartyId, permissions, objects, applevel){

   var skey = [cloudlet_id, type_id]
   var ekey = [cloudlet_id, type_id + "^"]

   applevel = true

   var ViewQuery = couchbase.ViewQuery;
   var query = ViewQuery.from('objects_views', 'object_by_type')
      .stale(ViewQuery.Update.BEFORE)
      .range(skey, ekey, true)
      .reduce(false)

   dbs['objects'].query(query, [], function (err, res) {

      if (err){
         return
      }

      var funs = {}

      for (var i = 0; i < res.length; i ++){
         var object_id = res[i].value[1]

         if ( -1 === objects.indexOf(object_id) ){
            funs[i] = (function(dbs, cloudlet_id, object_id, thirdPartyId, permissions, applevel){
               return function (callback) {
                  updateObjectsPermission(dbs, cloudlet_id, object_id, thirdPartyId, permissions, applevel, callback)
               }
            }(dbs, cloudlet_id, object_id, thirdPartyId, permissions, applevel))
         }
      }

      async.series(funs, function (err, results) {

         if (err) {
            logger.error(err);
         }
         else{
            //console.log(results)
         }
      });

   })
}

var updateObjectsPermission = function(dbs, cloudlet_id, object_id, thirdPartyId, permissions, applevel, callback){

   var key = cloudlet_id + '+' + object_id

   dbs['objects'].get(key, function (err, db_body) {

      if(err) {
         logger.error(err);
         callback(null, "not found: " + key)
         return
      }

      if ( undefined === db_body.value._permissions ){
         db_body.value._permissions = {}
      }

      if ( !applevel || (applevel && db_body.value._permissions.created_by === thirdPartyId) ){

         db_body.value._permissions[thirdPartyId] = permissions

         dbs['objects'].replace(key, db_body.value, function (err, result) {

            if (err) {
               logger.error(err);

               callback(null, "failure: " + key)
            }
            else {
               callback(null, "success: " + key)
            }
         });
      }
      else{
         callback(null, "success: " + key)
      }
   });
}

var createPemissions = function(couchbase, dbs, msg, db_body, perms_prop_f, callback){

   var data = {
      _current : msg.object_data,
      _history : []
   }

   dbs[msg['bucket']].insert(msg.database, data, {}, function (err, result) {
      if (err) {
         logger.error(err);
      }
      else {
         callback(null, { 'status': 'update' }, 200);
         if(msg['bucket']!== "app_permissions") {
            perms_prop_f.send({orig : msg, perms : data});
         }
      }
   });
}

var updateExistingPemissions = function(couchbase, dbs, msg, db_body, perms_prop_f, callback){

   if ( undefined !== db_body.value['_prev'] && null !== db_body.value['_prev']){
      db_body.value['_history'].push(db_body.value['_prev'])
   }

   db_body.value['_prev']    = db_body.value['_current']
   db_body.value['_current'] = msg.object_data

   dbs[msg['bucket']].replace(msg.database, db_body.value, {}, function (err, result) {
      if (err) {
         logger.error(err);
      }
      else {
         callback(null, { 'status': 'update' }, 200);

         perms_prop_f.send({orig : msg, perms : db_body.value});
      }
   });
};

var createAppPemissions = function(couchbase, dbs, msg, callback){

   dbs[msg['bucket']].insert(msg.database, msg.object_data, {}, function (err, result) {
      if (err) {
         logger.error(err);
      }
      else {
         callback(null, { 'status': 'update' }, 200);
      }
   });
}

var processPermissionsUpdate = function(couchbase, dbs, msg, perms_prop_f, callback){

   // get permissions
   dbs[msg['bucket']].get(msg.database, function (err, db_body) {

      if (err && 13 === err.code){
         logger.info("Permissions do not exist");
         createPemissions(couchbase, dbs, msg, db_body, perms_prop_f, callback)
      }
      else{
         updateExistingPemissions(couchbase, dbs, msg, db_body, perms_prop_f, callback)
      }
   });

}

var processAppPermissionsUpdate = function(couchbase, dbs, msg, perms_prop_f, callback){

   createAppPemissions(couchbase, dbs, msg, callback)

}

module.exports.init                        = init;
module.exports.processPermissionsUpdate    = processPermissionsUpdate;
module.exports.processAppPermissionsUpdate = processAppPermissionsUpdate;


text:
package org.apache.nutch.protocol.file;

import java.lang.invoke.MethodHandles;
import java.net.URL;
import java.util.List;

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

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.Text;

import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.net.protocols.Response;
import org.apache.nutch.protocol.Content;
import org.apache.nutch.protocol.Protocol;
import org.apache.nutch.protocol.ProtocolOutput;
import org.apache.nutch.protocol.ProtocolStatus;
import org.apache.nutch.protocol.RobotRulesParser;
import org.apache.nutch.util.NutchConfiguration;

import crawlercommons.robots.BaseRobotRules;

/**
 * This class is a protocol plugin used for file: scheme. It creates
 * {@link FileResponse} object and gets the content of the url from it.
 * Configurable parameters are {@code file.content.limit} and
 * {@code file.crawl.parent} in nutch-default.xml defined under
 * "file properties" section.
 *
 * @author John Xing
 */
public class File implements Protocol {

  protected static final Logger LOG = LoggerFactory
      .getLogger(MethodHandles.lookup().lookupClass());

  static final int MAX_REDIRECTS = 5;

  int maxContentLength;
  boolean crawlParents;

  /**
   * if true return a redirect for symbolic links and do not resolve the links
   * internally
   */
  boolean symlinksAsRedirects = true;

  private Configuration conf;

  public File() {
  }

  /**
   * Set the {@link Configuration} object
   */
  @Override
  public void setConf(Configuration conf) {
    this.conf = conf;
    this.maxContentLength = conf.getInt("file.content.limit", 1024 * 1024);
    this.crawlParents = conf.getBoolean("file.crawl.parent", true);
    this.symlinksAsRedirects = conf.getBoolean(
        "file.crawl.redirect_noncanonical", true);
  }

  /**
   * Get the {@link Configuration} object
   */
  @Override
  public Configuration getConf() {
    return this.conf;
  }

  /**
   * Set the length after at which content is truncated.
   * @param maxContentLength max content in bytes
   */
  public void setMaxContentLength(int maxContentLength) {
    this.maxContentLength = maxContentLength;
  }

  /**
   * Creates a {@link FileResponse} object corresponding to the url and return a
   * {@link ProtocolOutput} object as per the content received
   *
   * @param url
   *          Text containing the url
   * @param datum
   *          The CrawlDatum object corresponding to the url
   *
   * @return {@link ProtocolOutput} object for the content of the file indicated
   *         by url
   */
  @Override
  public ProtocolOutput getProtocolOutput(Text url, CrawlDatum datum) {
    String urlString = url.toString();
    try {
      URL u = new URL(urlString);

      int redirects = 0;

      while (true) {
        FileResponse response;
        response = new FileResponse(u, datum, this, getConf()); // make a
                                                                // request

        int code = response.getCode();

        if (code == 200) { // got a good response
          return new ProtocolOutput(response.toContent()); // return it

        } else if (code == 304) { // got not modified
          return new ProtocolOutput(response.toContent(),
              ProtocolStatus.STATUS_NOTMODIFIED);

        } else if (code == 401) { // access denied / no read permissions
          return new ProtocolOutput(response.toContent(), new ProtocolStatus(
              ProtocolStatus.ACCESS_DENIED));

        } else if (code == 404) { // no such file
          return new ProtocolOutput(response.toContent(),
              ProtocolStatus.STATUS_NOTFOUND);

        } else if (code >= 300 && code < 400) { // handle redirect
          u = new URL(response.getHeader("Location"));
          if (LOG.isTraceEnabled()) {
            LOG.trace("redirect to " + u);
          }
          if (symlinksAsRedirects) {
            return new ProtocolOutput(response.toContent(), new ProtocolStatus(
                ProtocolStatus.MOVED, u));
          } else if (redirects == MAX_REDIRECTS) {
            LOG.trace("Too many redirects: {}", url);
            return new ProtocolOutput(response.toContent(), new ProtocolStatus(
                ProtocolStatus.REDIR_EXCEEDED, u));
          }
          redirects++;

        } else { // convert to exception
          throw new FileError(code);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      return new ProtocolOutput(null, new ProtocolStatus(e));
    }
  }

  /**
   * Quick way for running this class. Useful for debugging.
   * @param args run with no args to print help
   * @throws Exception if there is a fatal error running this class
   * with the given input
   */
  public static void main(String[] args) throws Exception {
    int maxContentLength = Integer.MIN_VALUE;
    boolean dumpContent = false;
    String urlString = null;

    String usage = "Usage: File [-maxContentLength L] [-dumpContent] url";

    if (args.length == 0) {
      System.err.println(usage);
      System.exit(-1);
    }

    for (int i = 0; i < args.length; i++) {
      if (args[i].equals("-maxContentLength")) {
        maxContentLength = Integer.parseInt(args[++i]);
      } else if (args[i].equals("-dumpContent")) {
        dumpContent = true;
      } else if (i != args.length - 1) {
        System.err.println(usage);
        System.exit(-1);
      } else
        urlString = args[i];
    }

    File file = new File();
    file.setConf(NutchConfiguration.create());

    if (maxContentLength != Integer.MIN_VALUE) // set maxContentLength
      file.setMaxContentLength(maxContentLength);

    // set log level
    // LOG.setLevel(Level.parse((new String(logLevel)).toUpperCase()));

    ProtocolOutput output = file.getProtocolOutput(new Text(urlString),
        new CrawlDatum());
    Content content = output.getContent();

    System.err.println("URL: " + content.getUrl());
    System.err.println("Status: " + output.getStatus());
    System.err.println("Content-Type: " + content.getContentType());
    System.err.println("Content-Length: "
        + content.getMetadata().get(Response.CONTENT_LENGTH));
    System.err.println("Last-Modified: "
        + content.getMetadata().get(Response.LAST_MODIFIED));
    String redirectLocation = content.getMetadata().get("Location");
    if (redirectLocation != null) {
      System.err.println("Location: " + redirectLocation);
    }

    if (dumpContent) {
      System.out.print(new String(content.getContent()));
    }

    file = null;
  }

  /**
   * No robots parsing is done for file protocol. So this returns a set of empty
   * rules which will allow every url.
   */
  @Override
  public BaseRobotRules getRobotRules(Text url, CrawlDatum datum,
      List<Content> robotsTxtContent) {
    return RobotRulesParser.EMPTY_RULES;
  }

}


text:
package com.cloud.dc;

import com.cloud.utils.db.GenericDao;

import java.util.Map;

public interface ClusterDetailsDao extends GenericDao<ClusterDetailsVO, Long> {
    Map<String, String> findDetails(long clusterId);

    void persist(long clusterId, Map<String, String> details);

    void persist(long clusterId, String name, String value);

    ClusterDetailsVO findDetail(long clusterId, String name);

    void deleteDetails(long clusterId);

}


text:
var assert = require('assert')

var o  = require('@carbon-io/carbon-core').atom.o(module).main
var testtube = require('@carbon-io/carbon-core').testtube

var LimiterSelector = require('../../lib/limiter/LimiterSelector')

module.exports = o({
  _type: testtube.Test,
  name: 'LimiterSelectorTests',
  description: 'LimiterSelector interface tests',
  tests: [
    o({
      _type: testtube.Test,
      name: 'TestInstantiate',
      description: 'Test instantiation fails',
      doTest: function() {
        assert.throws(function() {
          var limiterSelector = o({_type: LimiterSelector})
        }, Error)
      }
    }),
  ]
})


text:
package org.mule.transport.zmq.adapters;

import org.mule.api.Capabilities;
import org.mule.api.Capability;
import org.mule.transport.zmq.ZMQTransport;

public class ZMQTransportCapabilitiesAdapter extends ZMQTransport implements Capabilities {

    public boolean isCapableOf(Capability capability) {
        if (capability == Capability.LIFECYCLE_CAPABLE) {
            return true;
        }
        if (capability == Capability.CONNECTION_MANAGEMENT_CAPABLE) {
            return true;
        }
        return false;
    }

}


text:
using System;

namespace HourGlass
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("XXXXXXXXXXXX");
            Console.WriteLine(" \\*******/");
            Console.WriteLine("  \\*****/");
            Console.WriteLine("   \\***/");
            Console.WriteLine("    \\*/");
            Console.WriteLine("    / \\");
            Console.WriteLine("   /   \\");
            Console.WriteLine("  /     \\");
            Console.WriteLine(" /       \\");
            Console.WriteLine("XXXXXXXXXXXX");
            Console.ReadLine();
            Console.Clear();

            Console.WriteLine("XXXXXXXXXXXX");
            Console.WriteLine(" \\       /");
            Console.WriteLine("  \\*****/");
            Console.WriteLine("   \\***/");
            Console.WriteLine("    \\*/");
            Console.WriteLine("    / \\");
            Console.WriteLine("   /   \\");
            Console.WriteLine("  /     \\");
            Console.WriteLine(" /*******\\");
            Console.WriteLine("XXXXXXXXXXXX");
            Console.ReadLine();
            Console.Clear();

            Console.WriteLine("XXXXXXXXXXXX");
            Console.WriteLine(" \\       /");
            Console.WriteLine("  \\     /");
            Console.WriteLine("   \\***/");
            Console.WriteLine("    \\*/");
            Console.WriteLine("    / \\");
            Console.WriteLine("   /   \\");
            Console.WriteLine("  /*****\\");
            Console.WriteLine(" /*******\\");
            Console.WriteLine("XXXXXXXXXXXX");
            Console.ReadLine();
            Console.Clear();

            Console.WriteLine("XXXXXXXXXXXX");
            Console.WriteLine(" \\       /");
            Console.WriteLine("  \\     /");
            Console.WriteLine("   \\   /");
            Console.WriteLine("    \\*/");
            Console.WriteLine("    / \\");
            Console.WriteLine("   /***\\");
            Console.WriteLine("  /*****\\");
            Console.WriteLine(" /*******\\");
            Console.WriteLine("XXXXXXXXXXXX");
            Console.ReadLine();
            Console.Clear();

            Console.WriteLine("XXXXXXXXXXXX");
            Console.WriteLine(" \\       /");
            Console.WriteLine("  \\     /");
            Console.WriteLine("   \\   /");
            Console.WriteLine("    \\ /");
            Console.WriteLine("    /*\\");
            Console.WriteLine("   /***\\");
            Console.WriteLine("  /*****\\");
            Console.WriteLine(" /*******\\");
            Console.WriteLine("XXXXXXXXXXXX");
            Console.ReadLine();

            Console.WriteLine("時間到!");
            Console.ReadLine();
        }
    }
}


text:
using System;
using System.Linq;
using System.Reactive.Linq;
using System.Windows.Forms;
using System.Reactive.Disposables;
using Excercise9.DictionarySuggestService;

namespace Excercise9
{
    class Program
    {
        static void Main()
        {
            var txt = new TextBox();
            var lst = new ListBox { Top = txt.Height + 10 };

            var frm = new Form()
            {
                Controls = { txt, lst }
            };

#if PRODUCTION
            // Turn the user input into a tamed sequence of strings.
            var textChanged = from evt in Observable.FromEventPattern(txt, "TextChanged")
                              select ((TextBox)evt.Sender).Text;

            var input = textChanged
                        .Throttle(TimeSpan.FromSeconds(1))
                        .DistinctUntilChanged();
#else
            const string INPUT = "reactive";

            var rand = new Random();

            var input = Observable.Generate(
                3,
                len => len <= INPUT.Length,
                len => len + 1,
                len => INPUT.Substring(0, len),
                _ => TimeSpan.FromMilliseconds(rand.Next(200, 1200))
            )
            .ObserveOn(txt)
            .Do(term => txt.Text = term)
            .Throttle(TimeSpan.FromSeconds(1));
#endif

            // Bridge with the web service's MatchInDict method.
            var svc = new DictServiceSoapClient("DictServiceSoap");
            var matchInDict = Observable.FromAsyncPattern<string, string, string, DictionaryWord[]>
                (svc.BeginMatchInDict, svc.EndMatchInDict);

#if PRODUCTION
            Func<string, IObservable<DictionaryWord[]>> matchInWordNetByPrefix =
                term => matchInDict("wn", term, "prefix");
#else
            Func<string, IObservable<DictionaryWord[]>> matchInWordNetByPrefix =
                term => Observable.Return
                (
                    (from i in Enumerable.Range(0, rand.Next(0, 50))
                     select new DictionaryWord { Word = term + i })
                     .ToArray()
                ).Delay(TimeSpan.FromSeconds(rand.Next(1, 10)));
#endif

            // The grand composition connecting the user input with the web service.
            var res = (from term in input
                      select matchInWordNetByPrefix(term))
                      .Switch();

            // Synchronize with the UI thread and populate the ListBox or signal an error.
            using (res.ObserveOn(lst).Subscribe(
                words =>
                {
                    lst.Items.Clear();
                    lst.Items.AddRange((from word in words select word.Word).ToArray());
                },
                ex =>
                {
                    MessageBox.Show(
                        "An error occurred: " + ex.Message, frm.Text, MessageBoxButtons.OK, MessageBoxIcon.Error
                    );
                }))
            {
                Application.Run(frm);
            } // Proper disposal happens upon exiting the application.
        }
    }
}


text:
Do Project 0 MyAppPortfolio.

# References
Online course "Android nanodegree" from Udacity/Google
<https://www.udacity.com/course/android-developer-nanodegree--nd801>

<https://www.udacity.com/course/viewer#!/c-nd801/l-4182219172/m-4178939069>

<http://udacity.github.io/android-nanodegree-guidelines/index.html>

<http://udacity.github.io/android-nanodegree-guidelines/core.html>

## Android device
Nexus 4 running Android 5.1.1

# Results

## Background
This app will become a launcher app for other apps I will build in course.

## Android version
In build.gradle, specified

        minSdkVersion 22
        targetSdkVersion 22

For release build, probably would want to reduce minSdkVersion so more users can run app.
<https://developer.android.com/guide/topics/manifest/uses-sdk-element.html>

## Project name
I named project without spaces "MyAppPortfolio".
Changed app_name to include spaces "My App Portfolio".

<http://stackoverflow.com/questions/5443304/how-to-change-an-android-apps-name>


text:
<?php

require __DIR__.'/../models/connection.class.php';

if(isset($_POST['connection'])){
	$username = htmlentities($_POST['username']);
	$password = htmlentities($_POST['password']);
	$message = "";

	if(!empty($username) && !empty($password)){

		$sql = "SELECT * FROM users WHERE username='".$username."' AND password='".$password."' LIMIT 1";
		$res = connection::getInstance()->query($sql);

		if($res->rowCount() > 0){

			session_start();

			$_SESSION['username'] = $username;

			foreach($res as $value){

				$_SESSION['firstname']  = $value['firstname'];
				$_SESSION['lastname'] = $value['lastname'];
				$_SESSION['email'] = $value['email'];

			}

			header ("Location: ../views/dashboard.php");
		}
		else{
			header ("Location: ../views/index.php?status=0");
		}
	}
}
?>


text:
string BindingEnv::LookupVariable(const string& var) {
  map<string, string>::iterator i = bindings_.find(var);
  if (i != bindings_.end())
    return i->second;
  if (parent_)
    return parent_->LookupVariable(var);
  return "";
}

void BindingEnv::AddBinding(const string& key, const string& val) {
  bindings_[key] = val;
}

bool EvalString::Parse(const string& input, string* err, size_t* err_index) {
  unparsed_ = input;

  string::size_type start, end;
  start = 0;
  do {
    end = input.find('$', start);
    if (end == string::npos) {
      end = input.size();
      break;
    }
    if (end > start)
      parsed_.push_back(make_pair(input.substr(start, end - start), RAW));
    start = end + 1;
    if (start < input.size() && input[start] == '{') {
      ++start;
      for (end = start + 1; end < input.size(); ++end) {
        if (input[end] == '}')
          break;
      }
      if (end >= input.size()) {
        *err = "expected closing curly after ${";
        if (err_index)
          *err_index = end;
        return false;
      }
      parsed_.push_back(make_pair(input.substr(start, end - start), SPECIAL));
      ++end;
    } else if (start < input.size() && input[start] == '$') {
      parsed_.push_back(make_pair("$", RAW));
      end = start + 1;
    } else {
      for (end = start; end < input.size(); ++end) {
        char c = input[end];
        if (!(('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') ||
              ('0' <= c && c <= '9') || c == '_')) {
          break;
        }
      }
      if (end == start) {
        *err = "expected variable after $";
        if (err_index)
          *err_index = start;
        return false;
      }
      parsed_.push_back(make_pair(input.substr(start, end - start), SPECIAL));
    }
    start = end;
  } while (end < input.size());
  if (end > start)
    parsed_.push_back(make_pair(input.substr(start, end - start), RAW));

  return true;
}

string EvalString::Evaluate(Env* env) const {
  string result;
  for (TokenList::const_iterator i = parsed_.begin(); i != parsed_.end(); ++i) {
    if (i->second == RAW)
      result.append(i->first);
    else
      result.append(env->LookupVariable(i->first));
  }
  return result;
}


text:
<?php

namespace eecli\Command;

use eecli\Command\Contracts\HasExamples;
use eecli\Command\Contracts\HasLongDescription;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;

class DeleteSnippetCommand extends Command implements HasExamples, HasLongDescription
{
    /**
     * {@inheritdoc}
     */
    protected $name = 'delete:snippet';

    /**
     * {@inheritdoc}
     */
    protected $description = 'Delete a snippet.';

    /**
     * {@inheritdoc}
     */
    protected function getArguments()
    {
        return array(
            array(
                'name', // name
                InputArgument::IS_ARRAY | InputArgument::REQUIRED, // mode
                'The name of the snippet(s) to delete.', // description
            ),
        );
    }

    /**
     * {@inheritdoc}
     */
    protected function getOptions()
    {
        return array(
            array(
                'global', // name
                null, // shortcut
                InputOption::VALUE_NONE, // mode
                'Delete a global snippet.', // description
                null, // default value
            ),
            array(
                'force', // name
                'f', // shortcut
                InputOption::VALUE_NONE, // mode
                'Do not ask for confirmation before deleting', // description
            ),
        );
    }

    /**
     * {@inheritdoc}
     */
    protected function fire()
    {
        $names = $this->argument('name');

        $siteId = $this->option('global') ? 0 : ee()->config->item('site_id');
        $siteName = $this->option('global') ? 'global_snippets' : ee()->config->item('site_short_name');

        if (! $this->option('force') && ! $this->confirm('Are you sure you want to delete? [Yn]', true)) {
            $this->error('Did not delete snippet(s): '.implode(' ', $names));

            return;
        }

        $query = ee()->db->select('snippet_id, snippet_name, snippet_contents')
            ->where('site_id', $siteId)
            ->where_in('snippet_name', $names)
            ->get('snippets');

        $snippets = array();

        foreach ($query->result() as $row) {
            $snippets[$row->snippet_name] = $row;
        }

        $query->free_result();

        foreach ($names as $name) {
            if (! isset($snippets[$name])) {
                $this->error('Snippet '.$name.' not found.');

                continue;
            }

            $snippet = $snippets[$name];

            ee()->db->delete('snippets', array('snippet_id' => $snippet->snippet_id));

            ee()->extensions->call('eecli_delete_snippet', $snippet->snippet_id, $snippet->snippet_name, $snippet->snippet_contents, $siteId, $siteName);

            $this->info('Snippet '.$name.' deleted.');
        }
    }

    public function getLongDescription()
    {
        return "Delete one or more snippets. You will be asked to confirm that you want to delete the specified snippet(s), unless you use the `--force` option.\n\nWhen you have [Sync Snippets](https://github.com/rsanchez/sync_snippets) installed and configured, this command will delete the snippet file as well.";
    }

    public function getExamples()
    {
        return array(
            'Delete a snippet' => 'your_snippet_name',
            'Delete a snippet accessible to all sites' => '--global your_snippet_name',
            'Delete multiple snippets' => 'your_snippet_name your_other_snippet_name',
            'Delete a snippet without confirmation' => '--force your_snippet_name',
        );
    }
}


text:
layout: post
title: "Symfony PHP Code Sniffer"
excerpt: "Symfony Coding Standards Code Sniffer, O que é ? Aprenda e Instale!"
tags:
 - Symfony
feature: images/postagens/symfonyPhpCs/symfonyPhpCs.jpg
comments: true
---
Symfony PHP Code Sniffer ?!
Mas e aí o que é primeiramente o **PHP Code Sniffer** ?

Vamos explicando aos poucos logo abaixo...

Sabemos que dificilmente um código será mantido pelo seu criador eternamente.

Por isso precisamos de padrões de código, para manter um código bem escrito e descrito, e as convenções de código padronizam de acordo com a experiência já testada na área.

**O PHP Code Sniffer, visa validar um padrão de código.**

Os Padrões de Código Definem:

  > Indentação do Código
  >  Conveção de nomenclatura
  >  Espaços em Branco
  >  Padrão de Comentários
  >  Etc...

Assim sendo, padrões de código definem um código com qualidade, legibilidade, assim como reduzem custo de manutenção.

O `Php Code Sniffer` é um módulo da biblioteca `PEAR`, que possui um "Script" que verifica violações no Standard ( Padrão ) definido.

Para inicio de conversa precisamos ter o `PEAR` instalado execute:

{% highlight shell %}
sudo apt-get install php-pear
{% endhighlight %}

Agora vamos para a parte do `CodeSniffer` propriamente dita.

Executaremos agora:
{% highlight shell %}
sudo pear install PHP_CodeSniffer
{% endhighlight %}

Após a instalação, verificaremos se está instalado, execute:
{% highlight shell %}
phpcs -i
{% endhighlight %}

Você será capaz de ver os Standards instalados que será algo parecido com isso:

Porém o nosso Querido `SYMFONY 2` não aparecerá aí ...
Porque esse **Standard** ainda não está instalado.

Agora vamos encontrar qual o caminho está seu `PEAR` para instalarmos este **Standard**.
Execute:
{% highlight shell %}
pear config-show | grep php_dir
{% endhighlight %}

Agora entre dentro do caminho acima `+ PHP/CodeSniffer/Standards`, no meu caso assim:

Agora dentro da Pasta de **Standards**, vamos adicionar o nosso `Symfony 2` como padrão reconhecido, clonando o projeto do **[Symfony Standards](https://github.com/leaphub/phpcs-symfony2-standard)**, para dentro desta pasta, com os seguinte comando:
{% highlight shell %}
sudo git clone https://github.com/leaphub/phpcs-symfony2-standard.git Symfony2
{% endhighlight %}

Logo configuraremos o nosso `PHPCS` para analisar como padrão os Standards do Symfony2...
{% highlight shell %}
phpcs --config-set default_standard Symfony2
{% endhighlight %}

Para utilizar, podemos ou via linha de comando chamar o `PHPCS` para analisar a pasta `src/` do projeto ou integrar com a IDE.
Para fazer a chamada via linha de comando utilize:
{% highlight shell %}
phpcs --standard=Symfony2 --extensions=php src/
{% endhighlight %}

Lembre-se que só irá funcionar desta forma se você estiver dentro da pasta do projeto, senão você terá que referenciar o caminho completo para a pasta `src/`` .

Aqui finalizamos a instalação do `Symfony 2 Standard Php Code Sniffer` !

Como utilizo o `PhpStorm` (recomendo demais esta IDE), vou ensinar como integrar com esta IDE.

Primeito entre em Settings em sua IDE, e na busca dos Settings digite `Code Sniffer`.

Onde se encontra Configuration Local clique nos três pontinhos **...** para validarmos nosso `phpcs` , conforme imagem abaixo:

Após esta mensagem voltaremos e clicaremos em Inspections lá nos Settings, logo a direita onde marquei de amarelo selecione Default.

Onde fiz um circulo vermelho, clique para atualizar, e na setinha selecione o nosso Padrão `Symfony 2`.

Provavelmente acenderá algumas luzes em sua IDE passe o mouse por cima, e comece a melhorar seu código...

Veja os exemplos abaixo:

Bom meus amigos, é isso, espero que tenham gostado, e que sigam no passo a passo de fazer um código, limpo, legivel e inteligivel !
Seja inteligente !

Um abraço.


text:
package net.johnewart.gearman.engine.queue.persistence;

import com.codahale.metrics.Counter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jolbox.bonecp.BoneCP;
import com.jolbox.bonecp.BoneCPConfig;
import net.johnewart.gearman.common.Job;
import net.johnewart.gearman.constants.JobPriority;
import net.johnewart.gearman.engine.core.QueuedJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collection;
import java.util.LinkedList;

public class PostgresPersistenceEngine implements PersistenceEngine {
    private static Logger LOG = LoggerFactory.getLogger(PostgresPersistenceEngine.class);
    private static final int JOBS_PER_PAGE = 5000;
    private final String url;
    private final String tableName;
    private final BoneCP connectionPool;

    private final String updateJobQuery;
    private final String insertJobQuery;
    private final String deleteJobQuery;
    private final String findJobQuery;
    private final String readAllJobsQuery;
    private final String countQuery;
    private final String findAllJobsForFunctionQuery;
    private final String findJobByHandleQuery;
    private final MetricRegistry metricRegistry;
    private final Timer writeTimer, readTimer;
    private final Counter deleteCounter, writeCounter, pendingCounter;

    public PostgresPersistenceEngine(final String hostname,
                                     final int port,
                                     final String database,
                                     final String user,
                                     final String password,
                                     final String tableName,
                                     final MetricRegistry metricRegistry) throws SQLException
    {
        this.metricRegistry = metricRegistry;
        this.pendingCounter = metricRegistry.counter("postgresql.pending");
        this.writeTimer = metricRegistry.timer("postgresql.write");
        this.readTimer = metricRegistry.timer("postgresql.read");
        this.writeCounter = metricRegistry.counter("postgresql.write");
        this.deleteCounter = metricRegistry.counter("postgresql.delete");

        this.url = "jdbc:postgresql://" + hostname + ":" + port + "/" + database;
        this.tableName = tableName;

        this.updateJobQuery = String.format("UPDATE %s SET job_handle = ?, priority = ?, time_to_run = ?, json_data = ? WHERE unique_id = ? AND function_name = ?", tableName);
        this.insertJobQuery = String.format("INSERT INTO %s (unique_id, function_name, time_to_run, priority, job_handle, json_data) VALUES (?, ?, ?, ?, ?, ?)", tableName);
        this.deleteJobQuery = String.format("DELETE FROM %s WHERE function_name = ? AND unique_id = ?", tableName);
        this.findJobQuery = String.format("SELECT * FROM %s WHERE function_name = ? AND unique_id = ?", tableName);
        this.readAllJobsQuery = String.format("SELECT function_name, priority, unique_id, time_to_run FROM %s LIMIT ? OFFSET ?", tableName);
        this.countQuery = String.format("SELECT COUNT(*) AS jobCount FROM %s", tableName);
        this.findAllJobsForFunctionQuery = String.format("SELECT unique_id, time_to_run, priority FROM %s WHERE function_name = ?", tableName);
        this.findJobByHandleQuery= String.format("SELECT * FROM %s WHERE job_handle = ?", tableName);

        final BoneCPConfig config = new BoneCPConfig();
        config.setJdbcUrl(this.url);
        config.setUsername(user);
        config.setPassword(password);
        config.setMinConnectionsPerPartition(10);
        config.setMaxConnectionsPerPartition(20);
        config.setPartitionCount(1);

        connectionPool = new BoneCP(config);

        if (!validateOrCreateTable()) {
            throw new SQLException("Unable to validate or create jobs table '" + tableName + "'. Check credentials.");
        }
    }

    @Override
    public String getIdentifier() {
        String result = url;

        try {
            Connection connection = connectionPool.getConnection();
            DatabaseMetaData metaData = connection.getMetaData();
            int majorVersion, minorVersion;
            String productName, productVersion;

            majorVersion = metaData.getDatabaseMajorVersion();
            minorVersion = metaData.getDatabaseMinorVersion();
            productName = metaData.getDatabaseProductName();
            productVersion = metaData.getDatabaseProductVersion();
            result = String.format("%s (%s v%d.%d) - %s", productName, productVersion, majorVersion, minorVersion, url);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return result;
    }

    @Override
    public boolean write(final Job job) {
        Timer.Context context = writeTimer.time();
        PreparedStatement st = null;
        Connection conn = null;
        ObjectMapper mapper = new ObjectMapper();

        try {
            conn = connectionPool.getConnection();
            if(conn != null)
            {
                String jobJSON = mapper.writeValueAsString(job);

                // Update an existing job if one exists based on unique id
                st = conn.prepareStatement(updateJobQuery);
                st.setString(1, job.getJobHandle());
                st.setString(2, job.getPriority().toString());
                st.setLong  (3, job.getTimeToRun());
                st.setString(4, jobJSON);
                st.setString(5, job.getUniqueID());
                st.setString(6, job.getFunctionName());
                int updated = st.executeUpdate();

                // No updates, insert a new record.
                if(updated == 0)
                {
                    st = conn.prepareStatement(insertJobQuery);
                    st.setString(1, job.getUniqueID());
                    st.setString(2, job.getFunctionName());
                    st.setLong(3, job.getTimeToRun());
                    st.setString(4, job.getPriority().toString());
                    st.setString(5, job.getJobHandle());
                    st.setString(6, jobJSON);
                    int inserted = st.executeUpdate();
                    LOG.debug("Inserted " + inserted + " records for UUID " + job.getUniqueID());
                }
            }

            writeCounter.inc();
            pendingCounter.inc();
            return true;
        } catch (SQLException se) {
            LOG.error("SQL Error writing job: " , se);
            return false;
        } catch (IOException e) {
            LOG.error("I/O Error writing job: " , e);
            return false;
        } finally {
            context.stop();
            try {
                if(st != null)
                    st.close();

                if(conn != null)
                    conn.close();

            } catch (SQLException innerEx) {
                LOG.debug("Error cleaning up: " + innerEx);
            }
        }
    }

    @Override
    public void delete(final Job job) {
       this.delete(job.getFunctionName(), job.getUniqueID());
    }

    @Override
    public void delete(final String functionName, final String uniqueID) {
        PreparedStatement st = null;
        Connection conn = null;

        try {
            conn = connectionPool.getConnection();
            if(conn != null)
            {
                st = conn.prepareStatement(deleteJobQuery);
                st.setString(1, functionName);
                st.setString(2, uniqueID);
                int deleted = st.executeUpdate();
                LOG.debug("Deleted " + deleted + " records for " + functionName + "/" +uniqueID);
            }
            deleteCounter.inc();
            pendingCounter.dec();
        } catch (SQLException se) {
            LOG.error("SQL Error deleting job: " , se);
        } finally {
            try {
                if(st != null)
                    st.close();

                if(conn != null)
                    conn.close();

            } catch (SQLException innerEx) {
                LOG.debug("Error cleaning up: " + innerEx);
            }
        }
    }

    @Override
    public void deleteAll() {
        Statement st = null;
        Connection conn = null;
        try {
            conn = connectionPool.getConnection();
            if(conn != null)
            {
                st = conn.createStatement();
                final String deleteAllQuery = String.format("DELETE FROM %s", tableName);
                int deleted = st.executeUpdate(deleteAllQuery);
                LOG.debug("Deleted " + deleted + " jobs...");
            }
        } catch (SQLException se) {
            LOG.error("SQL Error deleting all jobs: " , se);
        } finally {
            try {
                if(st != null)
                    st.close();

                if(conn != null)
                    conn.close();

            } catch (SQLException innerEx) {
                LOG.debug("Error cleaning up: " + innerEx);
            }
        }
    }

    @Override
    public Job findJob(final String functionName, final String uniqueID) {
        PreparedStatement st = null;
        ResultSet rs = null;
        Connection conn = null;
        Timer.Context timer = readTimer.time();
        Job job = null;

        try {
            conn = connectionPool.getConnection();
            if(conn != null)
            {
                st = conn.prepareStatement(findJobQuery);
                st.setString(1, functionName);
                st.setString(2, uniqueID);

                ObjectMapper mapper = new ObjectMapper();
                rs = st.executeQuery();

                if(rs.next())
                {
                    String jobJSON = rs.getString("json_data");
                    job = mapper.readValue(jobJSON, Job.class);
                } else {
                    LOG.warn("No job for unique ID: " + uniqueID + " -- this could be an internal consistency problem...");
                }
            }
        } catch (SQLException se) {
            LOG.debug(se.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            timer.stop();
            try {
                if(rs != null)
                    rs.close();

                if(st != null)
                    st.close();

                if(conn != null)
                    conn.close();

            } catch (SQLException innerEx) {
                LOG.debug("Error cleaning up: " + innerEx);
            }
        }

        return job;
    }

    @Override
    public Collection<QueuedJob> readAll() {
        LinkedList<QueuedJob> jobs = new LinkedList<>();
        PreparedStatement st = null;
        ResultSet rs = null;
        Connection conn = null;
        // Which page of results are we on?
        int pageNum = 0;

        try {
            conn = connectionPool.getConnection();
            if(conn != null)
            {

                LOG.debug("Reading all job data from PostgreSQL");
                st = conn.prepareStatement(countQuery);
                rs = st.executeQuery();

                if(rs.next())
                {
                    int totalJobs = rs.getInt("jobCount");
                    int fetchedJobs = 0;
                    LOG.debug("Reading " + totalJobs + " jobs from PostgreSQL");
                    do {

                        st.setFetchSize(JOBS_PER_PAGE);
                        st.setMaxRows(JOBS_PER_PAGE);

                        st = conn.prepareStatement(readAllJobsQuery);
                        st.setInt(1, JOBS_PER_PAGE);
                        st.setInt(2, (pageNum * JOBS_PER_PAGE));

                        rs = st.executeQuery();

                        while(rs.next())
                        {

                            try {
                                final String uniqueId = rs.getString("unique_id");
                                final long timeToRun = rs.getLong("time_to_run");
                                final JobPriority jobPriority = JobPriority.valueOf(rs.getString("priority"));
                                final String functionName = rs.getString("function_name");

                                jobs.add(new QueuedJob(uniqueId, timeToRun, jobPriority, functionName));
                            } catch (Exception e) {
                                LOG.error("Unable to load job '" + rs.getString("unique_id") + "'");
                            }
                            fetchedJobs += 1;
                        }

                        pageNum += 1;
                        LOG.debug("Loaded " + fetchedJobs + "...");
                    } while(fetchedJobs != totalJobs);
                }

            }

        } catch (SQLException se) {
            LOG.debug(se.toString());
        } finally {
            try {
                if(rs != null)
                    rs.close();

                if(st != null)
                    st.close();

                if(conn != null)
                    conn.close();

            } catch (SQLException innerEx) {
                LOG.debug("Error cleaning up: " + innerEx);
            }
        }

        return jobs;
    }

    @Override
    public Collection<QueuedJob> getAllForFunction(final String functionName) {
        LinkedList<QueuedJob> jobs = new LinkedList<>();
        PreparedStatement st = null;
        ResultSet rs = null;
        Connection conn = null;
        QueuedJob job;

        try {
            conn = connectionPool.getConnection();
            if(conn != null)
            {
                st = conn.prepareStatement(findAllJobsForFunctionQuery);
                st.setString(1, functionName);
                ObjectMapper mapper = new ObjectMapper();
                rs = st.executeQuery();

                while(rs.next())
                {
                    job = new QueuedJob(rs.getString("unique_id"), rs.getLong("time_to_run"), JobPriority.valueOf(rs.getString("priority")), functionName);
                    jobs.add(job);
                }
            }
        } catch (SQLException se) {
            LOG.debug(se.toString());
        } finally {
            try {
                if(rs != null)
                    rs.close();

                if(st != null)
                    st.close();

                if(conn != null)
                    conn.close();

            } catch (SQLException innerEx) {
                LOG.debug("Error cleaning up: " + innerEx);
            }
        }

        return jobs;
    }

    public Job findJobByHandle(String jobHandle) {
        PreparedStatement st = null;
        ResultSet rs = null;
        Connection conn = null;

        Job job = null;

        try {
            conn = connectionPool.getConnection();
            if(conn != null)
            {
                st = conn.prepareStatement(findJobByHandleQuery);
                st.setString(1, jobHandle);

                ObjectMapper mapper = new ObjectMapper();
                rs = st.executeQuery();

                if(rs.next())
                {
                    String jobJSON = rs.getString("json_data");
                    job = mapper.readValue(jobJSON, Job.class);
                } else {
                    LOG.warn("No job for job handle: " + jobHandle +
                             " -- this could be an internal consistency problem...");
                }
            }
        } catch (SQLException se) {
            LOG.debug(se.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(rs != null)
                    rs.close();

                if(st != null)
                    st.close();

                if(conn != null)
                    conn.close();

            } catch (SQLException innerEx) {
                LOG.debug("Error cleaning up: " + innerEx);
            }
        }

        return job;    }

    private boolean validateOrCreateTable()
    {
        PreparedStatement st = null;
        ResultSet rs = null;
        Connection conn = null;
        ObjectMapper mapper = new ObjectMapper();
        boolean success = false;

        try {
            conn = connectionPool.getConnection();
            if(conn != null)
            {
                DatabaseMetaData dbm = conn.getMetaData();
                ResultSet tables = dbm.getTables(null, null, tableName, null);
                if(!tables.next())
                {
                    final String createQuery = String.format("CREATE TABLE %s(id bigserial, unique_id varchar(255), priority varchar(50), function_name varchar(255), time_to_run bigint, job_handle text, json_data text)", tableName);
                    final String indexUidQuery = String.format("CREATE INDEX %s_unique_id ON %s(unique_id)", tableName, tableName);
                    final String indexJobHandleQuery = String.format("CREATE INDEX %s_job_handle ON %s(job_handle)", tableName, tableName);
                    st = conn.prepareStatement(createQuery);
                    st.executeUpdate();
                    st = conn.prepareStatement(indexUidQuery);
                    st.executeUpdate();
                    st = conn.prepareStatement(indexJobHandleQuery);
                    st.executeUpdate();

                    // Make sure it worked
                    ResultSet createdTables = dbm.getTables(null, null, tableName, null);
                    if(createdTables.next()) {
                        LOG.debug("Created jobs table '" + tableName + "'");
                        success = true;
                    } else {
                        LOG.debug("Unable to create jobs table '" + tableName + "'");
                        success = false;
                    }
                }  else {
                    LOG.debug("Jobs table '" + tableName + "' already exists.");
                    success = true;
                }
            }
        } catch (SQLException se) {
            se.printStackTrace();
        } finally {
            try {
                if(st != null)
                    st.close();

                if(conn != null)
                    conn.close();

            } catch (SQLException innerEx) {
                innerEx.printStackTrace();
            }
        }

        return success;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

using XenAdmin.Actions;
using XenAdmin.Controls;
using XenAdmin.Controls.DataGridViewEx;
using XenAdmin.Dialogs;
using XenAPI;

namespace XenAdmin.Wizards.HAWizard_Pages
{
    public partial class ChooseSR : XenTabPage
    {
        public ChooseSR()
        {
            InitializeComponent();
        }

        private Pool pool;
        public Pool Pool
        {
            set
            {
                this.pool = value;
            }
        }

        private SR selectedHeartbeatSR;
        public SR SelectedHeartbeatSR
        {
            get
            {
                return selectedHeartbeatSR;
            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <returns>Whether any SRs suitable for heartbeating were found.</returns>
        internal bool ScanForHeartbeatSRs()
        {
            System.Diagnostics.Trace.Assert(pool != null);

            // Start action and show progress with a dialog
            GetHeartbeatSRsAction action = new GetHeartbeatSRsAction(pool);
            using (var dialog = new ActionProgressDialog(action, ProgressBarStyle.Blocks))
            {
                dialog.ShowCancel = true;
                dialog.ShowDialog(this);
            }
            if (action.Cancelled || action.Cancelling || !action.IsCompleted)
                return false;

            if (!action.Succeeded || action.SRs.Count == 0)
            {
                dataGridViewExSRs.Enabled = false;
                return true;
            }

            dataGridViewExSRs.Enabled = true;

            List<SRWrapper> srs = action.SRs;
            srs.Sort((a, b) => a.enabled != b.enabled
                                   ? b.enabled.CompareTo(a.enabled)
                                   : a.sr.NameWithoutHost().CompareTo(b.sr.NameWithoutHost()));

            dataGridViewExSRs.Rows.Clear();

            foreach (SRWrapper srWrapper in srs)
            {
                var row = new StorageRow(srWrapper);
                dataGridViewExSRs.Rows.Add(row);
                row.Enabled = srWrapper.enabled;

                // coming forward to this page after having already been through it once
                if (selectedHeartbeatSR != null && srWrapper.sr.opaque_ref == selectedHeartbeatSR.opaque_ref)
                {

                    if (srWrapper.enabled)
                        row.Selected = true;
                    else
                    {
                        selectedHeartbeatSR = null;
                        OnPageUpdated();
                    }
                }
            }

            return true;
        }

        public override string Text { get { return Messages.HA_CHOOSESR_PAGE_TEXT; } }

        public override string PageTitle { get { return Messages.HA_CHOOSESR_PAGE_PAGETITLE; } }

        public override bool EnableNext()
        {
            return selectedHeartbeatSR != null;
        }

        private void dataGridViewExSRs_Paint(object sender, PaintEventArgs e)
        {
            if (!dataGridViewExSRs.Enabled)
            {
                TextRenderer.DrawText(e.Graphics, Messages.HA_NO_SHARED_SRS, dataGridViewExSRs.Font,
                                      dataGridViewExSRs.ClientRectangle, SystemColors.WindowText,
                                      TextFormatFlags.VerticalCenter | TextFormatFlags.HorizontalCenter | TextFormatFlags.LeftAndRightPadding | TextFormatFlags.WordBreak);
            }
        }

        private void dataGridViewExSRs_SelectionChanged(object sender, EventArgs e)
        {
            if (dataGridViewExSRs.SelectedRows.Count == 1)
            {
                SRWrapper srw = ((StorageRow)dataGridViewExSRs.SelectedRows[0]).SrWrapper;
                selectedHeartbeatSR = srw.enabled ? srw.sr : null;
            }
            else
                selectedHeartbeatSR = null;

            OnPageUpdated();
        }

        private class StorageRow : DataGridViewExRow
        {
            private DataGridViewImageCell cellImage;
            private DataGridViewTextBoxCell cellSr;
            private DataGridViewTextBoxCell cellDescription;
            private DataGridViewTextBoxCell cellComment;

            public SRWrapper SrWrapper { get; private set; }

            public StorageRow(SRWrapper srw)
            {
                SrWrapper = srw;

                cellImage = new DataGridViewImageCell(false)
                                {
                                    ValueType = typeof(Image),
                                    Value =  Images.GetImage16For(srw.sr)
                                };
                cellSr = new DataGridViewTextBoxCell {Value = srw.sr.NameWithoutHost()};
                cellDescription = new DataGridViewTextBoxCell {Value = srw.sr.Description()};
                cellComment = new DataGridViewTextBoxCell {Value = srw.ReasonUnsuitable};

                Cells.AddRange(new DataGridViewCell[] {cellImage, cellSr, cellDescription, cellComment});
            }
        }
    }
}


text:
#ifndef TENSORFLOW_LITE_KERNELS_INTERNAL_REFERENCE_LOGISTIC_H_
#define TENSORFLOW_LITE_KERNELS_INTERNAL_REFERENCE_LOGISTIC_H_

#include <cmath>

#include "fixedpoint/fixedpoint.h"
#include "tensorflow/lite/kernels/internal/common.h"
#include "tensorflow/lite/kernels/internal/cppmath.h"
#include "tensorflow/lite/kernels/internal/quantization_util.h"
#include "tensorflow/lite/kernels/internal/types.h"
#include "tensorflow/lite/kernels/op_macros.h"

namespace tflite {
namespace reference_ops {

inline void Logistic(const RuntimeShape& input_shape, const float* input_data,
                     const RuntimeShape& output_shape, float* output_data) {
  const float cutoff_upper = 16.619047164916992188f;
  const float cutoff_lower = -9.f;

  const int flat_size = MatchingFlatSize(input_shape, output_shape);

  // Rational for using approximation in reference kernel.
  // 0. This approximation gives enough precision for float.
  // 1. This works around an issue on an embedded chipset where exp() does not
  // return correctly as expected - exp(x) should return inf when overflown
  // not 1.701417   IEEE 754 defines representation for inf.
  // 2. This will speed up calculation and is matching the behavior in the
  // optimized kernels. (check the definition of scalar_logistic_op<float>)

  for (int i = 0; i < flat_size; i++) {
    float val = input_data[i];
    float result;
    if (val > cutoff_upper) {
      result = 1.0f;
    } else if (val < cutoff_lower) {
      result = std::exp(val);
    } else {
      result = 1.f / (1.f + std::exp(-val));
    }
    output_data[i] = result;
  }
}

// Convenience version that allows, for example, generated-code calls to be
// uniform between data types.
inline void Logistic(const LogisticParams&, const RuntimeShape& input_shape,
                     const float* input_data, const RuntimeShape& output_shape,
                     float* output_data) {
  // Drop params: not needed.
  Logistic(input_shape, input_data, output_shape, output_data);
}

inline void Logistic(const LogisticParams& params,
                     const RuntimeShape& input_shape, const int16* input_data,
                     const RuntimeShape& output_shape, int16* output_data) {
  const int flat_size = MatchingFlatSize(input_shape, output_shape);

  for (int i = 0; i < flat_size; i++) {
    // F0 uses 0 integer bits, range [-1, 1].
    // This is the return type of math functions such as tanh, logistic,
    // whose range is in [-1, 1].
    using F0 = gemmlowp::FixedPoint<std::int16_t, 0>;
    // F3 uses 3 integer bits, range [-8, 8], the input range expected here.
    using F3 = gemmlowp::FixedPoint<std::int16_t, 3>;

    const F3 input = F3::FromRaw(input_data[i]);
    F0 output = gemmlowp::logistic(input);
    output_data[i] = output.raw();
  }
}

// Quantized int8 logistic activation.  Cheats by dequantizing and requantizing
// around the floating point logistic method.  This implementation is slow on
// platforms without a floating point unit.

// TODO(b/141211002): Delete this int8 implementation once we can reuse the
// approach used in TFLite for int8 Logistic.
inline void Logistic(const RuntimeShape& input_shape, const int8_t* input_data,
                     float input_scale, int input_zero_point,
                     const RuntimeShape& output_shape, int8_t* output_data,
                     float output_scale, int output_zero_point) {
  const float cutoff_upper = 16.619047164916992188f;
  const float cutoff_lower = -9.f;

  const int flat_size = MatchingFlatSize(input_shape, output_shape);

  // Rational for using approximation in reference kernel.
  // 0. This approximation gives enough precision for float.
  // 1. This works around an issue on an embedded chipset where exp() does not
  // return correctly as expected - exp(x) should return inf when overflown
  // not 1.701417   IEEE 754 defines representation for inf.
  // 2. This will speed up calculation and is matching the behavior in the
  // optimized kernels. (check the definition of scalar_logistic_op<float>)

  for (int i = 0; i < flat_size; i++) {
    // Dequantize.
    float val =
        static_cast<float>((input_data[i] - input_zero_point) * input_scale);
    float result;
    if (val > cutoff_upper) {
      result = 1.0f;
    } else if (val < cutoff_lower) {
      result = std::exp(val);
    } else {
      result = 1.f / (1.f + std::exp(-val));
    }
    // Requantize
    int8_t output =
        static_cast<int8_t>(result / output_scale + output_zero_point);
    output_data[i] = output;
  }
}

}  // namespace reference_ops
}  // namespace tflite

#endif  // TENSORFLOW_LITE_KERNELS_INTERNAL_REFERENCE_LOGISTIC_H_


text:
package fr.haploid.webservices;

public class WebServicesResponseData {
    private String responseData;
    private int statusCode;
    private boolean success;

    public WebServicesResponseData(String responseData, int statusCode, boolean success) {
        super();
        this.responseData = responseData;
        this.statusCode = statusCode;
        this.success = success;

    }

    public void setResponseData(String responseData) {
        this.responseData = responseData;
    }

    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }

    public int getStatusCode() {

        return statusCode;
    }

    public String getResponseData() {

        return responseData;
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

}


text:
var Foo = function Foo() {
  "use strict";

  babelHelpers.classCallCheck(this, Foo);
  this.bar = "foo";
};


text:
import sys

from sumologic import SumoLogic

args = sys.argv
sumo = SumoLogic(args[1], args[2])
oldWindow = args[3]
newWindow = args[4]

ds = sumo.dashboards()


text:
Rolls Royce is a minimal and responsive [Ghost](http://ghost.org) theme focusing on your content. With smooth and slick javascripts transitions, the experience is elegant and simple - just like the Ghost blogging platform. [See](http://roycehaynes.com) for yourself.

Expect updates - this theme is maturing along with Ghost. Feel free to [add suggested features](https://github.com/roycehaynes/rollsroyce/issues?state=open).

## How to install

1. Navigate to your Ghost theme directory ghost/content/themes

2. Clone theme repo using below command ```git clone https://github.com/roycehaynes/rollsroyce "rollsroyce"```

3. Restart ghost and log into your dashboard

4. On settings page, select rollsroyce as theme and save.

5. To make custom changes, go to ```default.hbs``` and search for 'TODOs' to add things like twitter handle, google analytics ID, etc. This is a temporary fix to a problem in Ghost v0.4.

*Note:* Ping me (royce dot haynes at gmail dot.com) if you have any issues.

## Releases

See the [changelog](CHANGELOG.md) for release details.

| Version | Release Date |
| :-----: | :----------: |
| 0.2 | 2014-01-19 |
| 0.1.1 | 2014-01-05 |
| 0.1 | 2014-01-05 |

## Contributing and Forking

*RollsRoyce* is open source and released under the MIT License, and contributions to the code base are welcome and encouraged. Find [more information about contributing here](CONTRIBUTING.md).

## Thanks

Thanks to [@JohnONolan](http://twitter.com/JohnONolan), [@ErisDS](http://twitter.com/ErisDS), and the Ghost team for creating this blog platform.

Special shout out to [Dave Gamache](http://blog.davegamache.com/articles), the original designer.

## Copyright & License

Copyright (c) 2014 Royce Haynes - Released under The MIT License.