text:
var wH = $(window).height();
var wW = $(window).width();
function contextHeight() {
	 var top = 73;
	 var bottom = 58;
	//浏览器高度小于900,则main_bottom高度改为38px
	 if(document.documentElement.clientHeight<900){
			$(".main_bottom").css("height","38px")
			$(".main_bottom_copyright").find("p").addClass("fl mt8 mr5");
			bottom=38;
	} else {
		$(".main_bottom").css("height","58px")
		$(".main_bottom_copyright").find("p").removeClass("fl mt8 mr5");
		bottom=58;
	}
	 var height = wH - top -bottom;
	 document.getElementById("iframe_center").style.height = height+"px";
	 document.getElementById("iframe_center").style["overflow-y"] = "scroll";
	 document.getElementById("iframe_left_div").style.height = document.documentElement.clientHeight - top + "px";

	wH = $(window).height();
	wW = $(window).width();
 }

var menuBarSize = 6;
var menuBarStart = 1;
var menuBarEnd = menuBarSize;
var menus = $("#top_nav_content .top_nav_content_item");

// 注册点击左侧箭头的事件
function turnLeft(num) {
	if(menuBarStart > num) {
		menuBarStart = menuBarStart - num;
	} else {
		menuBarStart = 1;
	}
	if(menuBarEnd > (menuBarSize + num)) {
		menuBarEnd = menuBarEnd - num;
	} else {
		menuBarEnd = menuBarSize;
	}
	setTopSubnav();
	var mainObj = document.getElementById("top_nav_content");
	//alert($("#top_nav_content").scrollLeft());
	if(mainObj.scrollLeft > 0) {
		var nowLocal = 0;
		nowLocal = $("#top_nav_content").scrollLeft() - 96 * num;
		$("#top_nav_content").animate({
			"scrollLeft": nowLocal + "px"
		}, "fast");
	}
}
// 注册点击右侧箭头的事件
function turnRight(num) {
	if(menuBarStart <= (menus.length - menuBarSize)) {
		menuBarStart = menuBarStart + num;
	}
	if(menuBarEnd < menus.length) {
		menuBarEnd = menuBarEnd + num;
	}
	setTopSubnav();
	var mainObj = document.getElementById("top_nav_content");
	if((mainObj.scrollWidth - mainObj.scrollLeft) > 575) {
		var nowLocal = 0;
		nowLocal = $("#top_nav_content").scrollLeft() + 96 * num;
		$("#top_nav_content").animate({
			"scrollLeft": nowLocal + "px"
		}, "fast");
	}
}
// 给快捷菜单赋值
function setTopSubnav() {
	var ulNode = "";
	$.each(menus, function(index, menu) {
		index = index + 1;
		if(index < menuBarStart) {
			ulNode += '
' + menu.tabName + '
';
		}

		if(index > menuBarEnd) {
			ulNode += '
' + menu.tabName + '
';
		}
	});

	$("#topSubnav").html(ulNode);
	//alert(ulNode);
}


text:
<resources>

    <!-- Strings related to Settings -->
    <string name="transmitter_title">Transmitter</string>
    <string name="device_info_title">Device Info</string>
    <string name="dexcom_account_title">Dexcom Account</string>

</resources>

redpajama_set_name: RedPajamaGithub


text:
package proto

import (
	"time"

	"github.com/NebulousLabs/Sia/build"
	"github.com/NebulousLabs/Sia/crypto"
	"github.com/NebulousLabs/Sia/modules"
)

const (
	// contractExtension is the extension given to contract files.
	contractExtension = ".contract"
)

var (
	// connTimeout determines the number of seconds the dialer will wait
	// for a connect to complete
	connTimeout = build.Select(build.Var{
		Dev:      10 * time.Second,
		Standard: 60 * time.Second,
		Testing:  5 * time.Second,
	}).(time.Duration)

	// hostPriceLeeway is the amount of flexibility we give to hosts when
	// choosing how much to pay for file uploads. If the host does not have the
	// most recent block yet, the host will be expecting a slightly larger
	// payment.
	//
	// TODO: Due to the network connectivity issues that v1.3.0 introduced, we
	// had to increase the amount moderately because hosts would not always be
	// properly connected to the peer network, and so could fall behind on
	// blocks. Once enough of the network has upgraded, we can move the number
	// to '0.003' for 'Standard'.
	hostPriceLeeway = build.Select(build.Var{
		Dev:      0.05,
		Standard: 0.01,
		Testing:  0.002,
	}).(float64)

	// sectorHeight is the height of a Merkle tree that covers a single
	// sector. It is log2(modules.SectorSize / crypto.SegmentSize)
	sectorHeight = func() uint64 {
		height := uint64(0)
		for 1<<height < (modules.SectorSize / crypto.SegmentSize) {
			height++
		}
		return height
	}()
)


text:
cask "font-kaushan-script" do
  version :latest
  sha256 :no_check

  url "https://github.com/google/fonts/raw/main/ofl/kaushanscript/KaushanScript-Regular.ttf",
      verified: "github.com/google/fonts/"
  name "Kaushan Script"
  homepage "https://fonts.google.com/specimen/Kaushan+Script"

  font "KaushanScript-Regular.ttf"
end


text:
During bootstrap, Shipped creates both a local repository that contains a service's source code and a VM for building and running the service. The local directory containing the source code is shared with the VM, so that any changes you make there are available to the VM. This makes it easy to build and test your changes.

1. Issue the `local reload` command, and provide the name of the project to be reloaded.

    Example:

        shipped lcl reload testproject

    Shipped stops the service, rebuilds it, and restarts it.

    ![](posts/files/shipped-cli-labs/assets/local-reload.png)

1. Redeploy the service to the cloud.
   See Commit and Build and Deploy Build.


text:
package it.unimi.dsi.fastutil.ints;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.util.Random;

import org.junit.Test;

public class IntArrayIndirectPriorityQueueTest {

	@Test
	public void testFront() {
		final int refArray[] = { 4, 3, 2, 1, 0, 3, 2, 1, 0, 2, 1, 0, 1, 0, 0 };
		final int tops[] = new int[refArray.length];
		final IntArrayIndirectPriorityQueue queue = new IntArrayIndirectPriorityQueue(refArray);
		for (int i = refArray.length; i-- != 0;)
			queue.enqueue(i);

		assertEquals(5, queue.front(tops));
		assertEquals(new IntOpenHashSet(new int[] { 4, 8, 11, 13, 14 }), new IntOpenHashSet(tops, 0, 5));
		for (int i = 4; i-- != 0;) {
			queue.dequeue();
			assertEquals(i + 1, queue.front(tops));
		}
		queue.dequeue();

		assertEquals(4, queue.front(tops));
		assertEquals(new IntOpenHashSet(new int[] { 3, 7, 10, 12 }), new IntOpenHashSet(tops, 0, 4));
		for (int i = 3; i-- != 0;) {
			queue.dequeue();
			assertEquals(i + 1, queue.front(tops));
		}
		queue.dequeue();

		assertEquals(3, queue.front(tops));
		assertEquals(new IntOpenHashSet(new int[] { 2, 6, 9 }), new IntOpenHashSet(tops, 0, 3));
		for (int i = 2; i-- != 0;) {
			queue.dequeue();
			assertEquals(i + 1, queue.front(tops));
		}
		queue.dequeue();

		assertEquals(2, queue.front(tops));
		assertEquals(new IntOpenHashSet(new int[] { 1, 5 }), new IntOpenHashSet(tops, 0, 2));
		queue.dequeue();
		assertEquals(1, queue.front(tops));
		queue.dequeue();

		assertEquals(1, queue.front(tops));
	}

	private int[] ref;

	private boolean heapEqual(final int[] a, final int[] b, int sizea, final int sizeb) {
		if (sizea != sizeb) return false;
		final int[] aa = new int[sizea];
		final int[] bb = new int[sizea];
		for (int i = 0; i < sizea; i++) {
			aa[i] = ref[a[i]];
			bb[i] = ref[b[i]];
		}
		java.util.Arrays.sort(aa);
		java.util.Arrays.sort(bb);
		while (sizea-- != 0)
			if (!((aa[sizea]) == (bb[sizea]))) return false;
		return true;
	}

