text:
package org.apache.spark.sql.execution

import java.util.Locale
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicInteger

import scala.collection.parallel.immutable.ParRange
import scala.concurrent.{ExecutionContext, Future}
import scala.concurrent.duration._

import org.apache.spark.{SparkConf, SparkContext, SparkFunSuite}
import org.apache.spark.scheduler.{SparkListener, SparkListenerEvent, SparkListenerJobStart}
import org.apache.spark.sql.{Row, SparkSession}
import org.apache.spark.sql.execution.ui.SparkListenerSQLExecutionStart
import org.apache.spark.sql.types._
import org.apache.spark.util.ThreadUtils
import org.apache.spark.util.Utils.REDACTION_REPLACEMENT_TEXT

class SQLExecutionSuite extends SparkFunSuite {

  test("concurrent query execution (SPARK-10548)") {
    val conf = new SparkConf()
      .setMaster("local[*]")
      .setAppName("test")
    val goodSparkContext = new SparkContext(conf)
    try {
      testConcurrentQueryExecution(goodSparkContext)
    } finally {
      goodSparkContext.stop()
    }
  }

  test("concurrent query execution with fork-join pool (SPARK-13747)") {
    val spark = SparkSession.builder
      .master("local[*]")
      .appName("test")
      .getOrCreate()

    import spark.implicits._
    try {
      // Should not throw IllegalArgumentException
      new ParRange(1 to 100).foreach { _ =>
        spark.sparkContext.parallelize(1 to 5).map { i => (i, i) }.toDF("a", "b").count()
      }
    } finally {
      spark.sparkContext.stop()
    }
  }

  /**
   * Trigger SPARK-10548 by mocking a parent and its child thread executing queries concurrently.
   */
  private def testConcurrentQueryExecution(sc: SparkContext): Unit = {
    val spark = SparkSession.builder.getOrCreate()
    import spark.implicits._

    // Initialize local properties. This is necessary for the test to pass.
    sc.getLocalProperties

    // Set up a thread that runs executes a simple SQL query.
    // Before starting the thread, mutate the execution ID in the parent.
    // The child thread should not see the effect of this change.
    var throwable: Option[Throwable] = None
    val child = new Thread {
      override def run(): Unit = {
        try {
          sc.parallelize(1 to 100).map { i => (i, i) }.toDF("a", "b").collect()
        } catch {
          case t: Throwable =>
            throwable = Some(t)
        }

      }
    }
    sc.setLocalProperty(SQLExecution.EXECUTION_ID_KEY, "anything")
    child.start()
    child.join()

    // The throwable is thrown from the child thread so it doesn't have a helpful stack trace
    throwable.foreach { t =>
      t.setStackTrace(t.getStackTrace ++ Thread.currentThread.getStackTrace)
      throw t
    }
  }

  test("Finding QueryExecution for given executionId") {
    val spark = SparkSession.builder.master("local[*]").appName("test").getOrCreate()
    import spark.implicits._

    var queryExecution: QueryExecution = null

    spark.sparkContext.addSparkListener(new SparkListener {
      override def onJobStart(jobStart: SparkListenerJobStart): Unit = {
        val executionIdStr = jobStart.properties.getProperty(SQLExecution.EXECUTION_ID_KEY)
        if (executionIdStr != null) {
          queryExecution = SQLExecution.getQueryExecution(executionIdStr.toLong)
        }
        SQLExecutionSuite.canProgress = true
      }
    })

    val df = spark.range(1).map { x =>
      while (!SQLExecutionSuite.canProgress) {
        Thread.sleep(1)
      }
      x
    }
    df.collect()

    assert(df.queryExecution === queryExecution)

    spark.stop()
  }

  test("SPARK-32813: Table scan should work in different thread") {
    val executor1 = Executors.newSingleThreadExecutor()
    val executor2 = Executors.newSingleThreadExecutor()
    var session: SparkSession = null
    SparkSession.cleanupAnyExistingSession()

    withTempDir { tempDir =>
      try {
        val tablePath = tempDir.toString + "/table"
        val df = ThreadUtils.awaitResult(Future {
          session = SparkSession.builder().appName("test").master("local[*]").getOrCreate()

          session.createDataFrame(
            session.sparkContext.parallelize(Row(Array(1, 2, 3)) :: Nil),
            StructType(Seq(
              StructField("a", ArrayType(IntegerType, containsNull = false), nullable = false))))
            .write.parquet(tablePath)

          session.read.parquet(tablePath)
        }(ExecutionContext.fromExecutorService(executor1)), 1.minute)

        ThreadUtils.awaitResult(Future {
          assert(df.rdd.collect()(0) === Row(Seq(1, 2, 3)))
        }(ExecutionContext.fromExecutorService(executor2)), 1.minute)
      } finally {
        executor1.shutdown()
        executor2.shutdown()
        session.stop()
      }
    }
  }

  test("SPARK-34735: Add modified configs for SQL execution in UI") {
    val spark = SparkSession.builder()
      .master("local[*]")
      .appName("test")
      .config("k1", "v1")
      .getOrCreate()

    try {
      val index = new AtomicInteger(0)
      spark.sparkContext.addSparkListener(new SparkListener {
        override def onOtherEvent(event: SparkListenerEvent): Unit = event match {
          case start: SparkListenerSQLExecutionStart =>
            if (index.get() == 0 && hasProject(start)) {
              assert(!start.modifiedConfigs.contains("k1"))
              index.incrementAndGet()
            } else if (index.get() == 1 && hasProject(start)) {
              assert(start.modifiedConfigs.contains("k2"))
              assert(start.modifiedConfigs("k2") == "v2")
              assert(start.modifiedConfigs.contains("redaction.password"))
              assert(start.modifiedConfigs("redaction.password") == REDACTION_REPLACEMENT_TEXT)
              index.incrementAndGet()
            }
          case _ =>
        }

        private def hasProject(start: SparkListenerSQLExecutionStart): Boolean =
          start.physicalPlanDescription.toLowerCase(Locale.ROOT).contains("project")
      })
      spark.sql("SELECT 1").collect()
      spark.sql("SET k2 = v2")
      spark.sql("SET redaction.password = 123")
      spark.sql("SELECT 1").collect()
      spark.sparkContext.listenerBus.waitUntilEmpty()
      assert(index.get() == 2)
    } finally {
      spark.stop()
    }
  }
}

object SQLExecutionSuite {
  @volatile var canProgress = false
}


text:
"""URL definitions for djangolg."""

from __future__ import print_function
from __future__ import unicode_literals

from django.conf.urls import url

from djangolg import views

urlpatterns = [
    url(r'^$', views.IndexView.as_view(), name="djangolg-index"),
    url(r'^enter/$', views.AcceptTermsView.as_view(), name="djangolg-enter"),
    url(r'^lg/$', views.LookingGlassJsonView.as_view(), name="djangolg-lg"),
]

redpajama_set_name: RedPajamaGithub


text:
fn division(dividend: int, divisor: int) -> int {
    if divisor == 0 {
        // Division by zero triggers a task panic
        panic!("division by zero");
    } else {
        dividend / divisor
    }
}

// The `main` task
fn main() {
    // Heap allocated integer
    let _x = box 0i;

    // This operation will trigger a task failure
    division(3, 0);

    println!("This point won't be reached!");

    // `_x` should get destroyed at this point
}


text:
package com.seeburger.research.securityframework.configuration;

import static org.junit.Assert.*;

import org.junit.Test;

public class ConfigurationReaderTest {

	@Test
	public void testConfigureFramework() {
		try {
			ConfigurationReader.configureFramework("/META-INF");
		} catch (Exception e) {
			e.printStackTrace();
			fail();
		}
	}

}


text:
require 'etc'

# Backend helpers
require 'serverspec/helper/ssh'
require 'serverspec/helper/exec'
require 'serverspec/helper/cmd'
require 'serverspec/helper/winrm'
require 'serverspec/helper/puppet'

# Command helpers
require 'serverspec/helper/redhat'
require 'serverspec/helper/debian'
require 'serverspec/helper/gentoo'
require 'serverspec/helper/plamo'
require 'serverspec/helper/aix'
require 'serverspec/helper/solaris'
require 'serverspec/helper/solaris10'
require 'serverspec/helper/solaris11'
require 'serverspec/helper/smartos'
require 'serverspec/helper/darwin'
require 'serverspec/helper/windows'
require 'serverspec/helper/freebsd'
require 'serverspec/helper/detect_os'

# Attributes helper
require 'serverspec/helper/attributes'
include Serverspec::Helper::Attributes

# Subject type helper
require 'serverspec/helper/type'
include Serverspec::Helper::Type

require 'serverspec/helper/configuration'


text:
require "rails_helper"

describe "Listing announcements in the announcements window" do
  it "lists the announcements" do
    announcement = Announcement.create(title: "Announcement title",
                                        text: "Announcement text",
                                        author: "Announcement author")

    visit root_url

    expect(page).to have_text(announcement.title)
    expect(page).to have_text(announcement.text)
  end
end


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Anal. Soc. cient. argent. 22: (1886)

#### Original name
Pucciniospora chusqueae Speg., 1886

### Remarks
null


text:
<nav class="sidebar">
<welcome></welcome>
<xmenu></xmenu>
<actions></actions>
</nav>


text:
package com.framework.impl;

import java.io.IOException;

import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;

import com.framework.Music;

public class AndroidMusic implements Music, OnCompletionListener {
    MediaPlayer mediaPlayer;
    boolean isPrepared = false;

