text:
package com.hits.modules.cgtable.bean;

/**
 *
 *  #(c) IFlytek cform

 *
 *  版本说明: $id:$

 *
 *  功能说明: 列 实体类
 *
 *
创建说明: 2016年2月1日 下午3:43:53 (☆笑死宝宝了☆)  创建文件

 *
 *  修改历史:

 *
 */
public class FormField {

	private  String fieldName; //字段名

	private  String fieldType; //字段类型

	private  int fieldSize; //字段长度

	private  int isPrimary; //是否是主键  0-否 ; 1-是

	private  int isRequired; //是否为空  0-否 ; 1-是

	private  String foreignkey; //外键字段

	private  String foreigntable; //外键表名

	public String getFieldName() {
		return fieldName;
	}

	public void setFieldName(String fieldName) {
		this.fieldName = fieldName;
	}

	public String getFieldType() {
		return fieldType;
	}

	public void setFieldType(String fieldType) {
		this.fieldType = fieldType;
	}

	public int getFieldSize() {
		return fieldSize;
	}

	public void setFieldSize(int fieldSize) {
		this.fieldSize = fieldSize;
	}

	public int getIsPrimary() {
		return isPrimary;
	}

	public void setIsPrimary(int isPrimary) {
		this.isPrimary = isPrimary;
	}

	public int getIsRequired() {
		return isRequired;
	}

	public void setIsRequired(int isRequired) {
		this.isRequired = isRequired;
	}

	public String getForeignkey() {
		return foreignkey;
	}

	public void setForeignkey(String foreignkey) {
		this.foreignkey = foreignkey;
	}

	public String getForeigntable() {
		return foreigntable;
	}

	public void setForeigntable(String foreigntable) {
		this.foreigntable = foreigntable;
	}

}


text:
package io.fluxcapacitor.common.api.search.bulkupdate;

import com.fasterxml.jackson.annotation.JsonTypeInfo;
import io.fluxcapacitor.common.api.search.BulkUpdate;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.NonNull;
import lombok.Value;

import java.time.Instant;

import static io.fluxcapacitor.common.api.search.BulkUpdate.Type.index;

@Value
@AllArgsConstructor
@Builder(toBuilder = true)
public class IndexDocument implements BulkUpdate {
    @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
    @NonNull Object object;
    String id;
    String collection;
    Instant timestamp;
    Instant end;

    @Override
    public BulkUpdate.Type getType() {
        return index;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.goodworkalan.go.go.commands;

import com.goodworkalan.go.go.Argument;
import com.goodworkalan.go.go.Command;
import com.goodworkalan.go.go.Commandable;
import com.goodworkalan.go.go.Environment;

/**
 * Test output messages.
 *
 * @author Alan Gutierrez
 */
@Command(parent = Snap.class)
public class PrattleCommand implements Commandable {
    /** The debugging message code. */
    @Argument
    public String code;

    /**
     * Send some blather to stderr.
     *
     * @param env
     *            The environment.
     */
    public void execute(Environment env) {
        env.debug(code, "World");
    }
}


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title>JimOrr.info - References</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width">

<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css" rel="stylesheet">
<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css" rel="stylesheet">
<link href="//netdna.bootstrapcdn.com/bootswatch/3.0.1/spacelab/bootstrap.min.css" rel="stylesheet">

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

JimOrr.info

Contact

References

Links

References are available on request, to help keep my reference's contact info just a bit more private.

Will soon provide them here, protected by a password that I can provide you on request.

To be completed 11/25, contact me for more immediate needs.

 Skill Tags

                      PHP
                      HTML
                      CSS
                      JQuery
                      MySQL
                      PostgreSQL
                      REST
                      API
                      OOP
                      GIT
                      CVS
                      Bootstrap
                      Backbone
                      LAMP
                      Node
                      OSX
                      CLI
                      Vi/Vim
                      PSD
                      AI
                      MS Office

 Commute Range

			        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">Close ×</button>

Maximum desired commute range

Contact

jim@jimorr.info

909.851.2915

Baldwin Park, CA


text:
require 'rails_helper'

describe UsersController do

    describe 'GET #show' do
      it 'assigns the requested user to @user' do
        user = FactoryGirl.create(:user)
        get :show, id: user
        expect(assigns(:user)).to eq user
      end

      it 'renders the :show template' do
        user = FactoryGirl.create(:user)
        get :show, id: user
        expect(response).to render_template :show
      end
    end

    describe 'GET #new' do
      it 'assigns the new User to @user' do
        get :new
        expect(assigns(:user)).to be_a_new(User)
      end

      it 'renders the :new template' do
        get :new
        expect(response).to render_template :new
      end
    end

end


text:
cd ~/tomcat/bin
./shutdown.sh


text:
package org.apache.gobblin.cluster;

class SingleTaskRunnerMainArgumentsDataProvider {
  static final String TEST_JOB_ID = "1";
  static final String TEST_WORKUNIT = "/_workunits/store/workunit.wu";
  static final String TEST_CLUSTER_CONF = "/cluster.conf";

  static String[] getArgs() {
    return new String[]{"--job_id", TEST_JOB_ID, "--work_unit_file_path", TEST_WORKUNIT,
        "--cluster_config_file_path", TEST_CLUSTER_CONF};
  }
}


text: goog.require('ol.format.WMSGetFeatureInfo');


text:
package db

import (
	"fmt"

	_ "github.com/go-sql-driver/mysql" //dbrで使用する
	"github.com/gocraft/dbr"

	"github.com/mryp/squidgirl-go/config"
)

//ConnectDB DB接続
func ConnectDB() (*dbr.Session, error) {
	dbConfig := config.GetConfig().DB
	db, err := dbr.Open("mysql", dbConfig.UserID+":"+dbConfig.Password+"@tcp("+dbConfig.HostName+":"+dbConfig.PortNumber+")/"+dbConfig.Name+"?parseTime=true", nil)
	if err != nil {
		fmt.Printf("connectDB err=%v\n", err)
		return nil, err
	}

	dbsession := db.NewSession(nil)
	return dbsession, nil
}

func ConnectDBRecheck(session *dbr.Session) (*dbr.Session, error) {
	if session == nil {
		newSession, err := ConnectDB()
		if err != nil {
			return nil, err
		}
		session = newSession
	}

	return session, nil
}


text:
// coding: utf-8

// ----------------------------------------------------------------------------

#ifndef XPCC_GUI_BUTTON_HPP
#define XPCC_GUI_BUTTON_HPP

#include <xpcc/ui/display/font.hpp>
#include "widget.hpp"

namespace xpcc
{

namespace gui
{

/**
 * @ingroup	gui
 * @author	Daniel Krebs
 */
class ButtonWidget : public Widget
{
public:
	ButtonWidget(const char* lbl, Dimension d) :
		Widget(d, true),
		label(lbl)
	{
	}

	void
	render(View* view);

	void
	setLabel(char* lbl)
	{
		this->label = lbl;
	}

private:
	const char *label;
};

/**
 * @ingroup	gui
 * @author	Daniel Krebs
 */
class ArrowButton : public Widget
{
public:
	ArrowButton(bool orientation, Dimension d) :
		Widget(d, true),
		orientation(orientation)
	{
	}

	void
	render(View* view);

private:
	// Orientation of the arrow. false: left | true: right
	bool orientation;
};

/**
 * @ingroup	gui
 * @author	Daniel Krebs
 */
class FilledAreaButton : public Widget
{
public:
	FilledAreaButton(xpcc::glcd::Color color, Dimension d) :
		Widget(d, true),
		color(color)
	{
	}

	void
	setBackgroundColor(xpcc::glcd::Color color)
	{
		this->color = color;
	}

	void
	render(View* view);

private:
	xpcc::glcd::Color color;
};

}	// namespace gui

}	// namespace xpcc

#endif  // XPCC_GUI_BUTTON_HPP


text:
package ru.job4j.control.controllers;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class MainViewController extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/WEB-INF/views/index.jsp").forward(req, resp);
    }
}


text:
package voldemort.client;

import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;

import org.apache.log4j.Logger;

import voldemort.VoldemortException;
import voldemort.cluster.Node;
import voldemort.versioning.ObsoleteVersionException;
import voldemort.versioning.Version;
import voldemort.versioning.Versioned;

/**
 * A {@link StoreClient} with lazy initialization. This is useful existing codes
 * that initializes clients at service deployment time, when the servers may or
 * may not be available
 *
 */
public class LazyStoreClient<K, V> implements StoreClient<K, V> {

    private final Logger logger = Logger.getLogger(LazyStoreClient.class);
    private final Callable<StoreClient<K, V>> storeClientThunk;
    private StoreClient<K, V> storeClient;

    public LazyStoreClient(Callable<StoreClient<K, V>> storeClientThunk) {
        this(storeClientThunk, false);
    }

    /**
     * A Hybrid store client which tries to do immediate bootstrap. In case of
     * an exception, we fallback to the lazy way of doing initialization.
     *
     * @param storeClientThunk The callback invoked for doing the actual
     *        bootstrap
     * @param instantInit A boolean flag when set indicates that we should try
     *        to immediately bootstrap
     */
    public LazyStoreClient(Callable<StoreClient<K, V>> storeClientThunk, boolean wrapsRESTClient) {
        this.storeClientThunk = storeClientThunk;

        try {
            storeClient = initStoreClient();
        } catch(Exception e) {
            storeClient = null;
            logger.info(e.getMessage());
            if(wrapsRESTClient) {
                logger.info("D2 client might not have been completely initialized. Trying on the next call ...");
            } else {
                logger.info("Could not bootstrap right away. Trying on the next call ... ");
            }
        }
    }

    public synchronized StoreClient<K, V> getStoreClient() {
        if(storeClient == null)
            storeClient = initStoreClient();

        return storeClient;
    }

    protected StoreClient<K, V> initStoreClient() {
        try {
            return storeClientThunk.call();
        } catch(VoldemortException ve) {
            throw ve;
        } catch(Exception e) {
            // Callable's type signature includes checked exceptions
            throw new VoldemortException("Unexpected exception during initialization", e);
        }
    }

    public V getValue(K key) {
        return getStoreClient().getValue(key);
    }

    public V getValue(K key, V defaultValue) {
        return getStoreClient().getValue(key, defaultValue);
    }

    public Versioned<V> get(K key) {
        return getStoreClient().get(key);
    }

    public Versioned<V> get(K key, Object transforms) {
        return getStoreClient().get(key, transforms);
    }

