text:
require 'spec_helper'

describe 'Commands / Update' do
  include_context 'database setup'

  subject(:users) { rom.commands.users }

  let(:relation) { rom.relations.users }
  let(:piotr) { relation.by_name('Piotr').first }
  let(:peter) { { name: 'Peter' } }

  before do
    setup.relation(:users) do
      def by_id(id)
        where(id: id).limit(1)
      end

      def by_name(name)
        where(name: name)
      end
    end

    setup.commands(:users) do
      define(:update)
    end

    relation.insert(name: 'Piotr')
  end

  context '#transaction' do
    it 'update record if there was no errors' do
      result = users.update.transaction do
        users.update.by_id(piotr[:id]).set(peter)
      end

      expect(result.value).to eq([{ id: 1, name: 'Peter' }])
    end

    it 'updates nothing if error was raised' do
      users.update.transaction do
        users.update.by_id(piotr[:id]).set(peter)
        raise ROM::SQL::Rollback
      end

      expect(relation.first[:name]).to eq('Piotr')
    end
  end

  it 'updates everything when there is no original tuple' do
    result = users.try do
      users.update.by_id(piotr[:id]).set(peter)
    end

    expect(result.value.to_a).to match_array([{ id: 1, name: 'Peter' }])
  end

  it 'updates when attributes changed' do
    result = users.try do
      users.update.by_id(piotr[:id]).change(piotr).to(peter)
    end

    expect(result.value.to_a).to match_array([{ id: 1, name: 'Peter' }])
  end

  it 'does not update when attributes did not change' do
    piotr_rel = double('piotr_rel').as_null_object

    expect(relation).to receive(:by_id).with(piotr[:id]).and_return(piotr_rel)
    expect(piotr_rel).not_to receive(:update)

    result = users.try do
      users.update.by_id(piotr[:id]).change(piotr).to(name: piotr[:name])
    end

    expect(result.value.to_a).to be_empty
  end
end

redpajama_set_name: RedPajamaGithub


text:
package com.github.ckwen.je.spring.boot.mybatis;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;

import com.github.ckwen.je.spring.boot.mybatis.mapper.UserMapper;
import com.github.ckwen.je.spring.boot.mybatis.model.User;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@Transactional
public class UserMapperTest {

    @Autowired
    private UserMapper userMapper;

    @Test
    @Rollback
    public void test() {
        userMapper.insert("AAA", 20);
        User u = userMapper.findByName("AAA");
        Assert.assertEquals(20, u.getAge().intValue());
    }

}


text:
package org.apache.syncope.fit.core.reference;

import org.apache.syncope.common.lib.policy.AbstractCorrelationRuleConf;
import org.apache.syncope.common.lib.policy.PullCorrelationRuleConf;

public class DummyPullCorrelationRuleConf
        extends AbstractCorrelationRuleConf implements PullCorrelationRuleConf {

    private static final long serialVersionUID = -2984203196323732531L;

}