    public AndroidMusic(AssetFileDescriptor assetDescriptor) {
        mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setDataSource(	assetDescriptor.getFileDescriptor(),
            							assetDescriptor.getStartOffset(),
        								assetDescriptor.getLength());
            mediaPlayer.prepare();
            isPrepared = true;
            mediaPlayer.setOnCompletionListener(this);
        } catch (Exception e) {
            throw new RuntimeException("Couldn't load music");
        }
    }

    @Override
    public void dispose() {
        if (mediaPlayer.isPlaying())
            mediaPlayer.stop();
        mediaPlayer.release();
    }

    @Override
    public boolean isLooping() {
        return mediaPlayer.isLooping();
    }

    @Override
    public boolean isPlaying() {
        return mediaPlayer.isPlaying();
    }

    @Override
    public boolean isStopped() {
        return !isPrepared;
    }

    @Override
    public void pause() {
        if (mediaPlayer.isPlaying())
            mediaPlayer.pause();
    }

    @Override
    public void play() {
        if (mediaPlayer.isPlaying())
            return;

        try {
            synchronized (this) {
                if (!isPrepared)
                    mediaPlayer.prepare();
                mediaPlayer.start();
            }
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void setLooping(boolean isLooping) {
        mediaPlayer.setLooping(isLooping);
    }

    @Override
    public void setVolume(float volume) {
        mediaPlayer.setVolume(volume, volume);
    }

    @Override
    public void stop() {
        mediaPlayer.stop();
        synchronized (this) {
            isPrepared = false;
        }
    }

    @Override
    public void onCompletion(MediaPlayer player) {
        synchronized (this) {
            isPrepared = false;
        }
    }
}


text:
[CocoaPods](https://cocoapods.org/) is used for dependency management. It can be installed with [Homebrew](https://brew.sh/) package manager. For more information about CocoaPods read the [CocoaPods Guides](https://guides.cocoapods.org/).

## Versioning scheme

It uses the shipped syncthing executable version appended with a `-<build index>` number.
So for Syncthing `0.14.28` with first build/package it is versioned as `0.14.28-1`.
Currently there is no need for having a separate version for `syncthing-macos`. As it also keeps the wrapper tightly coupled with the syncthing releases.

## Compilation and packaging process

* Xcode builds all sources
* Syncthing resource is fetched with `syncthing/Scripts/syncthing-resource.sh`
* Fancy DMG disk image is generated with `syncthing/Scripts/create-dmg.sh`
  * The version part of the DMG name is fetched from `syncthing/Info.plist, key CFBundleShortVersionString`
* Both the app bundle and the DMG are signed with the first available Developer ID certificate, if found (or the one specified through `SYNCTHING_APP_CODE_SIGN_IDENTITY` environment variable)

`syncthing/syncthing-macos` will only ship [stable releases and no release candidates](https://forum.syncthing.net/t/introducing-stable-releases-and-release-candidates/9167) of the Syncthing Service (daemon).

## New release

* Update `syncthing/Scripts/syncthing-resource.sh`, `SYNCTHING_VERSION`
* Update `syncthing/Info.plist`
  * `CFBundleShortVersionString` (e.g `0.14.50-dev` or `0.14.50-1`)
  * `CFBundleVersion` (e.g `145000` or `145001`)
* Create git tag on develop
* Merge develop to master branch


text:
<?php

//-----------------------------------------------------------------------------
// Earthbound (Mr. Saturn Font) (SNES) for FEIDIAN
// Written by Derrick Sobodash
//
// Byte Count: 32
// Dimensions: 16x16 font
// Structure:  AAAAAAAAQQQQQQQQ
//             BBBBBBBBRRRRRRRR
//             CCCCCCCCSSSSSSSS
//             DDDDDDDDTTTTTTTT
//             EEEEEEEEUUUUUUUU
//             FFFFFFFFVVVVVVVV
//             GGGGGGGGWWWWWWWW
//             HHHHHHHHXXXXXXXX
//             IIIIIIIIYYYYYYYY
//             JJJJJJJJZZZZZZZZ
//             KKKKKKKKaaaaaaaa
//             LLLLLLLLbbbbbbbb
//             MMMMMMMMcccccccc
//             NNNNNNNNdddddddd
//             OOOOOOOOeeeeeeee
//             PPPPPPPPffffffff
//-----------------------------------------------------------------------------

// Define what tile definition format this is
  define("COLOR_DEPTH", "2"); // Monochrome    (Single Plane)
//define("COLOR_DEPTH", "4"); // Four Color    (Two Plane)
//define("COLOR_DEPTH", "8"); // Eight Color   (Three Plane)
//define("COLOR_DEPTH","16"); // Sixteen Color (Four Plane)

// Tiles width and height in pixels (bits)
$tile_width  = 16;
$tile_height = 16;

// You only need to define the pattern up till where it repeats. You may use
// whitespaces to help you align everything (they will be stripped when your
// string is used). 64 bytes is the limit.
//
// The hirearchy of letters is [A-Z] [a-z] [2-9] [!?@*]
//
// Basically, each unique letter is a byte, and the repeats of that letter are
// bits within that byte.

$plane1  = "AAAAAAAAQQQQQQQQ
            BBBBBBBBRRRRRRRR
            CCCCCCCCSSSSSSSS
            DDDDDDDDTTTTTTTT
            EEEEEEEEUUUUUUUU
            FFFFFFFFVVVVVVVV
            GGGGGGGGWWWWWWWW
            HHHHHHHHXXXXXXXX
            IIIIIIIIYYYYYYYY
            JJJJJJJJZZZZZZZZ
            KKKKKKKKaaaaaaaa
            LLLLLLLLbbbbbbbb
            MMMMMMMMcccccccc
            NNNNNNNNdddddddd
            OOOOOOOOeeeeeeee
            PPPPPPPPffffffff";

// How many bytes are in the above pattern?
$pat_size    = 32;

?>


text:
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE MultiParamTypeClasses #-}
-- {-# LANGUAGE OverlappingInstances #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE UndecidableInstances #-}

module Control.ForFree where {

-- | Free monad from a functor
;
  data Free f x = Pure x | Free (f (Free f x));

  deriving instance (Eq (f (Free f a)), Eq a) => Eq (Free f a);
  deriving instance (Ord (f (Free f a)), Ord a) => Ord (Free f a);
  deriving instance (Read (f (Free f a)), Read a) => Read (Free f a);
  deriving instance (Show (f (Free f a)), Show a) => Show (Free f a);
}


text:
[William Bruno](/profiles/mentors/profiles/william_bruno.md)

## Meu Nome

Bruno Ferreira

## Qual meu sonho na carreira?

Sempre em busca de me tornar um desenvolvedor full-stack cada vez mais capacitado e preparado para aceitar qualquer desafio em desenvolvimento web.

## Alguns links para me conhecer melhor

- [Facebook](https://www.facebook.com/fsbrunoferreira)
- [GitHub](https://github.com/brunoferreiras)
- [LinkedIn](https://www.linkedin.com/in/bruno-ferreira-91547310b)


text:
package org.marketcetera.photon.views;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;

import org.eclipse.swtbot.eclipse.finder.SWTWorkbenchBot;
import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotView;
import org.eclipse.swtbot.swt.finder.SWTBot;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotButton;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotCombo;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotText;
import org.eclipse.ui.PlatformUI;
import org.marketcetera.photon.test.AbstractUIRunner;
import org.marketcetera.photon.test.AbstractUIRunner.ThrowableRunnable;

/* $License$ */

/**
 * Helps test order ticket views.
 *
 * @author Will Horn
 * @version $Id: OrderTicketViewFixture.java 16154 2012-07-14 16:34:05Z colin $
 * @since 2.0.0
 */
public abstract class OrderTicketViewFixture<T extends IOrderTicket> {

    private final SWTWorkbenchBot mBot = new SWTWorkbenchBot();
    private final SWTBotView mView;
    private volatile OrderTicketView<?, T> mRealView;
    private final SWTBotCombo mSideCombo;
    private final SWTBotText mQuantityText;
    private final SWTBotText mSymbolText;
    private final SWTBotCombo mOrderTypeCombo;
    private final SWTBotText mPriceText;
    private final SWTBotCombo mBrokerCombo;
    private final SWTBotCombo mTimeInForceCombo;
    private final SWTBotText mAccountText;
    private final SWTBotButton mSendButton;
    private final SWTBotButton mClearButton;

    protected OrderTicketViewFixture(final String id) throws Exception {
        AbstractUIRunner.syncRun(new ThrowableRunnable() {
            @Override
            @SuppressWarnings("unchecked")
            public void run() throws Exception {
                mRealView = (OrderTicketView<?, T>) PlatformUI.getWorkbench()
                        .getActiveWorkbenchWindow().getActivePage()
                        .showView(id);
            }
        });
        mView = mBot.viewById(id);
        SWTBot bot = mView.bot();
        mSideCombo = findSide(bot);
        mQuantityText = findQuantity(bot);
        SWTBotText findSymbol = bot.text(1);
        mSymbolText = findSymbol;
        mOrderTypeCombo = findOrderType(bot);
        mPriceText = findPrice(bot);
        mBrokerCombo = findBroker(bot);
        mTimeInForceCombo = findTimeInForce(bot);
        mAccountText = findAccount(bot);
        mSendButton = bot.button("Send");
        mClearButton = bot.button("Clear");
    }

    protected SWTBotCombo findSide(SWTBot bot) {
        return bot.comboBox(0);
    }

    protected SWTBotText findQuantity(SWTBot bot) {
        return bot.text(0);
    }

    protected SWTBotCombo findOrderType(SWTBot bot) {
        return bot.comboBox(1);
    }

    protected SWTBotText findPrice(SWTBot bot) {
        return bot.text(2);
    }

    protected SWTBotCombo findBroker(SWTBot bot) {
        return bot.comboBox(2);
    }

    protected SWTBotCombo findTimeInForce(SWTBot bot) {
        return bot.comboBox(3);
    }

    protected SWTBotText findAccount(SWTBot bot) {
        return bot.text(3);
    }

    public SWTBotView getView() {
        return mView;
    }

    /**
     * Warning: returned view must be accessed from UI thread.
     */
    public OrderTicketView<?, T> getRealView() {
        return mRealView;
    }

    public void assertTicket(String side, String quantity, String symbol,
            String orderType, String price, String broker, String timeInForce,
            String account) {
        assertThat(mSideCombo.getText(), is(side));
        assertThat(mQuantityText.getText(), is(quantity));
        assertThat(mSymbolText.getText(), is(symbol));
        assertThat(mOrderTypeCombo.getText(), is(orderType));
        assertThat(mPriceText.getText(), is(price));
        assertThat(mBrokerCombo.getText(), is(broker));
        assertThat(mTimeInForceCombo.getText(), is(timeInForce));
        assertThat(mAccountText.getText(), is(account));
    }

    public void assertEnabled(boolean side, boolean quantity, boolean symbol,
            boolean type, boolean price, boolean broker, boolean tif,
            boolean account) {
        assertThat(mSideCombo.isEnabled(), is(side));
        assertThat(mQuantityText.isEnabled(), is(quantity));
        assertThat(mSymbolText.isEnabled(), is(symbol));
        assertThat(mOrderTypeCombo.isEnabled(), is(type));
        assertThat(mPriceText.isEnabled(), is(price));
        assertThat(mBrokerCombo.isEnabled(), is(broker));
        assertThat(mTimeInForceCombo.isEnabled(), is(tif));
        assertThat(mAccountText.isEnabled(), is(account));
    }

    public SWTBotButton getSendButton() {
        return mSendButton;
    }

    public SWTBotButton getClearButton() {
        return mClearButton;
    }

    public SWTBotCombo getSideCombo() {
        return mSideCombo;
    }

    public SWTBotText getQuantityText() {
        return mQuantityText;
    }

    public SWTBotText getSymbolText() {
        return mSymbolText;
    }

    public SWTBotCombo getOrderTypeCombo() {
        return mOrderTypeCombo;
    }

    public SWTBotText getPriceText() {
        return mPriceText;
    }

    public SWTBotCombo getBrokerCombo() {
        return mBrokerCombo;
    }

    public SWTBotCombo getTimeInForceCombo() {
        return mTimeInForceCombo;
    }

    public SWTBotText getAccountText() {
        return mAccountText;
    }

    public void assertError(String errorText) {
        mView.bot().label(errorText);
    }
}


text:
package material

import (
	"log"
	"path/filepath"
	"strings"

	"gopkg.in/fsnotify.v1"
)

func watchShaders() (chan string, chan bool) {
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		log.Fatal(err)
	}

	event := make(chan string)
	quit := make(chan bool)

	// Process events
	go func() {
		for {
			select {
			case ev := <-watcher.Events:
				log.Println(ev)
				// expects filenames such as triangle-vert.glsl or triangle-frag.glsl
				if filepath.Ext(ev.Name) == ".glsl" && ev.Op == fsnotify.Write {
					b := filepath.Base(ev.Name)
					i := strings.LastIndex(b, "-")
					b = b[:i]
					event <- b
				}
			case err := <-watcher.Errors:
				log.Println("watch error:", err)
			case <-quit:
				watcher.Close()
				return
			}
		}
	}()

	err = watcher.Add("./assets")
	if err != nil {
		log.Fatal("Failed to watch folder.", err)
	}

	return event, quit
}


text:
package org.hl7.fhir.instance;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.hl7.fhir.instance.model.*;
import org.hl7.fhir.instance.model.api.*;

import ca.uhn.fhir.context.*;
import ca.uhn.fhir.context.support.IContextValidationSupport;
import ca.uhn.fhir.fluentpath.IFluentPath;
import ca.uhn.fhir.model.api.IFhirVersion;
import ca.uhn.fhir.model.base.composite.BaseCodingDt;
import ca.uhn.fhir.rest.api.IVersionSpecificBundleFactory;
import ca.uhn.fhir.rest.server.provider.dstu2hl7org.Dstu2Hl7OrgBundleFactory;
import ca.uhn.fhir.util.ReflectionUtil;

public class FhirDstu2Hl7Org implements IFhirVersion {

  private String myId;

  @Override
  public IFluentPath createFluentPathExecutor(FhirContext theFhirContext) {
    throw new UnsupportedOperationException("FluentPath is not supported in DSTU2 contexts");
  }

  @Override
  public IContextValidationSupport<?, ?, ?, ?, ?, ?> createValidationSupport() {
    throw new UnsupportedOperationException("Validation support is not supported in DSTU2 contexts");
  }

  @Override
  public StructureDefinition generateProfile(RuntimeResourceDefinition theRuntimeResourceDefinition, String theServerBase) {
    StructureDefinition retVal = new StructureDefinition();

    RuntimeResourceDefinition def = theRuntimeResourceDefinition;

    myId = def.getId();
    if (StringUtils.isBlank(myId)) {
      myId = theRuntimeResourceDefinition.getName().toLowerCase();
    }

    retVal.setId(myId);
    return retVal;
  }

  @SuppressWarnings("rawtypes")
  @Override
  public Class<ArrayList> getContainedType() {
    return ArrayList.class;
  }

  @Override
  public InputStream getFhirVersionPropertiesFile() {
    String path = "/org/hl7/fhir/instance/model/fhirversion.properties";
    InputStream str = FhirDstu2Hl7Org.class.getResourceAsStream(path);
    if (str == null) {
      str = FhirDstu2Hl7Org.class.getResourceAsStream(path.substring(1));
    }
    if (str == null) {
      throw new ConfigurationException("Can not find model property file on classpath: " + path);
    }
    return str;
  }

  @Override
  public IPrimitiveType<Date> getLastUpdated(IBaseResource theResource) {
    return ((Resource) theResource).getMeta().getLastUpdatedElement();
  }

  @Override
  public String getPathToSchemaDefinitions() {
    return "/org/hl7/fhir/instance/model/schema";
  }

  @Override
  public Class<Reference> getResourceReferenceType() {
    return Reference.class;
  }

  @Override
  public Object getServerVersion() {
    return ReflectionUtil.newInstanceOfFhirServerType("org.hl7.fhir.instance.FhirServerDstu2Hl7Org2");
  }

  @Override
  public FhirVersionEnum getVersion() {
    return FhirVersionEnum.DSTU2_HL7ORG;
  }

  @Override
  public IVersionSpecificBundleFactory newBundleFactory(FhirContext theContext) {
    return new Dstu2Hl7OrgBundleFactory(theContext);
  }

  @Override
  public BaseCodingDt newCodingDt() {
    throw new UnsupportedOperationException();
  }

  @Override
  public IIdType newIdType() {
    return new IdType();
  }

}


text:
//
// CryptoConfig.cs: Handles cryptographic implementations and OIDs mappings.
//
// Author:
//	Sebastien Pouliot (sebastien@ximian.com)
//	Tim Coleman (tim@timcoleman.com)
//
// (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) Tim Coleman, 2004
// Copyright (C) 2004-2007,2011 Novell, Inc (http://www.novell.com)
// Copyright (C) 2011 Xamarin Inc. http://www.xamarin.com
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System;

namespace Tweetinvi.Security
{
    public class CryptoConfig
    {
        public static object CreateFromName(string name)
        {
            if (name == "SHA1")
            {
                return Activator.CreateInstance<SHA1CryptoServiceProvider>();
            }

            return null;
        }
    }
}


text:
require 'dm-mongo-adapter'
require 'dm-core/spec/setup'

module DataMapper
  module Spec
    module Adapters

      class MongoAdapter < Adapter
      end

      use MongoAdapter

    end
  end
end


text:
<?php

namespace App\Weixin2\Models\Authorize;

class Authorizer extends \App\Common\Models\Weixin2\Authorize\Authorizer
{

    //应用类型 1:公众号 2:小程序 3:订阅号
    const APPTYPE_PUB = 1;

    const APPTYPE_MICROAPP = 2;

    const APPTYPE_SUB = 3;

    /**
     * 获取应用的信息
     *
     * @return array
     */
    public function getInfoByAppid($component_appid, $appid, $is_get_latest = false)
    {
        $cacheKey = $this->getCacheKey4Appid($component_appid, $appid);
        $cache = $this->getDI()->get('cache');
        $application = $cache->get($cacheKey);

        if ($is_get_latest || empty($application)) {
            $application = $this->findOne(array(
                'appid' => $appid,
                'component_appid' => $component_appid
            ));
            if (!empty($application)) {
                // 加缓存处理
                $expire_time = 5 * 60;
                $cache->save($cacheKey, $application, $expire_time);
            }
        }
        return $application;
    }

    /**
     * 获取有效的token信息
     *
     * @throws Exception
     * @return mixed array
     */
    public function getTokenByAppid($component_appid, $appid)
    {
        $token = $this->getInfoByAppid($component_appid, $appid, true);
        if ($token == null) {
            return null;
        }
        try {
            $token = $this->refreshInfo($token);
        } catch (\Exception $e) {
        }

        return $token;
    }

    public function createAndUpdateAuthorizer($component_appid, $appid, $access_token, $refresh_token, $expires_in, $func_info, $memo = array())
    {
        $lockKey = $this->getCacheKey4Appid($component_appid, $appid);
        $objLock = new \iLock($lockKey);
        if (!$objLock->lock()) {
            $token = $this->getInfoByAppid($component_appid, $appid);
            if (empty($token)) {
                // 创建
                $datas = array(
                    'component_appid' => $component_appid,
                    'appid' => $appid,
                    'access_token' => $access_token,
                    'access_token_expire' => \App\Common\Utils\Helper::getCurrentTime(time() + $expires_in),
                    'refresh_token' => $refresh_token,
                    'func_info' => \App\Common\Utils\Helper::myJsonEncode($func_info),
                    'memo' => $memo
                );
                return $this->insert($datas);
            } else {
                $memo = array_merge($token['memo'], $memo);
                return $this->updateAccessToken($token['_id'], $access_token, $refresh_token, $expires_in, $func_info, $memo);
            }
        }
    }

    public function updateAccessToken($id, $access_token, $refresh_token, $expires_in, $func_info, $memo = array())
    {
        $updateData = array();
        $updateData['access_token'] = $access_token;
        $updateData['refresh_token'] = $refresh_token;
        $updateData['access_token_expire'] = \App\Common\Utils\Helper::getCurrentTime(time() + $expires_in);
        if (!empty($func_info)) {
            $updateData['func_info'] = \App\Common\Utils\Helper::myJsonEncode($func_info);
        }
        if (!empty($memo)) {
            $updateData["memo"] = $memo;
        }
        $affectRows = $this->update(array('_id' => $id), array('$set' => $updateData));
        // 重新获取数据
        $newInfo = $this->getInfoById($id);
        if (!empty($newInfo)) {
            $expire_time = 5 * 60;
            $cache = $this->getDI()->get('cache');
            $cache->save($this->getCacheKey4Appid($newInfo['component_appid'], $newInfo['appid']), $newInfo, $expire_time);
        }
        return $newInfo;
    }

    public function updateJsapiTicket($id, $jsapi_ticket, $expires_in, $memo = array())
    {
        $updateData = array();
        $updateData['jsapi_ticket'] = $jsapi_ticket;
        $updateData['jsapi_ticket_expire'] = \App\Common\Utils\Helper::getCurrentTime(time() + $expires_in);
        if (!empty($memo)) {
            $updateData["memo"] = $memo;
        }
        $affectRows = $this->update(array('_id' => $id), array('$set' => $updateData));
        // 重新获取数据
        $newInfo = $this->getInfoById($id);
        if (!empty($newInfo)) {
            $expire_time = 5 * 60;
            $cache = $this->getDI()->get('cache');
            $cache->save($this->getCacheKey4Appid($newInfo['component_appid'], $newInfo['appid']), $newInfo, $expire_time);
        }

        return $newInfo;
    }

    public function updateWxcardApiTicket($id, $wx_card_api_ticket, $expires_in, $memo = array())
    {
        $updateData = array();
        $updateData['wx_card_api_ticket'] = $wx_card_api_ticket;
        $updateData['wx_card_api_ticket_expire'] = \App\Common\Utils\Helper::getCurrentTime(time() + $expires_in);
        if (!empty($memo)) {
            $updateData["memo"] = $memo;
        }
        $affectRows = $this->update(array('_id' => $id), array('$set' => $updateData));
        // 重新获取数据
        $newInfo = $this->getInfoById($id);
        if (!empty($newInfo)) {
            $expire_time = 5 * 60;
            $cache = $this->getDI()->get('cache');
            $cache->save($this->getCacheKey4Appid($newInfo['component_appid'], $newInfo['appid']), $newInfo, $expire_time);
        }

        return $newInfo;
    }

    public function updateAuthorizerInfo($id, $res, $orginalMemo)
    {
        $updateData = array();
        $memo = array();
        $memo['get_authorizer_info_ret'] = $res;
        $updateData['memo'] = array_merge($orginalMemo, $memo);
        $updateData['nick_name'] = $res['authorizer_info']['nick_name'];
        $updateData['head_img'] = $res['authorizer_info']['head_img'];
        $updateData['user_name'] = $res['authorizer_info']['user_name'];
        $updateData['alias'] = $res['authorizer_info']['alias'];
        $updateData['qrcode_url'] = $res['authorizer_info']['qrcode_url'];
        // $updateData['principal_name'] = $res['authorizer_info']['principal_name'];
        // $updateData['signature'] = $res['authorizer_info']['signature'];
        $affectRows = $this->update(array('_id' => $id), array('$set' => $updateData));
        return $affectRows;
    }

    public function getSignKey($openid, $secretKey, $timestamp = 0)
    {
        return sha1($openid . "|" . $secretKey . "|" . $timestamp);
    }

    private function getCacheKey4Appid($component_appid, $appid)
    {
        $cacheKey = "authorizer:component_appid:{$component_appid}:appid:{$appid}";
        $cacheKey = \App\Common\Utils\Helper::myCacheKey(__CLASS__, $cacheKey);
        return $cacheKey;
    }

    private function refreshInfo($token)
    {
        if (empty($token['access_token_expire']) || strtotime($token['access_token_expire']) <= time()) {
            if (((!empty($token['refresh_token']) && !empty($token['component_appid'])) || empty($token['component_appid'])) && !empty($token['appid'])) {
                $lockKey = \App\Common\Utils\Helper::myCacheKey(__CLASS__, __METHOD__, __LINE__, $token['component_appid'], $token['appid']);
                $objLock = new \iLock($lockKey);
                if (!$objLock->lock()) {
                    // 如果是微信开放平台的话
                    if (!empty($token['component_appid'])) {
                        $modelComponent = new \App\Weixin2\Models\Component\Component();
                        $componentInfo = $modelComponent->getInfoByAppId($token['component_appid'], true);
                        if (!empty($componentInfo)) {
                            $objToken = new \Weixin\Component($componentInfo['appid'], $componentInfo['appsecret']);
                            $objToken->setAccessToken($componentInfo['access_token']);
                            $arrToken = $objToken->apiAuthorizerToken($token['appid'], $token['refresh_token']);
                            $token = $this->updateAccessToken($token['_id'], $arrToken['authorizer_access_token'], $arrToken['authorizer_refresh_token'], $arrToken['expires_in'], null);
                        }
                    } else {
                        // 如果不是微信开放平台的话
                        $objToken = new \Weixin\Token\Server($token['appid'], $token['appsecret']);
                        $arrToken = $objToken->getAccessToken();
                        if (!isset($arrToken['access_token'])) {
                            throw new \Exception(\App\Common\Utils\Helper::myJsonEncode($arrToken));
                        }
                        if (!isset($arrToken['refresh_token'])) {
                            $arrToken['refresh_token'] = $arrToken['access_token'];
                        }
                        $token = $this->updateAccessToken($token['_id'], $arrToken['access_token'], $arrToken['refresh_token'], $arrToken['expires_in'], null);
                    }
                }
            }
        }

        // 缓存有效期不能超过token过期时间
        if ((time() + $this->_expire) > strtotime($token['access_token_expire'])) {
            $this->_expire = strtotime($token['access_token_expire']) - time();
        }

        jsnoLock:
        // 获取jsapi_ticket
        if (empty($token['jsapi_ticket_expire']) || strtotime($token['jsapi_ticket_expire']) <= time()) {
            if (!empty($token['access_token'])) {
                $lockKey = \App\Common\Utils\Helper::myCacheKey(__CLASS__, __METHOD__, __LINE__, $token['appid']);
                $objLock = new \iLock($lockKey);
                if (!$objLock->lock()) {
                    // 获取jsapi_ticket
                    $objJssdk = new \Weixin\Jssdk();
                    $objJssdk->setAppId($token['appid']);
                    $objJssdk->setAccessToken($token['access_token']);
                    $arrJsApiTicket = $objJssdk->getJsApiTicket();
                    $token = $this->updateJsapiTicket($token['_id'], $arrJsApiTicket['ticket'], $arrJsApiTicket['expires_in']);
                }
            }
        }

        weixincardnoLock:
        // 获取微信卡券的api_ticket
        if (!empty($token['is_weixin_card'])) {
            if (empty($token['wx_card_api_ticket_expire']) || strtotime($token['wx_card_api_ticket_expire']) <= time()) {
                if (!empty($token['access_token'])) {
                    $lockKey = \App\Common\Utils\Helper::myCacheKey(__CLASS__, __METHOD__, __LINE__, $token['appid']);
                    $objLock = new \iLock($lockKey);
                    if (!$objLock->lock()) {
                        // 获取微信卡券的api_ticket
                        $weixin = new \Weixin\Client();
                        $weixin->setAccessToken($token['access_token']);
                        $ret = $weixin->getCardManager()->getApiTicket();
                        $token = $this->updateWxcardApiTicket($token['_id'], $ret['ticket'], $ret['expires_in']);
                    }
                }
            }
        }
        return $token;
    }

    protected $_expire = 0;
}


text:
<?php

namespace Dez\Db;

/**
 * Class Stmt
 * @package Dez\Db
 */
class Stmt extends \PDOStatement implements StmtInterface
{

  /**
   * @var Connection|null
   */
  protected $connection = null;

  /**
   * Stmt constructor.
   * @param Connection $connection
   */
  protected function __construct(Connection $connection)
  {
    $this->connection = $connection;
  }

  /**
   * @param null $parameter
   * @param null $value
   * @param null $type
   * @param null $maxLength
   * @param null $driverData
   * @return $this
   */
  public function bindParam($parameter = null, & $value = null, $type = null, $maxLength = null, $driverData = null)
  {
    parent::bindParam($parameter, $value, $type);
    return $this;
  }

  /**
   * @param array $params
   * @return $this
   */
  public function bindParams(array $params = [])
  {
    foreach ($params as $parameter => & $value) {
      $this->bindParam((is_numeric($parameter) ? $parameter + 1 : $parameter), $value, Connection::PARAM_STR);
    }
    return $this;
  }

  /**
   * @param null $parameter
   * @param null $value
   * @param null $type
   * @return $this
   */
  public function bindValue($parameter = null, $value = null, $type = null)
  {
    parent::bindValue($parameter, $value, $type);
    return $this;
  }

  /**
   * @param array $params
   * @return $this
   */
  public function multiBind(array $params = [])
  {
    foreach ($params as $parameter => $value) {
      $this->bindValue((is_numeric($parameter) ? $parameter + 1 : $parameter), $value, Connection::PARAM_STR);
    }
    return $this;
  }

  /**
   * @param array $params
   * @return $this
   */
  public function execute($params = [])
  {
    if (count($params) > 0) {
      $this->bindParams($params);
    }
    parent::execute();
    return $this;
  }

  /**
   * @return int
   */
  public function numRows()
  {
    return parent::rowCount();
  }

  /**
   * @return mixed
   */
  public function loadArray()
  {
    return $this->fetch(Connection::FETCH_ASSOC);
  }

  /**
   * @return mixed
   */
  public function loadNum()
  {
    return $this->fetch(Connection::FETCH_NUM);
  }

  /**
   * @return mixed
   */
  public function loadObject()
  {
    return $this->fetch(Connection::FETCH_OBJ);
  }

  /**
   * @param $class
   * @return mixed
   * @throws DbException
   */
  public function loadWithClass($class = \stdClass::class)
  {
    throw new DbException('[:method] Not implement yet...', [
      'method' => __METHOD__,
    ]);
  }

  /**
   * @return mixed
   */
  public function loadColumn()
  {
    return $this->fetch(Connection::FETCH_COLUMN);
  }

  /**
   * @param string $target
   * @return null|string
   * @throws DbException
   */
  public function loadIntoObject($target = \stdClass::class)
  {
    if (is_string($target) && class_exists($target)) {
      $object = new $target();
    } else if (is_object($target)) {
      $object = $target;
    } else {
      throw new DbException('Target object or class ":class" not found', [
        'class' => is_object($target) ? get_class($target) : $target
      ]);
    }

    $row = $this->loadObject();
    if (!$row) return null;

    foreach ($row as $key => $value) {
      $object->$key = $value;
    }

    return $object;
  }

  /**
   * @param null $style
   * @param int $cursor
   * @param int $cursorOffset
   * @return mixed
   */
  public function fetch($style = null, $cursor = \PDO::FETCH_ORI_NEXT, $cursorOffset = 0)
  {
    return parent::fetch($style, $cursor, $cursorOffset);
  }

}


text:
package com.creditease.agent.feature.monitoragent.handlers;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.creditease.agent.helpers.JSONHelper;
import com.creditease.agent.http.api.UAVHttpMessage;
import com.creditease.agent.monitor.api.MonitorDataFrame;
import com.creditease.agent.spi.AbstractHttpHandler;

public class MDFListenServerHandler extends AbstractHttpHandler<UAVHttpMessage> {

    public MDFListenServerHandler(String cName, String feature) {
        super(cName, feature);
    }

    @Override
    public String getContextPath() {

        return "/ma/put/mdf";
    }

    @SuppressWarnings("rawtypes")
    @Override
    public void handle(UAVHttpMessage data) {

        try {
            String body = data.getRequest(UAVHttpMessage.BODY);

            List<MonitorDataFrame> mdfs = new ArrayList<MonitorDataFrame>();

            // MDF array
            if (body.indexOf("[") == 0) {
                List<Map> mdfList = JSONHelper.toObjectArray(body, Map.class);

                for (Map mdfMap : mdfList) {
                    MonitorDataFrame mdf = new MonitorDataFrame(mdfMap);
                    mdfs.add(mdf);
                }

            }
            // MDF
            else {
                MonitorDataFrame mdf = new MonitorDataFrame(body);
                mdfs.add(mdf);
            }

            // send MDFs
            MonitorDataPublishHandler mdph = (MonitorDataPublishHandler) this.getConfigManager()
                    .getComponent(this.feature, "MonitorDataPublishHandler");

            mdph.handle(mdfs);

            data.putResponse(UAVHttpMessage.RESULT, "OK");
        }
        catch (Exception e) {
            data.putResponse(UAVHttpMessage.ERR, e.getMessage());
        }
    }

}


text:
package com.tvntd.service.user;

import java.util.LinkedList;
import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.tvntd.forms.QuestionForm.AnsChoice;
import com.tvntd.forms.QuestionForm.AnsInput;
import com.tvntd.forms.QuestionForm.AnswerForm;
import com.tvntd.models.Answer;
import com.tvntd.models.Question;
import com.tvntd.service.api.IAnswerSvc;

@Service
@Transactional
public class AnswerSvc implements IAnswerSvc
{
    @Override
    public List<AnswerDTO> getAnswers(String articleUuid)
    {
        return null;
    }

    @Override
    public List<Answer> processAnswerForm(AnswerForm form, Question quest)
    {
        AnsChoice[] choices = form.getChoices();
        if (choices != null) {
            return fillinChoices(choices, quest);
        }
        AnsInput input = form.getInput();
        if (input != null) {
            return fillinInput(input, quest);
        }
        return null;
    }

    protected List<Answer> fillinChoices(AnsChoice[] choices, Question quest)
    {
        List<Answer> out = new LinkedList<>();
        String artUuid   = quest.getArticleUuid();
        String questUuid = quest.getQuestUuid();

        for (AnsChoice ans : choices) {
            out.add(new Answer(artUuid, questUuid, ans.getChoice(), ans.getCorrect()));
        }
        return out;
    }

    protected List<Answer> fillinInput(AnsInput input, Question quest)
    {
        List<Answer> out = new LinkedList<>();
        String artUuid   = quest.getArticleUuid();
        String questUuid = quest.getQuestUuid();

        out.add(new Answer(artUuid, questUuid, input.getAnsInput(),
                    input.getAnsHolder(), input.getAnsValidate()));
        return out;
    }
}


text:
require 'spec_helper'

describe CASinoCore::Model::ServiceRule do
  describe '.allowed?' do
    context 'with an empty table' do
      ['https://www.example.org/', 'http://www.google.com/'].each do |service_url|
        it "allows access to #{service_url}" do
          described_class.allowed?(service_url).should == true
        end
      end
    end

    context 'with a regex rule' do
      before(:each) do
        FactoryBot.create :service_rule, :regex, url: '^https://.*'
      end

      ['https://www.example.org/', 'https://www.google.com/'].each do |service_url|
        it "allows access to #{service_url}" do
          described_class.allowed?(service_url).should == true
        end
      end

      ['http://www.example.org/', 'http://www.google.com/'].each do |service_url|
        it "does not allow access to #{service_url}" do
          described_class.allowed?(service_url).should == false
        end
      end
    end

    context 'with many regex rules' do
      before(:each) do
        100.times do |counter|
          FactoryBot.create :service_rule, :regex, url: "^https://www#{counter}.example.com"
        end
      end

      let(:service_url) { 'https://www111.example.com/bla' }

      it 'does not take too long to check a denied service' do
        start = Time.now
        described_class.allowed?(service_url).should == false
        (Time.now - start).should < 0.1
      end
    end

    context 'with a non-regex rule' do
      before(:each) do
        FactoryBot.create :service_rule, url: 'https://www.google.com/foo'
      end

      ['https://www.google.com/foo'].each do |service_url|
        it "allows access to #{service_url}" do
          described_class.allowed?(service_url).should == true
        end
      end

      ['https://www.example.org/', 'http://www.example.org/', 'https://www.google.com/test'].each do |service_url|
        it "does not allow access to #{service_url}" do
          described_class.allowed?(service_url).should == false
        end
      end
    end
  end
end


text:
<!DOCTYPE html>

    <title>Pickle - {{title}}</title>

    <link rel="stylesheet" href="/assets/css/bootstrap.css"/>
    <link rel="stylesheet" href="/assets/css/font-awesome.css"/>
    <link rel="stylesheet" href="/assets/css/pickle.css"/>

            {% block header %}
                {% include "partials/header.html" %}
            {% endblock %}

            {% include "partials/flash.html" with { "type": "info" } %}
            {% include "partials/flash.html" with { "type": "success" } %}
            {% include "partials/flash.html" with { "type": "warning" } %}
            {% include "partials/flash.html" with { "type": "error", class: "danger" } %}

            {% block content %}{% endblock %}

© Copyright 2015 by Pickle.


text:
package io.github.rcarlosdasilva.weixin.model.response.comment.bean;

import com.google.gson.annotations.SerializedName;

public class Reply {

  private String content;
  @SerializedName("create_time")
  private long time;

  /**
   * 作者回复内容
   *
   * @return content
   */
  public String getContent() {
    return content;
  }

  /**
   * 作者回复时间
   *
   * @return create_time
   */
  public long getTime() {
    return time;
  }

}


text:
FROM jboss/wildfly:latest

MAINTAINER Lin Gao <lgao@redhat.com>

USER root

# install softwares
RUN yum -y update \
  && yum install -y java-1.8.0-openjdk java-1.8.0-openjdk-devel \
  postgresql-server postgresql-libs postgresql \
  openssh-server \
  passwd wget which curl tree \
  && yum clean all

# prepare mount point
RUN chown -R jboss.jboss /opt/

# configure postgresql server
USER postgres
WORKDIR /var/lib/pgsql
RUN rm -rf /var/lib/pgsql/data
RUN initdb -A trust -D /var/lib/pgsql/data
RUN echo "host all all 0.0.0.0/0 trust" >> /var/lib/pgsql/data/pg_hba.conf
RUN echo "listen_addresses = '*'" >> /var/lib/pgsql/data/postgresql.conf
RUN pg_ctl start -D /var/lib/pgsql/data -l data/pg.log && sleep 5 && createuser -s -w newcastle && createdb -O newcastle newcastle

USER jboss
WORKDIR /opt/
RUN rm -rf /opt/jboss/wildfly/standalone/configuration/standalone.xml && rm -rf /opt/jboss/wildfly/standalone/deployments && ln -s /mnt/deployments /opt/jboss/wildfly/standalone/deployments

RUN echo "JAVA_OPTS=\"\$JAVA_OPTS -Dpnc-config-file=/mnt/config/pnc-config.json -Djenkins-job-template=/mnt/config/job-template.xml\"" >> /opt/jboss/wildfly/bin/standalone.conf

# pnc standalone.xml
ADD standalone.xml /opt/jboss/wildfly/standalone/configuration/

# postgresql jdbc driver module
RUN mkdir -p /opt/jboss/wildfly/modules/system/layers/base/org/postgresql/main/
ADD module.xml /opt/jboss/wildfly/modules/system/layers/base/org/postgresql/main/
RUN wget -O /opt/jboss/wildfly/modules/system/layers/base/org/postgresql/main/postgresql-9.3-1103-jdbc4.jar http://repo1.maven.org/maven2/org/postgresql/postgresql/9.3-1103-jdbc4/postgresql-9.3-1103-jdbc4.jar

# install aprox
RUN wget -O aprox.zip http://repo1.maven.org/maven2/org/commonjava/aprox/launch/aprox-launcher-savant/0.19.1/aprox-launcher-savant-0.19.1-launcher.zip
RUN unzip -q -d /opt/ aprox.zip

ENV APROX_HOME "/opt/aprox/"

EXPOSE 5432 8080 8090 9990

ADD start.sh /opt/

VOLUME ["/mnt/deployments", "/mnt/config"]

USER root
RUN chmod a+x /opt/start.sh
RUN update-alternatives --set java /usr/lib/jvm/jre-1.8.0-openjdk.x86_64/bin/java

CMD ["/opt/start.sh"]


text:
// <copyright file="EnvironmentInfoProvider.cs" company="App Metrics Contributors">
// Copyright (c) App Metrics Contributors. All rights reserved.
// </copyright>

using System;
using System.Globalization;

namespace App.Metrics.Infrastructure
{
    public sealed class EnvironmentInfoProvider
    {
        public EnvironmentInfo Build()
        {
            var localTimeString = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.ffffK", CultureInfo.InvariantCulture);

            return new EnvironmentInfo(
                EnvironmentInfoProviderCache.Instance.RunningEnvironment,
                EnvironmentInfoProviderCache.Instance.FrameworkDescription,
                EnvironmentInfoProviderCache.Instance.EntryAssemblyName,
                EnvironmentInfoProviderCache.Instance.EntryAssemblyVersion,
                localTimeString,
                EnvironmentInfoProviderCache.Instance.MachineName,
                EnvironmentInfoProviderCache.Instance.OperatingSystemPlatform,
                EnvironmentInfoProviderCache.Instance.OperatingSystemVersion,
                EnvironmentInfoProviderCache.Instance.OperatingSystemArchitecture,
                EnvironmentInfoProviderCache.Instance.ProcessArchitecture,
                EnvironmentInfoProviderCache.Instance.ProcessorCount);
        }
    }
}


text:
using osu.Framework.Bindables;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics.Sprites;
using osuTK.Graphics;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Input.Events;
using osu.Framework.Localisation;

namespace osu.Framework.Graphics.UserInterface
{
    public class BasicButton : Button
    {
        public LocalisableString Text
        {
            get => SpriteText?.Text ?? default;
            set
            {
                if (SpriteText != null)
                    SpriteText.Text = value;
            }
        }

        public Color4 BackgroundColour
        {
            get => Background.Colour;
            set => Background.FadeColour(value);
        }

        private Color4? flashColour;

        /// <summary>
        /// The colour the background will flash with when this button is clicked.
        /// </summary>
        public Color4 FlashColour
        {
            get => flashColour ?? BackgroundColour;
            set => flashColour = value;
        }

        /// <summary>
        /// The additive colour that is applied to the background when hovered.
        /// </summary>
        public Color4 HoverColour
        {
            get => Hover.Colour;
            set => Hover.FadeColour(value);
        }

        private Color4 disabledColour = Color4.Gray;

        /// <summary>
        /// The additive colour that is applied to this button when disabled.
        /// </summary>
        public Color4 DisabledColour
        {
            get => disabledColour;
            set
            {
                if (disabledColour == value)
                    return;

                disabledColour = value;
                Enabled.TriggerChange();
            }
        }

        /// <summary>
        /// The duration of the transition when hovering.
        /// </summary>
        public double HoverFadeDuration { get; set; } = 200;

        /// <summary>
        /// The duration of the flash when this button is clicked.
        /// </summary>
        public double FlashDuration { get; set; } = 200;

        /// <summary>
        /// The duration of the transition when toggling the Enabled state.
        /// </summary>
        public double DisabledFadeDuration { get; set; } = 200;

        protected Box Hover;
        protected Box Background;
        protected SpriteText SpriteText;

        public BasicButton()
        {
            AddRange(new Drawable[]
            {
                Background = new Box
                {
                    Anchor = Anchor.Centre,
                    Origin = Anchor.Centre,
                    RelativeSizeAxes = Axes.Both,
                    Colour = FrameworkColour.BlueGreen
                },
                Hover = new Box
                {
                    Alpha = 0,
                    Anchor = Anchor.Centre,
                    Origin = Anchor.Centre,
                    RelativeSizeAxes = Axes.Both,
                    Colour = Color4.White.Opacity(.1f),
                    Blending = BlendingParameters.Additive
                },
                SpriteText = CreateText()
            });

            Enabled.BindValueChanged(enabledChanged, true);
        }

        protected virtual SpriteText CreateText() => new SpriteText
        {
            Depth = -1,
            Origin = Anchor.Centre,
            Anchor = Anchor.Centre,
            Font = FrameworkFont.Regular,
            Colour = FrameworkColour.Yellow
        };

        protected override bool OnClick(ClickEvent e)
        {
            if (Enabled.Value)
                Background.FlashColour(FlashColour, FlashDuration);

            return base.OnClick(e);
        }

        protected override bool OnHover(HoverEvent e)
        {
            if (Enabled.Value)
                Hover.FadeIn(HoverFadeDuration);

            return base.OnHover(e);
        }

        protected override void OnHoverLost(HoverLostEvent e)
        {
            base.OnHoverLost(e);

            Hover.FadeOut(HoverFadeDuration);
        }

        private void enabledChanged(ValueChangedEvent<bool> e)
        {
            this.FadeColour(e.NewValue ? Color4.White : DisabledColour, DisabledFadeDuration, Easing.OutQuint);
        }
    }
}


text:
#include "benchmark/algorithm.hpp"
#include "wx_ppc.hpp"

using wm_ppc_8  = wx_ppc<uint8_t, false>;
using wm_ppc_16 = wx_ppc<uint16_t, false>;
using wm_ppc_32 = wx_ppc<uint32_t, false>;

CONSTRUCTION_REGISTER("wm_ppc",
  "Parallel wavelet matrix construction with 8-bit alphabet "
  "(using counting).", wm_ppc_8)
CONSTRUCTION_REGISTER("wm_ppc",
  "Parallel wavelet matrix construction with 16-bit alphabet "
  "(using counting).", wm_ppc_16)
CONSTRUCTION_REGISTER("wm_ppc",
  "Parallel wavelet matrix construction with 32-bit alphabet "
  "(using counting).", wm_ppc_32)

using wt_ppc_8  = wx_ppc<uint8_t, true>;
using wt_ppc_16 = wx_ppc<uint16_t, true>;
using wt_ppc_32 = wx_ppc<uint32_t, true>;

CONSTRUCTION_REGISTER("wt_ppc",
  "Parallel wavelet tree construction with 8-bit alphabet "
  "(using counting).", wt_ppc_8)
CONSTRUCTION_REGISTER("wt_ppc",
  "Parallel wavelet tree construction with 16-bit alphabet "
  "(using counting).", wt_ppc_16)
CONSTRUCTION_REGISTER("wt_ppc",
  "Parallel wavelet tree construction with 32-bit alphabet "
  "(using counting).", wt_ppc_32)

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


text:
Rails.application.routes.draw do

  mount MfgOrderx::Engine => "/mfg_orderx"
  mount Authentify::Engine => "/authentify"
  mount Commonx::Engine => "/commonx"
  mount JobshopRfqx::Engine => '/jobshop_rfqx'
  mount JobshopQuotex::Engine => '/jobshop_quotex'
  mount Kustomerx::Engine => '/kustomerx'
  mount MfgProcessx::Engine => '/mfg_processx'
  mount EventTaskx::Engine => '/event_taskx'

  resource :session

  root :to => "authentify::sessions#new"
  match '/signin',  :to => 'authentify::sessions#new'
  match '/signout', :to => 'authentify::sessions#destroy'
  match '/user_menus', :to => 'user_menus#index'
  match '/view_handler', :to => 'authentify::application#view_handler'
end


text:
function editaregistro_clasificado(id){
    var json = {
        id: id,
        accion: "obtener_datos"
    };

    $.ajax({
        data: {json: $.toJSON(json) },
        type: 'POST',
        dataType: 'json',
        url: 'pages/layout/clasificados_data.php',
        success: function(data){
            //alert(data.msg);
            $("#formulario_clasificados #id").val(id);
            $("#formulario_clasificados #texto_corto").val(data.texto_corto);
            $("#formulario_clasificados #texto_largo").val(data.texto_largo);
            $("#formulario_clasificados #libro").val(data.libro);

            $("#formulario_clasificados #titulo_formulario").html("Editar clasificado.");
            $("#formulario_clasificados .box-body").show("slow");
            $("#formulario_clasificados #accion").val("e");
        }
   });
}
function enviar_form_clasificado(){
    var json = {
        id: $("#formulario_clasificados #id").val() ,
        texto_corto: $("#formulario_clasificados #texto_corto").val() ,
        texto_largo: $("#formulario_clasificados #texto_largo").val() ,
        libro: $("#formulario_clasificados #libro").val(),
        accion: $("#formulario_clasificados #accion").val()
    };
    $.ajax({
        data: {json: $.toJSON(json) },
        type: 'POST',
        dataType: 'json',
        url: 'pages/layout/clasificados_data.php',
        success: function(data){
                alert(data.msg);
                refreshDivs('cuerpocentro','pages/layout/clasificados.php');
        }
   });
}
function borrar_clasificado(id){
    var json = {
        id: id,
        accion: "d"
    };
    $.ajax({
        data: {json: $.toJSON(json) },
        type: 'POST',
        dataType: 'json',
        url: 'pages/layout/clasificados_data.php',
        success: function(data){
            alert(data.msg);
            refreshDivs('cuerpocentro','pages/layout/clasificados.php');
        }
   });
}
function formateartabla(){
    $("#lista_clasif").DataTable( {
        "language": {
            "lengthMenu": "Mostrando _MENU_ registros por pagina",
            "zeroRecords": "No se encontraron registros",
            "info": "Mostrando pagina _PAGE_ de _PAGES_",
            "infoEmpty": "No se encontraron registros",
            "infoFiltered": "(_MAX_ registros totales)",
            "paginate": {
                "previous": "Anterior",
                "next": "Siguiente"
            },
            "search": "Filtrar:"
        }
    } );
}
function solicitarcolaborar(id){
    var json = {
        id: id,
        accion: "solicitarcolaborar"
    };
    $.ajax({
        data: {json: $.toJSON(json) },
        type: 'POST',
        dataType: 'json',
        url: 'pages/layout/clasificados_data.php',
        success: function(data){
            alert(data.msg);
            refreshDivs('cuerpocentro','pages/layout/clasificados_lista.php');
            formateartabla();
        }
   });
}


text:
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using CK.CodeGen;
using FluentAssertions;

namespace System
{
    using System.Reflection;
    public static class CKFixDBNull
    {
        public static object Value = typeof( object ).Assembly.GetType( "System.DBNull" ).GetField( "Value" ).GetValue( null );
    }
}

namespace CK.CodeGen.Roslyn.Tests
{

    [TestFixture]
    public class CompileWithCodeModuleTests
    {
        class DoChangeDBNull : ICodeGeneratorModule
        {
            class DBNullToCKFixRewriter : CSharpSyntaxRewriter
            {
                public override SyntaxNode VisitIdentifierName( IdentifierNameSyntax node )
                {
                    if( node.Identifier.Text == "DBNull" )
                    {
                        return node.WithIdentifier( SyntaxFactory.Identifier( "CKFixDBNull" ) );
                    }
                    return node;
                }

                public static SyntaxTree Run( SyntaxTree t )
                {
                    return t.WithRootAndOptions( new DBNullToCKFixRewriter().Visit( t.GetRoot() ), t.Options );
                }
            }

            public IReadOnlyList<SyntaxTree> Rewrite( IReadOnlyList<SyntaxTree> trees )
            {
                return trees.Select( t => DBNullToCKFixRewriter.Run( t ) ).ToList();
            }

            public void Inject( ICodeWorkspace code )
            {
                code.Global
                    .EnsureUsing( "System" )
                    .EnsureUsing( "System.Reflection" )
                    .Append(
                      @"static class CKFixDBNull
                        {
                            // This was the original required code (before netcoreapp2.0):
                            // public static object Value = typeof( object ).Assembly.GetType( ""System.DBNull"" ).GetField( ""Value"" ).GetValue( null );
                            // Here we use a stupid value for the demo.
                            public static object Value = ""I'm the DBNull."";
                        }" );
            }
        }

        class ThisModuleUsesTheRealDBNullValue : ICodeGeneratorModule
        {
            public IReadOnlyList<SyntaxTree> Rewrite( IReadOnlyList<SyntaxTree> trees ) => trees;

            public void Inject( ICodeWorkspace code )
            {
                code.Global
                    .EnsureUsing( "System" )
                    .CreateType( "public static class RealDBNull" )
                    .Append( "public static object V = DBNull.Value;" ).NewLine();
            }

        }

        [Test]
        public void demonstrating_simple_transformations()
        {
            var workspace = CodeWorkspace.Create();
            workspace.Global
                .FindOrCreateNamespace( "Original" )
                .EnsureUsing( "System" )
                .CreateType( "public static class DBNullWillBeReplaced" )
                .Append( "public static object V = DBNull.Value;" ).NewLine();

            var gen = new CodeGenerator( CodeWorkspace.Factory );
            gen.Modules.Add( new DoChangeDBNull() );
            gen.Modules.Add( new ThisModuleUsesTheRealDBNullValue() );

            var r = gen.Generate( workspace, TestHelper.RandomDllPath, false, Assembly.LoadFrom );
            r.LogResult( TestHelper.Monitor );
            r.Success.Should().BeTrue();
            gen.Modules.Should().BeEmpty();

            var replaced = r.Assembly.ExportedTypes.Single( t => t.FullName == "Original.DBNullWillBeReplaced" );
            replaced.GetField( "V", BindingFlags.Static | BindingFlags.Public ).GetValue( null )
                .Should().Be( "I'm the DBNull." );

            var real = r.Assembly.ExportedTypes.Single( t => t.FullName == "RealDBNull" );
            real.GetField( "V", BindingFlags.Static | BindingFlags.Public ).GetValue( null )
                .Should().Be( DBNull.Value );

        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<XnaContent xmlns:Pipeline="Microsoft.Xna.Framework.Content.Pipeline">
  <Asset Type="Pipeline:BuildItemCollection">
    <Item>
      <Source>Sprites\Characters\01.png</Source>
      <Name>Sprites\Characters\01</Name>
      <Importer>TextureImporter</Importer>
      <Processor>TextureProcessor</Processor>
      <Options>None</Options>
      <Output>C:\Users\Max\Documents\GIT-REPOS\Game-Projects\JulietDreamLand\JulietDreamLand\JulietDreamLand\JulietDreamLand\bin\x86\Debug\Content\Sprites\Characters\01.xnb</Output>
      <Time>2015-03-09T09:17:57.8612951-04:00</Time>
    </Item>
    <BuildSuccessful>true</BuildSuccessful>
    <Settings>
      <ContentProjectGUID>{96ACC1DE-42CA-417E-9B5B-E9D4B836C7C6}</ContentProjectGUID>
      <TargetPlatform>Windows</TargetPlatform>
      <TargetProfile>Reach</TargetProfile>
      <BuildConfiguration>Debug</BuildConfiguration>
      <CompressContent>false</CompressContent>
      <RootDirectory>C:\Users\Max\Documents\GIT-REPOS\Game-Projects\JulietDreamLand\JulietDreamLand\JulietDreamLand\JulietDreamLandContent\</RootDirectory>
      <LoggerRootDirectory>C:\Users\Max\Documents\GIT-REPOS\Game-Projects\JulietDreamLand\JulietDreamLand\JulietDreamLand\JulietDreamLand\</LoggerRootDirectory>
      <IntermediateDirectory>C:\Users\Max\Documents\GIT-REPOS\Game-Projects\JulietDreamLand\JulietDreamLand\JulietDreamLand\JulietDreamLand\obj\x86\Debug\</IntermediateDirectory>
      <OutputDirectory>C:\Users\Max\Documents\GIT-REPOS\Game-Projects\JulietDreamLand\JulietDreamLand\JulietDreamLand\JulietDreamLand\bin\x86\Debug\Content\</OutputDirectory>
    </Settings>
    <Assemblies>
      <Assembly>
        <Key>C:\Program Files (x86)\Microsoft XNA\XNA Game Studio\v4.0\References\Windows\x86\Microsoft.Xna.Framework.Content.Pipeline.XImporter.dll</Key>
        <Value>2011-09-01T16:22:30-04:00</Value>
      </Assembly>
      <Assembly>
        <Key>C:\Program Files (x86)\Microsoft XNA\XNA Game Studio\v4.0\References\Windows\x86\Microsoft.Xna.Framework.Content.Pipeline.VideoImporters.dll</Key>
        <Value>2011-09-01T16:22:30-04:00</Value>
      </Assembly>
      <Assembly>
        <Key>C:\Program Files (x86)\Microsoft XNA\XNA Game Studio\v4.0\References\Windows\x86\Microsoft.Xna.Framework.Content.Pipeline.TextureImporter.dll</Key>
        <Value>2011-09-01T16:22:30-04:00</Value>
      </Assembly>
      <Assembly>
        <Key>C:\Program Files (x86)\Microsoft XNA\XNA Game Studio\v4.0\References\Windows\x86\Microsoft.Xna.Framework.Content.Pipeline.FBXImporter.dll</Key>
        <Value>2011-09-01T16:22:30-04:00</Value>
      </Assembly>
      <Assembly>
        <Key>C:\Program Files (x86)\Microsoft XNA\XNA Game Studio\v4.0\References\Windows\x86\Microsoft.Xna.Framework.Content.Pipeline.EffectImporter.dll</Key>
        <Value>2011-09-01T16:22:30-04:00</Value>
      </Assembly>
      <Assembly>
        <Key>C:\Program Files (x86)\Microsoft XNA\XNA Game Studio\v4.0\References\Windows\x86\Microsoft.Xna.Framework.Content.Pipeline.AudioImporters.dll</Key>
        <Value>2011-09-01T16:22:30-04:00</Value>
      </Assembly>
      <Assembly>
        <Key>C:\windows\Microsoft.Net\assembly\GAC_32\Microsoft.Xna.Framework.Content.Pipeline\v4.0_4.0.0.0__842cf8be1de50553\Microsoft.Xna.Framework.Content.Pipeline.dll</Key>
        <Value>2015-03-08T00:21:57.8158645-04:00</Value>
      </Assembly>
    </Assemblies>
  </Asset>
</XnaContent>


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>src/core/depthBuf.js - xeoengine</title>
    <link rel="stylesheet" href="http://yui.yahooapis.com/3.9.1/build/cssgrids/cssgrids-min.css">
    <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
    <link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
    <link rel="icon" href="../assets/favicon.ico">

            API Docs for: 0.1.0

APIs

Classes

Modules

                            <input type="search" id="api-filter" placeholder="Type to filter APIs">

AmbientLight

Camera

Canvas

Clip

Clips

ColorBuf

ColorTarget

Component

Configs

DepthBuf

DepthTarget

DirLight

Fresnel

Frustum

GameObject

Geometry

Input

Layer

Lights

Lookat

Material

math

Modes

MorphTargets

Ortho

PBRMaterial

Perspective

PhongMaterial

PointLight

Quaternion

Reflect

Rotate

Scale

Scene

Shader

ShaderParams

Stage

Stats

Task

Tasks

Texture

Transform

Translate

Visibility

XEO

XEO

                    Show:

                        <input type="checkbox" id="api-show-inherited" checked>
                        Inherited

                        <input type="checkbox" id="api-show-protected">
                        Protected

                        <input type="checkbox" id="api-show-private">
                        Private

                        <input type="checkbox" id="api-show-deprecated">
                        Deprecated

File: src/core/depthBuf.js

/**
 A **DepthBuf** configures the WebGL depth buffer for attached {{#crossLink "GameObject"}}GameObjects{{/crossLink}}.

 ## Overview

 <ul>
 <li>A DepthBuf configures **the way** that pixel depths are written to the WebGL depth buffer</li>
 <li>DepthBuf is not to be confused with {{#crossLink "DepthTarget"}}DepthTarget{{/crossLink}}, which stores rendered pixel
 depths for consumption by {{#crossLink "Texture"}}Textures{{/crossLink}}, used when performing *render-to-texture*.</li>
 </ul>

 <img src="../../../assets/images/DepthBuf.png"></img>

 ## Example

 In this example we're configuring the WebGL depth buffer for a {{#crossLink "GameObject"}}{{/crossLink}}.

 The scene contains:

 <ul>
 <li>a DepthBuf that configures the clear depth and depth comparison function,</li>
 <li>a {{#crossLink "Geometry"}}{{/crossLink}} that is the default box shape and
 <li>a {{#crossLink "GameObject"}}{{/crossLink}} attached to all of the above.</li>
 </ul>

 ````javascript
 var scene = new XEO.Scene();

 // Create a DepthBuf that configures the WebGL depth buffer to set pixels depths to 0.5
 // whenever it is cleared, and to use the "less" depth comparison function
 var depthBuf = new XEO.DepthBuf(scene, {
    clearDepth: 0.5,
    depthFunc: "less"
});

 var geometry = new XEO.Geometry(scene); // Defaults to a 2x2x2 box

 // Create a Object that renders the Geometry to the depth buffer,
 // as configured by our DepthBuf
 var gameObject = new XEO.GameObject(scene, {
    depthBuf: depthBuf,
    geometry: geometry
});
 ````

 @class DepthBuf
 @module XEO
 @constructor
 @param [scene] {Scene} Parent {{#crossLink "Scene"}}Scene{{/crossLink}} - creates this DepthBuf
 within the default {{#crossLink "Scene"}}Scene{{/crossLink}} when omitted.
 @param [cfg] {*} DepthBuf configuration
 @param [cfg.id] {String} Optional ID, unique among all components in the parent {{#crossLink "Scene"}}Scene{{/crossLink}}, generated automatically when omitted.
 @param [cfg.meta] {String:Object} Optional map of user-defined metadata to attach to this DepthBuf.
 @param [cfg.clearDepth=1.0] {Number} The clear depth.
 @param [cfg.depthFunc="less"] {String} The depth function.
 @extends Component
 */
(function () {

    "use strict";

    XEO.DepthBuf = XEO.Component.extend({

        className: "XEO.DepthBuf",

        type: "DepthBuf",

        _init: function (cfg) {

            this._state = new XEO.renderer.DepthBuf({
                clearDepth: 1.0,
                depthFunc: "less"
            });

            this.clearDepth = cfg.clearDepth;
            this.depthFunc = cfg.depthFunc;
        },

        _props: {

            /**
             * The clear depth for this DepthBuf.
             *
             * Fires a {{#crossLink "DepthBuf/clearDepth:event"}}{{/crossLink}} event on change.
             *
             * @property clearDepth
             * @default 1.0
             * @type Number
             */
            clearDepth: {

                set: function (value) {

                    this._state.clearDepth = value !== undefined ? value : 1.0;

                    this._renderer.imageDirty = true;

                    /**
                     Fired whenever this DepthBuf's {{#crossLink "DepthBuf/clearDepth:property"}}{{/crossLink}} property changes.

                     @event clearDepth
                     @param value {Number} The property's new value
                     */
                    this.fire("clearDepth",  this._state.clearDepth);
                },

                get: function () {
                    return this._state.clearDepth;
                }
            },

            /**
             * The depth function for this DepthBuf.
             *
             * Accepted values are:
             *
             * <ul>
             *     <li>"less"</li>
             *     <li>"equal"</li>
             *     <li>"lequal"</li>
             *     <li>"greater"</li>
             *     <li>"notequal"</li>
             *     <li>"gequal"</li>
             * </ul>
             *
             * Fires a {{#crossLink "DepthBuf/depthFunc:event"}}{{/crossLink}} event on change.
             *
             * @property depthFunc
             * @default "less"
             * @type Number
             */
            depthFunc: {

                set: function (value) {

                    value = value || "less";

                    var enumName = this._depthFuncNames[value];
                    if (enumName === undefined) {
                        this.error("unsupported value for 'clearFunc' attribute on depthBuf component: '" + value +
                            "' - supported values are 'less', 'equal', 'lequal', 'greater', 'notequal' and 'gequal'");
                        return;
                    }

                    this._state.depthFunc = this.scene.canvas.gl[enumName];
                    this._state.depthFuncName = value;

                    this._renderer.imageDirty = true;

                    /**
                     Fired whenever this DepthBuf's {{#crossLink "DepthBuf/depthFunc:property"}}{{/crossLink}} property changes.
                     @event depthFunc
                     @param value {String} The property's new value
                     */
                    this.fire("depthFunc", this._state.depthFuncName);
                },

                get: function () {
                    return this._state.depthFuncName;
                }
            }
        },

        /**
         * Lookup GL depth function enums
         * @private
         */
        _depthFuncNames: {
            less: "LESS",
            equal: "EQUAL",
            lequal: "LEQUAL",
            greater: "GREATER",
            notequal: "NOTEQUAL",
            gequal: "GEQUAL"
        },

        _compile: function () {
            this._renderer.depthBuf = this._state;
        },

        _getJSON: function () {
            return {
                clearDepth: this._state.clearDepth,
                depthFunc: this._state.depthFuncName
            };
        },

        _destroy: function () {
            this._state.destroy();
        }
    });

})();


text:
package com.jiwhiz.rest.admin;

import static com.jiwhiz.rest.UtilConstants.API_ROOT;
import static com.jiwhiz.rest.admin.AdminApiUrls.URL_ADMIN_BLOGS;
import static com.jiwhiz.rest.admin.AdminApiUrls.URL_ADMIN_COMMENTS;
import static com.jiwhiz.rest.admin.AdminApiUrls.URL_ADMIN_USERS;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;

import javax.inject.Inject;

import org.springframework.data.web.PagedResourcesAssembler;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.ResourceAssembler;
import org.springframework.hateoas.UriTemplate;
import org.springframework.hateoas.mvc.BasicLinkBuilder;
import org.springframework.stereotype.Component;

import com.jiwhiz.domain.account.UserAccount;
import com.jiwhiz.domain.post.BlogPost;

/**
 * @author Yuan Ji
 */
@Component
public class AdminAccountResourceAssembler implements ResourceAssembler<UserAccount, AdminAccountResource> {

    private final PagedResourcesAssembler<BlogPost> assembler;

    @Inject
    public AdminAccountResourceAssembler(PagedResourcesAssembler<BlogPost> assembler) {
        this.assembler = assembler;
    }

    @Override
    public AdminAccountResource toResource(UserAccount userAccount) {
        AdminAccountResource resource = new AdminAccountResource(userAccount);

        resource.add(linkTo(methodOn(AdminAccountRestController.class).getAdminAccount()).withSelfRel());

        String baseUri = BasicLinkBuilder.linkToCurrentMapping().toString();

        Link usersLink = new Link(
                new UriTemplate(baseUri + API_ROOT + URL_ADMIN_USERS), AdminAccountResource.LINK_NAME_USERS);
        resource.add(assembler.appendPaginationParameterTemplates(usersLink));

        Link blogsLink = new Link(
                new UriTemplate(baseUri + API_ROOT + URL_ADMIN_BLOGS), AdminAccountResource.LINK_NAME_BLOGS);
        resource.add(assembler.appendPaginationParameterTemplates(blogsLink));

        Link commentsLink = new Link(
                new UriTemplate(baseUri + API_ROOT + URL_ADMIN_COMMENTS), AdminAccountResource.LINK_NAME_COMMENTS);
        resource.add(assembler.appendPaginationParameterTemplates(commentsLink));

        return resource;

    }

}


text:
package com.adafruit.bluefruit.le.connect.app;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.adafruit.bluefruit.le.connect.R;

/**
 * Created by OS on 10/05/2016.
 */
public class CharacterFragment extends Fragment {

    public CharacterFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_character, container, false);
    }

}


text:
[![GoDoc](https://godoc.org/github.com/gwatts/rootcerts?status.svg)](https://godoc.org/github.com/gwatts/rootcerts)
[![Build Status](https://travis-ci.org/gwatts/rootcerts.svg?branch=master)](https://travis-ci.org/gwatts/rootcerts)

This project converts root certificate authority certificates provided by the
Mozilla project into a .go package that can be statically compiled into a Go
project.

## Motivation

Many Go programs need to access remote SSL/TLS services (eg. over https).
The crypto/tls package validates remote certificates by loading public CA
certificates from the filesystem as provided by the operating system
(eg. in /etc/ssl).

This works well, unless the program is running in any environment where these
certificates are not installed, are not accessible, or are out of date.  This
commonly occurs when running Go programs in a minimal docker container or the
binary is distributed as-is to end users who may or may not be running the program
on a machine with up to date certificates installed/accessible.

Compiling the root certificates into the program provides guaranteed stable
access to them without external dependencies.

## Alternatives

Instead of compiling the certificates into the binary, one could:

* Install packages at the OS level and mount /etc/ssl as a volume for the
container
* Add a certificates layer to the image when defining the Dockerfile

Compiling the certificates may, however, be simpler to deploy in many cases and
result in a predictable outcome whether the binary is executed in a container
or on a host.

## Usage

You may either use the certificates provided at the root level of this project,
which are periodically refreshed, or use the gencerts tool to create a
rootcerts.go file that may be copied into your project.

Calling the `UpdateDefaultTransport` method will make the certificates available
to the default http transport, which is sufficient for many projects.

### Using gencerts

The gencerts tool reads a certdata.txt file, either from the local filesystem,
or directly from the Mozilla Mercurial site (though note, it uses https by
default so does itself require local ca certificates!)

Note also that the format of certdata.txt changes occasionally, which may break
the gencerts tool.  Relying on -download for a production build process may
thus be a bad idea!

```bash
gencerts -download -package mypackage -target rootcerts.go
```

gencerts will generate a rootcerts.go and also a rootcerts_16.go if there are
any certificate with a negative serial number.  Only Go version 1.6 and later
supports such certificates, so rootcerts_16.go uses a build flag to ensure
compatibility with older versions of Go.

## Other Notes

gencerts only outputs certificates that the certdata.txt file has labeled as
a trusted delegator (ie. certificates that are suitable for use a certificate
authority).

Certificates may be marked as trusted for servers, email or code signing.

## Useful Resources

Some of the information I came across while writing this tool:

* [https://github.com/ralphholz/root-store-archaeology]
* [http://curl.haxx.se/cvssource/lib/mk-ca-bundle.pl]
* Ubuntu ca-certificates package (certdata2pem.py)

## Similar Projects

* https://github.com/breml/rootcerts


text:
namespace Void
{
    // VDecisionTreeSplit
    // Complete: categorical, ordinal features
    // Binary: categorical, ordinal, continuous features
    // Clustering
    //----------------------------------------------------------------------------------------------------
    enum class VDecisionTreeSplit
    {
        Default = 0,
        Complete,
        BinaryCategorical,
        BinaryOrdinal,
        BinaryContinuous,
    };

    // VDecisionTreeSplitParameter
    //----------------------------------------------------------------------------------------------------
    template<typename _T>
    struct VDecisionTreeSplitParameter
    {
    public:
        //----------------------------------------------------------------------------------------------------
        VDecisionTreeSplitParameter(const std::vector<std::pair<std::vector<VAny>, _T>*>& _samples, unsigned _featureIndex)
            :
            samples(_samples),
            featureIndex(_featureIndex)
        {
        }

    public:
        //----------------------------------------------------------------------------------------------------
        const std::vector<std::pair<std::vector<VAny>, _T>*>& samples;
        unsigned featureIndex;
    };

    // VDecisionTreeSplitResult
    //----------------------------------------------------------------------------------------------------
    template<typename _T>
    struct VDecisionTreeSplitResult
    {
    public:
        //----------------------------------------------------------------------------------------------------
        VDecisionTreeSplitResult()
        {
        }

        //----------------------------------------------------------------------------------------------------
        VDecisionTreeSplitResult(std::vector<std::vector<std::pair<std::vector<VAny>, _T>*>> _branches, std::function<unsigned(const VAny&)> _routes)
            :
            branches(_branches),
            routes(_routes)
        {
        }

        //----------------------------------------------------------------------------------------------------
        void Swap(VDecisionTreeSplitResult& _other)
        {
            std::swap(branches, _other.branches);
            std::swap(routes, _other.routes);
        }

        //----------------------------------------------------------------------------------------------------
        void Clear()
        {
            branches.clear();
            routes = nullptr;
        }

    public:
        //----------------------------------------------------------------------------------------------------
        std::vector<std::vector<std::pair<std::vector<VAny>, _T>*>> branches;
        std::function<unsigned(const VAny&)> routes;
    };

    // VDecisionTreeSplitInterface
    //----------------------------------------------------------------------------------------------------
    template<typename _T>
    class VDecisionTreeSplitInterface
    {
    public:
        //----------------------------------------------------------------------------------------------------
        inline virtual ~VDecisionTreeSplitInterface() {}

        //----------------------------------------------------------------------------------------------------
        virtual bool Process(const VDecisionTreeSplitParameter<_T>& _parameter) = 0;
        virtual bool Next(VDecisionTreeSplitResult<_T>& _result) = 0;
    };

    // VDecisionTreeSplitOperator
    // _T: target type
    // _F: feature type
    // samples -> (split by one of the features) -> branches + routes
    //----------------------------------------------------------------------------------------------------
    template<typename _T, typename _F,  VDecisionTreeSplit _S>
    class VDecisionTreeSplitOperator : public VDecisionTreeSplitInterface<_T>
    {
    public:
        //----------------------------------------------------------------------------------------------------
        bool Process(const VDecisionTreeSplitParameter<_T>& _parameter)
        {
            return false;
        }

        //----------------------------------------------------------------------------------------------------
        bool Next(VDecisionTreeSplitResult<_T>& _result)
        {
            return false;
        }
    };

    //----------------------------------------------------------------------------------------------------
    template<typename _T, typename _F>
    class VDecisionTreeSplitOperator<_T, _F, VDecisionTreeSplit::Complete> : public VDecisionTreeSplitInterface<_T>
    {
    public:
        //----------------------------------------------------------------------------------------------------
        VDecisionTreeSplitOperator()
            :
            mFlag(false)
        {
        }

        //----------------------------------------------------------------------------------------------------
        bool Process(const VDecisionTreeSplitParameter<_T>& _parameter)
        {
            // Count
            mBranchMap.clear();
            for (auto& sample : _parameter.samples)
            {
                mBranchMap[VAnyCast<_F>(sample->first[_parameter.featureIndex])].push_back(sample);
            }
            return 2 <= mBranchMap.size() ? true : false;
        }

        //----------------------------------------------------------------------------------------------------
        bool Next(VDecisionTreeSplitResult<_T>& _result)
        {
            if (2 <= mBranchMap.size() && !mFlag)
            {
                mFlag = true;
                _result.Clear();
                std::map<_F, unsigned> routeMap;
                for (auto& branch : mBranchMap)
                {
                    _result.branches.push_back(branch.second);
                    routeMap[VAnyCast<_F>(branch.first)] = (unsigned)(_result.branches.size() - 1);
                }
                _result.routes = [routeMap](const VAny& _feature)->unsigned
                {
                    _F feature = VAnyCast<_F>(_feature);
                    auto it = routeMap.find(feature);
                    return it != routeMap.end() ? it->second : -1;
                };
                return true;
            }
            return false;
        }

    protected:
        //----------------------------------------------------------------------------------------------------
        bool mFlag;
        std::map<_F, std::vector<std::pair<std::vector<VAny>, _T>*>> mBranchMap;
    };

    //----------------------------------------------------------------------------------------------------
    template<typename _T, typename _F>
    class VDecisionTreeSplitOperator<_T, _F, VDecisionTreeSplit::BinaryContinuous> : public VDecisionTreeSplitInterface<_T>
    {
    public:
        //----------------------------------------------------------------------------------------------------
        VDecisionTreeSplitOperator()
            :
            mThresholdIndex(0)
        {
        }

        //----------------------------------------------------------------------------------------------------
        bool Process(const VDecisionTreeSplitParameter<_T>& _parameter)
        {
            // Count
            mBranchMap.clear();
            for (auto& sample : _parameter.samples)
            {
                mBranchMap[VAnyCast<_F>(sample->first[_parameter.featureIndex])].push_back(sample);
            }
            // Sort
            mSortedValues.clear();
            mSortedValues.reserve(mBranchMap.size());
            for (auto& pair : mBranchMap)
            {
                mSortedValues.push_back(pair.first);
            }
            std::sort(mSortedValues.begin(), mSortedValues.end());
            mThresholdIndex = 0;
            return 2 <= mBranchMap.size() ? true : false;
        }

        //----------------------------------------------------------------------------------------------------
        bool Next(VDecisionTreeSplitResult<_T>& _result)
        {
            if (2 <= mBranchMap.size() && mThresholdIndex < mSortedValues.size() - 1)
            {
                _result.Clear();
                _F threshold = (mSortedValues[mThresholdIndex] + mSortedValues[mThresholdIndex + 1]) / 2;

                _result.branches.resize(2);
                for (_F& value : mSortedValues)
                {
                    std::vector<std::pair<std::vector<VAny>, _T>*>& branch = mBranchMap[value];
                    if (value <= threshold)
                    {
                        std::copy(branch.begin(), branch.end(), std::back_inserter(_result.branches[0]));
                    }
                    else
                    {
                        std::copy(branch.begin(), branch.end(), std::back_inserter(_result.branches[1]));
                    }
                }
                _result.routes = [threshold](const VAny& _feature)->unsigned
                {
                    _F feature = VAnyCast<_F>(_feature);
                    return feature <= threshold ? 0 : 1;
                };
                ++mThresholdIndex;
                return true;
            }
            return false;
        }

    protected:
        //----------------------------------------------------------------------------------------------------
        unsigned mThresholdIndex;
        std::vector<_F> mSortedValues;
        std::map<_F, std::vector<std::pair<std::vector<VAny>, _T>*>> mBranchMap;
    };

    // VDecisionTreeSplitHelper
    //----------------------------------------------------------------------------------------------------
    template<typename _T>
    class VDecisionTreeSplitHelper
    {
    public:
        //----------------------------------------------------------------------------------------------------
        VDecisionTreeSplitHelper()
        {
            Initialize();
        }

        //----------------------------------------------------------------------------------------------------
        bool Process(const VDecisionTreeSplitParameter<_T>& _parameter, VDecisionTreeSplit _split)
        {
            if (_parameter.samples.size())
            {
                std::string typeName = _parameter.samples[0]->first[_parameter.featureIndex].Type().name();
                auto it = mSplitOperators[_split].find(typeName);
                if (it != mSplitOperators[_split].end())
                {
                    mCurrentInterface = it->second;
                    if (mCurrentInterface->Process(_parameter))
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        //----------------------------------------------------------------------------------------------------
        bool Next(VDecisionTreeSplitResult<_T>& _result)
        {
            if (mCurrentInterface && mCurrentInterface->Next(_result))
            {
                return true;
            }
            return false;
        }

    protected:
        // Todo: extension
        //----------------------------------------------------------------------------------------------------
        void Initialize()
        {
            // Complete (int)
            mSplitOperators[VDecisionTreeSplit::Complete][typeid(int).name()] = new VDecisionTreeSplitOperator<_T, int, VDecisionTreeSplit::Complete>();
            // Complete (string)
            mSplitOperators[VDecisionTreeSplit::Complete][typeid(std::string).name()] = new VDecisionTreeSplitOperator<_T, std::string, VDecisionTreeSplit::Complete>();
            // BinaryContinuous (float)
            mSplitOperators[VDecisionTreeSplit::BinaryContinuous][typeid(float).name()] = new VDecisionTreeSplitOperator<_T, float, VDecisionTreeSplit::BinaryContinuous>();

        }

    protected:
        //----------------------------------------------------------------------------------------------------
        VSharePointer<VDecisionTreeSplitInterface<_T>> mCurrentInterface;
        std::map<VDecisionTreeSplit, std::map<std::string, VSharePointer<VDecisionTreeSplitInterface<_T>>>> mSplitOperators;
    };
}

#endif