    public Map<K, Versioned<V>> getAll(Iterable<K> keys) {
        return getStoreClient().getAll(keys);
    }

    public Map<K, Versioned<V>> getAll(Iterable<K> keys, Map<K, Object> transforms) {
        return getStoreClient().getAll(keys, transforms);
    }

    public Versioned<V> get(K key, Versioned<V> defaultValue) {
        return getStoreClient().get(key, defaultValue);
    }

    public Version put(K key, V value) {
        return getStoreClient().put(key, value);
    }

    public Version put(K key, V value, Object transforms) {
        return getStoreClient().put(key, value, transforms);
    }

    public Version put(K key, Versioned<V> versioned) throws ObsoleteVersionException {
        return getStoreClient().put(key, versioned);
    }

    public boolean putIfNotObsolete(K key, Versioned<V> versioned) {
        return getStoreClient().putIfNotObsolete(key, versioned);
    }

    public boolean applyUpdate(UpdateAction<K, V> action) {
        return getStoreClient().applyUpdate(action);
    }

    public boolean applyUpdate(UpdateAction<K, V> action, int maxTries) {
        return getStoreClient().applyUpdate(action, maxTries);
    }

    public boolean delete(K key) {
        return getStoreClient().delete(key);
    }

    public boolean delete(K key, Version version) {
        return getStoreClient().delete(key, version);
    }

    public List<Node> getResponsibleNodes(K key) {
        return getStoreClient().getResponsibleNodes(key);
    }
}


text:
#include "time/timestamp.h"

#include "math/math.h"

#if defined(__APPLE__)
#include <mach/mach.h>
#include <mach/mach_time.h>
#include <sys/time.h>
#include <math.h>
#include <time.h>
#elif defined(unix) || defined(__unix) || defined(__unix__)
#include <time.h>
#elif defined(_WIN32) || defined(_WIN64)
#include <windows.h>
#endif

namespace CppCommon {

//! @cond INTERNALS
namespace Internals {

#if defined(__APPLE__)

uint32_t CeilLog2(uint32_t x)
{
    uint32_t result = 0;

    --x;
    while (x > 0)
    {
        ++result;
        x >>= 1;
    }

    return result;
}

// This function returns the rational number inside the given interval with
// the smallest denominator (and smallest numerator breaks ties; correctness
// proof neglects floating-point errors).
mach_timebase_info_data_t BestFrac(double a, double b)
{
    if (floor(a) < floor(b))
    {
        mach_timebase_info_data_t rv = { (uint32_t)ceil(a), 1 };
        return rv;
    }

    double m = floor(a);
    mach_timebase_info_data_t next = BestFrac(1 / (b - m), 1 / (a - m));
    mach_timebase_info_data_t rv = { (int)m * next.numer + next.denom, next.numer };
    return rv;
}

// This is just less than the smallest thing we can multiply numer by without
// overflowing. CeilLog2(numer) = 64 - number of leading zeros of numer
uint64_t GetExpressibleSpan(uint32_t numer, uint32_t denom)
{
  uint64_t maxDiffWithoutOverflow = ((uint64_t)1 << (64 - CeilLog2(numer))) - 1;
  return maxDiffWithoutOverflow * numer / denom;
}

// The clock may run up to 0.1% faster or slower than the "exact" tick count.
// However, although the bound on the error is the same as for the pragmatic
// answer, the error is actually minimized over the given accuracy bound.
uint64_t PrepareTimebaseInfo(mach_timebase_info_data_t& tb)
{
    tb.numer = 0;
    tb.denom = 1;

    kern_return_t mtiStatus = mach_timebase_info(&tb);
    if (mtiStatus != KERN_SUCCESS)
        return 0;

    double frac = (double)tb.numer / tb.denom;
    uint64_t spanTarget = 315360000000000000llu;
    if (GetExpressibleSpan(tb.numer, tb.denom) >= spanTarget)
        return 0;

    for (double errorTarget = 1 / 1024.0; errorTarget > 0.000001;)
    {
        mach_timebase_info_data_t newFrac = BestFrac((1 - errorTarget) * frac, (1 + errorTarget) * frac);
        if (GetExpressibleSpan(newFrac.numer, newFrac.denom) < spanTarget)
            break;
        tb = newFrac;
        errorTarget = fabs((double)tb.numer / tb.denom - frac) / frac / 8;
    }

    return 0;
}

#endif

} // namespace Internals
//! @endcond

uint64_t Timestamp::utc()
{
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
    struct timespec timestamp;
    if (clock_gettime(CLOCK_REALTIME, &timestamp) != 0)
        throwex SystemException("Cannot get value of CLOCK_REALTIME timer!");
    return (timestamp.tv_sec * 1000000000) + timestamp.tv_nsec;
#elif defined(_WIN32) || defined(_WIN64)
    FILETIME ft;
    GetSystemTimePreciseAsFileTime(&ft);

    ULARGE_INTEGER result;
    result.LowPart = ft.dwLowDateTime;
    result.HighPart = ft.dwHighDateTime;
    return (result.QuadPart - 116444736000000000ull) * 100;
#endif
}

uint64_t Timestamp::local()
{
#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
    uint64_t timestamp = utc();

    // Adjust UTC time with local timezone offset
    struct tm local;
    time_t seconds = timestamp / (1000000000);
    if (localtime_r(&seconds, &local) != &local)
        throwex SystemException("Cannot convert CLOCK_REALTIME time to local date & time structure!");
    return timestamp + (local.tm_gmtoff * 1000000000);
#elif defined(_WIN32) || defined(_WIN64)
    FILETIME ft;
#if (_WIN32_WINNT >= _WIN32_WINNT_WIN8)
    GetSystemTimePreciseAsFileTime(&ft);
#else
    GetSystemTimeAsFileTime(&ft);
#endif

    FILETIME ft_local;
    if (!FileTimeToLocalFileTime(&ft, &ft_local))
        throwex SystemException("Cannot convert UTC file time to local file time structure!");

    ULARGE_INTEGER result;
    result.LowPart = ft_local.dwLowDateTime;
    result.HighPart = ft_local.dwHighDateTime;
    return (result.QuadPart - 116444736000000000ull) * 100;
#endif
}

uint64_t Timestamp::nano()
{
#if defined(__APPLE__)
    static mach_timebase_info_data_t info;
    static uint64_t bias = Internals::PrepareTimebaseInfo(info);
    return ((mach_absolute_time() - bias) * info.numer) / info.denom;
#elif defined(unix) || defined(__unix) || defined(__unix__)
    struct timespec timestamp = { 0 };
    if (clock_gettime(CLOCK_MONOTONIC, &timestamp) != 0)
        throwex SystemException("Cannot get value of CLOCK_MONOTONIC timer!");
    return (timestamp.tv_sec * 1000000000) + timestamp.tv_nsec;
#elif defined(_WIN32) || defined(_WIN64)
    static uint64_t offset = 0;
    static LARGE_INTEGER first = { 0 };
    static LARGE_INTEGER frequency = { 0 };
    static bool initialized = false;
    static bool qpc = true;

    if (!initialized)
    {
        // Calculate timestamp offset
        FILETIME timestamp;
        GetSystemTimePreciseAsFileTime(&timestamp);

        ULARGE_INTEGER result;
        result.LowPart = timestamp.dwLowDateTime;
        result.HighPart = timestamp.dwHighDateTime;

        // Convert 01.01.1601 to 01.01.1970
        result.QuadPart -= 116444736000000000ll;
        offset = result.QuadPart * 100;

        // Setup performance counter
        qpc = QueryPerformanceFrequency(&frequency) && QueryPerformanceCounter(&first);

        initialized = true;
    }

    if (qpc)
    {
        LARGE_INTEGER timestamp = { 0 };
        QueryPerformanceCounter(&timestamp);
        timestamp.QuadPart -= first.QuadPart;
        return offset + Math::MulDiv64(timestamp.QuadPart, 1000000000, frequency.QuadPart);
    }
    else
        return offset;
#else
    #error Unsupported platform
#endif
}

uint64_t Timestamp::rdts()
{
#if defined(__APPLE__)
    // This goes at the top because we need ALL Macs, regardless of
    // architecture, to return the number of "mach time units" that
    // have passed since startup.  See sysinfo.cc where
    // InitializeSystemInfo() sets the supposed cpu clock frequency of
    // macs to the number of mach time units per second, not actual
    // CPU clock frequency (which can change in the face of CPU
    // frequency scaling).  Also note that when the Mac sleeps, this
    // counter pauses; it does not continue counting, nor does it
    // reset to zero.
    return mach_absolute_time();
#elif defined(_MSC_VER)
    return __rdtsc();
#elif defined(__i386__)
    int64_t ret;
    __asm__ volatile("rdtsc" : "=A"(ret));
    return ret;
#elif defined(__x86_64__) || defined(__amd64__)
    uint64_t low, high;
    __asm__ volatile("rdtsc" : "=a"(low), "=d"(high));
    return (high << 32) | low;
#elif defined(__powerpc__) || defined(__ppc__)
    // This returns a time-base, which is not always precisely a cycle-count.
    int64_t tbl, tbu0, tbu1;
    asm("mftbu %0" : "=r"(tbu0));
    asm("mftb  %0" : "=r"(tbl));
    asm("mftbu %0" : "=r"(tbu1));
    tbl &= -static_cast<int64>(tbu0 == tbu1);
    // High 32 bits in tbu1;
    // How 32 bits in tbl (tbu0 is garbage)
    return (tbu1 << 32) | tbl;
#elif defined(__sparc__)
    int64_t tick;
    asm(".byte 0x83, 0x41, 0x00, 0x00");
    asm("mov   %%g1, %0" : "=r"(tick));
    return tick;
#elif defined(__ia64__)
    int64_t itc;
    asm("mov %0 = ar.itc" : "=r"(itc));
    return itc;
#elif defined(COMPILER_MSVC) && defined(_M_IX86)
    // Older MSVC compilers (like 7.x) don't seem to support the
    // __rdtsc intrinsic properly, so I prefer to use _asm instead
    // when I know it will work.  Otherwise, I'll use __rdtsc and hope
    // the code is being compiled with a non-ancient compiler.
    _asm rdtsc
#elif defined(__aarch64__)
    // System timer of ARMv8 runs at a different frequency than the CPU's.
    // The frequency is fixed, typically in the range 1-50MHz.  It can be
    // read at CNTFRQ special register.  We assume the OS has set up
    // the virtual timer properly.
    int64_t virtual_timer_value;
    asm volatile("mrs %0, cntvct_el0" : "=r"(virtual_timer_value));
    return virtual_timer_value;
#elif defined(__ARM_ARCH)

    // V6 is the earliest arch that has a standard cyclecount
    #if (__ARM_ARCH >= 6)
    uint32_t pmccntr;
    uint32_t pmuseren;
    uint32_t pmcntenset;
    // Read the user mode perf monitor counter access permissions.
    asm volatile("mrc p15, 0, %0, c9, c14, 0" : "=r"(pmuseren));
    if (pmuseren & 1)
    {
        // Allows reading perfmon counters for user mode code.
        asm volatile("mrc p15, 0, %0, c9, c12, 1" : "=r"(pmcntenset));
        if (pmcntenset & 0x80000000ul)
        {
            // Is it counting?
            asm volatile("mrc p15, 0, %0, c9, c13, 0" : "=r"(pmccntr));
            // The counter is set up to count every 64th cycle
            return static_cast<int64_t>(pmccntr) * 64;
        }
    }
    #endif

    struct timeval tv;
    gettimeofday(&tv, nullptr);
    return static_cast<int64_t>(tv.tv_sec) * 1000000 + tv.tv_usec;
#elif defined(__mips__)
    // mips apparently only allows rdtsc for superusers, so we fall back to gettimeofday.
    // It's possible clock_gettime would be better.
    struct timeval tv;
    gettimeofday(&tv, nullptr);
    return static_cast<int64_t>(tv.tv_sec) * 1000000 + tv.tv_usec;
#else
    #error Unsupported platform
#endif
}

} // namespace CppCommon