	public void test(final int n, final IntComparator comparator) {
		Exception mThrowsIllegal, tThrowsIllegal, mThrowsOutOfBounds, tThrowsOutOfBounds, mThrowsNoElement, tThrowsNoElement;
		int rm = 0, rt = 0;
		final Random r = new Random(0);
		ref = new int[n];

		for (int i = 0; i < n; i++) ref[i] = r.nextInt();

		IntArrayIndirectPriorityQueue m = new IntArrayIndirectPriorityQueue(ref, comparator);
		final IntHeapIndirectPriorityQueue t = new IntHeapIndirectPriorityQueue(ref, comparator);

		/* We add pairs to t. */
		for (int i = 0; i < n / 2; i++) {
			t.enqueue(i);
			m.enqueue(i);
		}

		assertTrue("Error: m and t differ after creation (" + m + ", " + t + ")", heapEqual(m.array, t.heap, m.size(), t.size()));

		/* Now we add and remove random data in m and t, checking that the result is the same. */

		for (int i = 0; i < 2 * n; i++) {
			if (r.nextDouble() < 0.01) {
				t.clear();
				m.clear();
				for (int j = 0; j < n / 2; j++) {
					t.enqueue(j);
					m.enqueue(j);
				}
			}

			final int T = r.nextInt(2 * n);

			mThrowsNoElement = tThrowsNoElement = mThrowsOutOfBounds = tThrowsOutOfBounds = mThrowsIllegal = tThrowsIllegal = null;

			try {
				t.enqueue(T);
			}
			catch (final IndexOutOfBoundsException e) {
				tThrowsOutOfBounds = e;
			}
			catch (final IllegalArgumentException e) {
				tThrowsIllegal = e;
			}

			if (tThrowsIllegal == null) { // To skip duplicates
				try {
					m.enqueue(T);
				}
				catch (final IndexOutOfBoundsException e) {
					mThrowsOutOfBounds = e;
				}
				catch (final IllegalArgumentException e) {
					mThrowsIllegal = e;
				}
			}

			mThrowsIllegal = tThrowsIllegal = null; // To skip duplicates

			assertTrue("Error: enqueue() divergence in IndexOutOfBoundsException for " + T + " (" + mThrowsOutOfBounds + ", " + tThrowsOutOfBounds + ")",
					(mThrowsOutOfBounds == null) == (tThrowsOutOfBounds == null));
			assertTrue("Error: enqueue() divergence in IllegalArgumentException for " + T + " (" + mThrowsIllegal + ", " + tThrowsIllegal + ")",
					(mThrowsIllegal == null) == (tThrowsIllegal == null));

			assertTrue("Error: m and t differ after enqueue (" + m + ", " + t + ")", heapEqual(m.array, t.heap, m.size(), t.size()));

			if (m.size() != 0) {
				assertTrue("Error: m and t differ in first element after enqueue (" + m.first() + "->" + ref[m.first()] + ", " + t.first() + "->" + ref[t.first()] + ")",
						((ref[m.first()]) == (ref[t.first()])));
			}

			mThrowsOutOfBounds = tThrowsOutOfBounds = null;

			try {
				rm = m.dequeue();
				while (!m.isEmpty() && ((ref[m.first()]) == (ref[rm])))	m.dequeue();
			}
			catch (final IndexOutOfBoundsException e) {
				mThrowsOutOfBounds = e;
			}
			catch (final IllegalArgumentException e) {
				mThrowsIllegal = e;
			}
			catch (final java.util.NoSuchElementException e) {
				mThrowsNoElement = e;
			}

			try {
				rt = t.dequeue();
				while (!t.isEmpty() && ((ref[t.first()]) == (ref[rt])))
					t.dequeue();
			}
			catch (final IndexOutOfBoundsException e) {
				tThrowsOutOfBounds = e;
			}
			catch (final IllegalArgumentException e) {
				tThrowsIllegal = e;
			}
			catch (final java.util.NoSuchElementException e) {
				tThrowsNoElement = e;
			}

			assertTrue("Error: dequeue() divergence in IndexOutOfBoundsException (" + mThrowsOutOfBounds + ", " + tThrowsOutOfBounds + ")",
					(mThrowsOutOfBounds == null) == (tThrowsOutOfBounds == null));
			assertTrue("Error: dequeue() divergence in IllegalArgumentException  (" + mThrowsIllegal + ", " + tThrowsIllegal + ")", (mThrowsIllegal == null) == (tThrowsIllegal == null));
			assertTrue("Error: dequeue() divergence in java.util.NoSuchElementException  (" + mThrowsNoElement + ", " + tThrowsNoElement + ")",
					(mThrowsNoElement == null) == (tThrowsNoElement == null));
			if (mThrowsOutOfBounds == null) assertTrue("Error: divergence in dequeue() between m and t (" + rm + "->" + ref[rm] + ", " + rt + "->" + ref[rt] + ")",
					((ref[rt]) == (ref[rm])));

			assertTrue("Error: m and t differ after dequeue (" + m + ", " + t + ")", heapEqual(m.array, t.heap, m.size(), t.size()));

			if (m.size() != 0) {
				assertTrue("Error: m and t differ in first element after dequeue (" + m.first() + "->" + ref[m.first()] + ", " + t.first() + "->" + ref[t.first()] + ")",
						((ref[m.first()]) == (ref[t.first()])));
			}

			mThrowsNoElement = tThrowsNoElement = mThrowsOutOfBounds = tThrowsOutOfBounds = mThrowsIllegal = tThrowsIllegal = null;

			int pos = r.nextInt(n * 2);

			try {
				m.remove(pos);
			}
			catch (final IndexOutOfBoundsException e) {
				mThrowsOutOfBounds = e;
			}
			catch (final IllegalArgumentException e) {
				mThrowsIllegal = e;
			}
			catch (final java.util.NoSuchElementException e) {
				mThrowsNoElement = e;
			}

			try {
				t.remove(pos);
			}
			catch (final IndexOutOfBoundsException e) {
				tThrowsOutOfBounds = e;
			}
			catch (final IllegalArgumentException e) {
				tThrowsIllegal = e;
			}
			catch (final java.util.NoSuchElementException e) {
				tThrowsNoElement = e;
			}

			assertTrue("Error: remove(int) divergence in IndexOutOfBoundsException (" + mThrowsOutOfBounds + ", " + tThrowsOutOfBounds + ")",
					(mThrowsOutOfBounds == null) == (tThrowsOutOfBounds == null));
			assertTrue("Error: remove(int) divergence in IllegalArgumentException  (" + mThrowsIllegal + ", " + tThrowsIllegal + ")", (mThrowsIllegal == null) == (tThrowsIllegal == null));
			assertTrue("Error: remove(int) divergence in java.util.NoSuchElementException  (" + mThrowsNoElement + ", " + tThrowsNoElement + ")",
					(mThrowsNoElement == null) == (tThrowsNoElement == null));

			assertTrue("Error: m and t differ after remove(int) (" + m + ", " + t + ")", heapEqual(m.array, t.heap, m.size(), t.size()));

			if (m.size() != 0) {
				assertTrue("Error: m and t differ in first element after remove(int) (" + m.first() + "->" + ref[m.first()] + ", " + t.first() + "->" + ref[t.first()] + ")",
						((ref[m.first()]) == (ref[t.first()])));
			}

			mThrowsNoElement = tThrowsNoElement = mThrowsOutOfBounds = tThrowsOutOfBounds = mThrowsIllegal = tThrowsIllegal = null;

			pos = r.nextInt(n);

			try {
				t.changed(pos);
			}
			catch (final IndexOutOfBoundsException e) {
				tThrowsOutOfBounds = e;
			}
			catch (final IllegalArgumentException e) {
				tThrowsIllegal = e;
			}
			catch (final java.util.NoSuchElementException e) {
				tThrowsNoElement = e;
			}

			if (tThrowsIllegal == null) {
				try {
					m.changed(pos);
				}
				catch (final IndexOutOfBoundsException e) {
					mThrowsOutOfBounds = e;
				}
				catch (final IllegalArgumentException e) {
					mThrowsIllegal = e;
				}
				catch (final java.util.NoSuchElementException e) {
					mThrowsNoElement = e;
				}
			}

			assertTrue("Error: change(int) divergence in IndexOutOfBoundsException (" + mThrowsOutOfBounds + ", " + tThrowsOutOfBounds + ")",
					(mThrowsOutOfBounds == null) == (tThrowsOutOfBounds == null));
			// assertTrue("Error: change(int) divergence in IllegalArgumentException  (" +
			// mThrowsIllegal + ", " + tThrowsIllegal + ")" , (mThrowsIllegal == null) == (
			// tThrowsIllegal == null));
			assertTrue("Error: change(int) divergence in java.util.NoSuchElementException  (" + mThrowsNoElement + ", " + tThrowsNoElement + ")",
					(mThrowsNoElement == null) == (tThrowsNoElement == null));

			assertTrue("Error: m and t differ after change(int) (" + m + ", " + t + ")", heapEqual(m.array, t.heap, m.size(), t.size()));

			if (m.size() != 0) {
				assertTrue("Error: m and t differ in first element after change(int) (" + m.first() + "->" + ref[m.first()] + ", " + t.first() + "->" + ref[t.first()] + ")",
						((ref[m.first()]) == (ref[t.first()])));
			}

			final int[] temp = t.heap.clone();
			IntArrays.quickSort(temp, 0, t.size()); // To scramble a bit
			m = new IntArrayIndirectPriorityQueue(m.refArray, temp, t.size(), comparator);

			assertTrue("Error: m and t differ after wrap (" + m + ", " + t + ")", heapEqual(m.array, t.heap, m.size(), t.size()));

			if (m.size() != 0) {
				assertTrue("Error: m and t differ in first element after wrap (" + m.first() + "->" + ref[m.first()] + ", " + t.first() + "->" + ref[t.first()] + ")",
						((ref[m.first()]) == (ref[t.first()])));
			}

			if (m.size() != 0 && ((new it.unimi.dsi.fastutil.ints.IntOpenHashSet(m.array, 0, m.size)).size() == m.size())) {

				final int first = m.first();
				ref[first] = r.nextInt();

				// System.err.println("Pre-change m: " +m);
				// System.err.println("Pre-change t: " +t);
				m.changed();
				t.changed(first);

				// System.err.println("Post-change m: " +m);
				// System.err.println("Post-change t: " +t);

				assertTrue("Error: m and t differ after change (" + m + ", " + t + ")", heapEqual(m.array, t.heap, m.size(), t.size()));

				if (m.size() != 0) {
					assertTrue("Error: m and t differ in first element after change (" + m.first() + "->" + ref[m.first()] + ", " + t.first() + "->" + ref[t.first()] + ")",
							((ref[m.first()]) == (ref[t.first()])));
				}
			}
		}

		/* Now we check that m actually holds the same data. */

		m.clear();
		assertTrue("Error: m is not empty after clear()", m.isEmpty());
	}

	@Test
	public void test1() {
		test(1, null);
		test(1, IntComparators.OPPOSITE_COMPARATOR);

	}

	@Test
	public void test10() {
		test(10, null);
		test(10, IntComparators.OPPOSITE_COMPARATOR);
	}

	@Test
	public void test100() {
		test(100, null);
		test(100, IntComparators.OPPOSITE_COMPARATOR);
	}

	@Test
	public void test1000() {
		test(1000, null);
		test(1000, IntComparators.OPPOSITE_COMPARATOR);
	}

}


text:
namespace Hotcakes.Commerce.Data.EF
{
    using System;
    using System.Collections.Generic;

    public partial class hcc_ProductReview
    {
        public int Id { get; set; }
        public System.DateTime lastUpdated { get; set; }
        public System.Guid bvin { get; set; }
        public int Approved { get; set; }
        public string Description { get; set; }
        public int Karma { get; set; }
        public System.DateTime ReviewDate { get; set; }
        public int Rating { get; set; }
        public string UserID { get; set; }
        public long StoreId { get; set; }
        public System.Guid ProductId { get; set; }

        public virtual hcc_Product hcc_Product { get; set; }
    }
}


text:
<?php
namespace Chamilo\Application\Weblcms\Integration\Chamilo\Core\Reporting\Block\Assessment;

use Chamilo\Application\Weblcms\Storage\DataClass\ContentObjectPublication;
use Chamilo\Core\Reporting\ReportingData;
use Chamilo\Libraries\Platform\Translation;

/**
 *
 * @package application.weblcms.php.reporting.blocks Reporting block displaying information about the assessment and
 *          access details
 * @author Joris Willems <joris.willems@gmail.com>
 * @author Alexander Van Paemel
 */
class AssessmentInformationBlock extends AssessmentsBlock
{

    public function count_data()
    {
        $reporting_data = new ReportingData();

        $categories = $this->get_assessment_information_headers();
        $categories = array_merge($categories, $this->get_assessment_reporting_info_headers());

        $reporting_data->set_categories($categories);

        $publication_id = $this->get_publication_id();
        $publication = \Chamilo\Application\Weblcms\Storage\DataManager::retrieve_by_id(
            ContentObjectPublication::class_name(),
            $publication_id);

        $this->add_category_from_array(
            Translation::get('Details'),
            $this->get_assessment_information($publication),
            $reporting_data);

        $reporting_data->set_rows(array(Translation::get('Details')));

        $assessment_reporting_info = $this->get_assessment_reporting_info($publication);
        foreach ($assessment_reporting_info as $translation => $value)
        {
            $reporting_data->add_data_category_row($translation, Translation::get('Details'), $value);
        }

        return $reporting_data;
    }

    public function retrieve_data()
    {
        return $this->count_data();
    }

    public function get_views()
    {
        return array(\Chamilo\Core\Reporting\Viewer\Rendition\Block\Type\Html::VIEW_TABLE);
    }
}


text:
module.exports = function(DwServiceType) {

};


text:
using System;
using System.Globalization;
namespace Microsoft.WindowsAzure.Storage.Blob
{
public class PageRange
{
    public long StartOffset
    {
        get; internal set;
    }

    public long EndOffset
    {
        get; internal set;
    }

    public PageRange(long start, long end)
    {
        throw new System.NotImplementedException();
    }
    public override string ToString()
    {
        throw new System.NotImplementedException();
    }
}

}


text:
class Plyushkin::StringValue < Plyushkin::BaseValue
  persisted_attr :value
end


text:
package cz.muni.ics.phil.bis.api.domain;