text:
**Author:** [lukewood](https://lukewood.xyz)

**Date created:** 11/03/2021

**Last modified:** 11/03/2021

**Description:** This example shows how to implement custom convolution layers using the `Conv.convolution_op()` API.

 [**View in Colab**](https://colab.research.google.com/github/keras-team/keras-io/blob/master/examples/keras_recipes/ipynb/subclassing_conv_layers.ipynb)  • [**GitHub source**](https://github.com/keras-team/keras-io/blob/master/examples/keras_recipes/subclassing_conv_layers.py)

---
## Introduction

You may sometimes need to implement custom versions of convolution layers like `Conv1D` and `Conv2D`.
Keras enables you do this without implementing the entire layer from scratch: you can reuse
most of the base convolution layer and just customize the convolution op itself via the
`convolution_op()` method.

This method was introduced in Keras 2.7. So before using the
`convolution_op()` API, ensure that you are running Keras version 2.7.0 or greater.

```python
import tensorflow.keras as keras

print(keras.__version__)
```

```
2.7.0

```

---
## A Simple `StandardizedConv2D` implementation

There are two ways to use the `Conv.convolution_op()` API. The first way
is to override the `convolution_op()` method on a convolution layer subclass.
Using this approach, we can quickly implement a
[StandardizedConv2D](https://arxiv.org/abs/1903.10520) as shown below.

```python
import tensorflow as tf
import tensorflow.keras as keras
import keras.layers as layers
import numpy as np

class StandardizedConv2DWithOverride(layers.Conv2D):
    def convolution_op(self, inputs, kernel):
        mean, var = tf.nn.moments(kernel, axes=[0, 1, 2], keepdims=True)
        return tf.nn.conv2d(
            inputs,
            (kernel - mean) / tf.sqrt(var + 1e-10),
            padding="VALID",
            strides=list(self.strides),
            name=self.__class__.__name__,
        )

```

The other way to use the `Conv.convolution_op()` API is to directly call the
`convolution_op()` method from the `call()` method of a convolution layer subclass.
A comparable class implemented using this approach is shown below.

```python

class StandardizedConv2DWithCall(layers.Conv2D):
    def call(self, inputs):
        mean, var = tf.nn.moments(self.kernel, axes=[0, 1, 2], keepdims=True)
        result = self.convolution_op(
            inputs, (self.kernel - mean) / tf.sqrt(var + 1e-10)
        )
        if self.use_bias:
            result = result + self.bias
        return result

```

---
## Example Usage

Both of these layers work as drop-in replacements for `Conv2D`. The following
demonstration performs classification on the MNIST dataset.

```python
# Model / data parameters
num_classes = 10
input_shape = (28, 28, 1)

# the data, split between train and test sets
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()

# Scale images to the [0, 1] range
x_train = x_train.astype("float32") / 255
x_test = x_test.astype("float32") / 255
# Make sure images have shape (28, 28, 1)
x_train = np.expand_dims(x_train, -1)
x_test = np.expand_dims(x_test, -1)
print("x_train shape:", x_train.shape)
print(x_train.shape[0], "train samples")
print(x_test.shape[0], "test samples")

# convert class vectors to binary class matrices
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)

model = keras.Sequential(
    [
        keras.layers.InputLayer(input_shape=input_shape),
        StandardizedConv2DWithCall(32, kernel_size=(3, 3), activation="relu"),
        layers.MaxPooling2D(pool_size=(2, 2)),
        StandardizedConv2DWithOverride(64, kernel_size=(3, 3), activation="relu"),
        layers.MaxPooling2D(pool_size=(2, 2)),
        layers.Flatten(),
        layers.Dropout(0.5),
        layers.Dense(num_classes, activation="softmax"),
    ]
)

model.summary()
```

```python
batch_size = 128
epochs = 5

model.compile(loss="categorical_crossentropy", optimizer="adam", metrics=["accuracy"])

model.fit(x_train, y_train, batch_size=batch_size, epochs=5, validation_split=0.1)
```

```
x_train shape: (60000, 28, 28, 1)
60000 train samples
10000 test samples
Model: "sequential"
_________________________________________________________________
 Layer (type)                Output Shape              Param #
=================================================================
 standardized_conv2d_with_ca  (None, 26, 26, 32)       320
 ll (StandardizedConv2DWithC
 all)

 max_pooling2d (MaxPooling2D  (None, 13, 13, 32)       0
 )

 standardized_conv2d_with_ov  (None, 11, 11, 64)       18496
 erride (StandardizedConv2DW
 ithOverride)

 max_pooling2d_1 (MaxPooling  (None, 5, 5, 64)         0
 2D)

 flatten (Flatten)           (None, 1600)              0

 dropout (Dropout)           (None, 1600)              0

 dense (Dense)               (None, 10)                16010

=================================================================
Total params: 34,826
Trainable params: 34,826
Non-trainable params: 0
_________________________________________________________________

Epoch 1/5
422/422 [==============================] - 7s 15ms/step - loss: 1.8435 - accuracy: 0.8415 - val_loss: 0.1177 - val_accuracy: 0.9660
Epoch 2/5
422/422 [==============================] - 6s 14ms/step - loss: 0.2460 - accuracy: 0.9338 - val_loss: 0.0727 - val_accuracy: 0.9772
Epoch 3/5
422/422 [==============================] - 6s 14ms/step - loss: 0.1600 - accuracy: 0.9541 - val_loss: 0.0537 - val_accuracy: 0.9862
Epoch 4/5
422/422 [==============================] - 6s 14ms/step - loss: 0.1264 - accuracy: 0.9633 - val_loss: 0.0509 - val_accuracy: 0.9845
Epoch 5/5
422/422 [==============================] - 6s 14ms/step - loss: 0.1090 - accuracy: 0.9679 - val_loss: 0.0457 - val_accuracy: 0.9872

<keras.callbacks.History at 0x7f2ff6ed2f10>

```

---
## Conclusion

The `Conv.convolution_op()` API provides an easy and readable way to implement custom
convolution layers. A `StandardizedConvolution` implementation using the API is quite
terse, consisting of only four lines of code.


text:
from setuptools import setup, find_packages

install_requires = [
    'pyyaml',
]

metadata = {
    'name': 'summarize_hours',
    'version': "0.0.1",
    'description': 'Summarize billed hours recorded in a yaml file.',
    'license': 'New BSD',
    'author': 'Robert David Grant',
    'maintainer': 'Robert David Grant',
    'maintainer_email': "robert.david.grant@gmail.com",
    'packages': find_packages(),
    'install_requires': install_requires,
    'long_description': open("README.md").read(),
    'platforms': ["Linux", "Mac OS-X", "Windows"],
    'entry_points': {'console_scripts':
                        ['summarize_hours = '
                         'summarize_hours.summarize_hours:cli'
                         ]},
}

setup(**metadata)


text:
module EmailFetch::Hunt
  class Search
    extend GluttonRatelimit

    def initialize
      @start = Time.now
      @utils = Fetch::Utils.new
      @log = @utils.log
    end

    def search(query)
      raise NotImplementedError.new('This method should be overridden by a subclass.')
    end
  end
end


text:
<?php

namespace Tienvx\Bundle\MbtBundle\Model;

interface ValuesInterface
{
    public function getValues(): array;

    public function setValue(string $key, mixed $value): void;

    public function getValue(string $key): mixed;
}


text:
namespace base {

LockFreeAddressHashSet::LockFreeAddressHashSet(size_t buckets_count)
    : buckets_(buckets_count), bucket_mask_(buckets_count - 1) {
  DCHECK(bits::IsPowerOfTwo(buckets_count));
  DCHECK_LE(bucket_mask_, std::numeric_limits<uint32_t>::max());
}

LockFreeAddressHashSet::~LockFreeAddressHashSet() {
  for (std::atomic<Node*>& bucket : buckets_) {
    Node* node = bucket.load(std::memory_order_relaxed);
    while (node) {
      Node* next = node->next;
      delete node;
      node = next;
    }
  }
}

void LockFreeAddressHashSet::Insert(void* key) {
  DCHECK_NE(key, nullptr);
  CHECK(!Contains(key));
  ++size_;
  // Note: There's no need to use std::atomic_compare_exchange here,
  // as we do not support concurrent inserts, so values cannot change midair.
  std::atomic<Node*>& bucket = buckets_[Hash(key) & bucket_mask_];
  Node* node = bucket.load(std::memory_order_relaxed);
  // First iterate over the bucket nodes and try to reuse an empty one if found.
  for (; node != nullptr; node = node->next) {
    if (node->key.load(std::memory_order_relaxed) == nullptr) {
      node->key.store(key, std::memory_order_relaxed);
      return;
    }
  }
  // There are no empty nodes to reuse left in the bucket.
  // Create a new node first...
  Node* new_node = new Node(key, bucket.load(std::memory_order_relaxed));
  // ... and then publish the new chain.
  bucket.store(new_node, std::memory_order_release);
}

void LockFreeAddressHashSet::Copy(const LockFreeAddressHashSet& other) {
  DCHECK_EQ(0u, size());
  for (const std::atomic<Node*>& bucket : other.buckets_) {
    for (Node* node = bucket.load(std::memory_order_relaxed); node;
         node = node->next) {
      void* key = node->key.load(std::memory_order_relaxed);
      if (key)
        Insert(key);
    }
  }
}

}  // namespace base


text:
Types for Google Cloud Network Security v1beta1 API
===================================================

.. automodule:: google.cloud.network_security_v1beta1.types
    :members:
    :undoc-members:
    :show-inheritance:


text:
package net.badgekeeper.android.network.callbacks;

/**
 * Interfaces for notifying your app when error response received from Badge Keeper service.
 * Just for internal use.
 */
public interface BadgeKeeperErrorCallback {
    /**
     * Something goes wrong with request.
     * @param code - error code.
     * @param message - error message.
     */
    public void onError(int code, String message);
}


text:
package com.gs.fw.common.mithra.test.domain.dated;

import java.sql.Timestamp;

public class TestTamsAccountIncomeFunction extends TestTamsAccountIncomeFunctionAbstract
{

	public TestTamsAccountIncomeFunction(Timestamp businessDate, Timestamp processingDate)
	{
		super(businessDate, processingDate);
	}
}


text:
FactoryGirl.define do
  factory :port_mapping, class: 'Atmosphere::PortMapping' do |f|
    public_ip '8.8.8.8'
    source_port { 2000 + Random.rand(20000) }
    port_mapping_template
    virtual_machine
  end
end


text:
"""
Verse celery configuration
"""
import os

from celery import Celery

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'verse.settings')

app = Celery('verse')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()

@app.task(bind=True)
def debug_task(self):
    print('Request: {0!r}'.format(self.request))


text:
<?php
namespace Simply_Static;

class Wrapup_Task extends Task {

	/**
	 * @var string
	 */
	protected static $task_name = 'wrapup';

	public function perform() {
		if ( $this->options->get( 'delete_temp_files' ) === '1' ) {
			Util::debug_log( "Deleting temporary files" );
			$this->save_status_message( __( 'Wrapping up', 'simply-static' ) );
			$deleted_successfully = $this->delete_temp_static_files();
		} else {
			Util::debug_log( "Keeping temporary files" );
		}

		return true;
	}

	/**
	 * Delete temporary, generated static files
	 * @return true|\WP_Error True on success, WP_Error otherwise
	 */
	public function delete_temp_static_files() {
		$archive_dir = $this->options->get_archive_dir();

		if ( file_exists( $archive_dir ) ) {
			$directory_iterator = new \RecursiveDirectoryIterator( $archive_dir, \FilesystemIterator::SKIP_DOTS );
			$recursive_iterator = new \RecursiveIteratorIterator( $directory_iterator, \RecursiveIteratorIterator::CHILD_FIRST );

			// recurse through the entire directory and delete all files / subdirectories
			foreach ( $recursive_iterator as $item ) {
				$success = $item->isDir() ? rmdir( $item ) : unlink( $item );
				if ( ! $success ) {
					$message = sprintf( __( "Could not delete temporary file or directory: %s", 'simply-static' ), $item );
					$this->save_status_message( $message );
					return true;
				}
			}

			// must make sure to delete the original directory at the end
			$success = rmdir( $archive_dir );
			if ( ! $success ) {
				$message = sprintf( __( "Could not delete temporary file or directory: %s", 'simply-static' ), $archive_dir );
				$this->save_status_message( $message );
				return true;
			}
		}

		return true;
	}
}


text:
module Deploy

  module Execute

    def Execute.bag bag
      bag.each do | item |
        command,dest,opts = item
        p [command,dest,opts]
        case command
        when :mkdir then
          FileOps.mkdir(dest,opts[:mode])
        when :copy_recursive then
          FileOps.copy_recursive(opts[:source],dest)
        when :copy_file then
          FileOps.copy_file(opts[:source],dest,opts[:mode])
        when :edit_file then
          FileOps.edit_file(opts[:source],dest,opts[:edit_lines])
        else
          p item
          raise "Uknown bag command #{command}!"
        end
      end
      bag
    end
  end
end


text:
PUT Map containig List of bools with PHP serializer.

--FILE--
<?php
include dirname(__FILE__)."/../../astestframework/astest-phpt-loader.inc";
aerospike_phpt_runtest("Put", "testPutMapListBoolsWithPHPSerializer");
--EXPECT--
OK


text:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class jFUSE_lowlevel_FuseStat */

#ifndef _Included_jFUSE_lowlevel_FuseStat
#define _Included_jFUSE_lowlevel_FuseStat
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __cplusplus
}
#endif
#endif


text:
.centerDropdown {
    left: auto !important;
    right: -25% !important;
}
.centerDropdown:after {
   left: auto !important;
   right: 45% !important;
}
.ContentDivs
        {
                        display:none;
        }


text:
<!DOCTYPE>
<html>
	<head>
		<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=0.1, maximum-scale=1.0">
		<script src="UI/libs/jquery.js" type="text/javascript"></script>
		<script src="UI/libs/jquery.tmpl.min.js" type="text/javascript"></script>
		<script src="UI/libs/jquery-ui.min.js" type="text/javascript"></script>

		<link href="UI/libs/jquery-ui.min.css" rel="stylesheet"></link>

        <script src="UI/libs/jwt.min.js"></script>
		<script src="libs/lodash.min.js"></script>
		<script src='libs/anonymousassertion.js'></script>
		<script src="kore-bot-sdk-client.js"></script>
		<script src="UI/chatWindow.js" type="text/javascript"></script>
		<script src="libs/emoji.js" type="text/javascript"></script>
		<script src="libs/recorder.js" type="text/javascript"></script>
		<script src="libs/recorderWorker.js" type="text/javascript"></script>
		<link href="UI/chatWindow.css" rel="stylesheet"></link>
		<link href="libs/emojione.sprites.css" rel="stylesheet"></link>
		<script type="text/javascript">
			$(document).on("ready", function () {

	function koreGenerateUUID() {
	var d = new Date().getTime();
	if (window.performance && typeof window.performance.now === "function"){
	d += performance.now(); //use high-precision timer if available
  	}
	var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
	var r = (d + Math.random() * 16) % 16 | 0;
	 d = Math.floor(d / 16);
	return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
	});
	return uuid;
	 }

	function generateJWT() {
		var korecookie = localStorage.getItem("korecom");
	 var uuid = (korecookie) || koreGenerateUUID();
	 localStorage.setItem("korecom", uuid);
        // Header
        var oHeader = {alg: 'HS256', typ: 'JWT'};
        // Payload
        var oPayload = {};
        var tNow = KJUR.jws.IntDate.get('now');
              var tEnd = KJUR.jws.IntDate.get('now + 1day');
        oPayload.iss = "cs-c0803125-87e8-5f41-829d-83260e9f1486";
        oPayload.sub = uuid;
        oPayload.iat = tNow;
        oPayload.exp = tEnd;
        oPayload.aud = "https://idproxy.kore.com/authorize";
        oPayload.isAnonymous = false;

        // Sign JWT
        var sHeader = JSON.stringify(oHeader);
        var sPayload = JSON.stringify(oPayload);
        var sJWT = KJUR.jws.JWS.sign("HS256", sHeader, sPayload, "isTM2x0nFBSbmv0JI9HeHZv11j3rpAYMwRWg2URAaZU=");
        return sJWT;

    }
	function assertion(options, callback){

          options.assertion = generateJWT();
		  options.handleError = koreBot.showError;
		  callback(null, options);
		  setTimeout(function () {
		  if (koreBot && koreBot.initToken) {
			koreBot.initToken(options);
		  }
		}, 2000);
  }

				var botOptions = {};
				botOptions.logLevel = 'debug';
				botOptions.koreAPIUrl = "https://bots.kore.ai/api/";
				//botOptions.bearer = "bearer xyz-------------------";
				botOptions.speechSocketUrl = 'wss://';
				botOptions.assertionFn = assertion;
				botOptions.koreAnonymousFn = koreAnonymousFn;
				botOptions.clientId   = "cs-c0803125-87e8-5f41-829d-83260e9f1486"; // secure client-id
				botOptions.botInfo = {name:"Demo POC Bot","_id":"st-d1c12894-90ec-55ae-99fa-5056500f443e"}; // bot name is case sensitive

				var chatConfig={
					botOptions:botOptions,
					allowIframe: false
				};
				var koreBot = koreBotChat();
				koreBot.show(chatConfig);
				$('.openChatWindow').click(function () {
					koreBotChat().show(chatConfig);
				});
			});
		</script>
		<style>

		#chatContainer{
		position: absolute;
    top: 0;
    right: 0;

		}
		.openChatWindow{
		    float: right;
    margin: 18px 24px 0 0;
    border: 1px solid #00a4ff;
    background: #fff;
    border-radius: 4px;
    padding: 8px;
    color: #009dab;
	cursor:pointer;

		}

		.openChatWindow:hover{
		border: 1px solid #009dab;
		}
	.fit { /* set relative picture size */
    max-width: 100%;
    max-height: 100%;
  }
  .center {
    display: block;
    margin: auto;
  }

		</style>

	</head>

			<iframe id="siteWindow" src="https://www.cisco.com" style="margin:0px;width:100%;height:97%"  frameborder="0"/>
			<!-- Add x frame extemsion to chrome: https://chrome.google.com/webstore/detail/ignore-x-frame-headers/gleekbfjekiniecknbkamfmkohkpodhe/related -->	    	<div id="chatContainer">
			<button class="openChatWindow">Open Chat Window</button>
		</div>
	</body>
</html>


text:
title:  Kdo je naš Oče
date:   08/08/2022
---

Oswald Chambers piše: »Ali sprašuješ Boga, kaj bo naredil? Ne bo ti povedal; namesto tega ti bo pokazal, kdo je.« (My Utmost for His Highest [Uhrichsville, OH: Barbour & Company, Inc., 1963], 2. januar.)

`Kaj je Chambers po tvojem mnenju mislil s temi besedami?`

Jobova knjiga se začne s strašno tragedijo. Job je izgubil vse, razen življenja in žene, ki mu je svetovala, naj prekolne Boga in umre (Job 2,9). Temu je sledil pogovor, med katerim so njegovi prijatelji poskušali razumeti, čemu se je zgodilo vse to. Medtem je Bog molčal.

V Jobu 38 se Bog nenadoma pojavi in spregovori: »Kdo je ta, ki zatemnjuje posvèt z govori brez znanja?« (Job 38,2) Ne da bi počakal na odgovor, Jobu zastavi šestdeset osupljivih vprašanj. Preberi jih v Jobu 38 in 39.