text:
'use strict';
var tiles = require('../tile');
var cache = require('../cache');
var osw = module.exports = require('express')();

osw.get('/:map/:z/:x/:y.png', function(req, res){
  cache(req.path,360,function(){
    return tiles.get(req.params.map,req.params.z,req.params.x,req.params.y);
  }).then(function(buffer){
    res.type('png');
    res.send(new Buffer(buffer));
  },function(){
    res.send(404);
  });
});
osw.get('/:map/:z/:x/:y.(grid.)?json', function(req, res){
  cache(req.path,360,function(){
    return tiles.grid(req.params.map,req.params.z,req.params.x,req.params.y);
  }).then(function(resp){
    res.jsonp(resp);
  },function(e){
    res.send(404,e);
  });
});
osw.get('/:map.json', function(req, res){
  cache(req.path,360,function(){
    return tiles.info(req.params.map);
  }).then(function(resp){
    res.jsonp(resp);
  },function(reason){
    console.log(reason);
    res.send(500,reason);
  });
});


text:
namespace Lucia {
namespace Maigui {
    class Container : public Maigui::Item
    {
        public:
            Container(){};
            virtual void generate(Vertex position,Vertex dimensions,shared_ptr<Skin> sk);
            virtual void minimize();
            virtual void maximize();
            virtual void close();

        protected:
            Vertex maximumSize = Vertex(100,100,100);
            Vertex minimumSize = Vertex(10,10,10);
    };
} // namespace Maigui
}
#endif // MAIGUI_CONTAINER_H


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Web.Caching;
using System.Web.Http;
using System.Web.Http.Cors;
using Api.Extensions;
using Api.Objects;
using Newtonsoft.Json.Linq;

namespace Api.Controllers
{
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    [RoutePrefix("public")]
    public class PublicController : ApiController
    {
        [Route("WhatIsMyIp")]
        public HttpResponseMessage GetIps()
        {
            Console.WriteLine("WhatIsMyIp called");
            var output = Request.GetClientIpAddress();

            PublicObjects.KV kvobject = new PublicObjects.KV
            {
                Key = "IP",
                Value = output
            };

            JObject ob = (JObject)JToken.FromObject(kvobject);

            return Request.CreateResponse(HttpStatusCode.OK, ob);
        }

        [Route("WhereIsHortlak")]
        public HttpResponseMessage GetHostName()
        {
            Console.WriteLine("WhereIsHortlak called");

            PublicObjects.KV kvobject = new PublicObjects.KV
            {
                Key = "Host",
                Value = Environment.MachineName
            };

            JObject ob = (JObject) JToken.FromObject(kvobject);

            //JArray array = new JArray {ob};

            //JObject o = new JObject();
            //o["hosts"] = array;

            return Request.CreateResponse<JObject>(HttpStatusCode.OK, ob);
        }
    }
}


text:
#ifndef _FIFO_BUFFER_H_
#define _FIFO_BUFFER_H_

#include "stm32f10x.h"

/**
  *@breif A FIFO queue Template for FIFO application
  *
  *
  */
template<typename T, u16 MAX_SIZE>
class FIFOBuffer
{
private:
	T mData[MAX_SIZE];  //数据储存
	u16 mFront;         //头指针
	u16 mRear;          //尾指针
	//注意,没有使用长度这个变量,是为了防止有中断打断时快速反应(用mfront和mrear计算)
	//在put和get函数中体会,所以函数都是先操作头指针和为指针,再进行存数
public:

	/////////////////////////
	///@breif constructor
	/////////////////////////
	FIFOBuffer();

	/////////////////////////
	///@breif put node data to queue
	///@param data the node data will put into queue
	////////////////////////
	bool Put(const T &data);

	////////////////////////
	///@breif get one node data from queue,the length of queue will decrease one
	///@param data the destination of node data from queue
	////////////////////////
	bool Get(T &data);

	//////////////////////////////
	///@breif put multiple node data to queue
	///@param pdata the first node data adress of node data array will put into queue
	///@param num the length of node data that will put into queue
	/////////////////////////////
	bool Puts(T *pData, u16 num);

	//////////////////////////////
	///@breif get multiple node data from queue
	///@param pdata the first node data adress of node data array will get from the queue
	///@param num the length of node data that will get from the queue
	/////////////////////////////
	bool Gets(T *pData, u16 num);

	/**
	 * query first data from the queue, and the data remain be a part of the queue
	 * @param data the reference of the data that will be query
	 * @retval Is query succeed
	 */
	bool Query(T &data);

	/**
	 * query some data from the queue, and the data remain be a part of the queue
	 * @param data the address of the data save to
	 * @param startPosition Index of where to start query
	 * #param num The number of data will be query
	 * @retval Is query succeed
	 */
	bool QueryMul(T *data,u16 startPosition,u16 num);

	////////////////////////////
	///@breif get the size of queue
	///@retval the size of queue
	///////////////////////////
	u16 Size();

	////////////////////////////////
	///@breif clear the queue
	////////////////////////////////
	void Clear();
};

/**
 * Constructor,Initialize the queue
 */
template<typename T, u16 MAX_SIZE>
FIFOBuffer<T,MAX_SIZE>::FIFOBuffer()
:mFront(0),mRear(0)
{
//	for(u16 i=0;i<MAX_SIZE;++i)
//		mData[i]=0;
}

/**
 * input one node to buffer
 */
template<typename T, u16 MAX_SIZE>
bool FIFOBuffer<T,MAX_SIZE>::Put(const T &data)
{
	if((mRear+1)%MAX_SIZE == mFront)//队满
		return false;
	else
	{
		mRear = (mRear+1)%MAX_SIZE;
		mData[mRear] = data;
	}
	return true;
}

/**
 * input multi nodes to buffer
 */
template<typename T, u16 MAX_SIZE>
bool FIFOBuffer<T,MAX_SIZE>::Puts(T *pData, u16 num)
{
	if((mRear+num)%MAX_SIZE == mFront)//队满
		return false;
	for(u16 i=0;i<num;++i)
	{
		mRear = (mRear+1)%MAX_SIZE;
		mData[mRear] = pData[i];
	}
	return true;
}

/**
 * get one node from buffer
 */
template<typename T, u16 MAX_SIZE>
bool FIFOBuffer<T,MAX_SIZE>::Get(T &data)
{
	if(mFront == mRear)
		return false;
	mFront = (mFront+1)%MAX_SIZE;
	data = mData[mFront];
	return true;
}

/**
 * get multi nodes from buffer
 */
template<typename T, u16 MAX_SIZE>
bool FIFOBuffer<T,MAX_SIZE>::Gets(T *pData, u16 num)
{
	if(Size()<num)
		return false;

	for(u16 i=0;i<num;++i)
	{
		mFront = (mFront+1)%MAX_SIZE;
		pData[i] = mData[mFront];
	}
	return true;
}

/**
 * Get the number of nodes in buffer (_size)
 */
template<typename T, u16 MAX_SIZE>
u16 FIFOBuffer<T,MAX_SIZE>::Size()
{
	return (mRear - mFront)%MAX_SIZE;
}

/**
 *clear all nodes in buffer
 */
template<typename T, u16 MAX_SIZE>
void FIFOBuffer<T,MAX_SIZE>::Clear()
{
	mFront = 0;
	mRear = 0;
//	for(u16 i=0;i<MAX_SIZE;++i)
//		mData[i]=0;
}
#endif


text:
from multiprocessing import Process, cpu_count, JoinableQueue
from itertools import islice
from operator import truediv
import logging
import sys

log = logging.getLogger("leprechaun.multicore")

def cpuCount():
  """Retrieve the number of available cores on this system.

  Returns:
    - Number of available cores
  """

  result = 1
  try:
    result = cpu_count()
  except NotImplementedError:
    try:
      import psutil
      result = psutil.NUM_CPUS
    except:
      log.error("Cannot get number of cores, default to 1")

  return result

def file_len(fname):
  """Count the number of lines in file

  Parameters:
    - fname: file to read number of lines from

  Returns:
    - Number of lines in file
  """
  with open(fname,encoding="utf-8") as f:
    for i, l in enumerate(f):
      pass

  # Last line is not counted, so add it
  result = i + 1

  log.debug("%s, has %d lines",fname,result)
  return result