import java.util.Objects;

/**
 *
 * @author Dominik Szalai - emptulik at gmail.com
 */
public class FieldNoteDTO
{
    private Long id;
    private String field;
    private String note;

    public Long getId()
    {
        return id;
    }

    public void setId(Long id)
    {
        this.id = id;
    }

    public String getField()
    {
        return field;
    }

    public void setField(String field)
    {
        this.field = field;
    }

    public String getNote()
    {
        return note;
    }

    public void setNote(String note)
    {
        this.note = note;
    }

    @Override
    public int hashCode()
    {
        int hash = 3;
        hash = 11 * hash + Objects.hashCode(this.id);
        return hash;
    }

    @Override
    public boolean equals(Object obj)
    {
        if (obj == null)
        {
            return false;
        }
        if (getClass() != obj.getClass())
        {
            return false;
        }
        final FieldNoteDTO other = (FieldNoteDTO) obj;
        return Objects.equals(this.id, other.id);
    }
}


text:
casper.thenOpen('http://mstrutt.dev/blog/2015/02/notes-from-front-end-london-january/')
	.then(function() {
		phantomcss.screenshot('html', 'blog-post--default');
	});


text:
class User
  include Mongoid::Document
  include Mongoid::Timestamps

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  ## Database authenticatable
  field :username,           type: String
  field :email,              type: String, default: ''
  field :encrypted_password, type: String, default: ''

  ## Recoverable
  field :reset_password_token,   type: String
  field :reset_password_sent_at, type: Time

  ## Rememberable
  field :remember_created_at, type: Time

  ## Trackable
  field :sign_in_count,      type: Integer, default: 0
  field :current_sign_in_at, type: Time
  field :last_sign_in_at,    type: Time
  field :current_sign_in_ip, type: String
  field :last_sign_in_ip,    type: String

  # Confirmable
  field :confirmation_token,   type: String
  field :confirmed_at,         type: Time
  field :confirmation_sent_at, type: Time
  # field :unconfirmed_email,    type: String # Only if using reconfirmable

  ## Lockable
  # field :failed_attempts, type: Integer, default: 0 # Only if lock strategy is :failed_attempts
  # field :unlock_token,    type: String # Only if unlock strategy is :email or :both
  # field :locked_at,       type: Time

  ## Relations
  embeds_one  :role,          class_name: 'Role'
  has_many    :articles,      class_name: 'Article'

  ## Validations
  validates   :username,      presence: true, uniqueness: { case_sensitive: false }
  validates   :role,          presence: true

  ## Callbacks
  after_initialize :set_default_role

  ## Delegations
  delegate    :admin?, :member?, to: :role

  class << self
    def serialize_from_session(key, salt)
      record = to_adapter.get(key[0]["$oid"])
      record if record && record.authenticatable_salt == salt
    end
  end

  protected
  def set_default_role
    self.role ||= Role.find_or_create_by(name: 'member')
  end
end


text:
package org.jbpm.mobileclient.taskView;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import org.jbpm.mobileclient.R;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutionException;

public class TaskViewActivity extends Activity implements View.OnClickListener {

    ToggleButton btnClaim;
    String usrname;
    String authHeader;

    Button btnStart;
    Button btnFail;
    Button btnComplete;

    TextView taskId;
    TextView descriptionData;
    TextView responseId;

    EditText responseData;

    TaskObject taskObject;
    String taskname = " ",serverAddress="";
    Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task_view);

        intent = getIntent();
        usrname = intent.getExtras().getString("username");
        authHeader = intent.getExtras().getString("AuthHeader");
        taskObject = (TaskObject) intent.getSerializableExtra("taskObject");

        serverAddress+=intent.getExtras().getString("ServerAddress");

        // Claim and Release Button
        btnClaim = (ToggleButton) findViewById(R.id.claimRelease);
        btnClaim.setOnClickListener(this);
        if (taskObject.getStatus().equals("Ready")) {
            btnClaim.setChecked(false);
        } else {
            btnClaim.setChecked(true);
        }

        // Task Complete button
        btnStart = (Button) findViewById(R.id.taskStart);
        btnStart.setOnClickListener(this);

        if (taskObject.getStatus().equals("Reserved")) {
            btnStart.setVisibility(View.VISIBLE);
        } else if (taskObject.getStatus().equals("InProgress")) {
            btnStart.setVisibility(View.INVISIBLE);
        }

        // Task Fail button
        btnFail = (Button) findViewById(R.id.taskfail);
        btnFail.setOnClickListener(this);

        if (taskObject.getStatus().equals("InProgress")) {
            btnFail.setVisibility(View.VISIBLE);
        } else btnFail.setVisibility(View.INVISIBLE);

        // Task Delegate button
        btnComplete = (Button) findViewById(R.id.taskComplete);
        btnComplete.setOnClickListener(this);
        if (taskObject.getStatus().equals("InProgress")) {
            btnComplete.setVisibility(View.VISIBLE);
        } else {
            btnComplete.setVisibility(View.INVISIBLE);
        }
        // Task Name Description
        taskId = (TextView) findViewById(R.id.taskviewid);
        // Task Description Data
        descriptionData = (TextView) findViewById(R.id.descriptiondata);

        // Task Response Id
        responseId = (TextView) findViewById(R.id.responseId);
        // Task Response Data
        responseData = (EditText) findViewById(R.id.responsedata);

        taskname = taskObject.getTaskId() + " - " + taskObject.getName();
        taskId.setText(taskname);
        descriptionData.setText(taskObject.getDetails());

        intent = new Intent(this, TaskActivity.class);
        intent.putExtra("username", usrname);
        intent.putExtra("AuthHeader", authHeader);
        intent.putExtra("ServerAddress",serverAddress);
    }

    @Override
    public void onClick(View view) {

        String output = " Not Done";
        String responseMsg;
        switch (view.getId()) {
            case R.id.claimRelease:
                if (btnClaim.isChecked()) {
                    /**
                     * claim the task
                     **/
                    try {
                        output =
                                new getTaskDone()
                                        .execute(serverAddress+"/rest/task/" + taskObject.getTaskId() + "/claim")
                                        .get();
                    } catch (InterruptedException | ExecutionException e) {
                        e.printStackTrace();
                    }

                    responseMsg = setResponse(output);

                    if (responseMsg.equals("SUCCESS")) {

                        btnStart.setVisibility(View.VISIBLE);
                    }
                } else {
                    try {
                        /**
                         * release the task
                         **/
                        output =
                                new getTaskDone()
                                        .execute(serverAddress+"/rest/task/" + taskObject.getTaskId() + "/release")
                                        .get();

                    } catch (InterruptedException | ExecutionException e) {
                        e.printStackTrace();
                    }
                    responseMsg = setResponse(output);

                    if (responseMsg.equals("SUCCESS")) {
                        btnStart.setVisibility(View.INVISIBLE);
                        btnComplete.setVisibility(View.INVISIBLE);
                        btnFail.setVisibility(View.INVISIBLE);
                    }

                }

                break;
            case R.id.taskStart:
                /**
                 * start the task
                 **/

                try {
                    output =
                            new getTaskDone()
                                    .execute(serverAddress+"/rest/task/" + taskObject.getTaskId() + "/start")
                                    .get();

                } catch (InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                }

                responseMsg = setResponse(output);

                if (responseMsg.equals("SUCCESS")) {
                    taskObject.setStatus("InProgress");
                    btnComplete.setVisibility(View.VISIBLE);
                    btnFail.setVisibility(View.VISIBLE);
                }

                break;
            case R.id.taskfail:
                /**
                 * fail the task
                 **/

                try {
                    output =
                            new getTaskDone()
                                    .execute(serverAddress+"/rest/task/" + taskObject.getTaskId() + "/fail")
                                    .get();

                } catch (InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                }
                responseMsg = setResponse(output);

                finish();
                startActivity(intent);

                break;
            case R.id.taskComplete:
                /**
                 * complete the task
                 **/

                try {
                    output =
                            new getTaskDone()
                                    .execute(serverAddress+"/rest/task/" + taskObject.getTaskId() + "/complete?map_performance=" + responseData.getText().toString())
                                    .get();
                } catch (InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                }

                responseMsg = setResponse(output);

                finish();
                startActivity(intent);

                break;
        }
    }

    /**
     * set the task response
     **/
    private String setResponse(String output) {
        String responseMsg = "";
        if (output.length() > 10) {
            responseMsg = output.substring(output.indexOf("<status>") + 8, output.indexOf("</status>"));
            Toast.makeText(getApplicationContext(),
                    "response is " + responseMsg, Toast.LENGTH_LONG)
                    .show();
        }
        return responseMsg;
    }

    /**
     * check whether network is available
     **/
    public boolean isNetworkAvailable() {
        ConnectivityManager cm = (ConnectivityManager)
                getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        return networkInfo != null && networkInfo.isConnected();
    }

    /**
     * do operations on task
     **/
    public class getTaskDone extends AsyncTask<String, Integer, String> {
        HttpURLConnection conn;
        URL url;
        InputStreamReader inputStreamReader;
        BufferedReader bufferedReader;

        getTaskDone() {

        }

        @Override
        protected String doInBackground(String... params) {
            String line = "";
            if (isNetworkAvailable()) {

                try {

                    url = new URL(params[0]);
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setRequestProperty("Authorization", authHeader);

                    inputStreamReader = new InputStreamReader((conn.getInputStream()));
                    bufferedReader = new BufferedReader(inputStreamReader);
                    line = bufferedReader.readLine();

                    conn.disconnect();
                    inputStreamReader.close();
                    bufferedReader.close();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else
                Toast.makeText(getApplicationContext(),"Network Connection is not Available",Toast.LENGTH_SHORT).show();
            return line;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
        }
    }
}


text:
<?php

declare(strict_types=1);

namespace Sylius\Component\Channel\Context\RequestBased;

use Sylius\Component\Channel\Context\ChannelContextInterface;
use Sylius\Component\Channel\Context\ChannelNotFoundException;
use Sylius\Component\Channel\Model\ChannelInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;

final class ChannelContext implements ChannelContextInterface
{
    /** @var RequestResolverInterface */
    private $requestResolver;

    /** @var RequestStack */
    private $requestStack;

    public function __construct(RequestResolverInterface $requestResolver, RequestStack $requestStack)
    {
        $this->requestResolver = $requestResolver;
        $this->requestStack = $requestStack;
    }

    public function getChannel(): ChannelInterface
    {
        try {
            return $this->getChannelForRequest($this->getMasterRequest());
        } catch (\UnexpectedValueException $exception) {
            throw new ChannelNotFoundException(null, $exception);
        }
    }

    private function getChannelForRequest(Request $request): ChannelInterface
    {
        $channel = $this->requestResolver->findChannel($request);

        $this->assertChannelWasFound($channel);

        return $channel;
    }

    private function getMasterRequest(): Request
    {
        $masterRequest = $this->requestStack->getMasterRequest();
        if (null === $masterRequest) {
            throw new \UnexpectedValueException('There are not any requests on request stack');
        }

        return $masterRequest;
    }

    private function assertChannelWasFound(?ChannelInterface $channel): void
    {
        if (null === $channel) {
            throw new \UnexpectedValueException('Channel was not found for given request');
        }
    }
}


text:
<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);