Po zadnjem vprašanju Job odgovori: »Glej, premajhen sem. Kaj naj ti odgovorim? Svojo roko si polagam na usta. Enkrat sem govoril, pa ne bom več odgovarjal, dvakrat, pa ne bom več poskušal.« (Job 40,4-5) Toda Bog še ni končal. Postavljati je začel nova vprašanja.

`Preberi Jobov končni odziv v Jobu 42,1-6. Kaj mu je Bog želel povedati in kakšen učinek je to imelo nanj?`

Bog ni odgovoril na nobeno vprašanje Jobovih prijateljev. Namesto tega jim je pokazal svojo neprimerljivo veličino, ki se razodeva po osupljivih delih njegovega stvarstva. Po tem Job gotovo ni potreboval drugih odgovorov. Potrebo po pojasnilu je zasenčil mogočen prikaz Božje veličastnosti.

Ta zgodba razodeva navdušujoč paradoks. Upanje in spodbuda lahko izvirata iz spoznanja o tem, kako malo vemo. Nagonsko si prizadevamo najti odgovore, ker mislimo, da nam bo to prineslo tolažbo; ko spoznamo, da jih ne moremo najti, nam kopni pogum. Bog včasih izpostavi našo nevednost, da bi nam pokazal, da lahko svojo gotovost najdemo edino v Bitju, ki je veliko večje od nas.

`Ali se ti prav zdaj dogajajo stvari, ki jih ne razumeš? Če je tvoj odgovori pritrdilen, se osredotoči na Božji značaj. Kako ti lahko to vlije upanje, ki ga potrebuješ, da zdržiš to, kar se ti zdaj zdi nedoumljivo? `


text:
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <stdio.h>

#include <winpr/windows.h>

#include <freerdp/freerdp.h>
#include <freerdp/listener.h>

#include "wf_peer.h"
#include "wf_info.h"
#include "wf_mirage.h"

#include "wf_update.h"

DWORD WINAPI wf_update_thread(LPVOID lpParam)
{
	int index;
	DWORD fps;
	wfInfo* wfi;
	DWORD beg, end;
	DWORD diff, rate;

	wfi = (wfInfo*) lpParam;

	fps = wfi->framesPerSecond;
	rate = 1000 / fps;

	while (1)
	{
		beg = GetTickCount();

		if (wf_info_lock(wfi) > 0)
		{
			if (wfi->activePeerCount > 0)
			{
				wf_info_update_changes(wfi);

				if (wf_info_have_updates(wfi))
				{
					wf_update_encode(wfi);

					//printf("Start of parallel sending\n");

					for (index = 0; index < wfi->peerCount; index++)
					{
						if (wfi->peers[index]->activated)
						{
							//printf("Setting event for %d of %d\n", index + 1, wfi->activePeerCount);
							SetEvent(((wfPeerContext*) wfi->peers[index]->context)->updateEvent);
						}
					}

					for (index = 0; index < wfi->activePeerCount; index++)
					{
						//printf("Waiting for %d of %d\n", index + 1, wfi->activePeerCount);
						WaitForSingleObject(wfi->updateSemaphore, INFINITE);
					}

					//printf("End of parallel sending\n");

					wf_info_clear_invalid_region(wfi);
				}
			}

			wf_info_unlock(wfi);
		}

		end = GetTickCount();
		diff = end - beg;

		if (diff < rate)
		{
			Sleep(rate - diff);
		}
	}

	//printf("Exiting Update Thread\n");

	return 0;
}

void wf_update_encode(wfInfo* wfi)
{

	RFX_RECT rect;
	long height, width;
	uint8* pDataBits = NULL;
	int stride;

	SURFACE_BITS_COMMAND* cmd;

	wf_info_find_invalid_region(wfi);

	cmd = &wfi->cmd;

	stream_set_pos(wfi->s, 0);

	wf_info_getScreenData(wfi, &width, &height, &pDataBits, &stride);

	rect.x = 0;
	rect.y = 0;
	rect.width = (uint16) width;
	rect.height = (uint16) height;

	//printf("x:%d y:%d w:%d h:%d\n", wfi->invalid.left, wfi->invalid.top, width, height);

	rfx_compose_message(wfi->rfx_context, wfi->s, &rect, 1,
			pDataBits, width, height, stride);

	wfi->frame_idx = wfi->rfx_context->frame_idx;

	cmd->destLeft = wfi->invalid.left;
	cmd->destTop = wfi->invalid.top;
	cmd->destRight = wfi->invalid.left + width;
	cmd->destBottom = wfi->invalid.top + height;

	cmd->bpp = 32;
	cmd->codecID = 3;
	cmd->width = width;
	cmd->height = height;
	cmd->bitmapDataLength = stream_get_length(wfi->s);
	cmd->bitmapData = stream_get_head(wfi->s);
}

void wf_update_peer_send(wfInfo* wfi, wfPeerContext* context)
{
	freerdp_peer* client = ((rdpContext*) context)->peer;

	/* This happens when the RemoteFX encoder state is reset */

	if (wfi->frame_idx == 1)
		context->frame_idx = 0;

	/*
	 * When a new client connects, it is possible that old frames from
	 * from a previous encoding state remain. Those frames should be discarded
	 * as they will cause an error condition in mstsc.
	 */

	if ((context->frame_idx + 1) != wfi->frame_idx)
	{
		/* This frame is meant to be discarded */

		if (context->frame_idx == 0)
			return;

		/* This is an unexpected error condition */

		printf("Unexpected Frame Index: Actual: %d Expected: %d\n",
			wfi->frame_idx, context->frame_idx + 1);
	}

	wfi->cmd.codecID = client->settings->rfx_codec_id;
	client->update->SurfaceBits(client->update->context, &wfi->cmd);
	context->frame_idx++;
}

void wf_update_encoder_reset(wfInfo* wfi)
{
	if (wf_info_lock(wfi) > 0)
	{
		printf("Resetting encoder\n");

		if (wfi->rfx_context)
		{
			rfx_context_reset(wfi->rfx_context);
		}
		else
		{
			wfi->rfx_context = rfx_context_new();
			wfi->rfx_context->mode = RLGR3;
			wfi->rfx_context->width = wfi->width;
			wfi->rfx_context->height = wfi->height;
			rfx_context_set_pixel_format(wfi->rfx_context, RDP_PIXEL_FORMAT_B8G8R8A8);
			wfi->s = stream_new(0xFFFF);
		}

		wf_info_invalidate_full_screen(wfi);

		wf_info_unlock(wfi);
	}
}

void wf_update_peer_activate(wfInfo* wfi, wfPeerContext* context)
{
	if (wf_info_lock(wfi) > 0)
	{
		if (wfi->activePeerCount < 1)
		{
#ifndef WITH_WIN8
			wf_mirror_driver_activate(wfi);
#endif
			ResumeThread(wfi->updateThread);
		}

		wf_update_encoder_reset(wfi);
		wfi->activePeerCount++;

		printf("Activating Peer Updates: %d\n", wfi->activePeerCount);

		wf_info_unlock(wfi);
	}
}

void wf_update_peer_deactivate(wfInfo* wfi, wfPeerContext* context)
{
	if (wf_info_lock(wfi) > 0)
	{
		freerdp_peer* client = ((rdpContext*) context)->peer;

		if (client->activated)
		{
			if (wfi->activePeerCount <= 1)
			{
				wf_mirror_driver_deactivate(wfi);
			}

			client->activated = false;
			wfi->activePeerCount--;

			printf("Deactivating Peer Updates: %d\n", wfi->activePeerCount);
		}

		wf_info_unlock(wfi);
	}
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Urnularia lanceolata Markgr.

### Remarks
null


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

namespace ArmA.Studio.DataContext
{
    public class BreakpointsPane : PanelBase
    {
        public override string Title => Properties.Localization.PanelDisplayName_Breakpoints;

        public ICommand CmdEntryOnDoubleClick => new RelayCommand((p) =>
        {
            if (!(p is BreakpointInfo))
                return;
            var bp = (BreakpointInfo)p;
            var doc = Workspace.Instance.CreateOrFocusDocument(bp.FileRef);
            if (doc is TextEditorBaseDataContext)
            {
                var textDoc = doc as TextEditorBaseDataContext;
                textDoc.GetEditorInstanceAsync().ContinueWith((t) =>
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        t.Result.TextArea.Caret.Line = bp.Line;
                        t.Result.ScrollToLine(bp.Line);
                        t.Result.TextArea.Caret.Show();
                    });
                });
            }
        });

        public ICommand CmdBreakPointInfoUpdated => new RelayCommand((p) =>
        {
            if(p is BreakpointInfo)
            {
                var bpi = (BreakpointInfo)p;
                Workspace.Instance.BreakpointManager.SetBreakpoint(bpi);
                var doc = Workspace.Instance.GetCurrentDocument();
                if (doc.FileReference.Equals(bpi.FileRef))
                {
                    doc.RefreshVisuals();
                }
            }
        });
        public IEnumerable<BreakpointInfo> Breakpoints { get { return this._Breakpoints; } set { this._Breakpoints = value;
            this.RaisePropertyChanged(); } }
        private IEnumerable<BreakpointInfo> _Breakpoints;

        public BreakpointsPane()
        {
            Task.Run(() =>
            {
                SpinWait.SpinUntil(() => Workspace.Instance != null);
                SpinWait.SpinUntil(() => Workspace.Instance.BreakpointManager != null);
                Workspace.Instance.BreakpointManager.OnBreakPointsChanged += this.BreakpointManager_OnBreakPointsChanged;
                this.Breakpoints = Workspace.Instance.BreakpointManager;
            });
        }

        private void BreakpointManager_OnBreakPointsChanged(object sender, BreakpointManager.BreakPointsChangedEventArgs e)
        {
            this.Breakpoints = Workspace.Instance.BreakpointManager.ToList();
        }
    }
}


text:
In 2016 I want
===========