def start_multicore(wordlists,hashing_algorithm,output,use_database):
  """Start the multicore process.

  This devides words that needs to be hashed between cores

  Parameters:
    - wordlist: list containing words that need to be hashed
    - hashing_algorithm: which hashing algorithm should be used
    - output: format of the output file
    - use_database: if results should be stored in a database
  """

  global core_list
  chunk_size = 25000
  core_list = list()

  # Save 1 core for writing
  num_cores = cpuCount()
  num_hash_cores = num_cores -1

  result_queue = JoinableQueue()
  work_queue = JoinableQueue(num_hash_cores)

  # Start hash cores
  for core in range(num_hash_cores):

    cur_core = Process(target=hash_core_run,args=(core,result_queue,work_queue,hashing_algorithm))
    cur_core.start()
    core_list.append(cur_core)

  # Start output core
  out_core = Process(target=output_core_run,args=(result_queue,output,use_database))
  out_core.start()

  result_lines = []
  for wordlist in wordlists:
    with open(wordlist,encoding="utf-8") as fwordlist:

      for index,line in enumerate(fwordlist):
        result_lines.append(line)

        # Divides number of lines between hashcores
        if (index % chunk_size) == 0:
          work_queue.put(result_lines)
          result_lines = []

  if len(result_lines) > 0:
    work_queue.put(result_lines)

  # Send stop signal to hash cores
  for i in range(num_hash_cores):
    work_queue.put(None)

  # Wait for hashing cores to finish
  for hash_core in core_list:
    hash_core.join()

  # Send stop signal to output core to finish
  # and then wait for it
  result_queue.put(None)
  out_core.join()

  # Close Joinable queues
  work_queue.close()
  result_queue.close()

def output_core_run(result_queue,output,use_database):
  """Output process

  This process receives all generated hash values and writes it to the
  appropiate output stream

  Parameters:
    - result_queue: queue containing the hash results
    - output: the output file format
    - use_database: if results should be stored in a database
  """

  from .rainbow import _hash_wordlist, create_rainbow_table, close_output_stream,write_output,create_output_stream

  core_log = logging.getLogger("leprechaun.core.output")
  core_log.debug("Output-core started")

  # Open output stream
  output_stream = create_output_stream(output, use_database)

  while True:
    result_list = result_queue.get()

    # If result_list is None than al words are hashed so close the output stream
    if result_list is None:
      result_queue.task_done()
      break

    # store everything from the result list
    for result in result_list:
      write_output(output_stream,result,use_database)

    result_queue.task_done()

  close_output_stream(output_stream,use_database)
  core_log.debug("Output core exited")

def hash_core_run(core,result_queue,work_queue,hashing_algorithm):
  """Hash process

  This hash process will receive words from the work_queue and calculates
  them into hashes.

  Parameters:
    - core: identification of the process
    - result_queue: this queue will contain all the generated results that needs to be written
    - work_queue: containing words which needs to be hashed
    - hashing_algorithm: the hashing algorithm that should be used
  """

  from .rainbow import _hash_wordlist, create_rainbow_table, close_output_stream,write_output

  core_log = logging.getLogger("leprechaun.core.hash")
  core_log.debug("Hash-Core[%d] started",core)

  while True:
    work_list = work_queue.get()
    result_list = list()

    # if work_list is None that means input is empty, so finish
    if work_list is None:
      work_queue.task_done()
      break

    # hash the wordlist and store it in result queue
    for result in _hash_wordlist(work_list,hashing_algorithm):
        result_list.append(result)

    result_queue.put(result_list)
    work_queue.task_done()

  core_log.debug("Hash-Core[%d] exited",core)


text:
#import <UIKit/UIKit.h>
#import <MUKUserNotificationViewController/MUKUserNotification.h>
#import <MUKUserNotificationViewController/MUKUserNotificationView.h>

extern NSTimeInterval const MUKUserNotificationViewControllerDefaultMinimumIntervalBetweenNotifications;

typedef NS_ENUM(NSInteger, MUKUserNotificationViewPresentation) {
    MUKUserNotificationViewPresentationReplaceStatusBar = 0,
    MUKUserNotificationViewPresentationBehindStatusBar
};

/**
 View controller which displays an user notifications on top.
 Usually, especially on phones, you would use it as root view controller.
 */
@interface MUKUserNotificationViewController : UIViewController
/**
 Contained view controller.
 This view controller is about actual content you want to display to user.
 You can assign it in order to perform view controller containment inside
 -willWillAppear:. If you use storyboards this ivar will be automatically
 filled at -viewDidLoad.
 */
@property (nonatomic, strong) UIViewController *contentViewController;
/**
 How notifications are presented to user.
 It defaults to `MUKUserNotificationViewPresentationReplaceStatusBar`, which means
 status bar is hidden before to show notification views.
 Otherwise you could set `MUKUserNotificationViewPresentationBehindStatusBar` mode,
 which means status bar is never hidden and notification views slide under it.
 */
@property (nonatomic) MUKUserNotificationViewPresentation notificationViewsPresentation;
/**
 The amount of time which has to pass between a notification presentation and
 another.
 It defaults to `MUKUserNotificationViewControllerDefaultMinimumIntervalBetweenNotifications`.
 */
@property (nonatomic) NSTimeInterval minimumIntervalBetweenNotifications;
/**
 Notification views tend to adapt to contained navigation bar height.
 Default is YES. If YES and if notification view height is not too far from
 navigation bar one, the notification view's frame is slightly increased in order
 to fill navigation bar space.
 */
@property (nonatomic) BOOL notificationViewsSnapToNavigationBar;
/**
 Notifications which are displayed or pending (due rate limit).
 Keep in mind that not all notifications are currently displayed.
 */
@property (nonatomic, readonly) NSArray *notifications;
/**
 The latest notification which has been displayed.
 */
@property (nonatomic, readonly) MUKUserNotification *visibleNotification;
/**
 Display a notification.
 @param notification Notification which will be added to notifications and displayed
 if minimumIntervalBetweenNotifications has passed.
 @param animated If YES, notification view will be presented with an animation.
 @param completionHandler A block which will be invoked as transition finishes.
 */
- (void)showNotification:(MUKUserNotification *)notification animated:(BOOL)animated completion:(void (^)(BOOL completed))completionHandler;
/**
 Hide a notification.
 @param notification Notification which will be removed from notifications and
 hidden. You could also hide a notification which has not been presented yet (due
 rate limit).
 @param animated If YES, notification view will be hidden with an animation.
 @param completionHandler A block which will be invoked as transition finishes.
 */
- (void)hideNotification:(MUKUserNotification *)notification animated:(BOOL)animated completion:(void (^)(BOOL completed))completionHandler;
@end

@interface MUKUserNotificationViewController (Expiration)
/**
 Callback invoked when an expired notification is about to be hidden.
 @param notification Notification which will be removed from notifications and
 hidden.
 */
- (void)notificationWillExpire:(MUKUserNotification *)notification;
/**
 Callback invoked when an expired notification has been hidden.
 @param notification Notification which has been removed from notifications and
 hidden.
 */
- (void)notificationDidExpire:(MUKUserNotification *)notification;
@end

@interface MUKUserNotificationViewController (NotificationView)
/**
 Search presented view for a notification.
 @param notification Notification to search for.
 @return The view which is displayed for a notification. It could return nil.
 */
- (MUKUserNotificationView *)viewForNotification:(MUKUserNotification *)notification;
/**
 Search notification for a presented view.
 @param view Notification view to search for.
 @return The notification for a displayed notification view. It could return nil.
 */
- (MUKUserNotification *)notificationForView:(MUKUserNotificationView *)view;
/**
 Creates new notification view.
 @param notification The notification which originates this view.
 @return A new notification view.
 */
- (MUKUserNotificationView *)newViewForNotification:(MUKUserNotification *)notification;
/**
 Configures a new notification view with notification details.
 @param view The view to configure.
 @param notification The notification which originates this view.
 */
- (void)configureView:(MUKUserNotificationView *)view forNotification:(MUKUserNotification *)notification;
/**
 Frame for notification view.
 @param view The notification view. It will be inkoved -sizeThatFits: on it.
 @param notification The notification model object.
 @param minimumSize The minimum size for resulting frame.
 @return The frame that will be set on view.
 */
- (CGRect)frameForView:(MUKUserNotificationView *)view notification:(MUKUserNotification *)notification minimumSize:(CGSize)minimumSize;
/**
 Callback for tap gesture.
 It no tap gesture handler is set inside notification, it automatically hides
 the view.
 @param view The view where gesture occured.
 @param notification The notification which view displays.
 */
- (void)didTapView:(MUKUserNotificationView *)view forNotification:(MUKUserNotification *)notification;
/**
 Callback for pan up gesture.
 It no pan up gesture handler is set inside notification, it automatically hides
 the view.
 @param view The view where gesture occured.
 @param notification The notification which view displays.
 */
- (void)didPanUpView:(MUKUserNotificationView *)view forNotification:(MUKUserNotification *)notification;
@end

@interface MUKUserNotificationViewController (NavigationControllers)
/**
 Navigation controllers contained inside contentViewController.
 Default implementation does its best to autodiscover nested navigation controllers,
 by checking tab bar controllers and split view controllers.
 @return An array of all navigation controllers affected by notification view
 presentation. Those view controllers will be used in order to find navigation
 bar height and to fix strange behaviors that occur after device rotation.
 */
- (NSArray *)affectedNavigationControllers;
@end


text:
package org.kairosdb.auth;

import com.google.inject.Inject;
import com.google.inject.name.Named;
import org.kairosdb.core.DataPointSet;
import org.kairosdb.core.datapoints.LongDataPointFactory;
import org.kairosdb.core.datapoints.LongDataPointFactoryImpl;
import org.kairosdb.core.reporting.KairosMetricReporter;
import org.kairosdb.util.SimpleStats;
import org.kairosdb.util.SimpleStatsReporter;
import org.kairosdb.util.StatsMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

public class PulseAuthenticationStats implements KairosMetricReporter {

    private static final Logger logger = LoggerFactory.getLogger(PulseAuthenticationStats.class);

    private static final String AUTH_TOTAL_REQUESTS = "kairosdb.auth.total_requests";
    private static final String AUTH_SUCCESS = "kairosdb.auth.success";
    private static final String AUTH_FAIL = "kairosdb.auth.fail";
    private static final String AUTH_NO_CREDENTIALS = "kairosdb.auth.no_credentials";

    private final AtomicInteger m_authentication_total_requests = new AtomicInteger();
    private final AtomicInteger m_authentication_success_LDAP = new AtomicInteger();
    private final AtomicInteger m_authentication_fail_LDAP = new AtomicInteger();
    private final AtomicInteger m_authentication_fail_locked = new AtomicInteger();
    private final AtomicInteger m_authentication_no_credentials = new AtomicInteger();

    public int addGetTotalAuthRequests(int additionalRequests) {
        return m_authentication_total_requests.addAndGet(additionalRequests);
    }

    public int addGetSuccessLdap(int additionalSuccesses) {
        return m_authentication_success_LDAP.addAndGet(additionalSuccesses);
    }