require 'config.php';
require '../src/Be2bill/Api/Autoloader.php';

Be2bill_Api_Autoloader::registerAutoloader();

// Just implement BE2BILL_IDENTIFIER and BE2BILL_PASSWORD as defined
$be2bill = Be2bill_Api_ClientBuilder::buildSandboxDirectLinkClient(BE2BILL_IDENTIFIER, BE2BILL_PASSWORD);

$result = $be2bill->oneClickPayment(
    'A142429',
    100,
    'order_48',
    'client_123456',
    'john.doe@email.com',
    '127.0.0.1',
    'Oneclick payment',
    'mozilla',
    $options = array("EXTRADATA" => "Premium user")
);

var_dump($result);


text:
#ifndef TARANTOOL_XLOG_H_INCLUDED
#define TARANTOOL_XLOG_H_INCLUDED

#include <stdio.h>
#include <stdbool.h>
#include "tt_uuid.h"
#include "vclock.h"

/**
 * XlogError is raised when there is an error with contents
 * of the data directory or a log file. A special subclass
 * of exception is introduced to gracefully skip such errors
 * in panic_if_error = false mode.
 */
struct XlogError: public Exception
{
	XlogError(const char *file, unsigned line,
		  const char *format, ...);
protected:
	XlogError(const struct type *type, const char *file, unsigned line,
		  const char *format, ...);
};

struct XlogGapError: public XlogError
{
	XlogGapError(const char *file, unsigned line,
		  const struct vclock *from,
		  const struct vclock *to);
};

/* {{{ log dir */

/**
 * Type of log directory. A single filesystem directory can be
 * used for logs and snapshots, but an xlog object sees only
 * those files which match its type.
 */
enum xdir_type { SNAP, XLOG };

/**
 * Newly created snapshot files get .inprogress filename suffix.
 * The suffix is removed  when the file is finished
 * and closed.
 */
enum log_suffix { NONE, INPROGRESS };

/**
 * A handle for a data directory with write ahead logs or snapshots.
 * Can be used to find the last log in the directory, scan
 * through all logs, create a new log.
 */
struct xdir {
	/**
	 * Allow partial recovery from a damaged/incorrect
	 * data directory. Suppresses exceptions when scanning
	 * the directory, parsing file headers, or reading
	 * partial or corrupt rows. Incorrect objects
	 * are skipped.
	 */
	bool panic_if_error;

	/**
	 * true if a log file in this directory can by fsync()ed
	 * at close in a separate thread (we use this technique to
	 * speed up sync of write ahead logs, but not snapshots).
	 */
	bool sync_is_async;

	/* Default filename suffix for a new file. */
	enum log_suffix suffix;
	/**
	 * Additional flags to apply at fopen(2) to write.
	 * A write ahead log opened with write mode can use
	 * O_DIRECT flag, for example.
	 */
	char open_wflags[6];
	/**
	 * A pointer to this server uuid. If not assigned
	 * (tt_uuid_is_nil returns true), server id check
	 * for logs in this directory is not performed.
	 * Otherwise, any log in this directory must have
	 * the matching server id.
	 */
	const struct tt_uuid *server_uuid;
	/**
	 * Text of a marker written to the text file header:
	 * XLOG (meaning it's a write ahead log) or SNAP (a
	 * snapshot).
	 */
	const char *filetype;
	/**
	 * File name extension (.xlog or .snap).
	 */
	const char *filename_ext;
	/** File create mode in this directory. */
	mode_t mode;
	/*
	 * Index of files present in the directory. Initially
	 * empty, must be initialized with xdir_scan().
	 */
	vclockset_t index;
	/**
	 * Directory path.
	 */
	char dirname[PATH_MAX+1];
	/** Snapshots or xlogs */
	enum xdir_type type;
};

/**
 * Initialize a log dir.
 */
void
xdir_create(struct xdir *dir, const char *dirname, enum xdir_type type,
	    const struct tt_uuid *server_uuid);

/**
 * Destroy a log dir object.
 */
void
xdir_destroy(struct xdir *dir);

/**
 * Scan or re-scan a directory and update directory
 * index with all log files (or snapshots) in the directory.
 * Must be used if it is necessary to find the last log/
 * snapshot or scan through all logs.
 */
void
xdir_scan(struct xdir *dir);

/**
 * Check that a directory exists and is writable.
 */
void
xdir_check(struct xdir *dir);

/* }}} */

/**
 * Basic open mode for a log file: read or write.
 */
enum log_mode { LOG_READ, LOG_WRITE };

/**
 * A single log file - a snapshot or a write ahead log.
 */
struct xlog {
	/** The directory this file is in. */
	struct xdir *dir;
	/** File handle. */
	FILE *f;
	/** Mode in which this file has been opened: read or write. */
	enum log_mode mode;
	/**
	 * How many xlog rows are in the file last time it
	 * was read or written. Updated in xlog_cursor_close()
	 * and is used to check whether or not we have discovered
	 * a new row in the file since it was last read. This is
	 * used in local hot standby to "follow up" on new rows
	 * appended to the file.
	 */
	size_t rows;
	/** Log file name. */
	char filename[PATH_MAX + 1];
	/** Whether this file has .inprogress suffix. */
	bool is_inprogress;
	/** True if eof has been read when reading the log. */
	bool eof_read;
	/**
	 * Text file header: server uuid. We read
	 * only logs with our own uuid, to avoid situations
	 * when a DBA has manually moved a few logs around
	 * and messed the data directory up.
	 */
	tt_uuid server_uuid;
	/**
	 * Text file header: vector clock taken at the time
	 * this file was created. For WALs, this is vector
	 * clock *at start of WAL*, for snapshots, this
	 * is vector clock *at the time the snapshot is taken*.
	 */
	struct vclock vclock;
};

/**
 * Open an existing log file or snapshot for reading.
 *
 * @param  dir           the log directory to look for a file
 * @param  signature     file name
 *
 * The caller must free the returned structure with
 * xlog_close().
 * Raises an exception in case of error.
 */
struct xlog *
xlog_open(struct xdir *dir, int64_t signature);

/**
 * Open an xlog from a pre-created stdio stream.
 * The log is open for reading.
 * The file is closed on error, even if open fails.
 *
 * The caller must free the created xlog object with
 * xlog_close().
 *
 * Throws an exception in case of error.
 */

struct xlog *
xlog_open_stream(struct xdir *dir, int64_t signature,
		 FILE *file, const char *filename);

/**
 * Create a new file and open it in write (append) mode.
 * Note: an existing file is impossible to open for append,
 * the old files are never appended to.
 *
 * @param server uuid   the server which created the file
 * @param vclock        the global state of replication (vector
 *			clock) at the moment the file is created.
 *
 * @return  xlog object or NULL in case of error.
 */
struct xlog *
xlog_create(struct xdir *dir, const struct vclock *vclock);

/**
 * Sync a log file. The exact action is defined
 * by xdir flags.
 *
 * @retval 0 success
 * @retval -1 error
 */
int
xlog_sync(struct xlog *l);

/**
 * Close the log file and free xlog object.
 *
 * @retval 0 success
 * @retval -1 error (fclose() failed).
 */
int
xlog_close(struct xlog *l);

/**
 * atfork() handler function to close the log pointed
 * at by *lptr in the child.
 */
void
xlog_atfork(struct xlog **lptr);

/* {{{ xlog_cursor - read rows from a log file */

struct xlog_cursor
{
	struct xlog *log;
	int row_count;
	off_t good_offset;
	bool eof_read;
};

void
xlog_cursor_open(struct xlog_cursor *i, struct xlog *l);

void
xlog_cursor_close(struct xlog_cursor *i);

int
xlog_cursor_next(struct xlog_cursor *i, struct xrow_header *packet);

/* }}} */

/** {{{ miscellaneous log io functions. */

/**
 * Return a file name based on directory type, vector clock
 * sum, and a suffix (.inprogress or not).
 */
char *
format_filename(struct xdir *dir, int64_t signature, enum log_suffix suffix);

/**
 * Construct a row to write to the log file.
 */
int
xlog_encode_row(const struct xrow_header *packet, struct iovec *iov);

/** }}} */

#endif /* TARANTOOL_XLOG_H_INCLUDED */


text:
import logging
import threading
import time

logging.basicConfig(level = logging.DEBUG, format = '%(asctime)s.%(msecs)03d [%(levelname)s] (%(threadName)s) %(message)s', datefmt='%Y-%m-%d %H:%M:%S')

c = threading.Condition()
def worker(n):
  logging.debug("wait")
  c.acquire()
  c.wait()
  logging.debug("received !")
  c.release()

logging.debug("start")
for i in range(3):
  threading.Thread(name = 'THREAD-%01d' % (i), target = worker, args = (i,)).start()
logging.debug("set condition")

for i in range(3):
  time.sleep(1.0)
  c.acquire()
  logging.debug("notify one thread")
  c.notify()
  c.release()


text:
package com.thinkgem.jeesite.modules.act.service.ext;

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

import org.activiti.engine.identity.Group;
import org.activiti.engine.identity.GroupQuery;
import org.activiti.engine.impl.GroupQueryImpl;
import org.activiti.engine.impl.Page;
import org.activiti.engine.impl.persistence.entity.GroupEntity;
import org.activiti.engine.impl.persistence.entity.GroupEntityManager;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.utils.SpringContextHolder;
import com.thinkgem.jeesite.modules.act.utils.ActUtils;
import com.thinkgem.jeesite.modules.sys.entity.Role;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.SystemService;

/**
 * Activiti Group Entity Service
 * @author ThinkGem
 * @version 2013-12-05
 */
@Service
public class ActGroupEntityService extends GroupEntityManager {

	private SystemService systemService;

	public SystemService getSystemService() {
		if (systemService == null){
			systemService = SpringContextHolder.getBean(SystemService.class);
		}
		return systemService;
	}

	public Group createNewGroup(String groupId) {
		return new GroupEntity(groupId);
	}

	public void insertGroup(Group group) {
//		getDbSqlSession().insert((PersistentObject) group);
		throw new RuntimeException("not implement method.");
	}

	public void updateGroup(GroupEntity updatedGroup) {
//		CommandContext commandContext = Context.getCommandContext();
//		DbSqlSession dbSqlSession = commandContext.getDbSqlSession();
//		dbSqlSession.update(updatedGroup);
		throw new RuntimeException("not implement method.");
	}

	public void deleteGroup(String groupId) {
//		GroupEntity group = getDbSqlSession().selectById(GroupEntity.class, groupId);
//		getDbSqlSession().delete("deleteMembershipsByGroupId", groupId);
//		getDbSqlSession().delete(group);
		throw new RuntimeException("not implement method.");
	}

	public GroupQuery createNewGroupQuery() {
//		return new GroupQueryImpl(Context.getProcessEngineConfiguration().getCommandExecutorTxRequired());
		throw new RuntimeException("not implement method.");
	}

//	@SuppressWarnings("unchecked")
	public List<Group> findGroupByQueryCriteria(GroupQueryImpl query, Page page) {
//		return getDbSqlSession().selectList("selectGroupByQueryCriteria", query, page);
		throw new RuntimeException("not implement method.");
	}

	public long findGroupCountByQueryCriteria(GroupQueryImpl query) {
//		return (Long) getDbSqlSession().selectOne("selectGroupCountByQueryCriteria", query);
		throw new RuntimeException("not implement method.");
	}