Organização básica de algumas prioridades para o ano de [2016](http://ftonato.github.io/in-2016-i-want/).

## License
MIT licensed.


text:
/**
 * Configure RequireJS
 */
require({
    packagePaths: {
        "packages": [
            "lib-phpdebug",
            {
                name: "lib-phpdebug-test",
                lib: "browser",
            }
        ]
    }
});

/**
 * Boot example client
 */
require([
    "lib-phpdebug/xdebug"
], function(XDEBUG)
{
    require.ready(function()
    {

        registerTestRunner();

        initUI(XDEBUG);

        initDefaultClient(XDEBUG);

    });
});

/**
 * Register a test runner that can be triggered from the proxy server
 * to run a specific test on the client and report back the result
 * to the server.
 */
function registerTestRunner()
{
    // Connect to the "test" socket.io namespace
    var phpHostname = false,
        socketIO = io,
        testSocket = socketIO.connect("http://localhost/test");
    testSocket.on("run", function (data) {
        try {
            // Load the requested test module and run it reporting result back to server
            require(["lib-phpdebug-test/" + data.test, "lib-phpdebug/xdebug"], function(testModule, XDEBUG) {
                try {
                    testModule.run({
                    	equal: function(actual, expected, message)
                    	{
                    		if (actual != expected)
                    			console.error("Assertion error: " + message, {actual: actual, expected:expected});
                    	},
                    	fail: function(actual, expected, message)
                    	{
                    		if (actual != expected)
                    			console.error("Assertion error: " + message, {actual: actual, expected:expected});
                    	}
                    },
                    XDEBUG, {
                        socketIO: socketIO,
                        listenPort: 80,
                        helpers: {
                            debugScript: function(name, sessionName)
                            {
                                var url = "http://" + phpHostname + "/scripts/" + name + ".php?";
                                url += "XDEBUG_SESSION_START=" + sessionName;
                                url += "&t=" + new Date().getTime();
                                $("#phpscripts").attr("src", url);
                            }
                        }
                    }, function(result) {
                        if (result === true) {
                            testSocket.emit("run-result", { testIndex: data.testIndex, success: true });
                        } else {
                            testSocket.emit("run-result", { testIndex: data.testIndex, error: ""+result });
                        }
                    });
                } catch(e) {
                    testSocket.emit("run-result", { testIndex: data.testIndex, error: e + " " + e.stack });
                }
            });
        } catch(e) {
            testSocket.emit("run-result", { testIndex: data.testIndex, error: e + " " + e.stack });
        }
    });
    testSocket.on("init", function(data)
    {
        phpHostname = data.phpHostname;
        $("#phpscripts").attr("src", "http://" + phpHostname + "/?XDEBUG_SESSION_STOP");
    });
    window.runTests = function() {
        testSocket.emit("run-tests");
    }
}

function initUI(XDEBUG)
{
    var clients = {};

    function appendEvent(node, msg) {
        $('
' + msg + '
').appendTo(node);
    }

    XDEBUG.on("connect", function(client)
    {
        var clientNode = $('

Client ID: ' + client.id + '

').appendTo($("#clients"));

        appendEvent(clientNode, "Connect");

        client.on("disconnect", function()
        {
            appendEvent(clientNode, "Disconnect");

            setTimeout(function() {
                clientNode.remove();
            }, 5000);
        });

        client.on("session", function(session)
        {
            var sessionNode = $('

Session ID: ' + session.id + '

').appendTo(clientNode);

            appendEvent(sessionNode, "Start");

            session.on("ready", function()
            {
                appendEvent(sessionNode, "Ready");
            });

            session.on("end", function()
            {
                appendEvent(sessionNode, "End");

                setTimeout(function() {
                    sessionNode.remove();
                }, 5000);
            });

            session.on("*", function(name, args)
            {
                if (name === "event")
                {
                    if (args.type === "status")
                    {
                        appendEvent(sessionNode, "Status: " + args.status);
                    }
                    else
                    if (args.type === "command")
                    {
                        appendEvent(sessionNode, "Command: " + args.name);
                    }
                    else
                    if (args.type === "command-response")
                    {
                        appendEvent(sessionNode, "Command Response: " + args.name);
                    }
                    else
                    if (args.type === "stdout")
                    {
                        appendEvent(sessionNode, "STDOUT: " + args.data);
                    }
                    else
                        console.log("EVENT", name, args);
                }
                else
                if (name === "ready" || name === "end") {
                	// do nothing here (to prevent message in console)
                }
                else
                    console.log("EVENT", name, args);
            });
        });
    });
}

/**
 * A client that is always connected as long as the page is open.
 * When tests are run additional clients will be connected.
 */
function initDefaultClient(XDEBUG)
{
    var client = new XDEBUG.Client({
        socketIO: io
    });

    client.on("connect", function()
    {
    });

    client.connect({
    	id: "client-browser"
    });
}


text:
"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
var OuterSubscriber_1 = require("../OuterSubscriber");
var subscribeToResult_1 = require("../util/subscribeToResult");
/* tslint:enable:max-line-length */
/**
 * Projects each source value to the same Observable which is flattened multiple
 * times with {@link switch} in the output Observable.
 *
 * It's like {@link switchMap}, but maps each value
 * always to the same inner Observable.
 *
 *
 *
 * Maps each source value to the given Observable `innerObservable` regardless
 * of the source value, and then flattens those resulting Observables into one
 * single Observable, which is the output Observable. The output Observables
 * emits values only from the most recently emitted instance of
 * `innerObservable`.
 *
 * @example
Rerun an interval Observable on every click event

 * var clicks = Rx.Observable.fromEvent(document, 'click');
 * var result = clicks.switchMapTo(Rx.Observable.interval(1000));
 * result.subscribe(x => console.log(x));
 *
 * @see {@link concatMapTo}
 * @see {@link switch}
 * @see {@link switchMap}
 * @see {@link mergeMapTo}
 *
 * @param {ObservableInput} innerObservable An Observable to replace each value from
 * the source Observable.
 * @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
 * A function to produce the value on the output Observable based on the values
 * and the indices of the source (outer) emission and the inner Observable
 * emission. The arguments passed to this function are:
 * - `outerValue`: the value that came from the source
 * - `innerValue`: the value that came from the projected Observable
 * - `outerIndex`: the "index" of the value that came from the source
 * - `innerIndex`: the "index" of the value from the projected Observable
 * @return {Observable} An Observable that emits items from the given
 * `innerObservable` (and optionally transformed through `resultSelector`) every
 * time a value is emitted on the source Observable, and taking only the values
 * from the most recently projected inner Observable.
 * @method switchMapTo
 * @owner Observable
 */
function switchMapTo(innerObservable, resultSelector) {
    return function (source) { return source.lift(new SwitchMapToOperator(innerObservable, resultSelector)); };
}
exports.switchMapTo = switchMapTo;
var SwitchMapToOperator = /** @class */ (function () {
    function SwitchMapToOperator(observable, resultSelector) {
        this.observable = observable;
        this.resultSelector = resultSelector;
    }
    SwitchMapToOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new SwitchMapToSubscriber(subscriber, this.observable, this.resultSelector));
    };
    return SwitchMapToOperator;
}());
/**
 * We need this JSDoc comment for affecting ESDoc.
 * @ignore
 * @extends {Ignored}
 */
var SwitchMapToSubscriber = /** @class */ (function (_super) {
    __extends(SwitchMapToSubscriber, _super);
    function SwitchMapToSubscriber(destination, inner, resultSelector) {
        var _this = _super.call(this, destination) || this;
        _this.inner = inner;
        _this.resultSelector = resultSelector;
        _this.index = 0;
        return _this;
    }
    SwitchMapToSubscriber.prototype._next = function (value) {
        var innerSubscription = this.innerSubscription;
        if (innerSubscription) {
            innerSubscription.unsubscribe();
        }
        this.add(this.innerSubscription = subscribeToResult_1.subscribeToResult(this, this.inner, value, this.index++));
    };
    SwitchMapToSubscriber.prototype._complete = function () {
        var innerSubscription = this.innerSubscription;
        if (!innerSubscription || innerSubscription.closed) {
            _super.prototype._complete.call(this);
        }
    };
    SwitchMapToSubscriber.prototype._unsubscribe = function () {
        this.innerSubscription = null;
    };
    SwitchMapToSubscriber.prototype.notifyComplete = function (innerSub) {
        this.remove(innerSub);
        this.innerSubscription = null;
        if (this.isStopped) {
            _super.prototype._complete.call(this);
        }
    };
    SwitchMapToSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
        var _a = this, resultSelector = _a.resultSelector, destination = _a.destination;
        if (resultSelector) {
            this.tryResultSelector(outerValue, innerValue, outerIndex, innerIndex);
        }
        else {
            destination.next(innerValue);
        }
    };
    SwitchMapToSubscriber.prototype.tryResultSelector = function (outerValue, innerValue, outerIndex, innerIndex) {
        var _a = this, resultSelector = _a.resultSelector, destination = _a.destination;
        var result;
        try {
            result = resultSelector(outerValue, innerValue, outerIndex, innerIndex);
        }
        catch (err) {
            destination.error(err);
            return;
        }
        destination.next(result);
    };
    return SwitchMapToSubscriber;
}(OuterSubscriber_1.OuterSubscriber));
//# sourceMappingURL=switchMapTo.js.map


text:
layout: docs
authors:
  - blairanderson
date: 2014-08-12 22:22:22
title: .appendTo() in Javascript - without jQuery
description: Insert every element in the set of matched elements to the end of the target.
method: appendTo
href: "docs/appendTo.html"
status: "inactive"
---

#### Sorry, we do not have code examples for implementing [appendTo](http://api.jquery.com/appendTo/) in vanilla javascript.

It would be great if you submitted code on [github](https://github.com/blairanderson/without-jquery/blob/master/docs/appendTo.md)

### Example:

```javascript
  //jQuery
  var i = appendTo(taco);

  //Javascript
  var i = document[somethingOtherThanappendTo](taco);

```

**REASONS:**
> Faster, and creates an event upon xyz

*example is computer generated, obviously not real.*


text:
Already a JS/Vue.js developer? Pick an issue, push a PR, and instantly become a member of the vue-storefront contributors community. We've marked some issues as `Easy first pick` to make it easier for newcomers to begin!

Thank you for your interest and engagement!

## Branches

You should fork the project or create a branch for new features. The main branches used by the core team are:

- `master` - where we store the stable release of the app (that can be deployed to our demo instances).
- `develop` - the most recent version of the app, kind of a "nightly" build.

Please use `develop` for development purposes as the `master` can be merged just as the new release is coming out (about once a month).

## Issue reporting guidelines

Always define the type of issue:

- Bug report
- Feature request

While writing issues, please be as specific as possible. All requests regarding support with implementation or application setup should be sent to [contributors@vuestorefront.io](mailto:contributors@vuestorefront.io)

If the issue is about some changes with a particular theme, please prefix the issue with the theme name (ex. `[default] change product tile background color`).

## TypeScript

We're introducing TypeScript to Vue Storefront core, so you can use it where it's appropriate, but please be pragmatic. It would be nice to TS features only in new modules and Vuex. Here are some thoughts on how to use TS features in Vue Storefront: [TypeScript Action Plan](typescript.md).

## Pull request checklist

Here's how to submit a pull request. **Pull requests that don't meet these requirements will not be merged.**

::: warning
**ALWAYS** use [Pull Request template](https://github.com/DivanteLtd/vue-storefront/blob/master/PULL_REQUEST_TEMPLATE.md), it's automatically added to each PR.
:::

1. Fork the repository and clone it locally on the 'develop' branch.
2. Create a branch for your edits. Use the following branch naming conventions:

- `bugfix/task-title`
- `feature/task-name`

3. Describe what you've changed. Include screenshots of the new feature or the before and after if your changes include differences in HTML/CSS. Drag and drop the images into the body of your pull request.

4. Reference any relevant issues or supporting documentation in your PR (ex. `Issue: 39. Issue title.`).

5. If you are adding a new feature, please provide documentation along with the PR. Also, add it to the [upgrade notes](https://github.com/DivanteLtd/vue-storefront/blob/master/doc/Upgrade%20notes.md)

6. If you are removing/renaming something or changing its behavior, please also include it in the [upgrade notes](https://github.com/DivanteLtd/vue-storefront/blob/master/doc/Upgrade%20notes.md)

7. Test your changes! Run your changes against any existing tests and create new ones when needed. Make sure your changes don't break the existing project. Make sure that your branch is passing the Travis CI build.

8. If you have found a potential security vulnerability, please do not report it on the public issue tracker. Instead, send it to us at [contributors@vuestorefront.io](mailto:contributors@vuestorefront.io). We will work with you to verify and fix it as soon as possible.

## New features

If you are making any new feature, make sure it's adjusted to our new, modular approach. Read more [here](../modules/introduction.md)


text:
<?php

namespace WSW\SimpleUpload\Support;

use WSW\SimpleUpload\TestCase;

/**
 * Class TextTest
 * @package WSW\SimpleUpload\Support
 */
class TextTest extends TestCase
{
    /**
     * @codeCoverageIgnore
     */
    public function testNotFoundExtension()
    {
        $slug = Text::slug('ÁBCD', '-', ['Á']);
        $this->assertEquals('abcd', $slug);
    }
}


text:
package main

import (
	"crypto/md5"
	"crypto/sha1"
	"crypto/sha256"
	"encoding/json"
	"fmt"
	"hash"
	"io"
	"io/ioutil"
	"mime"
	"os"
	"path/filepath"
	"strconv"
	"strings"

	"github.com/progrium/go-basher"
)

var Version string

func assert(err error) {
	if err != nil {
		println("!!", err.Error())
		os.Exit(2)
	}
}

func fatal(msg string) {
	println("!!", msg)
	os.Exit(2)
}

func UploadUrl(args []string) {
	bytes, err := ioutil.ReadAll(os.Stdin)
	assert(err)
	var release map[string]interface{}
	assert(json.Unmarshal(bytes, &release))
	url, ok := release["upload_url"].(string)
	if !ok {
		os.Exit(2)
	}
	i := strings.Index(url, "{")
	if i > -1 {
		url = url[:i]
	}
	i = strings.Index(url, "?")
	if i > -1 {
		url = url[:i]
	}
	fmt.Println(url + "?name=")
}

func ReleaseIdFromTagname(args []string) {
	tagname := args[0]
	bytes, err := ioutil.ReadAll(os.Stdin)
	assert(err)
	var releases []map[string]interface{}
	assert(json.Unmarshal(bytes, &releases))
	for _, release := range releases {
		if release["tag_name"].(string) == tagname {
			fmt.Println(strconv.Itoa(int(release["id"].(float64))))
			return
		}
	}
	os.Exit(2)
}

func MimeType(args []string) {
	filename := args[0]
	ext := filepath.Ext(filename)
	mime.AddExtensionType(".gz", "application/gzip")
	mime.AddExtensionType(".tgz", "application/gzip")
	mime.AddExtensionType(".tar", "application/tar")
	mime.AddExtensionType(".zip", "application/zip")
	mimetype := mime.TypeByExtension(ext)
	if mimetype != "" {
		fmt.Println(mimetype)
	} else {
		fmt.Println("application/octet-stream")
	}
}

func Checksum(args []string) {
	if len(args) < 1 {
		fatal("No algorithm specified")
	}
	var h hash.Hash
	switch args[0] {
	case "md5":
		h = md5.New()
	case "sha1":
		h = sha1.New()
	case "sha256":
		h = sha256.New()
	default:
		fatal("Algorithm '" + args[0] + "' is unsupported")
	}
	io.Copy(h, os.Stdin)
	fmt.Printf("%x\n", h.Sum(nil))
}

func main() {
	os.Setenv("VERSION", Version)
	basher.Application(map[string]func([]string){
		"upload-url":              UploadUrl,
		"release-id-from-tagname": ReleaseIdFromTagname,
		"mimetype":                MimeType,
		"checksum":                Checksum,
	}, []string{
		"bash/gh-release.bash",
	}, Asset, true)
}


text:
package org.springframework.vault.support;

import java.util.Map;

/**
 * A key inside Vault's {@code transit} backend.
 *
 * @author Mark Paluch
 * @author Sven Schürmann
 */
public interface VaultTransitKey {

	/**
	 * @return name of the key
	 */
	String getName();

	/**
	 * @return the key type ({@code aes-gcm}, {@code ecdsa-p256}, ...).
	 */
	String getType();

	/**
	 * @return {@literal true} if deletion of the key is allowed. Key deletion must be
	 * turned on to make keys deletable.
	 */
	boolean isDeletionAllowed();

	/**
	 * @return {@literal true} if key derivation MUST be used.
	 */
	boolean isDerived();

	/**
	 * @return {@literal true} if the raw key is exportable.
	 */
	boolean isExportable();

	/**
	 * @return a {@link Map} of key version to its Vault-specific representation.
	 */
	Map<String, Object> getKeys();

	/**
	 * @return the latest key version.
	 */
	int getLatestVersion();

	/**
	 * @return required key version to still be able to decrypt data.
	 */
	int getMinDecryptionVersion();

	/**
	 * @return required key version to encrypt data.
	 * @since 1.1
	 */
	int getMinEncryptionVersion();

	/**
	 * @return whether the key supports decryption.
	 * @since 1.1
	 */
	boolean supportsDecryption();

	/**
	 * @return whether the key supports encryption.
	 * @since 1.1
	 */
	boolean supportsEncryption();

	/**
	 * @return whether the key supports derivation.
	 * @since 1.1
	 */
	boolean supportsDerivation();

	/**
	 * @return whether the key supports signing.
	 * @since 1.1
	 */
	boolean supportsSigning();
}


text:
package org.fest.swing.fixture;

import static org.fest.assertions.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.io.File;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JTextField;

import org.fest.swing.core.Robot;
import org.fest.swing.driver.JFileChooserDriver;
import org.junit.Before;
import org.junit.Test;

/**
 * Tests for {@link JFileChooserFixture}.
 *
 * @author Yvonne Wang
 * @author Alex Ruiz
 */
public class JFileChooserFixture_withMocks_Test {
  private JFileChooserDriver driver;
  private JFileChooser target;

  private JFileChooserFixture fixture;

  @Before
  public void setUp() {
    fixture = new JFileChooserFixture(mock(Robot.class), mock(JFileChooser.class));
    fixture.replaceDriverWith(mock(JFileChooserDriver.class));
    driver = fixture.driver();
    target = fixture.target();
  }

  @Test
  public void should_call_approve_in_driver() {
    fixture.approve();
    verify(driver).clickApproveButton(target);
  }

  @Test
  public void should_return_approve_button_using_driver() {
    JButton approveButton = mock(JButton.class);
    when(driver.approveButton(target)).thenReturn(approveButton);
    JButtonFixture buttonFixture = fixture.approveButton();
    assertThat(buttonFixture.target()).isSameAs(approveButton);
    verify(driver).approveButton(target);
  }

  @Test
  public void should_call_cancel_in_driver() {
    fixture.cancel();
    verify(driver).clickCancelButton(target);
  }

  @Test
  public void should_return_cancel_button_using_driver() {
    JButton cancelButton = mock(JButton.class);
    when(driver.cancelButton(target)).thenReturn(cancelButton);
    JButtonFixture buttonFixture = fixture.cancelButton();
    assertThat(buttonFixture.target()).isSameAs(cancelButton);
    verify(driver).cancelButton(target);
  }

  @Test
  public void should_return_file_name_textBox_using_driver() {
    JTextField fileNameTextBox = mock(JTextField.class);
    when(driver.fileNameTextBox(target)).thenReturn(fileNameTextBox);
    JTextComponentFixture textComponentFixture = fixture.fileNameTextBox();
    assertThat(textComponentFixture.target()).isSameAs(fileNameTextBox);
    verify(driver).fileNameTextBox(target);
  }

  @Test
  public void should_call_selectFile_in_driver_and_return_self() {
    File file = mock(File.class);
    assertThat(fixture.selectFile(file)).isSameAs(fixture);
    verify(driver).selectFile(target, file);
  }

  @Test
  public void should_call_selectFiles_in_driver_and_return_self() {
    File[] files = { mock(File.class) };
    assertThat(fixture.selectFiles(files)).isSameAs(fixture);
    verify(driver).selectFiles(target, files);
  }

  @Test
  public void should_call_setCurrentDirectory_in_driver_and_return_self() {
    File dir = mock(File.class);
    assertThat(fixture.setCurrentDirectory(dir)).isSameAs(fixture);
    verify(driver).setCurrentDirectory(target, dir);
  }
}


text:
from pipeline.param.hetero_sshe_linr_param import HeteroSSHELinRParam
from pipeline.component.component_base import FateComponent
from pipeline.interface import Input
from pipeline.interface import Output
from pipeline.utils.logger import LOGGER

class HeteroSSHELinR(FateComponent, HeteroSSHELinRParam):
    def __init__(self, **kwargs):
        FateComponent.__init__(self, **kwargs)

        # print (self.name)
        LOGGER.debug(f"{self.name} component created")

        new_kwargs = self.erase_component_base_param(**kwargs)

        HeteroSSHELinRParam.__init__(self, **new_kwargs)
        self.input = Input(self.name, data_type="multi")
        self.output = Output(self.name)
        self._module_name = "HeteroSSHELinR"


text:
using System;
using Abp.MultiTenancy;
using Microsoft.EntityFrameworkCore;

namespace Abp.EntityFrameworkCore
{
    public interface IDbContextProvider<out TDbContext>
        where TDbContext : DbContext
    {
        [Obsolete("Use GetDbContext() method instead")]
        TDbContext DbContext { get; }

        TDbContext GetDbContext();

        TDbContext GetDbContext(MultiTenancySides? multiTenancySide );
    }
}


text:
package org.terasology.rendering.dag.nodes;

import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.GL13;
import org.terasology.config.Config;
import org.terasology.config.RenderingConfig;
import org.terasology.config.RenderingDebugConfig;
import org.terasology.monitoring.PerformanceMonitor;
import org.terasology.registry.In;
import org.terasology.rendering.assets.material.Material;
import org.terasology.rendering.dag.AbstractNode;
import org.terasology.rendering.oculusVr.OculusVrHelper;
import org.terasology.rendering.opengl.FBO;
import org.terasology.rendering.opengl.FrameBuffersManager;
import org.terasology.rendering.opengl.PostProcessor;
import org.terasology.rendering.world.WorldRenderer;
import org.terasology.rendering.world.WorldRenderer.RenderingStage;
import static org.lwjgl.opengl.GL11.GL_COLOR_BUFFER_BIT;
import static org.lwjgl.opengl.GL11.GL_DEPTH_BUFFER_BIT;
import static org.lwjgl.opengl.GL11.glClear;
import static org.terasology.rendering.opengl.OpenGLUtils.bindDisplay;
import static org.terasology.rendering.opengl.OpenGLUtils.renderFullscreenQuad;
import static org.terasology.rendering.opengl.OpenGLUtils.setViewportToSizeOf;

/**
 * TODO: Add diagram of this node
 * TODO: Break into two different nodes
 */
public class FinalPostProcessingNode extends AbstractNode {

    @In
    private WorldRenderer worldRenderer;

    @In
    private Config config;

    @In
    private PostProcessor postProcessor;

    @In
    private FrameBuffersManager frameBuffersManager;

    private RenderingDebugConfig renderingDebugConfig;
    private RenderingConfig renderingConfig;

    private FBO.Dimensions fullScale;

    private Material finalPost;
    private Material debug;
    private Material ocDistortion;

    private FBO sceneFinal;
    private FBO ocUndistorted;
    private FBO sceneOpaque;

    @Override
    public void initialise() {
        renderingConfig = config.getRendering();
        renderingDebugConfig = renderingConfig.getDebug();

        ocDistortion = worldRenderer.getMaterial("engine:prog.ocDistortion");
        finalPost = worldRenderer.getMaterial("engine:prog.post"); // TODO: rename shader to finalPost
        debug = worldRenderer.getMaterial("engine:prog.debug");
        // TODO: rethink debug strategy in light of the DAG-based architecture
    }

    /**
     * If each is enabled through the rendering settings, this method
     * adds depth-of-field blur, motion blur and film grain to the rendering
     * obtained so far. If OculusVR support is enabled, it composes (over two
     * calls) the images for each eye into a single image, and applies a distortion
     * pattern to each, to match the optics in the OculusVR headset.
     *

     * Finally, it either sends the image to the display or, when taking a screenshot,
     * instructs the FrameBuffersManager to save it to a file.
     *

     * worldRenderer.getCurrentRenderStage() Can be MONO, LEFT_EYE or RIGHT_EYE, and communicates to the method weather
     * it is dealing with a standard display or an OculusVR setup, and in the
     * latter case, which eye is currently being rendered. Notice that if the
     * OculusVR support is enabled, the image is sent to screen or saved to
     * file only when the value passed in is RIGHT_EYE, as the processing for
     * the LEFT_EYE comes first and leads to an incomplete image.
     */
    @Override
    public void process() {
        PerformanceMonitor.startActivity("rendering/finalPostProcessing");

        ocUndistorted = frameBuffersManager.getFBO("ocUndistorted");
        sceneFinal = frameBuffersManager.getFBO("sceneFinal");
        sceneOpaque = frameBuffersManager.getFBO("sceneOpaque");

        fullScale = sceneOpaque.dimensions();

        if (!renderingDebugConfig.isEnabled()) {
            finalPost.enable();
        } else {
            debug.enable();
        }

        if (!renderingConfig.isOculusVrSupport()) {
            renderFinalMonoImage();
        } else {
            renderFinalStereoImage(worldRenderer.getCurrentRenderStage());
        }

        PerformanceMonitor.endActivity();
    }

    private void renderFinalMonoImage() {
        if (postProcessor.isNotTakingScreenshot()) {
            bindDisplay();
            renderFullscreenQuad(0, 0, Display.getWidth(), Display.getHeight());

        } else {
            sceneFinal.bind();

            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // TODO: verify this is necessary
            renderFullscreenQuad(0, 0, fullScale.width(), fullScale.height());

            postProcessor.saveScreenshot();
            // when saving a screenshot we do not send the image to screen,
            // to avoid the brief one-frame flicker of the screenshot

            // This is needed to avoid the UI (which is not currently saved within the
            // screenshot) being rendered for one frame with buffers.sceneFinal size.
            setViewportToSizeOf(sceneOpaque);
        }
    }

    // TODO: have a flag to invert the eyes (Cross Eye 3D), as mentioned in
    // TODO: http://forum.terasology.org/threads/happy-coding.1018/#post-11264
    private void renderFinalStereoImage(RenderingStage renderingStage) {
        if (postProcessor.isNotTakingScreenshot()) { // TODO: verify if this works
            sceneFinal.bind();
        } else {
            ocUndistorted.bind();
        }

        switch (renderingStage) {
            case LEFT_EYE:
                glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
                renderFullscreenQuad(0, 0, fullScale.width() / 2, fullScale.height());

                break;

            case RIGHT_EYE:
                // no glClear() here: the rendering for the second eye is being added besides the first eye's rendering
                renderFullscreenQuad(fullScale.width() / 2 + 1, 0, fullScale.width() / 2, fullScale.height());

                if (postProcessor.isNotTakingScreenshot()) {
                    bindDisplay();
                    applyOculusDistortion(sceneFinal);

                } else {
                    sceneFinal.bind();
                    applyOculusDistortion(ocUndistorted);
                    postProcessor.saveScreenshot();
                    // when saving a screenshot we do NOT send the image to screen,
                    // to avoid the brief flicker of the screenshot for one frame
                }

                break;
            case MONO:
                break;
        }
    }

    private void applyOculusDistortion(FBO inputBuffer) {
        ocDistortion.enable();

        int texId = 0;
        GL13.glActiveTexture(GL13.GL_TEXTURE0 + texId);
        inputBuffer.bindTexture();
        ocDistortion.setInt("texInputBuffer", texId, true);

        if (postProcessor.isNotTakingScreenshot()) {
            updateOcShaderParametersForVP(0, 0, fullScale.width() / 2, fullScale.height(), RenderingStage.LEFT_EYE);
            renderFullscreenQuad(0, 0, Display.getWidth(), Display.getHeight());
            updateOcShaderParametersForVP(fullScale.width() / 2 + 1, 0, fullScale.width() / 2, fullScale.height(), RenderingStage.RIGHT_EYE);
            renderFullscreenQuad(0, 0, Display.getWidth(), Display.getHeight());

        } else {
            // what follows -should- work also when there is no screenshot being taken, but somehow it doesn't, hence the block above
            updateOcShaderParametersForVP(0, 0, fullScale.width() / 2, fullScale.height(), RenderingStage.LEFT_EYE);
            renderFullscreenQuad(0, 0, fullScale.width(), fullScale.height());
            updateOcShaderParametersForVP(fullScale.width() / 2 + 1, 0, fullScale.width() / 2, fullScale.height(), RenderingStage.RIGHT_EYE);
            renderFullscreenQuad(0, 0, fullScale.width(), fullScale.height());
        }
    }

    private void updateOcShaderParametersForVP(int vpX, int vpY, int vpWidth, int vpHeight, RenderingStage renderingStage) {
        float w = (float) vpWidth / fullScale.width();
        float h = (float) vpHeight / fullScale.height();
        float x = (float) vpX / fullScale.width();
        float y = (float) vpY / fullScale.height();

        float as = (float) vpWidth / vpHeight;

        ocDistortion.setFloat4("ocHmdWarpParam", OculusVrHelper.getDistortionParams()[0], OculusVrHelper.getDistortionParams()[1],
                OculusVrHelper.getDistortionParams()[2], OculusVrHelper.getDistortionParams()[3], true);

        float ocLensCenter = (renderingStage == RenderingStage.RIGHT_EYE)
                ? -1.0f * OculusVrHelper.getLensViewportShift() : OculusVrHelper.getLensViewportShift();

        ocDistortion.setFloat2("ocLensCenter", x + (w + ocLensCenter * 0.5f) * 0.5f, y + h * 0.5f, true);
        ocDistortion.setFloat2("ocScreenCenter", x + w * 0.5f, y + h * 0.5f, true);

        float scaleFactor = 1.0f / OculusVrHelper.getScaleFactor();

        ocDistortion.setFloat2("ocScale", (w / 2) * scaleFactor, (h / 2) * scaleFactor * as, true);
        ocDistortion.setFloat2("ocScaleIn", (2 / w), (2 / h) / as, true);
    }
}


text:
$(document).ready(function() {
    var countries = [
        "Afghanistan", "Albania", "Algeria", "Andorra", "Angola", "Antigua and Barbuda",
        "Argentina", "Armenia", "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh",
        "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia",
        "Bosnia and Herzegovina", "Botswana", "Brazil", "Brunei", "Bulgaria", "Burkina Faso", "Burma",
        "Burundi", "Cambodia", "Cameroon", "Canada", "Cape Verde", "Central African Republic", "Chad",
        "Chile", "China", "Colombia", "Comoros", "Congo, Democratic Republic", "Congo, Republic of the",
        "Costa Rica", "Cote d'Ivoire", "Croatia", "Cuba", "Cyprus", "Czech Republic", "Denmark", "Djibouti",
        "Dominica", "Dominican Republic", "East Timor", "Ecuador", "Egypt", "El Salvador",
        "Equatorial Guinea", "Eritrea", "Estonia", "Ethiopia", "Fiji", "Finland", "France", "Gabon",
        "Gambia", "Georgia", "Germany", "Ghana", "Greece", "Greenland", "Grenada", "Guatemala", "Guinea",
        "Guinea-Bissau", "Guyana", "Haiti", "Honduras", "Hong Kong", "Hungary", "Iceland", "India",
        "Indonesia", "Iran", "Iraq", "Ireland", "Israel", "Italy", "Jamaica", "Japan", "Jordan",
        "Kazakhstan", "Kenya", "Kiribati", "Korea, North", "Korea, South", "Kuwait", "Kyrgyzstan", "Laos",
        "Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg",
        "Macedonia", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands",
        "Mauritania", "Mauritius", "Mexico", "Micronesia", "Moldova", "Mongolia", "Morocco", "Monaco",
        "Mozambique", "Namibia", "Nauru", "Nepal", "Netherlands", "New Zealand", "Nicaragua", "Niger",
        "Nigeria", "Norway", "Oman", "Pakistan", "Panama", "Papua New Guinea", "Paraguay", "Peru",
        "Philippines", "Poland", "Portugal", "Qatar", "Romania", "Russia", "Rwanda", "Samoa", "San Marino",
        "Sao Tome", "Saudi Arabia", "Senegal", "Serbia and Montenegro", "Seychelles", "Sierra Leone",
        "Singapore", "Slovakia", "Slovenia", "Solomon Islands", "Somalia", "South Africa", "Spain",
        "Sri Lanka", "Sudan", "Suriname", "Swaziland", "Sweden", "Switzerland", "Syria", "Taiwan",
        "Tajikistan", "Tanzania", "Thailand", "Togo", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey",
        "Turkmenistan", "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "United States",
        "Uruguay", "Uzbekistan", "Vanuatu", "Venezuela", "Vietnam", "Yemen", "Zambia", "Zimbabwe"
    ];

    var capitals = [
        "Abu Dhabi", "Abuja", "Accra", "Adamstown", "Addis Ababa", "Algiers", "Alofi", "Amman", "Amsterdam",
        "Andorra la Vella", "Ankara", "Antananarivo", "Apia", "Ashgabat", "Asmara", "Astana", "Asunción", "Athens",
        "Avarua", "Baghdad", "Baku", "Bamako", "Bandar Seri Begawan", "Bangkok", "Bangui", "Banjul", "Basseterre",
        "Beijing", "Beirut", "Belgrade", "Belmopan", "Berlin", "Bern", "Bishkek", "Bissau", "Bogotá", "Brasília",
        "Bratislava", "Brazzaville", "Bridgetown", "Brussels", "Bucharest", "Budapest", "Buenos Aires", "Bujumbura",
        "Cairo", "Canberra", "Caracas", "Castries", "Cayenne", "Charlotte Amalie", "Chisinau", "Cockburn Town",
        "Conakry", "Copenhagen", "Dakar", "Damascus", "Dhaka", "Dili", "Djibouti", "Dodoma", "Doha", "Douglas",
        "Dublin", "Dushanbe", "Edinburgh of the Seven Seas", "El Aaiún", "Episkopi Cantonment", "Flying Fish Cove",
        "Freetown", "Funafuti", "Gaborone", "George Town", "Georgetown", "Georgetown", "Gibraltar", "King Edward Point",
        "Guatemala City", "Gustavia", "Hagåtña", "Hamilton", "Hanga Roa", "Hanoi", "Harare", "Hargeisa", "Havana",
        "Helsinki", "Honiara", "Islamabad", "Jakarta", "Jamestown", "Jerusalem", "Juba", "Kabul", "Kampala",
        "Kathmandu", "Khartoum", "Kiev", "Kigali", "Kingston", "Kingston", "Kingstown", "Kinshasa", "Kuala Lumpur",
        "Kuwait City", "Libreville", "Lilongwe", "Lima", "Lisbon", "Ljubljana", "Lomé", "London", "Luanda", "Lusaka",
        "Luxembourg", "Madrid", "Majuro", "Malabo", "Malé", "Managua", "Manama", "Manila", "Maputo", "Marigot",
        "Maseru", "Mata-Utu", "Mbabane Lobamba", "Melekeok Ngerulmud", "Mexico City", "Minsk", "Mogadishu", "Monaco",
        "Monrovia", "Montevideo", "Moroni", "Moscow", "Muscat", "Nairobi", "Nassau", "Naypyidaw", "N'Djamena",
        "New Delhi", "Niamey", "Nicosia", "Nicosia", "Nouakchott", "Nouméa", "Nukuʻalofa", "Nuuk", "Oranjestad",
        "Oslo", "Ottawa", "Ouagadougou", "Pago Pago", "Palikir", "Panama City", "Papeete", "Paramaribo", "Paris",
        "Philipsburg", "Phnom Penh", "Plymouth Brades Estate", "Podgorica Cetinje", "Port Louis", "Port Moresby",
        "Port Vila", "Port-au-Prince", "Port of Spain", "Porto-Novo Cotonou", "Prague", "Praia", "Cape Town",
        "Pristina", "Pyongyang", "Quito", "Rabat", "Reykjavík", "Riga", "Riyadh", "Road Town", "Rome", "Roseau",
        "Saipan", "San José", "San Juan", "San Marino", "San Salvador", "Sana'a", "Santiago", "Santo Domingo",
        "São Tomé", "Sarajevo", "Seoul", "Singapore", "Skopje", "Sofia", "Sri Jayawardenepura Kotte", "St. George's",
        "St. Helier", "St. John's", "St. Peter Port", "St. Pierre", "Stanley", "Stepanakert", "Stockholm", "Sucre",
        "Sukhumi", "Suva", "Taipei", "Tallinn", "Tarawa Atoll", "Tashkent", "Tbilisi", "Tegucigalpa", "Tehran",
        "Thimphu", "Tirana", "Tiraspol", "Tokyo", "Tórshavn", "Tripoli", "Tskhinvali", "Tunis", "Ulan Bator", "Vaduz",
        "Valletta", "The Valley", "Vatican City", "Victoria", "Vienna", "Vientiane", "Vilnius", "Warsaw",
        "Washington, D.C.", "Wellington", "West Island", "Willemstad", "Windhoek", "Yamoussoukro", "Yaoundé", "Yaren",
        "Yerevan", "Zagreb"
    ];

    $.typeahead({
        input: "#typeahead-search-country-v1",
        order: "asc",
        minLength: 1,
        source: {
            data: countries
        }
    });

    $('#typeahead-search-country-v2').on('keyup', function() {
        if ($.trim($(this).val()) == '') {
            $('#result-container').text('No results matching');
        }
    });

    $.typeahead({
        input: "#typeahead-search-country-v2",
        order: "asc",
        minLength: 1,
        maxItem: 10,
        template: "{{display}} {{group}}",
        source: {
            country: {
                data: countries
            },
            capital: {
                data: capitals
            }
        },
        callback: {
            onResult: function (node, query, result, resultCount) {
                if (query === "")  {
                    $('#result-container').html('');

                    return;
                }

                var text = "";
                if (result.length > 0 && result.length < resultCount) {
                    text = "Showing " + result.length + " of " + resultCount + ' elements matching "' + query + '"';
                } else if (result.length > 0) {
                    text = 'Showing ' + result.length + ' elements matching "' + query + '"';
                } else {
                    text = 'No results matching "' + query + '"';
                }
                $('#result-container').html(text);
            },
            onMouseEnter: function (node, a, item, event) {
                if (item.group === "country") {
                    $(a).append('')
                }
            },
            onMouseLeave: function (node, a, item, event) {
                $(a).find('.flag-chart').remove();
            }
        }
    });

    var words = [
        "aberdeen-angus", "Abominablement", "abaca", "aberrance", "abominant", "abachi", "aberrant", "abomination", "aback",
        "aberration", "abomination de la désolation", "abacus", "aberration chromatique", "abominé", "abadir",
        "aberration chromosomique", "abominer", "abaissant", "aberration optique", "abondamment", "abaisse",
        "aberration sphérique", "abondance", "abaissé", "aberré", "abondance de biens ne nuit pas", "abaisse-langue",
        "abet", "abondant", "abaissement", "abêti", "abondé", "abaisser", "abêtir", "abondement", "abaisseur", "abêtissant",
        "abonder", "abajoue", "Abêtissement", "abonnant", "abalone", "abeyance", "abonné", "abalourdir", "abgal",
        "abonnement", "abamectine", "ab hoc", "abonner", "abandon", "abhor", "abonnir", "abandon de caddie", "abhorrant",
        "aboral", "abandon de créance", "abhorré", "abord", "abandon de poste", "abhorrence", "abordable", "abandonnant",
        "abhorrent", "abordage", "abandonné", "abhorrer", "abordant", "abandonner", "abide", "abordé", "abandonnique",
        "abiding", "aborder", "abaque", "abidjanais", "aborder un vaisseau ennemi", "abase", "abidjanaise", "abords",
        "abasie", "abies", "aborigène", "abasourdi", "abies alba", "aboriginal", "abasourdir", "abies fraseri", "aborigine",
        "abasourdissant", "abies numidica", "abornement", "abat", "abiétacée", "aborner", "abatage", "ability", "abort",
        "abâtardi", "abîmant", "abortif", "abâtardir", "abîme", "abortion", "abâtardissant", "abîmé", "abortive", "abate",
        "abimer", "abot", "abatellement", "abîmer", "abouchant", "abatement", "abouché", "abat-faim",
        "abiogenèse", "aboucher", "abatis", "abiose", "aboulant", "abat-jour", "abiotique", "aboulé", "abator", "ABIR",
        "abouler", "abats", "ab irato", "aboulie", "abat-son", "abject", "aboulique", "Abattable", "Abjectement", "abound",
        "abattage", "abjection", "about", "abattant", "abjurant", "aboutage", "abatte", "Abjuration", "aboutant",
        "abattement", "abjuratoire", "abouté", "abattement fiscal", "abjure", "aboutement", "Abatteur", "abjuré", "abouter",
        "abattis", "abjurer", "about-face", "abattoir", "abkhaze", "abouti", "abattre", "ablactation", "aboutir", "abattu",
        "ablatant", "aboutissant", "abattue", "ablaté", "aboutissants", "Abat-vent", "ablatif", "aboutissement", "abat-voix",
        "ablation", "above", "abave", "ablatir", "aboveboard", "abaxial", "ablative", "Above the line", "abbasside",
        "ablativo", "aboyant", "abbatial", "ablaze", "aboyé", "abbatiale", "able", "aboyer", "abbatiat", "ablégat",
        "aboyeur", "abbaye", "ablégation", "Abracadabra", "Abbaye de Westminster", "ableret", "abracadabrant", "abbé",
        "ablet", "abracadabresque", "abbess", "ablette", "abradant", "abbesse", "ablier", "abrasant", "abbevillien",
        "abloquant", "abrasé", "abbey", "abloqué", "abraser", "abbot", "abluant", "abrasif", "abbreviation", "abluer",
        "abrasimètre", "abc", "ablution", "abrasion", "abcès", "ablutions", "abrasive", "Abcès dentaire", "ablutophobie",
        "abréaction", "ABD", "ably", "abréagir", "abdicate", "abnegation", "abreast", "abdication", "abnégation", "abrégé",
        "abdiquant", "abnormal", "abrégeant", "abdiqué", "abnormality", "abrégement", "abdiquer", "abnormally", "abrègement",
        "abdomen", "aboard", "abrégément", "abdominal", "abode", "abréger", "abdominaux", "aboi", "abreuvage", "abduct",
        "aboiement", "abreuvant", "abducteur", "abois", "abreuvé", "abduction", "aboli", "Abreuvement", "abductor", "abolir",
        "abreuver", "abécédaire", "abolish", "abreuvoir", "abée", "abolissant", "abréviatif", "abeillage", "abolissement",
        "abréviation", "abeille", "abolition", "abréviativement", "abeille charpentière", "abolitionism", "abréviature",
        "abeiller", "abolitionist", "abrévié", "abeillère", "abolitionnisme", "abri", "abélien", "Abolitionniste", "abribus",
        "abelisaurus", "abomasum", "abricot", "aber", "abominable", "abricotant", "abricoté", "abricoter", "abricotier",
        "abricotier du japon", "abricot sec", "abrictosaurus", "abri de jardin", "abridge", "abrier", "abri météorologique",
        "abri-sous-roche", "abritant", "abrité", "abriter", "abrivent", "abroad", "abrogate", "abrogatif", "abrogation",
        "abrogé", "abrogeable", "abrogeant", "abroger", "abronia graminea", "abrosaurus", "abrouti", "abroutir", "abrupt",
        "abruptement", "abruptly", "abruti", "abrutir", "abrutissant", "abrutissement", "abrutisseur", "ABS", "ABSA",
        "abscess", "abscissa", "abscisse", "abscission", "abscond", "absconder", "absconding", "abscons", "absconse",
        "abseil", "abseiling", "absence", "absent", "absentant", "absenté", "absentee", "absenteeism", "absentéisme",
        "absentéiste", "absenter", "absentia", "absidal", "abside", "absidial", "absidiole", "absinth", "absinthe",
        "absinthé", "absolu", "absoluité", "absolument", "absolute", "absolutely", "absolutif", "absolution", "absolutism",
        "absolutisme", "absolutist", "absolutiste", "absolutoire", "absolvant", "absolve", "absorb", "absorbable",
        "absorbant", "absorbé", "absorbement", "absorbent", "absorber", "absorbeur", "Absorbeur de vapeurs d'essence",
        "absorptiométrie", "absorption", "absorption intestinale", "absorption racinaire", "absorptivité", "absoudre",
        "absous", "absoute", "abstain", "abstème", "abstemious", "abstenant", "abstention", "abstentionnisme",
        "abstentionniste", "abstenu", "abstergent", "absterger", "abstersif", "abstersion", "abstinence", "abstinent",
        "abstracteur", "abstractif", "abstraction", "abstractivement", "abstraire", "abstrait", "abstraitement",
        "abstrayant", "abstrus", "abstruse", "absurd", "absurde", "absurdement", "absurdité", "absurdity", "abundance",
        "abundant", "abundantly", "abus", "abusant", "abus de bien social", "abus de biens sociaux", "abus de confiance",
        "abus de droit", "abus de faiblesse", "abus de langage", "abus de majorité", "abus de minorité", "abuse", "abusé",
        "abuser", "abuser d'une personne", "abuseur", "abusif", "abusive", "abusivement", "abusus", "abut", "abuter",
        "abutilon", "abutment", "abyme", "abysmal", "abyss", "abyssal", "abysse", "abyssin", "Abyssinian", "abyssinien", "abyssinienne"
    ];

    $('#words').typeahead({
        minLength: 0,
        maxItem: 10,
        order: "asc",
        hint: true,
        accent: true,
        searchOnFocus: true,
        backdrop: {
            "background-color": "#3879d9",
            "opacity": "0.1",
            "filter": "alpha(opacity=10)"
        },
        source: words
    });

    var categories = {
        ale: [
            "Affligem Blonde", "Amsterdam Big Wheel", "Amsterdam Boneshaker IPA", "Amsterdam Downtown Brown", "Amsterdam Oranje Summer White",
            "Anchor Liberty Ale", "Beaus Lug Tread Lagered Ale", "Beerded Lady", "Belhaven Best Ale", "Big Rock Grasshopper Wheat",
            "Big Rock India Pale Ale", "Big Rock Traditional Ale", "Big Rock Warthog Ale", "Black Oak Nut Brown Ale", "Black Oak Pale Ale",
            "Boddingtons Pub Ale", "Boundary Ale", "Caffreys", "Camerons Auburn Ale", "Camerons Cream Ale", "Camerons Rye Pale Ale", "Ceres Strong Ale",
            "Cheval Blanc", "Crazy Canuck Pale Ale", "Creemore Springs Altbier", "Crosswind Pale Ale", "De Koninck", "Delirium Tremens",
            "Erdinger Dunkel Weissbier", "Erdinger Weissbier", "Export", "Flying Monkeys Amber Ale", "Flying Monkeys Antigravity",
            "Flying Monkeys Hoptical", "Flying Monkeys Netherworld", "Flying Monkeys Smashbomb", "Fruli", "Fullers Extra Spec Bitter",
            "Fullers London Pride", "Granville English Bay Pale", "Granville Robson Hefeweizen", "Griffon Pale Ale", "Griffon Red Ale",
            "Hacker-Pschorr Hefe Weisse", "Hacker-Pschorr Munchen Gold", "Hockley Dark Ale", "Hoegaarden", "Hops & Robbers IPA", "Houblon Chouffe",
            "James Ready Original Ale", "Kawartha Cream Ale", "Kawartha Nut Brown Ale", "Kawartha Premium Pale Ale", "Kawartha Raspberry Wheat",
            "Keiths", "Keiths Cascade Hop Ale", "Keiths Galaxy Hop Ale", "Keiths Hallertauer Hop Ale", "Keiths Hop Series Mixer",
            "Keiths Premium White", "Keiths Red", "Kilkenny Cream Ale", "Konig Ludwig Weissbier", "Kronenbourg 1664 Blanc", "La Chouffe",
            "La Messager Red Gluten Free", "Labatt 50 Ale", "Labatt Bass Pale Ale", "Lakeport Ale", "Leffe Blonde", "Leffe Brune",
            "Legendary Muskoka Oddity", "Liefmans Fruitesse", "Lions Winter Ale", "Maclays", "Mad Tom IPA", "Maisels Weisse Dunkel",
            "Maisels Weisse Original"
        ],
        lager: [
            "AC-DC Premium Lager", "Alpine Lager", "Amstel Light", "Amsterdam (416) Local Lager", "Amsterdam Natural Blonde", "Anchor Steam Beer",
            "Barking Squirrel Lager", "Bavaria 8.6", "Bavaria 8.6 Red", "Bavaria Grapefruit Radler", "Bavaria Premium Beer", "Bavik Pils",
            "Baysville Rock Cut Lager", "Becks", "Belle Gueule", "Big Rock Brewmasters Selection", "Big Rock Light Lime", "Big Rock Saaz Republic Pilz",
            "Birra Castello", "Birra Moretti", "Bitburger", "Black Ice", "Black Label", "Blue", "Blue Light", "Bohemian", "Boris Beer",
            "Boris Bold Strong Beer", "Boxer Ice", "Boxer Lager", "Brava", "Brava 5.5", "Brava Light", "Brouczech Premium Lager", "Bud Light",
            "Bud Light Lime", "Bud Light Lime Labatt", "Bud Light Platinum", "Budweiser", "Budweiser Crown", "Budweiser Shot Labatt", "Busch Ice",
            "Busch Lager", "Busch Light", "Camerons Dark266", "Camerons Lager", "Canadian", "Canadian 67", "Canadian 67 Sublime", "Canadian Coldshots",
            "Carib Lager", "Carling Ice", "Carling Lager", "Carling Light", "Carlsberg", "Carlsberg Lite", "Cool Beer Lager", "Coors Banquet", "Coors Light",
            "Corona", "Corona Light", "Cracked Canoe", "Creemore Collection", "Creemore Kellerbier", "Creemore Lager", "Creemore Springs Combo Pack",
            "Creemore Trad Pilsner", "Creemore Urbock", "Crest Super", "Crystal", "Czechvar", "Dab Maibock", "Dab Original Lager", "Dead Frog Mixed Pack",
            "Desperados Tequila Beer", "Dos Equis Amber", "Dos Equis Lager", "Dunkel Weihenstephaner", "Faxe Amber Lager", "Faxe Extra Strong - 10",
            "Faxe Premium Lager - 5", "Faxe Red", "Faxe Strong", "Formosa Springs Draft", "Fosters Import", "Fuerstenberg Prem Pilsener", "Get2gether",
            "Granville Summer Mingler", "Grolsch Lager 450ml", "Grolsch Premium Lager", "Guinness Black Lager", "Hacker-Pschorr Kellerbier", "Harbin Beer",
            "Harp Lager", "Heineken", "Henninger Premium Lager", "Hockley Taster Pack", "Hofbraeu Muenchen Original", "Hogsback Vintage Lager",
            "Hollandia Pilsner", "Holsten Festbock", "Holsten Maibock", "Holsten Premium Bier", "Hopf Weisse", "Hops Bolts India Pale Lager",
            "James Ready 5.5"
        ],
        "stout and porter": [
            "Belhaven Black Scottish Stout", "Guinness Draught Bottle", "Guinness Extra Stout", "Guinness Pub Draught", "Murphys Irish Stout",
            "Muskoka Chocolate Cranberry", "Sleeman Fine Porter"
        ],
        malt: [
            "Boxer Watermelon", "Bud Light Lime Lime-a-rita", "Bud Light Lime Mang-o-rita", "Bud Light Lime Straw-ber-rita", "Colt 45",
            "DJ Trotters Flirty Daiquiri", "DJ Trotters Lolita", "Four Loko Black Cherry", "Four Loko Fruit Punch", "Four Loko Grape", "Four Loko Lemonade",
            "Four Loko Peach", "Four Loko Watermelon", "Kensington Watermelon Wheat", "Mad Jack", "Mickeys", "Mojo Fruit Punch", "Mojo Shot Blue Lagoon",
            "Mojo Shot Melon Ball", "Mojo Shot Sourberry", "Mojo Strawberry & Kiwi", "Mons Abbey Blonde", "Mons Abbey Witte", "Olde English 800",
            "Pepito Sangria", "Poppers Cran Ice", "Poppers Hard Ice", "Poppers Orange Smoothie", "Poppers Pink", "Poppers Ricco Sangria", "Poppers Wild Ice",
            "Seagram Iced Lemon Tea", "Seagram Lemon Lime", "Seagram Orange Mango", "Seagram Wildberry", "Seagram Wildberry Extra 6.9", "Twisted Tea", "Wellington Iron Duke"
        ]
    };

    $('#categories').typeahead({
        minLength: 1,
        maxItem: 15,
        order: "asc",
        hint: true,
        group: [true, "{{group}} beers!"],
        maxItemPerGroup: 5,
        dropdownFilter: "all beers",
        emptyTemplate: 'No result for "{{query}}"',
        source: {
            ale: {
                data: categories.ale
            },
            lager: {
                data: categories.lager
            },
            "stout and porter": {
                data: categories['stout and porter']
            },
            malt: {
                data: categories.malt
            }
        }
    });

    $('#users').typeahead({
        minLength: 1,
        order: "asc",
        dynamic: true,
        delay: 500,
        template: function (query, item) {
            var color = "#777";
            if (item.status === "owner") {
                color = "#ff1493";
            }

            return '' +
                '' +
                '' +
                "" +
                '{{username}} ({{status}})' +
                '({{id}})' +
                ""
        },
        source: {
            user: {
                display: "username",
                href: "https://www.github.com/{{username}}",
                data: [{
                    "id": 415849,
                    "username": "an inserted user that is not inside the database",
                    "avatar": "https://avatars3.githubusercontent.com/u/415849",
                    "status":  "contributor"
                }],
                url: [{
                    type: "GET",
                    url: "http://themesanytime.com/startui/data/typeahead/users.php",

                    data: {
                        q: "{{query}}"
                    },
                    callback: {
                        done: function (data) {
                            for (var i = 0; i < data.data.user.length; i++) {
                                if (data.data.user[i].username === 'running-coder') {
                                    data.data.user[i].status = 'owner';
                                } else {
                                    data.data.user[i].status = 'contributor';
                                }
                            }
                            return data;
                        }
                    }
                }, "data.user"]
            },
            project: {
                display: "project",
                href: function (item) {
                    return '/' + item.project.replace(/\s+/g, '').toLowerCase() + '/documentation/'
                },
                url: [{
                    type: "GET",
                    url: "http://themesanytime.com/startui/data/typeahead/users.php",
                    data: {
                        q: "{{query}}"
                    }
                }, "data.project"],
                template: '' +
                '' +
                '' +
                '' +
                '' +
                '{{project}} {{version}}' +
                '
' +
                '
{{demo}} Demos
' +
                '
{{option}}+ Options
' +
                '
{{callback}}+ Callbacks
' +
                '
' +
                '' +
                ''
            }
        },
        callback: {
            onClick: function (node, a, item, event) {
                // You can do a simple window.location of the item.href
                //alert(JSON.stringify(item));
            },
            onSendRequest: function (node, query) {
                console.log('request is sent, perhaps add a loading animation?')
            },
            onReceiveRequest: function (node, query) {
                console.log('request is received, stop the loading animation?')
            }
        }
    });

    function formatRepo (repo) {
        if (repo.loading) return repo.text;

        var markup = "
" +
            "

" +
            "
" +
            "
" + repo.full_name + "
";

        if (repo.description) {
            markup += "
" + repo.description + "
";
        }

        markup += "
" +
            "
 " + repo.forks_count + " Forks
" +
            "
 " + repo.stargazers_count + " Stars
" +
            "
 " + repo.watchers_count + " Watchers
" +
            "
" +
            "

";

        return markup;
    }

    function formatRepoSelection (repo) {
        return repo.full_name || repo.text;
    }

    $("#js-data-example-ajax").select2({
        ajax: {
            url: "https://api.github.com/search/repositories",
            dataType: 'json',
            delay: 250,
            data: function (params) {
                console.log(params);

                return {
                    q: params.term, // search term
                    page: params.page
                };
            },
            processResults: function (data, params) {
                // parse the results into the format expected by Select2
                // since we are using custom formatting functions we do not need to
                // alter the remote JSON data, except to indicate that infinite
                // scrolling can be used
                params.page = params.page || 1;

                return {
                    results: data.items,
                    pagination: {
                        more: (params.page * 30) < data.total_count
                    }
                };
            },
            cache: false
        },
        escapeMarkup: function (markup) { return markup; },
        minimumInputLength: 1,
        templateResult: formatRepo,
        templateSelection: formatRepoSelection
    });
});