    public int addGetFailLdap(int additionalFailures) {
        return m_authentication_fail_LDAP.addAndGet(additionalFailures);
    }

    public int addGetFailLocked(int additionalLocked) {
        return m_authentication_fail_locked.addAndGet(additionalLocked);
    }

    public int addGetNoCredentials(int additionalNoCredentials) {
        return m_authentication_no_credentials.addAndGet(additionalNoCredentials);
    }

    private final StatsMap m_statsMap = new StatsMap();

    @Inject
    @Named("HOSTNAME")
    private String hostName = "localhost";

    @Inject
    private LongDataPointFactory m_longDataPointFactory = new LongDataPointFactoryImpl();

    @Inject
    private SimpleStatsReporter m_simpleStatsReporter = new SimpleStatsReporter();

    @Override
    public List<DataPointSet> getMetrics(long now) {

        List<DataPointSet> ret = new ArrayList<>();

        int total_requests = m_authentication_total_requests.getAndSet(0);
        int success_ldap = m_authentication_success_LDAP.getAndSet(0);
        int fail_ldap = m_authentication_fail_LDAP.getAndSet(0);
        int fail_locked = m_authentication_fail_locked.getAndSet(0);
        int no_credentials = m_authentication_no_credentials.getAndSet(0);

        getTotalRequestsMetric(ret, now, total_requests);
        getSuccessLdapMetric(ret, now, success_ldap);
        getSuccessCachedMetric(ret, now, total_requests, success_ldap, fail_ldap, fail_locked, no_credentials);
        getFailLdapMetric(ret, now, fail_ldap);
        getFailLockedMetric(ret, now, fail_locked);
        getNoCredentialsMetric(ret, now, no_credentials);

        Map<String, SimpleStats> statsMap = m_statsMap.getStatsMap();

        for (Map.Entry<String, SimpleStats> entry : statsMap.entrySet())
        {
            String metric = entry.getKey();
            SimpleStats.Data stats = entry.getValue().getAndClear();

            m_simpleStatsReporter.reportStats(stats, now, metric, ret);
        }

        return ret;
    }

    private void getTotalRequestsMetric(List<DataPointSet> ret, long now, int total_requests){
        if (total_requests != 0)
        {
            DataPointSet dpsRequests = new DataPointSet(AUTH_TOTAL_REQUESTS);
            dpsRequests.addTag("host", hostName);
            dpsRequests.addDataPoint(m_longDataPointFactory.createDataPoint(now, total_requests));
            ret.add(dpsRequests);
        }
    }

    private void getSuccessLdapMetric(List<DataPointSet> ret, long now, int success_ldap){
        if (success_ldap != 0)
        {
            DataPointSet dpsSuccessLDAP = new DataPointSet(AUTH_SUCCESS);
            dpsSuccessLDAP.addTag("host", hostName);
            dpsSuccessLDAP.addTag("cause", "ldap");
            dpsSuccessLDAP.addDataPoint(m_longDataPointFactory.createDataPoint(now, success_ldap));
            ret.add(dpsSuccessLDAP);
        }
    }

    private void getSuccessCachedMetric(List<DataPointSet> ret, long now, int total_requests, int success_ldap, int fail_ldap, int fail_locked, int no_credentials){
        int success_cached = total_requests - (success_ldap + fail_ldap + fail_locked + no_credentials);
        if(success_cached != 0)
        {
            DataPointSet dpsSuccessCached = new DataPointSet(AUTH_SUCCESS);
            dpsSuccessCached.addTag("host", hostName);
            dpsSuccessCached.addTag("cause", "cached");
            dpsSuccessCached.addDataPoint(m_longDataPointFactory.createDataPoint(now, success_cached));
            ret.add(dpsSuccessCached);
        }
    }

    private void getFailLdapMetric(List<DataPointSet> ret, long now, int fail_ldap) {
        if(fail_ldap != 0)
        {
            DataPointSet dpsFailLDAP = new DataPointSet(AUTH_FAIL);
            dpsFailLDAP.addTag("host", hostName);
            dpsFailLDAP.addTag("cause", "ldap");
            dpsFailLDAP.addDataPoint(m_longDataPointFactory.createDataPoint(now, fail_ldap));
            ret.add(dpsFailLDAP);
        }
    }

    private void getFailLockedMetric(List<DataPointSet> ret, long now, int fail_locked) {
        if(fail_locked != 0)
        {
            DataPointSet dpsFailLocked = new DataPointSet(AUTH_FAIL);
            dpsFailLocked.addTag("host", hostName);
            dpsFailLocked.addTag("cause", "locked");
            dpsFailLocked.addDataPoint(m_longDataPointFactory.createDataPoint(now, fail_locked));
            ret.add(dpsFailLocked);
        }
    }

    private void getNoCredentialsMetric(List<DataPointSet> ret, long now, int no_credentials) {
        if(no_credentials != 0)
        {
            DataPointSet dpsNoCredentials = new DataPointSet(AUTH_NO_CREDENTIALS);
            dpsNoCredentials.addTag("host", hostName);
            dpsNoCredentials.addDataPoint(m_longDataPointFactory.createDataPoint(now, no_credentials));
            ret.add(dpsNoCredentials);
        }
    }
}


text:
% Explicit examples on how to use the different classifiers

size_cache=10;
C=1;
use_bias=false;
epsilon=1e-5;
width=2.1;

addpath('tools');
label_train_twoclass=load_matrix('../data/label_train_twoclass.dat');
fm_train_real=load_matrix('../data/fm_train_real.dat');
fm_test_real=load_matrix('../data/fm_test_real.dat');

% LibSVM
disp('LibSVM');

sg('set_kernel', 'GAUSSIAN', 'REAL', size_cache, width);
sg('set_features', 'TRAIN', fm_train_real);
sg('set_labels', 'TRAIN', label_train_twoclass);
sg('new_classifier', 'LIBSVM');
sg('svm_epsilon', epsilon);
sg('svm_use_bias', use_bias);
sg('c', C);

sg('train_classifier');

sg('set_features', 'TEST', fm_test_real);
result=sg('classify');


text:
var Rule = require('./Rule');

/**
 * CSS keyframes rule definition
 *
 * @param {string} rule
 * @param {Object.<string, Object.<string, string>>} frames
 * @constructor
 */
function KeyFrames(rule, frames) {
    this.rule = rule;
    this.frames = Object.keys(frames).map(
        function transformToRules(selector) {
            return new Rule(selector, frames[selector]);
        }
    );

    this._cachedRule = null;
}

/**
 * Returns CSS rule definition
 *
 * @returns {string}
 */
KeyFrames.prototype.toString = function toString() {
    if (this._cachedRule !== null) {
        return this._cachedRule;
    }

    this._cachedRule = this.rule + '{' + this.frames.map(
            function transformRuleToString(rule) { return rule.toString(''); }
        ).join('') + '}';

    return this._cachedRule;
};

module.exports = KeyFrames;


text:
module Blinky
  module DelcomEngineering
    module VisualIndicator
      module GenerationI

        def success!
          set_colour(0xFF && ~0x01)
        end

        def failure!
          set_colour(0xFF && ~0x02)
        end

        def building!
          set_colour(0xFF && ~0x04)
        end

        def warning!
          set_colour(0xFF && ~0x03)
        end

        def off!
          set_colour(0xFF)
        end

        def init
        end

        private
        def set_colour colour
          begin
            @handle.usb_control_msg(0xc8, 0x12, 0x020a, colour,"",0)
          rescue  Errno::EPIPE
            # broken pipe error are always thrown here - this is fixed in the ribusb branch
          end
        end
      end
    end
  end
end


text:
using System;
using System.Drawing;
using System.Threading.Tasks;

namespace Twipe.Core.Internals
{
    /// <summary>
    /// This is the base class for algorithms that pixelate a given image.
    /// </summary>
    /// <typeparam name="T">Type of the object used for susbstitution of each pixel in the given image.</typeparam>
    public abstract class PixelatorBase<T> : IProgressable
    {
        protected Bitmap input;
        protected ITiledImage<T> output;
        protected ISubstitutionTable<T> table;

        public event EventHandler<ProgressEventArgs> ProgressChanged;

        public event EventHandler Completed;

        public virtual ISubstitutionTable<T> SubstitutionTable
        {
            get { return table; }

            set { table = value; }
        }

        public virtual Bitmap InputImage
        {
            get { return input; }

            set { input = value; }
        }

        public virtual int TileSize { get; set; }

        public virtual ITiledImage<T> Result
        {
            get { return output; }
        }

        public abstract ITiledImage<T> Pixelate();

        public abstract Task<ITiledImage<T>> PixelateAsync();

        protected virtual void OnProgressChanged(float progress)
        {
            if (ProgressChanged != null)
                ProgressChanged(this, new ProgressEventArgs(progress));
        }
    }
}


text:
// ###replace: package tasks;
package javaguide.scheduling;

import akka.actor.ActorSystem;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import scala.concurrent.ExecutionContext;
import scala.concurrent.duration.Duration;

// #schedule-block-with-interval
public class CodeBlockTask {

  private final ActorSystem actorSystem;
  private final ExecutionContext executionContext;

  @Inject
  public CodeBlockTask(ActorSystem actorSystem, ExecutionContext executionContext) {
    this.actorSystem = actorSystem;
    this.executionContext = executionContext;

    this.initialize();
  }

  private void initialize() {
    this.actorSystem
        .scheduler()
        .scheduleAtFixedRate(
            Duration.create(10, TimeUnit.SECONDS), // initialDelay
            Duration.create(1, TimeUnit.MINUTES), // interval
            () -> actorSystem.log().info("Running block of code"),
            this.executionContext);
  }
}
// #schedule-block-with-interval


text:
class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable, :confirmable,
         :recoverable, :rememberable, :trackable, :validatable,
         :omniauthable, :omniauth_providers => [:facebook, :twitter]

  has_many :characters

  def self.from_omniauth(auth)
    user = User.where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
      user.uid = auth.uid
      user.provider = auth.provider
      user.email = auth.provider == "twitter" ? "#{auth.info.nickname}@twitter.com" : auth.info.email
      user.name = auth.info.name
      user.password = Devise.friendly_token[0,20]
      user.skip_confirmation!
    end
    user
  end
end


text:
using System;

namespace Module.Core.Models.Exceptions
{
    /// <summary>
    ///     INCATIVE RECORD EXCEPTION
    /// </summary>
    [Serializable]
    public class InactiveRecordException : Exception
    {
        public InactiveRecordException()
        {
        }