	/**
	 * 根据用户id查找该用户所属的角色
	 */
	public List<Group> findGroupsByUser(String userId) {
//		return getDbSqlSession().selectList("selectGroupsByUserId", userId);
		List<Group> list = Lists.newArrayList();
		User user = getSystemService().getUserByLoginName(userId);
		if (user != null && user.getRoleList() != null){
			for (Role role : user.getRoleList()){
				list.add(ActUtils.toActivitiGroup(role));
			}
		}
		return list;
	}

	public List<Group> findGroupsByNativeQuery(Map<String, Object> parameterMap, int firstResult, int maxResults) {
//		return getDbSqlSession().selectListWithRawParameter("selectGroupByNativeQuery", parameterMap, firstResult, maxResults);
		throw new RuntimeException("not implement method.");
	}

	public long findGroupCountByNativeQuery(Map<String, Object> parameterMap) {
//		return (Long) getDbSqlSession().selectOne("selectGroupCountByNativeQuery", parameterMap);
		throw new RuntimeException("not implement method.");
	}

}


text:
/**
 * Root package of commonmark-java
 *

 *

 *
{@link org.commonmark.parser} for parsing input text to AST nodes

 *
{@link org.commonmark.node} for AST node types and visitors

 *
{@link org.commonmark.renderer.html} for HTML rendering

 *

 */
package org.commonmark;


text:
title:  Skapelse i skriften
date:  28/05/2020
---

**Les disse skriftstedene og skriv ned hvordan hver av disse forfatterne henviste til 1 Mos 1–11:**

`Matt 19,4–5.`

`Mark 10,6–9.`

`Luk 11,50–51.`

`Joh 1,1–3.`

`Apg 14,15.`

`Rom 1,20.`

`2 Kor 4,6.`

`Ef 3,9.`

`1 Tim 2,12–15.`

`Jak 3,9.`

`1 Pet 3,20.`

`Jud 11; Jud 14.`

`Åp 2,7; Åp 3,14; Åp 22,2–3.`

Jesus og alle forfatterne i NT omtaler 1 Mos 1–11 som pålitelig historie. Jesus viser til det Moses har skrevet og skapelsen av mann og kvinne (Matt 19,4). Paulus bruker flere ganger skapelsesberetningen for å underbygge de teologiske poengene han uttrykker i brevene. Til de lærde i Athen sa han: "Gud, han som skapte verden og alt som er i den, han som er herre over himmel og jord, han bor ikke i templer reist av menneskehender" (Apg 17,24). Slik bygget NTs forfattere på 1. Mosebok for å vise leseren betydningen av denne bokstavelige begivenheten.

Les f.eks. Rom 5. Paulus kobler en rekke ganger sammen Adam og Jesus (se Rom 5,12; Rom 5,14–19). Det vil si at han forutsetter en historisk Adam, noe som kullkastes når en evolusjonær opphavsmodell erstatter en bokstavelig lesning av tekstene.

`Hvis NTs forfattere, som ble inspirert av Den hellige ånd, og Jesus selv, så på skapelsesberetningen som pålitelig historie, hvorfor er det da grunn til å stole på feilbarlige menneskers påstander?`


text:
#import <ComponentKit/CKComponent.h>

struct CKComponentSize;

/**
 A component that displays an image using UIImageView.
 */
@interface CKImageComponent : CKComponent

/**
 Uses a static layout with the given image size and applies additional attributes.
 */
+ (instancetype)newWithImage:(UIImage *)image
                  attributes:(const CKViewComponentAttributeValueMap &)attributes
                        size:(const CKComponentSize &)size;

@end


text:
using namespace llvm;

namespace {
/// DAGISelEmitter - The top-level class which coordinates construction
/// and emission of the instruction selector.
class DAGISelEmitter {
  CodeGenDAGPatterns CGP;
public:
  explicit DAGISelEmitter(RecordKeeper &R) : CGP(R) {}
  void run(raw_ostream &OS);
};
} // End anonymous namespace

//===----------------------------------------------------------------------===//
// DAGISelEmitter Helper methods
//

/// getResultPatternCost - Compute the number of instructions for this pattern.
/// This is a temporary hack.  We should really include the instruction
/// latencies in this calculation.
static unsigned getResultPatternCost(TreePatternNode *P,
                                     CodeGenDAGPatterns &CGP) {
  if (P->isLeaf()) return 0;

  unsigned Cost = 0;
  Record *Op = P->getOperator();
  if (Op->isSubClassOf("Instruction")) {
    Cost++;
    CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op);
    if (II.usesCustomInserter)
      Cost += 10;
  }
  for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
    Cost += getResultPatternCost(P->getChild(i), CGP);
  return Cost;
}

/// getResultPatternCodeSize - Compute the code size of instructions for this
/// pattern.
static unsigned getResultPatternSize(TreePatternNode *P,
                                     CodeGenDAGPatterns &CGP) {
  if (P->isLeaf()) return 0;

  unsigned Cost = 0;
  Record *Op = P->getOperator();
  if (Op->isSubClassOf("Instruction")) {
    Cost += Op->getValueAsInt("CodeSize");
  }
  for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
    Cost += getResultPatternSize(P->getChild(i), CGP);
  return Cost;
}

namespace {
// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
// In particular, we want to match maximal patterns first and lowest cost within
// a particular complexity first.
struct PatternSortingPredicate {
  PatternSortingPredicate(CodeGenDAGPatterns &cgp) : CGP(cgp) {}
  CodeGenDAGPatterns &CGP;

  bool operator()(const PatternToMatch *LHS, const PatternToMatch *RHS) {
    const TreePatternNode *LHSSrc = LHS->getSrcPattern();
    const TreePatternNode *RHSSrc = RHS->getSrcPattern();

    if (LHSSrc->getNumTypes() != 0 && RHSSrc->getNumTypes() != 0 &&
        LHSSrc->getType(0) != RHSSrc->getType(0)) {
      MVT::SimpleValueType V1 = LHSSrc->getType(0), V2 = RHSSrc->getType(0);
      if (MVT(V1).isVector() != MVT(V2).isVector())
        return MVT(V2).isVector();

      if (MVT(V1).isFloatingPoint() != MVT(V2).isFloatingPoint())
        return MVT(V2).isFloatingPoint();
    }

    // Otherwise, if the patterns might both match, sort based on complexity,
    // which means that we prefer to match patterns that cover more nodes in the
    // input over nodes that cover fewer.
    unsigned LHSSize = LHS->getPatternComplexity(CGP);
    unsigned RHSSize = RHS->getPatternComplexity(CGP);
    if (LHSSize > RHSSize) return true;   // LHS -> bigger -> less cost
    if (LHSSize < RHSSize) return false;

    // If the patterns have equal complexity, compare generated instruction cost
    unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), CGP);
    unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), CGP);
    if (LHSCost < RHSCost) return true;
    if (LHSCost > RHSCost) return false;

    unsigned LHSPatSize = getResultPatternSize(LHS->getDstPattern(), CGP);
    unsigned RHSPatSize = getResultPatternSize(RHS->getDstPattern(), CGP);
    if (LHSPatSize < RHSPatSize) return true;
    if (LHSPatSize > RHSPatSize) return false;

    // Sort based on the UID of the pattern, giving us a deterministic ordering
    // if all other sorting conditions fail.
    assert(LHS == RHS || LHS->ID != RHS->ID);
    return LHS->ID < RHS->ID;
  }
};
} // End anonymous namespace

void DAGISelEmitter::run(raw_ostream &OS) {
  emitSourceFileHeader("DAG Instruction Selector for the " +
                       CGP.getTargetInfo().getName() + " target", OS);

  OS << "// *** NOTE: This file is #included into the middle of the target\n"
     << "// *** instruction selector class.  These functions are really "
     << "methods.\n\n";

  DEBUG(errs() << "\n\nALL PATTERNS TO MATCH:\n\n";
        for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
             E = CGP.ptm_end(); I != E; ++I) {
          errs() << "PATTERN: ";   I->getSrcPattern()->dump();
          errs() << "\nRESULT:  "; I->getDstPattern()->dump();
          errs() << "\n";
        });

  // Add all the patterns to a temporary list so we can sort them.
  std::vector<const PatternToMatch*> Patterns;
  for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
       I != E; ++I)
    Patterns.push_back(&*I);

  // We want to process the matches in order of minimal cost.  Sort the patterns
  // so the least cost one is at the start.
  std::sort(Patterns.begin(), Patterns.end(), PatternSortingPredicate(CGP));

  // Convert each variant of each pattern into a Matcher.
  std::vector<Matcher*> PatternMatchers;
  for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
    for (unsigned Variant = 0; ; ++Variant) {
      if (Matcher *M = ConvertPatternToMatcher(*Patterns[i], Variant, CGP))
        PatternMatchers.push_back(M);
      else
        break;
    }
  }

  Matcher *TheMatcher = new ScopeMatcher(&PatternMatchers[0],
                                         PatternMatchers.size());

  TheMatcher = OptimizeMatcher(TheMatcher, CGP);
  //Matcher->dump();
  EmitMatcherTable(TheMatcher, CGP, OS);
  delete TheMatcher;
}

namespace llvm {

void EmitDAGISel(RecordKeeper &RK, raw_ostream &OS) {
  DAGISelEmitter(RK).run(OS);
}

} // End llvm namespace


text:
public class ConstantMethodOverload {
	public int method(int i) {
		return 2;
	}

	public int method(byte b) {
		return 1;
	}

	public int call() {
		return method(1);
	}

	public static int test() {
		var obj = new ConstantMethodOverload();
		return obj.call();
	}
}


text:
//  Copyright © 2021 650 Industries. All rights reserved.

#import <ABI44_0_0EXManifests/ABI44_0_0EXManifestsManifest.h>
#import <ABI44_0_0EXManifests/ABI44_0_0EXManifestsBaseManifest.h>

NS_ASSUME_NONNULL_BEGIN

@interface ABI44_0_0EXManifestsNewManifest : ABI44_0_0EXManifestsBaseManifest<ABI44_0_0EXManifestsManifestBehavior>

/**
 * An ID representing this manifest, not the ID for the experience.
 */
- (NSString *)rawId;

/**
 * Incorrect for now until we figure out how to get this in the new manifest format.
 */
- (NSString *)stableLegacyId DEPRECATED_MSG_ATTRIBUTE("Modern manifests don't support stable legacy IDs");

- (NSString *)scopeKey;
- (nullable NSString *)easProjectId;

- (NSString *)createdAt;
- (NSString *)runtimeVersion;
- (NSDictionary *)launchAsset;
- (nullable NSArray *)assets;

- (nullable NSDictionary *)expoGoConfigRootObject;
- (nullable NSDictionary *)expoClientConfigRootObject;

@end

NS_ASSUME_NONNULL_END


text:
package org.kaaproject.kaa.server.appenders.flume.appender.client;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.apache.flume.Event;
import org.apache.flume.EventDeliveryException;
import org.apache.flume.FlumeException;
import org.kaaproject.kaa.server.appenders.flume.appender.client.async.AppendAsyncResultPojo;
import org.kaaproject.kaa.server.appenders.flume.appender.client.async.AppendBatchAsyncResultPojo;
import org.kaaproject.kaa.server.appenders.flume.appender.client.async.AsyncRpcClient;
import org.kaaproject.kaa.server.appenders.flume.appender.client.async.AvroAsyncRpcClient;
import org.kaaproject.kaa.server.appenders.flume.config.gen.PrioritizedFlumeNode;
import org.kaaproject.kaa.server.appenders.flume.config.gen.PrioritizedFlumeNodes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.util.concurrent.ListenableFuture;