        public InactiveRecordException(string ex)
            : base(ex)
        {
        }
    }
}


text:
/*
 * crypto_rng/try.c version 20180227
 * D. J. Bernstein
 * Public domain.
 * Auto-generated by trygen.py; do not edit.
 */

#include "crypto_rng.h"
#include "try.h"

const char *primitiveimplementation = crypto_rng_implementation;

#define TUNE_BYTES 1536
#ifdef SMALL
#define MAXTEST_BYTES 128
#else
#define MAXTEST_BYTES 4096
#endif
#ifdef SMALL
#define LOOPS 64
#else
#define LOOPS 512
#endif

static unsigned char *k;
static unsigned char *r;
static unsigned char *n;
static unsigned char *k2;
static unsigned char *r2;
static unsigned char *n2;
#define klen crypto_rng_KEYBYTES
#define rlen crypto_rng_OUTPUTBYTES
#define nlen crypto_rng_KEYBYTES

void preallocate(void)
{
}

void allocate(void)
{
  unsigned long long alloclen = 0;
  if (alloclen < TUNE_BYTES) alloclen = TUNE_BYTES;
  if (alloclen < MAXTEST_BYTES) alloclen = MAXTEST_BYTES;
  if (alloclen < crypto_rng_KEYBYTES) alloclen = crypto_rng_KEYBYTES;
  if (alloclen < crypto_rng_OUTPUTBYTES) alloclen = crypto_rng_OUTPUTBYTES;
  if (alloclen < crypto_rng_KEYBYTES) alloclen = crypto_rng_KEYBYTES;
  k = alignedcalloc(alloclen);
  r = alignedcalloc(alloclen);
  n = alignedcalloc(alloclen);
  k2 = alignedcalloc(alloclen);
  r2 = alignedcalloc(alloclen);
  n2 = alignedcalloc(alloclen);
}

void predoit(void)
{
}

void doit(void)
{
  crypto_rng(r,n,k);
}

void test(void)
{
  unsigned long long loop;

  for (loop = 0;loop < LOOPS;++loop) {

    output_prepare(r2,r,rlen);
    output_prepare(n2,n,nlen);
    input_prepare(k2,k,klen);
    if (crypto_rng(r,n,k) != 0) fail("crypto_rng returns nonzero");
    checksum(r,rlen);
    checksum(n,nlen);
    output_compare(r2,r,rlen,"crypto_rng");
    output_compare(n2,n,nlen,"crypto_rng");
    input_compare(k2,k,klen,"crypto_rng");

    double_canary(r2,r,rlen);
    double_canary(n2,n,nlen);
    double_canary(k2,k,klen);
    if (crypto_rng(r2,n2,k2) != 0) fail("crypto_rng returns nonzero");
    if (memcmp(r2,r,rlen) != 0) fail("crypto_rng is nondeterministic");
    if (memcmp(n2,n,nlen) != 0) fail("crypto_rng is nondeterministic");

    double_canary(r2,r,rlen);
    double_canary(n2,n,nlen);
    double_canary(k2,k,klen);
    if (crypto_rng(k2,n,k2) != 0) fail("crypto_rng with k=r overlap returns nonzero");
    if (memcmp(k2,r,rlen) != 0) fail("crypto_rng does not handle k=r overlap");
    memcpy(k2,k,klen);

    double_canary(r2,r,rlen);
    double_canary(n2,n,nlen);
    double_canary(k2,k,klen);
    if (crypto_rng(r,k2,k2) != 0) fail("crypto_rng with k=n overlap returns nonzero");
    if (memcmp(k2,n,nlen) != 0) fail("crypto_rng does not handle k=n overlap");
    memcpy(k2,k,klen);
  }
}


text:
#include "StarHUD.h"
#include "AssetList.h"

extern CR::Graphics::GraphicsEngine *graphics_engine;

StarHUD::StarHUD()
{
	Input_Button::Input_Button();
	SetSpriteAndBounds(0, 0, CR::AssetList::Star_HUD, 900);
	DesignSize(48, 57);

	starSprite = graphics_engine->CreateSprite1(true,800);
	starSprite->SetImage(CR::AssetList::Star_HUD_Animation);
	starSprite->SetDesignSize(29, 28);

	numberFont = new NumberFont(CR::AssetList::Font_StarHUD, 700);
	numberFont->SetDesignSize(10, 14);
	m_numStars = 0;

	maxTag = graphics_engine->CreateSprite1(false, 800);
	maxTag->SetImage(CR::AssetList::Max_Tag);
	maxTag->SetDesignSize(34, 21);

	maxedOut = false;
}

StarHUD::~StarHUD()
{
	starSprite->Release();
	maxTag->Release();
	delete numberFont;
}

void StarHUD::Update()
{
	if (m_numStars > 0)
	{
		if (!starSprite->IsAnimating())
		{
			starSprite->SetAutoAnimate(true);
		}
	}
	else if (m_numStars == 0)
	{
		if (starSprite->IsAnimating())
		{
			starSprite->SetAutoAnimate(false);
			starSprite->SetFrame(0);
		}
	}
}

void StarHUD::Render()
{
	Input_Button::Render();
	starSprite->Render();

	if (maxedOut)
		maxTag->Render();
	else
		numberFont->RenderNumber(m_numStars);
}
void StarHUD::SetPosition(float xLoc, float yLoc)
{
	offset.X(xLoc);
	offset.Y(yLoc);

	Input_Button::SetPosition(xLoc, yLoc);
	starSprite->SetPositionAbsolute(xLoc + 25, yLoc + 20);

	numberFont->SetPosition(xLoc + 30, yLoc + 43);
	maxTag->SetPositionAbsolute(xLoc + 25, yLoc + 46);
}

void StarHUD::PauseAnimation(bool pause)
{
	starSprite->PauseAnimation(pause);
}

void StarHUD::AddStar()
{
	//if (m_numStars < 90)
		m_numStars++;
}

void StarHUD::SetStars(int _value)
{
	m_numStars = _value;
}

int StarHUD::GetStars() const
{
	return m_numStars;
}


text:
        {view_lateral}

                <fieldset class="">
                    <legend>Encontre mais livros</legend>
                    Use a tela de busca para encontrar mais livros

                    ir para "Buscar Livros"

                    <?php

                    ?>

                </fieldset>

                <fieldset>
                    <legend>Meus Pedidos Solicitados</legend>

                         <?php
                     if ($livrosSolicitados){ ?>

                                        Livro	Solicitante:	Ação

                  <?php /*print_r($livrosSolicitados);die();*/ foreach ($livrosSolicitados as $key => $value) { ?>

                                         <img src="{local}imagens/capa/<?= $value['FOTO']; ?>" class="capa img-responsive">
                                        <?= $value['TITULO']; ?>
                                        <?= $value['NOME_USUARIO']; ?>

                                            <?php if ($value['STATUS']=='1'){ ?>
                                            <a class="btn btn-success" href="{base_url}pedido/aceitarPedido/<?= $value['CODIGO']?>">Aceitar
                                            <a class="btn btn-danger" href="{base_url}pedido/recusarPedido/<?= $value['CODIGO']?>">Recusar

                                            <?php }else{
                                                if($value['MODO_ENTREGA']=='1'){
                                                    if( trim($value['COD_RASTREIO'])==""){ ?>

                                               <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#inserirCodigo" data-whatever="<?= $value['CODIGO']?>">Inserir Código de Rastreio</button>
                                            <?php }else{ ?>
                                               <button type="button" class="btn btn-primary btn-lg " data-toggle="modal" data-target="#rastrearPedido" data-whatever="<?= $value['CODIGO']?>">Rastrear Pedido</button>
                                            <?php } }
                                            else{
                                               echo "Usuário escolheu modo de entrega a combinar
 entre em contato ";
                                            }}?>

                   <?php }?>

                      <?php  }else{
                        echo "
Atenção
Nenhuma solicitação de Livros.
";
                     }
                    ?>

                </fieldset>

        Direitos reservados

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Inserir código de rastreio

          <form id="updateRastreio" method="POST" action="{base_url}pedido/enviarCR">
              <input type="hidden" name="codigo_pedido" id="codigo_pedido" readonly="" class="form-control">
          Código de Rastreio
          <input type="text" name="codigo_rastreio" id="codigo_rastreio" class="form-control" placeholder="Código de Rastreio" style="text-transform: uppercase;">
          </form>

        <button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
        <button type="button" id="salvarCodigo" class="btn btn-primary">Salvar</button>

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Rastreio de Pedido

          Carregando...

        <button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>


text:
public class TemplateMethodMain {
    public static void main(String[] args) {
        AbstractDisplay d1 = new CharDisplay('H');
        AbstractDisplay d2 = new TemplateStringDisplay("Hello, world.");
        d1.display();
        d2.display();
    }
}


text:
package vspk

import "github.com/nuagenetworks/go-bambou/bambou"

// NetworkLayoutIdentity represents the Identity of the object
var NetworkLayoutIdentity = bambou.Identity{
	Name:     "networklayout",
	Category: "networklayout",
}

// NetworkLayoutsList represents a list of NetworkLayouts
type NetworkLayoutsList []*NetworkLayout

// NetworkLayoutsAncestor is the interface of an ancestor of a NetworkLayout must implement.
type NetworkLayoutsAncestor interface {
	NetworkLayouts(*bambou.FetchingInfo) (NetworkLayoutsList, *bambou.Error)
	CreateNetworkLayouts(*NetworkLayout) *bambou.Error
}

// NetworkLayout represents the model of a networklayout
type NetworkLayout struct {
	ID                  string `json:"ID,omitempty"`
	ParentID            string `json:"parentID,omitempty"`
	ParentType          string `json:"parentType,omitempty"`
	Owner               string `json:"owner,omitempty"`
	LastUpdatedBy       string `json:"lastUpdatedBy,omitempty"`
	ServiceType         string `json:"serviceType,omitempty"`
	EntityScope         string `json:"entityScope,omitempty"`
	RouteReflectorIP    string `json:"routeReflectorIP,omitempty"`
	AutonomousSystemNum int    `json:"autonomousSystemNum,omitempty"`
	ExternalID          string `json:"externalID,omitempty"`
}

// NewNetworkLayout returns a new *NetworkLayout
func NewNetworkLayout() *NetworkLayout {

	return &NetworkLayout{}
}

// Identity returns the Identity of the object.
func (o *NetworkLayout) Identity() bambou.Identity {

	return NetworkLayoutIdentity
}

// Identifier returns the value of the object's unique identifier.
func (o *NetworkLayout) Identifier() string {

	return o.ID
}

// SetIdentifier sets the value of the object's unique identifier.
func (o *NetworkLayout) SetIdentifier(ID string) {

	o.ID = ID
}

// Fetch retrieves the NetworkLayout from the server
func (o *NetworkLayout) Fetch() *bambou.Error {

	return bambou.CurrentSession().FetchEntity(o)
}

// Save saves the NetworkLayout into the server
func (o *NetworkLayout) Save() *bambou.Error {

	return bambou.CurrentSession().SaveEntity(o)
}

// Delete deletes the NetworkLayout from the server
func (o *NetworkLayout) Delete() *bambou.Error {

	return bambou.CurrentSession().DeleteEntity(o)
}

// Metadatas retrieves the list of child Metadatas of the NetworkLayout
func (o *NetworkLayout) Metadatas(info *bambou.FetchingInfo) (MetadatasList, *bambou.Error) {

	var list MetadatasList
	err := bambou.CurrentSession().FetchChildren(o, MetadataIdentity, &list, info)
	return list, err
}

// CreateMetadata creates a new child Metadata under the NetworkLayout
func (o *NetworkLayout) CreateMetadata(child *Metadata) *bambou.Error {

	return bambou.CurrentSession().CreateChild(o, child)
}

// GlobalMetadatas retrieves the list of child GlobalMetadatas of the NetworkLayout
func (o *NetworkLayout) GlobalMetadatas(info *bambou.FetchingInfo) (GlobalMetadatasList, *bambou.Error) {

	var list GlobalMetadatasList
	err := bambou.CurrentSession().FetchChildren(o, GlobalMetadataIdentity, &list, info)
	return list, err
}

// CreateGlobalMetadata creates a new child GlobalMetadata under the NetworkLayout
func (o *NetworkLayout) CreateGlobalMetadata(child *GlobalMetadata) *bambou.Error {

	return bambou.CurrentSession().CreateChild(o, child)
}


text:
package cn.aposoft.tutorial.http.loop;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

/**
 * elapse:300367 for 10000 times Close_Connection for TLS1.2
 *
 * elapse:36822
 *
 * @author LiuJian
 * @date 2017年4月19日
 *
 */
public class TLS12CloseConnectionStub {

    /**
     * elapse:299200 for TLSv1 Close_Connection elapse:283293 elapse:37275
     * elapse:36237
     *
     * @param args
     */
    public static void main(String[] args)
            throws ClientProtocolException, IOException, KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException {
        System.setProperty("javax.net.debug", "ssl,handshake");
        // System.setProperty("javax.net.ssl.trustStore", "StartComRoot1.jks");
        // System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
        // HttpGet get = new HttpGet("https://www.aposoft.cn:8443/");
//        HttpGet get = new HttpGet("https://fen.gomemyf.com/");
        HttpGet get = new HttpGet("https://fen.gomemyf.com/");
        get.addHeader("Connection", "close");
        SSLContext sslContext = SSLContexts.createDefault();
        final String[] enabledProtocols = new String[] { "TLSv1.2" };
        final String[] supportedCipherSuites = null;// new String[] {
                                                    // "TLS_RSA_WITH_AES_256_CBC_SHA"
                                                    // };
        // cn.aposoft.tutorial.http.https.verifier
        HostnameVerifier hostNameVerifier = new DefaultHostnameVerifier();
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, enabledProtocols, supportedCipherSuites,
                hostNameVerifier);

        try (CloseableHttpClient client = HttpClients.custom()//
                .setSSLContext(sslContext) //
                .setSSLSocketFactory(sslSocketFactory).build()) {
            long begin = System.currentTimeMillis();

            for (int i = 0; i < 1; i++) {
                CloseableHttpResponse resp = client.execute(get);
                {
                    // System.out.println(EntityUtils.toString(resp.getEntity()));
                    EntityUtils.consumeQuietly(resp.getEntity());

                }
            }
            long end = System.currentTimeMillis();
            System.out.println("elapse:" + (end - begin));
        }
    }

}


text:
<?php

	header('Content-Type: application/xml');

	$SETTINGS['path_mod'] = "../";
	include('../conn.php');
	include('../includes/tags_functions.php');
	include('../includes/protection.php');
	include('rss_functions.php');

	$tagName = "";
	if (isset($_GET['tag']))
	{
	    $tagName = $_GET['tag'];
	}

	$tagName = filter($tagName);
	$tagName = strtolower($tagName);

	$tagNames = explode(' ', trim($tagName));

	$tagcount = count($tagNames);
	for ($i = 0; $i < $tagcount; $i ++)
	{
		$tagNames[$i] = trim($tagNames[$i]);
	}

	$bookmarks_tags = getTagsBookmarks($tagNames, 0, TAGS_PER_PAGE, "", "../");

	$bookmarks = getFeedVars($bookmarks_tags);

	$tagName = str_replace(" ", "%20", $tagName);

	$feedTitle = WEBSITE_NAME;
	$feedLink = WEBSITE_ROOT . "tags.php?tag=" . $tagName;
	$feedDesc = "Bookmarks for tag " . $tagName;
	$feedTTL = "60";

	include('../templates/rss.tpl.php');
?>


text:
package org.springframework.boot.actuate.autoconfigure.env;

import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnAvailableEndpoint;
import org.springframework.boot.actuate.env.EnvironmentEndpoint;
import org.springframework.boot.actuate.env.EnvironmentEndpointWebExtension;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

/**
 * {@link EnableAutoConfiguration Auto-configuration} for the {@link EnvironmentEndpoint}.
 *
 * @author Phillip Webb
 * @author Stephane Nicoll
 * @since 2.0.0
 */
@Configuration(proxyBeanMethods = false)
@ConditionalOnAvailableEndpoint(endpoint = EnvironmentEndpoint.class)
@EnableConfigurationProperties(EnvironmentEndpointProperties.class)
public class EnvironmentEndpointAutoConfiguration {

	@Bean
	@ConditionalOnMissingBean
	public EnvironmentEndpoint environmentEndpoint(Environment environment, EnvironmentEndpointProperties properties) {
		EnvironmentEndpoint endpoint = new EnvironmentEndpoint(environment);
		String[] keysToSanitize = properties.getKeysToSanitize();
		if (keysToSanitize != null) {
			endpoint.setKeysToSanitize(keysToSanitize);
		}
		return endpoint;
	}

	@Bean
	@ConditionalOnMissingBean
	@ConditionalOnBean(EnvironmentEndpoint.class)
	public EnvironmentEndpointWebExtension environmentEndpointWebExtension(EnvironmentEndpoint environmentEndpoint) {
		return new EnvironmentEndpointWebExtension(environmentEndpoint);
	}

}


text:
/*
 * (C) 2009 Nikhil Marathe <nsm.nikhil@gmail.com>
 * Licensed under the GNU General Public License.
 * See LICENSE for details
 */
#ifndef QOM_SETTINGS
#define QOM_SETTINGS

#include <QDragEnterEvent>
#include <QMessageBox>
#include <QUrl>

#include "ui_settings.h"

class QSettings;

class SettingsDialog : public QDialog
{
    Q_OBJECT

public:
    SettingsDialog(QWidget *);

    ~SettingsDialog()
    {
        delete settings;
        settings = NULL;
    };

    void dragEnterEvent(QDragEnterEvent *evt)
    {
        if (evt->mimeData()->hasUrls())
        {
            evt->acceptProposedAction();
        }
    };

    void dropEvent(QDropEvent *);

private slots:
    void on_buttonBox_accepted();

private:
    Ui::SettingsDialog ui;
    QSettings *settings;

    void loadSettings();

signals:
    // custom signal because if the listener listens to accept()
    // it might happen that our changes aren't synced yet
    void settingsChanged();
};

#endif


text:
---
sidebar_position: 1
---

# SQL File Conventions

HugSQL SQL files contain special single-line comments and multi-line comments in the following forms:

```sql title="SQL"
 -- :key value1 value2 value3
 OR
 /* :key
 value1
 value2
 value3
 */
```

Examples:

```sql title="SQL"
-- regular SQL comment ignored by hugsql
/*
regular SQL multi-line comment ignored by hugsql
*/

-- :name query-get-many :? :*
-- :doc My query doc string to end of this line
select * from my_table;

-- :name query-get-one :? :1
/* :doc
My multi-line
comment doc string
*/
select * from my_table limit 1
```

HugSQL recognizes the following keys:

- `:name` or `:name-` (private fn) Name of the function to create. Optionally followed by the command and result (e.g., `:name :? :*`) instead of providing these as separate key/value pairs.
- `:doc` Docstring for the created function.
- `:command` Underlying database command to run.
- `:result` Expected result type (shape).
- `:snip` or `:snip-` (private fn) Name of the function to create. `:snip` is used in place of `:name` for snippets.
- `:meta` Metadata in the form of an EDN hashmap to attach to function.
- `:require` Namespace require and aliases for Clojure expression support.


text:
class AddNameToDistList < ActiveRecord::Migration
  def change
    add_column :dist_lists, :name, :string
  end
end


text:
'use strict';

var React = require('React');
var StyleSheet = require('StyleSheet');
var TabBarItemIOS = require('TabBarItemIOS');
var View = require('View');

var requireNativeComponent = require('requireNativeComponent');

var TabBarIOS = React.createClass({
  statics: {
    Item: TabBarItemIOS,
  },

  propTypes: {
    style: View.propTypes.style,
    /**
     * Color of the currently selected tab icon
     */
    tintColor: React.PropTypes.string,
    /**
     * Background color of the tab bar
     */
    barTintColor: React.PropTypes.string,
    /**
     * A Boolean value that indicates whether the tab bar is translucent
     */
    translucent: React.PropTypes.bool,
  },

  render: function() {
    return (
      <RCTTabBar
        style={[styles.tabGroup, this.props.style]}
        tintColor={this.props.tintColor}
        barTintColor={this.props.barTintColor}
        translucent={this.props.translucent !== false}>
        {this.props.children}
      </RCTTabBar>
    );
  }
});

var styles = StyleSheet.create({
  tabGroup: {
    flex: 1,
  }
});

var RCTTabBar = requireNativeComponent('RCTTabBar', TabBarIOS);

module.exports = TabBarIOS;