public class PriorityFlumeClientManager extends FlumeClientManager<PrioritizedFlumeNodes> {

    private static final Logger LOG = LoggerFactory.getLogger(PriorityFlumeClientManager.class);

    private static final int DEFAULT_POSITION = 0;
    private List<PrioritizedFlumeNode> flumeNodes = null;
    private Integer currentPosition = DEFAULT_POSITION;
    private int maxClientThreads = 1;

    @Override
    public AsyncRpcClient initManager(PrioritizedFlumeNodes parameters) {
        parameters.getFlumeNodes();
        flumeNodes = parameters.getFlumeNodes();
        if (!flumeNodes.isEmpty()) {
            Collections.sort(flumeNodes, new Comparator<PrioritizedFlumeNode>() {
                @Override
                public int compare(PrioritizedFlumeNode o1, PrioritizedFlumeNode o2) {
                    int result;
                    if (o2 != null) {
                        result = o1.getPriority() - o2.getPriority();
                    } else {
                        result = -1;
                    }
                    return result;
                }
            });
        } else {
            LOG.warn("Can't initialize flume Rpc client. No required hosts paraneters.");
        }
        return getNextClient(true);
    }

    @Override
    public AsyncRpcClient initManager(PrioritizedFlumeNodes parameters, int maxClientThreads) {
        parameters.getFlumeNodes();
        flumeNodes = parameters.getFlumeNodes();
        this.maxClientThreads = maxClientThreads;
        if (!flumeNodes.isEmpty()) {
            Collections.sort(flumeNodes, new Comparator<PrioritizedFlumeNode>() {
                @Override
                public int compare(PrioritizedFlumeNode o1, PrioritizedFlumeNode o2) {
                    int result;
                    if (o2 != null) {
                        result = o1.getPriority() - o2.getPriority();
                    } else {
                        result = -1;
                    }
                    return result;
                }
            });
        } else {
            LOG.warn("Can't initialize flume Rpc client. No required hosts paraneters.");
        }
        return getNextClient(true);
    }

    private AsyncRpcClient getNextClient(boolean isInit) {
        return getNextClient(isInit, 0);
    }

    private AsyncRpcClient getNextClient(boolean isInit, int retryCount) {
        LOG.debug("Get next flume rpc client");
        AsyncRpcClient client = null;
        PrioritizedFlumeNode node = null;
        if (isInit) {
            node = flumeNodes.get(DEFAULT_POSITION);
        } else {
            if (++currentPosition >= flumeNodes.size()) {
                node = flumeNodes.get(DEFAULT_POSITION);
                currentPosition = DEFAULT_POSITION;
            } else {
                node = flumeNodes.get(currentPosition);
            }
        }
        try {
            LOG.warn("Initialize new flume client.");
            client = new AvroAsyncRpcClient(node.getHost(), node.getPort(), maxClientThreads);
        } catch (FlumeException e) {
            LOG.warn("Can't initialize flume client.", e);
            if (retryCount <= MAX_RETRY_COUNT) {
                client = getNextClient(false, ++retryCount);
            } else {
                LOG.warn("Wasn't initialized any clients. Got exception {}", e);
                throw e;
            }
        }
        return client;
    }

    @Override
    public void sendEventToFlume(Event event) throws EventDeliveryException {
        sendEventToFlume(event, 1);
    }

    @Override
    public void sendEventsToFlume(List<Event> events) throws EventDeliveryException {
        sendEventsToFlume(events, 1);
    }

    private void sendEventToFlume(Event event, int retryCount) throws EventDeliveryException {
        try {
            LOG.debug("Sending flume event to flume agent {}", event);
            currentClient.append(event);
        } catch (EventDeliveryException e) {
            LOG.warn("Can't send flume event. Got exception {}", e);
            currentClient.close();
            currentClient = getNextClient(false);
            if (retryCount <= MAX_RETRY_COUNT) {
                LOG.debug("Retry send flume event. Count {}", retryCount);
                sendEventToFlume(event, ++retryCount);
            } else {
                LOG.warn("Flume event wasn't sent. Got exception {}", e);
                throw e;
            }
        }
    }

    private void sendEventsToFlume(List<Event> events, int retryCount) throws EventDeliveryException {
        try {
            LOG.debug("Sending flume events to flume agent {}", events);
            currentClient.appendBatch(events);
        } catch (EventDeliveryException e) {
            LOG.warn("Can't send flume events. Got exception {}", e);
            currentClient.close();
            currentClient = getNextClient(false);
            if (retryCount <= MAX_RETRY_COUNT) {
                LOG.debug("Retry send flume events. Count {}", retryCount);
                sendEventsToFlume(events, ++retryCount);
            } else {
                LOG.warn("Flume events wasn't sent. Got exception {}", e);
                throw e;
            }
        }
    }

    @Override
    public ListenableFuture<AppendAsyncResultPojo> sendEventToFlumeAsync(Event event) throws EventDeliveryException {
        return sendEventToFlumeAsync(event, 1);
    }

    @Override
    public ListenableFuture<AppendBatchAsyncResultPojo> sendEventsToFlumeAsync(List<Event> events)
            throws EventDeliveryException {
        return sendEventsToFlumeAsync(events, 1);
    }

    public ListenableFuture<AppendAsyncResultPojo> sendEventToFlumeAsync(Event event, int retryCount)
            throws EventDeliveryException {
        try {
            LOG.debug("Sending flume event to flume agent {}", event);
            return currentClient.appendAsync(event);
        } catch (EventDeliveryException e) {
            LOG.warn("Can't send flume event. Got exception {}", e);
            currentClient.close();
            currentClient = getNextClient(false);
            if (retryCount <= MAX_RETRY_COUNT) {
                LOG.debug("Retry send flume event. Count {}", retryCount);
                return sendEventToFlumeAsync(event, ++retryCount);
            } else {
                LOG.warn("Flume event wasn't sent. Got exception {}", e);
                throw e;
            }
        }
    }

    public ListenableFuture<AppendBatchAsyncResultPojo> sendEventsToFlumeAsync(List<Event> events, int retryCount)
            throws EventDeliveryException {
        try {
            LOG.debug("Sending flume events to flume agent {}", events);
            return currentClient.appendBatchAsync(events);
        } catch (EventDeliveryException e) {
            LOG.warn("Can't send flume events. Got exception {}", e);
            currentClient.close();
            currentClient = getNextClient(false);
            if (retryCount <= MAX_RETRY_COUNT) {
                LOG.debug("Retry send flume events. Count {}", retryCount);
                return sendEventsToFlumeAsync(events, ++retryCount);
            } else {
                LOG.warn("Flume events wasn't sent. Got exception {}", e);
                throw e;
            }
        }
    }
}


text:
' Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

Imports System.Composition
Imports Microsoft.NetCore.Analyzers.Runtime
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax

Namespace Microsoft.NetCore.VisualBasic.Analyzers.Runtime
    ''' <summary>
    ''' CA2242: Test for NaN correctly
    ''' </summary>
    <ExportCodeFixProvider(LanguageNames.VisualBasic), [Shared]>
    Public NotInheritable Class BasicTestForNaNCorrectlyFixer
        Inherits TestForNaNCorrectlyFixer

        Protected Overrides Function GetBinaryExpression(node As SyntaxNode) As SyntaxNode
            Dim argumentSyntax = TryCast(node, ArgumentSyntax)
            Return If(argumentSyntax IsNot Nothing, argumentSyntax.GetExpression(), node)
        End Function

        Protected Overrides Function IsEqualsOperator(node As SyntaxNode) As Boolean
            return node.IsKind(SyntaxKind.EqualsExpression)
        End Function

        Protected Overrides Function IsNotEqualsOperator(node As SyntaxNode) As Boolean
            return node.IsKind(SyntaxKind.NotEqualsExpression)
        End Function

        Protected Overrides Function GetLeftOperand(binaryExpressionSyntax As SyntaxNode) As SyntaxNode
            Return DirectCast(binaryExpressionSyntax, BinaryExpressionSyntax).Left
        End Function

        Protected Overrides Function GetRightOperand(binaryExpressionSyntax As SyntaxNode) As SyntaxNode
            Return DirectCast(binaryExpressionSyntax, BinaryExpressionSyntax).Right
        End Function
    End Class
End Namespace


text:
package at.joma.apidesign.component.l2.client.api;

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

import javax.enterprise.util.Nonbinding;

import at.joma.apidesign.component.l2.client.api.types.SortingDirection;
import at.joma.apidesign.component.l2.client.api.types.SortingOrder;

@Retention(RetentionPolicy.RUNTIME)
@Target({
    ElementType.FIELD,
    ElementType.TYPE,
    ElementType.METHOD
})
public @interface Sorting {

    @Nonbinding
    SortingDirection direction() default SortingDirection.ASC;

    @Nonbinding
    SortingOrder order() default SortingOrder.ALPHABETICALLY;

}


text:
package org.olat.ims.qti.container.qtielements;

import java.util.Locale;

import org.dom4j.Element;
import org.olat.core.gui.translator.PackageTranslator;
import org.olat.core.gui.translator.Translator;
import org.olat.core.util.Util;
import org.olat.ims.qti.QTIModule;

/**
 * Initial Date: 24.11.2004
 *
 * @author Mike Stock
 */
public class SolutionMaterial extends GenericQTIElement {

	private static final String PACKAGE_QTI = Util.getPackageName(QTIModule.class);
	/**
	 * Comment for xmlClass
	 */
	public static final String xmlClass = "solutionmaterial";

	/**
	 * @param el_material
	 */
	public SolutionMaterial(final Element el_material) {
		super(el_material);
	}

	/**
	 * @see org.olat.ims.qti.container.qtielements.GenericQTIElement#render(java.lang.StringBuilder, org.olat.ims.qti.container.qtielements.RenderInstructions)
	 */
	@Override
	public void render(final StringBuilder buffer, final RenderInstructions ri) {
		final Translator translator = new PackageTranslator(PACKAGE_QTI, (Locale) ri.get(RenderInstructions.KEY_LOCALE));
		buffer.append("
");
		buffer.append(translator.translate("render.solution"));
		buffer.append("

");
		super.render(buffer, ri);
		buffer.append("

");

	}

}


text:
// Copyright (c) 2016 Framefield. All rights reserved.
// Released under the MIT license. (see LICENSE.txt)

using Framefield.Core;
using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace CoreTests
{
    [TestClass]
    public class ScriptCompilerTests
    {
        private string m_InvalidScript =
          @"using System;

            public class CompileTest {
                some type errors
            }";

        private const string _validScript =
           @"using System;

            public class CompilerTestClass {
            }";

        private string m_ScriptDependingOnFramefieldCore =
          @"using System;
            using System.Collections.Generic;
            using System.Linq;
            using System.Text;

            namespace Framefield.Core
            {
                public class FloatOperatorsasdfasdfasdfasdf
                {

                    public static OperatorPartContext GetRandomFloat(OperatorPartContext context, List<OperatorPart> inputs) {
                        int seed = (int)inputs[0].Eval(context).Value;
                        int min = (int)inputs[1].Eval(context).Value;
                        int max = (int)inputs[2].Eval(context).Value;
                        var random = new Random(seed);
                        context.Value = random.Next(min, max);
                        return context;
                    }

                }
            }";

        [TestMethod]
        public void compileScript_ScriptDependsOnFramefieldCore_returnsValidAssembly()
        {
          var assembliesLoaded = AppDomain.CurrentDomain.GetAssemblies().ToList();
          var coreAssembly = assembliesLoaded.Find(asm => asm.GetName().Name == "Core");

          var compiler = new ScriptCompiler(true);
          var assembly = compiler.CompileScript(new[] { "System.Core.dll", coreAssembly.Location }.ToList(), m_ScriptDependingOnFramefieldCore, null);

          Assert.AreNotEqual(null, assembly);
        }

        [TestMethod]
        public void compileScript_SimpleScript_returnsCorrectType()
        {
            var compiler = new ScriptCompiler(true);
            var assembly = compiler.CompileScript(new[] { "System.Core.dll" }, _validScript, null);

            var result = assembly.GetTypes().ToList().Find(type => type.Name == "CompilerTestClass");

            Assert.AreNotEqual(null, result);
        }

        [TestMethod]
        [ExpectedException(typeof(Exception))]
        public void compileScript_EmptyStript_throws()
        {
            var compiler = new ScriptCompiler(true);
            compiler.CompileScript(new string[] { }, "", null);
        }

        [TestMethod]
        [ExpectedException(typeof(ScriptCompilerException))]
        public void compileScript_InvalidStript_throws()
        {
            var compiler = new ScriptCompiler(true);
            compiler.CompileScript(new[] { "System.Core.dll" }, m_InvalidScript, null);
        }

    }
}


text:
<!DOCTYPE html>

no content


text:
.. Copyright (c) 2007-2019 UShareSoft, All rights reserved

.. _builder-ovf:

OVF
===

Default builder type: ``OVF or OVA``

Require Cloud Account: No

The OVF builder provides information for building OVF (Open Virtualization Format) compatible machine images.
This builder type is the default name provided by UForge AppCenter.

.. note:: This builder type name can be changed by your UForge administrator. To get the available builder types, please refer to :ref:`command-line-format`

The OVF builder section has the following definition when using YAML:

.. code-block:: yaml

	---
	builders:
	- type: OVF or OVA
		# the rest of the definition goes here.

If you are using JSON:

.. code-block:: javascript

	{
	  "builders": [
	    {
	      "type": "OVF or OVA",
	      ...the rest of the definition goes here.
	    }
	  ]
	}

The OVF builder has the following valid keys:

* ``type`` (mandatory): a string providing the machine image type to build. Default builder type for OVF: ``OVF or OVA``. To get the available builder type, please refer to :ref:`command-line-format`
* ``hardwareSettings`` (mandatory): an object providing hardware settings to be used for the machine image. The following valid keys for hardware settings are:
	* ``memory`` (mandatory): an integer providing the amount of RAM to provide to an instance provisioned from the machine image (in MB).
	* ``hwType`` (optional): an integer providing the hardware type for the machine image. This is the VMware hardware type: 4 (ESXi>3.x), 7 (ESXi>4.x) or 9 (ESXi>5.x)
* ``installation`` (optional): an object providing low-level installation or first boot options. These override any installation options in the :ref:`template-stack` section. The following valid keys for installation are:
	* ``diskSize`` (mandatory): an integer providing the disk size of the machine image to create. Note, this overrides any disk size information in the stack. This cannot be used if an advanced partitioning table is defined in the stack.

.. note:: When building from a scan, your yaml or json file must contain an ``installation`` section in ``builders``. This is mandatory when you create a new template, but might be missing when you build from a scan. Make sure it is present or your build will fail.

Example
-------

The following example shows an OVF builder.

If you are using YAML:

.. code-block:: yaml

	---
	builders:
	- type: OVF or OVA
	  hardwareSettings:
	    memory: 1024
	    hwType: "7 (ESXi>4.x)"

If you are using JSON:

.. code-block:: json

	{
	  "builders": [
	    {
	      "type": "OVF or OVA",
	      "hardwareSettings": {
	        "memory": 1024,
	        "hwType": "7 (ESXi>4.x)"
	      }
	    }
	  ]
	}


text:
title: "Martin Kleppe"
talk: "Daedalus – Though the Maze of Code"
path: "/speakers/martin-kleppe"
type: "speaker"
slug: "martin-kleppe"
twitter: "aemkei"
github: "aemkei"
website: "http://aem1k.com/"
company: "Ubilabs"
bio: "Mapper. Reducer. Creator of JSFuck, co-founder of Ubilabs, involved in JSUnconf, code golfing at aem1k.com, GDE for the Google Maps API."
---

In Greek mythology, Daedalus (Greek: Δαίδαλος "to work artfully") was a skillful craftsman and artist who created the first Labyrinth. People like him still exist and are known as creative coders and code golfers. They push the limits of what is possible with JavaScript and open new doors for others.

Follow Martin on his journey through a maze of JavaScript, CSS, and HTML where the boundaries between art and code are blurred. This entertaining talk will show off invisible code, tweet-sized games, Asian programs, symmetric JavaScript, polyglot inceptions, self-modifying functions, exotic symbols and much more mind-blowing examples.


text:
<?php

namespace App\Models\Admin;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Zizaco\Entrust\Traits\EntrustUserTrait;

class AdminUser extends Authenticatable
{
    use EntrustUserTrait;
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password','is_super',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * Check if user has a permission by its name.
     *
     * @param string|array $permission Permission string or array of permissions.
     * @param bool         $requireAll All permissions in the array are required.
     *
     * @return bool
     */
    /*public function can($permission, $requireAll = false)
    {

        if(Auth::guard('admin')->user()->id===1){
            return true;
        }
        if (is_array($permission)) {
            foreach ($permission as $permName) {
                $hasPerm = $this->can($permName);

                if ($hasPerm && !$requireAll) {
                    return true;
                } elseif (!$hasPerm && $requireAll) {
                    return false;
                }
            }

            // If we've made it this far and $requireAll is FALSE, then NONE of the perms were found
            // If we've made it this far and $requireAll is TRUE, then ALL of the perms were found.
            // Return the value of $requireAll;
            return $requireAll;
        } else {
            foreach ($this->cachedRoles() as $role) {
                // Validate against the Permission table
                foreach ($role->cachedPermissions() as $perm) {
                    if (str_is( $permission, $perm->name) ) {
                        return true;
                    }
                }
            }
        }

        return false;
    }*/

}


text:
package akka

import akka.actor.{ActorRef, ActorSystem, Props}
import akka.actors.{ControlActor, DatabaseActor, WorkerActor}
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global

object System {
  def main(args: Array[String]) {
    val system: ActorSystem = ActorSystem.create("Scheduler")

    val worker: ActorRef = system.actorOf(Props[WorkerActor])
    val database: ActorRef = system.actorOf(Props(new DatabaseActor(worker)))
    val controller: ActorRef = system.actorOf(Props(new ControlActor(database)))

    system.scheduler.schedule(0.seconds, SchedulerConfig.controllerInterval.seconds, controller, "Update")
  }

}


text:
export interface IBerConvertible {

  /**
   * Base function for converting block from BER encoded array of bytes
   * @param inputBuffer ASN.1 BER encoded array
   * @param inputOffset Offset in ASN.1 BER encoded array where decoding should be started
   * @param inputLength Maximum length of array of bytes which can be using in this function
   * @returns Offset after least decoded byte
   */
  fromBER(inputBuffer: ArrayBuffer | Uint8Array, inputOffset: number, inputLength: number): number;
  /**
   * Encoding of current ASN.1 block into ASN.1 encoded array (BER rules)
   * @param sizeOnly Flag that we need only a size of encoding, not a real array of bytes
   * @returns ASN.1 BER encoded array
   */
  toBER(sizeOnly?: boolean): ArrayBuffer;
}

export interface IDerConvertible {
  /**
   * Base function for converting block from DER encoded array of bytes
   * @param inputBuffer ASN.1 DER encoded array
   * @param inputOffset Offset in ASN.1 DER encoded array where decoding should be started
   * @param inputLength Maximum length of array of bytes which can be using in this function
   * @param expectedLength Expected length of converted VALUE_HEX buffer
   * @returns Offset after least decoded byte
   */
  fromDER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number, expectedLength?: number): number;
  /**
   * Encoding of current ASN.1 block into ASN.1 encoded array (DER rules)
   * @param sizeOnly Flag that we need only a size of encoding, not a real array of bytes
   * @returns ASN.1 DER encoded array
   */
  toDER(sizeOnly?: boolean): ArrayBuffer;
}

export interface IStringConvertible {
  /**
   * Returns a string representation of an object
   * @returns String representation of the class object
   */
  toString(): string;
  /**
   * Creates a class object from the string
   * @param data Input string to convert from
   */
  fromString(data: string): void;
}

export interface IDateConvertible {
  /**
   * Converts a class object into the JavaScrip Date Object
   * @returns Date object
   */
  toDate(): Date;
  /**
   * Creates a class object from the JavaScript Date object
   * @param date Date object
   */
  fromDate(date: Date): void;
}


text:
package razas;

import java.util.List;

import dominio.*;
public class Elfo extends Personaje{

	public Elfo(String nombre) {
		super(nombre);
		this.setRaza("ELFO");
		this.idRaza = 3;
		this.ataque = 6;
		this.defensa = 4;
		this.magia = 10;
	}

	public Elfo(int idPersonaje, String nombre) {
		super(nombre);
		this.idPersonaje = idPersonaje;
		this.setRaza("ELFO");
		this.idRaza = 3;
		this.ataque = 6;
		this.defensa = 4;
		this.magia = 10;
	}

	public Elfo(int idPersonaje, String nombre, int vida, int energia, int experiencia, int nivel, int puntos,
			int puedeAgregarAtaque,	int destreza, int velocidad, int potencia, Casta clase, List<Item> mochila)	{
		super(nombre);
		this.idPersonaje = idPersonaje;
		this.nombre = nombre;
		this.vida = vida;
		this.energia = energia;
		this.setRaza("ELFO");
		this.idRaza = 3;
		this.ataque = 6;
		this.defensa = 4;
		this.magia = 10;
		this.experiencia = experiencia;
		this.nivel = nivel;
		this.puntos = puntos;
		this.puedeAgregarAtaque = puedeAgregarAtaque;
		this.destreza = destreza;
		this.velocidad = velocidad;
		this.potencia = potencia;
		this.clase = clase;
		this.mochila = mochila;
	}

	public Elfo(Personaje p) {
		super(p);
		this.setRaza("ELFO");
	}

	@Override
	public boolean puedeAtacar() {
		return energia > (10 + this.calcularPuntosDeAtaque());
	}

	@Override
	public String getRaza() {
		return raza;
	}

	@Override
	protected Personaje clone() throws CloneNotSupportedException {
		Personaje aux = new Elfo(this);
		return aux;
	}

}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Optimization;

namespace HTMLBarsHelper
{
    public class TemplateNamer : ITemplateNamer
    {
        readonly char[] DirectorySeparator;

        public TemplateNamer()
        {
            this.DirectorySeparator = new char[] { Path.DirectorySeparatorChar };
        }

        public string GenerateName(string bundleRelativePath, string fileName)
        {
            var fileNameNoExtension = Path.GetFileNameWithoutExtension(fileName);

            var directories = bundleRelativePath.Split(DirectorySeparator, StringSplitOptions.RemoveEmptyEntries);

            var temp = String.Join("/", directories);

            if (!temp.EndsWith(fileNameNoExtension))
            {
                if (!string.IsNullOrEmpty(temp))
                {
                    temp += "/";
                }
                temp += fileNameNoExtension;
            }
            return temp;
        }
    }
}


text:
using Bonobo.Git.Server.App_GlobalResources;
using Bonobo.Git.Server.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Web;

namespace Bonobo.Git.Server.Helpers
{
    public class MembershipHelper
    {
        public static string GetBaseUrl()
        {
            var request = HttpContext.Current.Request;
            var appUrl = HttpRuntime.AppDomainAppVirtualPath;

            if (!string.IsNullOrWhiteSpace(appUrl)) appUrl += "/";

            var baseUrl = string.Format("{0}://{1}{2}", request.Url.Scheme, request.Url.Authority, appUrl);

            return baseUrl;
        }

        public static bool SendForgotPasswordEmail(User user, string token)
        {
            bool result = true;
            try
            {
                var passwordLink = MembershipHelper.GetBaseUrl() +
                  "Home/ResetPassword?digest=" +
                  HttpUtility.UrlEncode(Encoding.UTF8.GetBytes(token));

                var email = new MailMessage();

                //email.From = new MailAddress("admin@domain.com");
                email.To.Add(new MailAddress(user.Email));

                email.Subject =  Resources.Email_PasswordReset_Title;
                email.IsBodyHtml = true;

                email.Body = Resources.Email_PasswordReset_Body +
                           "" + passwordLink + "";

                SmtpClient smtpClient = new SmtpClient();

                smtpClient.Send(email);
            }
            catch (Exception ex)
            {
                result = false;
            }
            return result;
        }
    }
}


text:
init({ friends: true }, ({ friends }) => {
  const profileId = getQueryVariable('id');
  const button = createButton(friends.hasOwnProperty(profileId), profileId);
  observer.forEach('.author_name', el => el.appendChild(button));
});


text:
import * as React from 'react';
import * as RenderersModel from '../renderers-model';

export class RowRenderer<T> extends React.PureComponent<RenderersModel.RowRendererProps<T>, never> {
    private container: HTMLDivElement | null = null;

    public render() {
        const gridTemplateColumns: string[] = [];
        const elements: React.ReactNode[] = [];
        const minimumFraction = this.props.row.items.reduce((previous, item) => Math.min(previous, item.fraction), Number.POSITIVE_INFINITY);

        for (let i = 0; i < this.props.row.items.length; i++) {
            if (i > 0) {
                gridTemplateColumns.push('max-content');
                elements.push(
                    <this.props.floatyRenderers.rowSeparatorRenderer
                        key={`${i}-seperator`}
                        floatyRenderers={this.props.floatyRenderers}
                        index={i - 1}
                        onMove={this.handleMove}
                        clamp={this.clamp}
                    />
                );
            }
            gridTemplateColumns.push(`minmax(${this.props.floatyManager.getRowMinWidth()}px, ${this.props.row.items[i].fraction / minimumFraction}fr)`);
            elements.push(
                <this.props.floatyRenderers.layoutRenderer
                    key={i}
                    floatyRenderers={this.props.floatyRenderers}
                    floatyManager={this.props.floatyManager}
                    layout={this.props.row.items[i].child}
                />
            );
        }

        return <div ref={this.handleRef} style={{ display: 'grid', gridTemplateColumns: gridTemplateColumns.join(' '), gridTemplateRows: 'minmax(0, 100%)' }}>
            {elements}
        </div>;
    }

    private handleRef = (ref: HTMLDivElement | null) => {
        this.container = ref;
    }

    private clamp = (index: number, deltaX: number) => {
        if (this.container) {
            const minWidth = this.props.floatyManager.getRowMinWidth();
            const widthA = this.container.children[index * 2].getBoundingClientRect().width;
            const widthB = this.container.children[index * 2 + 2].getBoundingClientRect().width;
            const minimum = minWidth - widthA;
            const maximum = widthB - minWidth;
            return Math.min(maximum, Math.max(minimum, deltaX));
        }
        return null;
    }

    private handleMove = (index: number, deltaX: number) => {
        if (this.container) {
            const widthA = this.container.children[index * 2].getBoundingClientRect().width;
            const widthS = this.container.children[index * 2 + 1].getBoundingClientRect().width;
            const widthB = this.container.children[index * 2 + 2].getBoundingClientRect().width;
            const widthTotal = widthA + widthS + widthB;
            const fractionA = widthA / widthTotal;
            const fractionS = widthS / widthTotal;
            const fractionB = widthB / widthTotal;
            const fractionTotal = fractionA + fractionS + fractionB;
            const deltaF = fractionTotal * deltaX / widthTotal;
            const fractionOriginal = this.props.row.items[index].fraction + this.props.row.items[index + 1].fraction;
            const normalizer = fractionOriginal / (fractionA + fractionB);

            this.props.floatyManager.updateRowFractions(
                this.props.row,
                index,
                normalizer * (fractionA + deltaF),
                index + 1,
                normalizer * (fractionB - deltaF)
            );
        }
    }
}


text:
<?php

namespace Lists\DepartmentBundle\Interfaces;

/**
 * DepartmentAccessInterface interface
 */
interface DepartmentAccessInterface
{
    /**
     * @return bool
     */
    public function canUse();
}


text:
export default function curry(fn) {

    return function (arg) {

    	// invoked when only expecting one argument...
    	// or
    	// enought arguments where passed in to invoke the function
    	// return invoked value
        if (fn.length <= 1 || arguments.length >= fn.length ) {
        	return fn.apply(this, arguments);
        }

        // not enough arguments were provided
        // return curried version of partially-applied function
        return [].reduce.call(arguments, (l, c) => curry( l.bind(null, c) ), fn);

    };
}


text:
package org.wso2.developerstudio.datamapper.diagram.schemagen.util;

public enum FileType {

	XML,
	JSON,
	CSV,
	XSD,
	JSONSCHEMA,
	CONNECTOR

}


text:
package com.google.gwtexpui.clippy.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.resources.client.ClientBundle;

public interface ClippyResources extends ClientBundle {
  public static final ClippyResources I = GWT.create(ClippyResources.class);

  @Source("clippy.css")
  ClippyCss css();
}


text:
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
-->

# Airflow on Kubernetes

If you don't have minikube installed, please run `./minikube/start_minikube.sh` to start a k8s-instance on your local machine. Make sure that your `kubectl` is pointing to the local k8s instance.

First build the docker images by running `./docker/build.sh`. This will build the image and push it to the local registry. Secondly, deploy Apache Airflow using `./kube/deploy.sh -d persistent_mode`. Finally, open the Airflow webserver page by browsing to `http://192.168.99.100:30809/admin/` (on OSX).

When kicking of a new job, you should be able to see new pods being kicked off:

```
$ kubectl get pods
NAME                                                                  READY     STATUS              RESTARTS   AGE
airflow-6cf894578b-rkcpm                                              2/2       Running             0          36m
examplehttpoperatorhttpsensorcheck-490dc90941984812b934fceedf07ca81   1/1       Running             0          7s
examplehttpoperatorhttpsensorcheck-ea787dd2163243a78dfba96d81f47e0d   1/1       Running             0          9s
examplehttpoperatorpostop-3637d44e1b8a42789c59d2c6a66bec6a            0/1       ContainerCreating   0          0s
postgres-airflow-b4844754f-b8d8k                                      1/1       Running             0          36m
```


text:
namespace pythonic
{

  namespace bisect
  {
    namespace details
    {
      template <class X, class A>
      using bisect_fun =
          decltype(std::upper_bound<typename X::const_iterator, A>);
    }

    template <class X, class A>
    long bisect(X const &x, A const &a, long lo = 0,
                details::bisect_fun<X, A> const &fun =
                    std::upper_bound<typename X::const_iterator, A>);

    template <class X, class A>
    long bisect(X const &x, A const &a, long lo, long hi,
                details::bisect_fun<X, A> const &fun =
                    std::upper_bound<typename X::const_iterator, A>);

    DECLARE_FUNCTOR(pythonic::bisect, bisect);
  }
}

#endif


text:
package com.sh.ssm.taotao.front.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author JackSun.
 * @Date 2017/3/14 18:32.
 * @Version 1.0
 * @Description
 */
@RequestMapping("/front")
@Controller
public class IndexController {

    @RequestMapping("/index")
    public String showIndex() {
        return "front/index";
    }
}


text:
/*
 * Interpolation.h
 *
 *  Created on: Mar 5, 2013
 *      Author: kristof
 */

#ifndef PEANOCLAW_INTERSUBGRIDCOMMUNICATION_INTERPOLATION_H_
#define PEANOCLAW_INTERSUBGRIDCOMMUNICATION_INTERPOLATION_H_

#include "peano/utils/Dimensions.h"
#include "tarch/la/Vector.h"
#include "tarch/logging/Log.h"

namespace peanoclaw {
  namespace interSubgridCommunication {
    class Interpolation;
  }

  class Patch;

  namespace pyclaw {
    class PyClaw;
  }
}

class peanoclaw::interSubgridCommunication::Interpolation {

  private:
    /**
      * Logging device
      */
    static tarch::logging::Log _log;

  public:

    virtual ~Interpolation(){};

    /**
     * Copies data from the source patch to the destination patch. The difference
     * to the method copyGhostLayerDataBlock is that in this method a discrete
     * part (i.e. a rectangular block of cells) is specified in the destination
     * patch while the appropriate part from the source block is determined by
     * the positions, sizes and subdivision factors of the patches. Therefore,
     * this method also works on patches which have different subcell sizes, due
     * to level or subdivision factor.
     * This method performs a mapping from continuous points in one patch to the
     * discrete cells in the other patch. We use a d-linear interpolation. Since
     * for fine cells we might need information outside the source patch, we use
     * d-linear extrapolation for this.
     *
     * The two parameters interpolateToUOld and interpolateToCurrentTime are
     * helpers while the UNew array does not hold a ghostlayer. There are three
     * situations when an interpolation is performed:
     *
     *  - Filling of ghostlayer: Interpolating to UOld array but using the time
     *    of UNew
     *  - Interpolating to UNew of new patch: Interpolating to UNew array and
     *    using the time of UNew
     *  - Interpolating to UOld of new patch: Interpolating to UOld array and
     *    using the time of UOld
     *
     */
    virtual void interpolateSolution (
        const tarch::la::Vector<DIMENSIONS, int>&    destinationSize,
        const tarch::la::Vector<DIMENSIONS, int>&    destinationOffset,
        peanoclaw::Patch& source,
        peanoclaw::Patch& destination,
        bool interpolateToUOld,
        bool interpolateToCurrentTime,
        bool useTimeUNewOrTimeUOld
    ) = 0;
};

#endif /* PEANOCLAW_INTERSUBGRIDCOMMUNICATION_INTERPOLATION_H_ */