text:
describe('tbd-properties', function() {
    var tbd = require('../');
    it('should clone properties from source', function() {
        var data = tbd.from({ foo: 'bar' }).make(1);

        expect(data[0].hasOwnProperty('foo')).toBeTruthy();
        expect(data[0].foo).toEqual('bar');
    });

    it('should use default value for properties', function() {
        var data = tbd.from({
                foo: 'bar',
                bar: 1,
                baz: true
            }).make(1);

        expect(data[0].foo).toEqual('bar');
        expect(data[0].bar).toEqual(1);
        expect(data[0].baz).toBeTruthy();
    });

    it('should create properties when they don\'t exist', function() {
        var data = tbd.from({}).prop('foo').done().make(1);

        expect(data[0].hasOwnProperty('foo')).toBeTruthy();
    });

    it('should allow property values to be overriden', function() {
        var data = tbd
                    .from({ foo: 'bar' })
                    .prop('foo').use('baz').done()
                    .make(1);

        expect(data[0].foo).toEqual('baz');
    });

    it('should allow property values from functions', function() {
        var data = tbd.from({ foo: 'bar' })
                    .prop('foo').use(function() { return 'baz'; }).done()
                    .make(1);

        expect(data[0].foo).toEqual('baz');
    });
});


text:
package androidx.core.app;

import static androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP;

import android.app.Notification;
import android.app.Service;
import android.os.Build;

import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.annotation.RestrictTo;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

/**
 * Helper for accessing features in {@link android.app.Service}.
 */
public final class ServiceCompat {

    private ServiceCompat() {
        /* Hide constructor */
    }

    /**
     * Constant to return from {@link android.app.Service#onStartCommand}: if this
     * service's process is killed while it is started (after returning from
     * {@link android.app.Service#onStartCommand}), then leave it in the started
     * state but don't retain this delivered intent.  Later the system will try to
     * re-create the service.  Because it is in the started state, it will
     * guarantee to call {@link android.app.Service#onStartCommand} after creating
     * the new service instance; if there are not any pending start commands to be
     * delivered to the service, it will be called with a null intent
     * object, so you must take care to check for this.
     *
     *
This mode makes sense for things that will be explicitly started
     * and stopped to run for arbitrary periods of time, such as a service
     * performing background music playback.
     */
    public static final int START_STICKY = 1;

    /**
     * Flag for {@link #stopForeground(Service, int)}: if set, the notification previously provided
     * to {@link Service#startForeground(int, Notification)} will be removed.  Otherwise it
     * will remain until a later call (to {@link Service#startForeground(int, Notification)} or
     * {@link #stopForeground(Service, int)} removes it, or the service is destroyed.
     */
    public static final int STOP_FOREGROUND_REMOVE = 1<<0;

    /**
     * Flag for {@link #stopForeground(Service, int)}: if set, the notification previously provided
     * to {@link Service#startForeground(int, Notification)} will be detached from the service.
     * Only makes sense when {@link #STOP_FOREGROUND_REMOVE} is not set -- in this case, the
     * notification will remain shown, but be completely detached from the service and so no longer
     * changed except through direct calls to the
     * notification manager.
     *

     * This flag will only work on
     * {@link android.os.Build.VERSION_CODES#N} and later. It doesn't have any effect on earlier
     * platform versions.
     */
    public static final int STOP_FOREGROUND_DETACH = 1<<1;

    /** @hide */
    @RestrictTo(LIBRARY_GROUP)
    @IntDef(flag = true,
            value = {
                    STOP_FOREGROUND_REMOVE,
                    STOP_FOREGROUND_DETACH
            })
    @Retention(RetentionPolicy.SOURCE)
    public @interface StopForegroundFlags {}

    /**
     * Remove the passed service from foreground state, allowing it to be killed if
     * more memory is needed.
     * @param flags Additional behavior options: {@link #STOP_FOREGROUND_REMOVE},
     * {@link #STOP_FOREGROUND_DETACH}.
     * @see Service#startForeground(int, Notification)
     */
    public static void stopForeground(@NonNull Service service, @StopForegroundFlags int flags) {
        if (Build.VERSION.SDK_INT >= 24) {
            service.stopForeground(flags);
        } else {
            service.stopForeground((flags & ServiceCompat.STOP_FOREGROUND_REMOVE) != 0);
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace jui.Core
{
	public class AbstractBuilder<TModel, T> : IDisposable where T : HtmlElement<T>
	{
		protected readonly T element;

		protected readonly TextWriter textWriter;
		protected readonly HtmlHelper<TModel> htmlHelper;
		protected readonly AjaxHelper<TModel> ajaxHelper;

		internal AbstractBuilder(HtmlHelper<TModel> _htmlHelper, T _element)
        {
			if (_element == null)
            {
				throw new ArgumentNullException("_element");
            }

			element = _element;
			htmlHelper = _htmlHelper;
            textWriter = htmlHelper.ViewContext.Writer;
            textWriter.Write(element.StartTag);
        }

		internal AbstractBuilder(AjaxHelper<TModel> _ajaxHelper, T _element)
        {
            if (element == null)
            {
				throw new ArgumentNullException("_element");
            }

			element = _element;
			ajaxHelper = _ajaxHelper;
            textWriter = ajaxHelper.ViewContext.Writer;
            textWriter.Write(element.StartTag);
        }

		[EditorBrowsable(EditorBrowsableState.Never)]
		public virtual void Dispose()
		{
			textWriter.Write(element.EndTag);
		}
	}
}


text:
'use strict';

var mongoose = require('mongoose'),
	errorHandler = require('./errors.server.controller'),
	photo = mongoose.model('Photo'),
	_ = require('lodash');

exports.create = function(req, res) {
	var photo = new photo(req.body);
	photo.user = req.user;

	photo.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.json(photo);
		}
	});
};

exports.read = function(req, res) {
	res.json(req.photo);
};

exports.update = function(req, res) {
	var photo = req.photo;

	photo = _.extend(photo, req.body);

	photo.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.json(photo);
		}
	});
};

exports.delete = function(req, res) {
	var photo = req.photo;

	photo.remove(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.json(photo);
		}
	});
};

exports.list = function(req, res) {
	photo.find().sort('-created').populate('user', 'displayName').exec(function(err, photos) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.json(photos);
		}
	});
};

exports.photoByID = function(req, res, next, id) {

	if (!mongoose.Types.ObjectId.isValid(id)) {
		return res.status(400).send({
			message: 'photo is invalid'
		});
	}

	photo.findById(id).populate('user', 'displayName').exec(function(err, photo) {
		if (err) return next(err);
		if (!photo) {
			return res.status(404).send({
  				message: 'photo not found'
  			});
		}
		req.photo = photo;
		next();
	});
};

exports.hasAuthorization = function(req, res, next) {
	if (req.photo.user.id !== req.user.id) {
		return res.status(403).send({
			message: 'User is not authorized'
		});
	}
	next();
};


text:
package com.qc4w.ilocker.ui.adapter;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.qc4w.ilocker.R;
import com.qc4w.ilocker.config.ConfigManager;
import com.qc4w.ilocker.constant.Constants;
import com.qc4w.ilocker.ui.PreViewActivity;
import com.qc4w.ilocker.util.ViewHolder;

public class LockerScreenAdapter extends BaseAdapter {

	private LayoutInflater mInflater;

	private ConfigManager mConfig;

	private Context mContext;

	public LockerScreenAdapter(Context context) {
		mInflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mConfig = ConfigManager.getInstance(context);
		mContext = context;
	}

	private int[] images = new int[] { R.drawable.unlock_slide,
			R.drawable.unlock_mylover, R.drawable.unlock_myname/*, R.drawable.unlock_myname*/};

	private int[] names = new int[] { R.string.label_lock_type_slide,
			R.string.label_lock_type_mylover, R.string.label_lock_type_myname/*, R.string.label_lock_type_mood*/};

	@Override
	public int getCount() {
		return names.length;
	}

	@Override
	public Object getItem(int position) {
		return names[position];
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.list_lock_type_item, parent, false);
		}
		ImageView ivLockType = ViewHolder.get(convertView, R.id.iv_lock_type);
		final ImageView current = ViewHolder.get(convertView, R.id.iv_current_flag);
		TextView tvLockType = ViewHolder.get(convertView, R.id.tv_lock_type_name);
		tvLockType.setText(names[position]);
		ivLockType.setImageResource(images[position]);
		if (mConfig.getLockerScreenType() == position) {
			current.setVisibility(View.VISIBLE);
		} else {
			current.setVisibility(View.GONE);
		}
		convertView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(mContext, PreViewActivity.class);
				intent.putExtra(Constants.StringConstant.PARAMS_DATA, PreViewActivity.PREVIEW_TYPE_LOCKER_SCREEN);
				intent.putExtra(Constants.StringConstant.PARAMS_DATA1, position);
				mContext.startActivity(intent);
			}
		});
		return convertView;
	}

}


text:
package uri

import (
	"testing"

	"github.com/telehash/gogotelehash/Godeps/_workspace/src/github.com/stretchr/testify/assert"

	_ "github.com/telehash/gogotelehash/e3x"
)

func TestResolve(t *testing.T) {
	assert := assert.New(t)

	uri, err := Parse("01.test.simonmenke.me")
	if err != nil {
		panic(err)
	}

	ident, err := Resolve(uri)
	assert.NoError(err)
	assert.NotNil(ident)
	t.Logf("ident=%v addrs=%v keys=%v", ident, ident.Addresses(), ident.Keys())
}


text:
namespace Microsoft.Azure.Management.Migrate.ResourceMover.Models
{
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// Summary Collection.
    /// </summary>
    public partial class SummaryCollection
    {
        /// <summary>
        /// Initializes a new instance of the SummaryCollection class.
        /// </summary>
        public SummaryCollection()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the SummaryCollection class.
        /// </summary>
        /// <param name="fieldName">Gets or sets the field name on which
        /// summary is done.</param>
        /// <param name="summary">Gets or sets the list of summary
        /// items.</param>
        public SummaryCollection(string fieldName = default(string), IList<Summary> summary = default(IList<Summary>))
        {
            FieldName = fieldName;
            Summary = summary;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets the field name on which summary is done.
        /// </summary>
        [JsonProperty(PropertyName = "fieldName")]
        public string FieldName { get; set; }

        /// <summary>
        /// Gets or sets the list of summary items.
        /// </summary>
        [JsonProperty(PropertyName = "summary")]
        public IList<Summary> Summary { get; set; }

    }
}