text:
import types

from stp_core.loop.eventually import eventually

from plenum.test import waits
from plenum.test.delayers import ppDelay, pDelay
from plenum.test.helper import sdk_send_random_request
from plenum.test.test_node import getNonPrimaryReplicas

def testOrderingWhenPrePrepareNotReceived(looper, txnPoolNodeSet,
                                          sdk_wallet_client, sdk_pool_handle):
    """
    Send commits but delay pre-prepare and prepares such that enough
    commits are received, now the request should not be ordered until
    pre-prepare is received and ordering should just happen once,
    """
    delay = 10
    non_prim_reps = getNonPrimaryReplicas(txnPoolNodeSet, 0)

    slow_rep = non_prim_reps[0]
    slow_node = slow_rep.node
    slow_node.nodeIbStasher.delay(ppDelay(delay, 0))
    slow_node.nodeIbStasher.delay(pDelay(delay, 0))

    stash_pp = []
    stash_p = []
    orig_pp_method = slow_rep._ordering_service.process_preprepare
    orig_p_method = slow_rep._ordering_service.process_prepare

    def patched_pp(self, msg, sender):
        stash_pp.append((msg, sender))

    def patched_p(self, msg, sender):
        stash_p.append((msg, sender))

    slow_rep._ordering_service.process_preprepare = \
        types.MethodType(patched_pp, slow_rep)
    slow_rep._ordering_service.process_prepare = \
        types.MethodType(patched_p, slow_rep)

    def chk1():
        assert len(slow_rep._ordering_service.commitsWaitingForPrepare) > 0

    sdk_send_random_request(looper, sdk_pool_handle, sdk_wallet_client)
    timeout = waits.expectedPrePrepareTime(len(txnPoolNodeSet)) + delay
    looper.run(eventually(chk1, retryWait=1, timeout=timeout))

    for m, s in stash_pp:
        orig_pp_method(m, s)

    for m, s in stash_p:
        orig_p_method(m, s)

    def chk2():
        assert len(slow_rep._ordering_service.commitsWaitingForPrepare) == 0
        assert slow_rep._ordering_service.spylog.count(slow_rep._ordering_service._do_order.__name__) == 1

    timeout = waits.expectedOrderingTime(len(non_prim_reps) + 1) + 2 * delay
    looper.run(eventually(chk2, retryWait=1, timeout=timeout))


text:
package io.qubite.tomoko;

import io.qubite.tomoko.handler.value.converter.ParserConverterFactory;
import io.qubite.tomoko.operation.OperationExecutorImpl;
import io.qubite.tomoko.patcher.Patcher;
import io.qubite.tomoko.patcher.PatcherBase;
import io.qubite.tomoko.resolver.TreeHandlerResolver;
import io.qubite.tomoko.specification.PatcherTreeSpecification;
import io.qubite.tomoko.specification.descriptor.SpecificationDescriptor;
import io.qubite.tomoko.specification.dsl.HandlerConfigurationDSL;
import io.qubite.tomoko.specification.scanner.ClassScanner;

/**
 * Central Tomoko library facade. Quick and easy way to access all important elements.
 */
public class Tomoko {

    private final TomokoConfiguration configuration;

    Tomoko(TomokoConfiguration configuration) {
        this.configuration = configuration;
    }

    /**
     * Creates a new Tomoko instance using the provided configuration.
     *
     * @param configuration
     * @return
     */
    public static Tomoko instance(TomokoConfiguration configuration) {
        return new Tomoko(configuration);
    }

    /**
     * Allows registering handlers programmatically in a type-safe way.
     *
     * @return
     * @see io.qubite.tomoko.specification.dsl
     */
    public HandlerConfigurationDSL specificationDsl() {
        return HandlerConfigurationDSL.dsl(ParserConverterFactory.instance(configuration));
    }

    /**
     * Scans the target object and registers all properly annotated handlers.
     *
     * @param specification
     * @return handler tree model
     */
    public PatcherTreeSpecification scanHandlerTree(Object specification) {
        return ClassScanner.instance(ParserConverterFactory.instance(configuration)).scan(specification);
    }

    /**
     * Scans the target object and registers all properly annotated handlers.
     *
     * @param specification
     * @return patcher ready to be used
     */
    public Patcher scanPatcher(Object specification) {
        return patcher(scanHandlerTree(specification));
    }

    /**
     * Converts a handler tree model to a patcher.
     *
     * @param specification
     * @return
     */
    public Patcher patcher(PatcherTreeSpecification specification) {
        return PatcherBase.instance(TreeHandlerResolver.of(specification), new OperationExecutorImpl());
    }

    /**
     * Used to retrieve descriptors for handlers found in the provided class. Allows for type-safe patch creation.
     *
     * @param specificationClass
     * @param <T>
     * @return
     */
    public <T> SpecificationDescriptor<T> descriptorFor(Class<T> specificationClass) {
        return SpecificationDescriptor.forClass(specificationClass);
    }

}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<PRONOM-Report xmlns="http://pronom.nationalarchives.gov.uk">
  <report_format_detail>
    <FileFormat>
      <FormatID>2314</FormatID>
      <FormatName>Harvard Graphics Presentation</FormatName>
      <FormatVersion>1-3</FormatVersion>
      <FormatAliases>
      </FormatAliases>
      <FormatFamilies>
      </FormatFamilies>
      <FormatTypes>Presentation</FormatTypes>
      <FormatDisclosure>
      </FormatDisclosure>
      <FormatDescription>Harvard Graphics (originally named Harvard Presentation Graphics) was a presentation and vector graphics program, used mainly on the MS-DOS platform.</FormatDescription>
      <BinaryFileFormat>
      </BinaryFileFormat>
      <ByteOrders>
      </ByteOrders>
      <ReleaseDate>
      </ReleaseDate>
      <WithdrawnDate>
      </WithdrawnDate>
      <ProvenanceSourceID>220</ProvenanceSourceID>
      <ProvenanceName>The Church of Jesus Christ of Latter-Day Saints / The Church of Jesus Christ of Latter-Day Saints</ProvenanceName>
      <ProvenanceSourceDate>24 Oct 2021</ProvenanceSourceDate>
      <ProvenanceDescription>
      </ProvenanceDescription>
      <LastUpdatedDate>24 Oct 2021</LastUpdatedDate>
      <FormatNote>
      </FormatNote>
      <FormatRisk>
      </FormatRisk>
      <TechnicalEnvironment>
      </TechnicalEnvironment>
      <FileFormatIdentifier>
        <Identifier>fmt/1491</Identifier>
        <IdentifierType>PUID</IdentifierType>
      </FileFormatIdentifier>
      <ExternalSignature>
        <ExternalSignatureID>2712</ExternalSignatureID>
        <Signature>prs</Signature>
        <SignatureType>File extension</SignatureType>
      </ExternalSignature>
      <InternalSignature>
        <SignatureID>1864</SignatureID>
        <SignatureName>Harvard Graphics Presentation PRS</SignatureName>
        <SignatureNote>BOF: 0xDCFE {2} 0x0100010000 {1} 0x00C8</SignatureNote>
        <ByteSequence>
          <ByteSequenceID>2176</ByteSequenceID>
          <PositionType>Absolute from BOF</PositionType>
          <Offset>0</Offset>
          <MaxOffset>0</MaxOffset>
          <IndirectOffsetLocation>
          </IndirectOffsetLocation>
          <IndirectOffsetLength>
          </IndirectOffsetLength>
          <Endianness>
          </Endianness>
          <ByteSequenceValue>DCFE{2}0100010000{1}00C8</ByteSequenceValue>
        </ByteSequence>
      </InternalSignature>
    </FileFormat>
    <SearchCriteria>Criteria</SearchCriteria>
  </report_format_detail>
</PRONOM-Report>


text:
from sys import argv

script, user = argv

prompt = "> "

print "Hi %s, I'm the %s script" % (user, script)
print "Can I ask you a few questions?"

print "Do you like me %s" % user
likes = raw_input(prompt)

print "Where do you live %s" % user
lives = raw_input(prompt)

print "What kind of computer do you have %s" % user
computer = raw_input(prompt)

print '''
Alright, so you said %r about liking me.
You live in %r. Not sure where that is.
And you have a %r computer. Nice
''' % (likes, lives, computer)


text:
require 'db/hsqldb'
require 'transaction'

class HSQLDBTransactionTest < Test::Unit::TestCase
  include TransactionTestMethods

  def test_supports_savepoints
    assert_true ActiveRecord::Base.connection.supports_savepoints?
  end

  # @override whole table gets locked!
  def test_transaction_isolation_read_committed
    unless ActiveRecord::Base.connection.supports_transaction_isolation?
      omit("transaction isolation not supported")
    end

    Entry.transaction(:isolation => :read_committed) do
      assert_equal 0, Entry.count

      Entry2.transaction do
        Entry2.create
        #assert_equal 0, Entry.count
      end
    end
    assert_equal 1, Entry.count
  end if Test::Unit::TestCase.ar_version('4.0')

  # @override whole table gets locked!
  def test_transaction_isolation_repeatable_read
    unless ActiveRecord::Base.connection.supports_transaction_isolation?
      omit("transaction isolation not supported")
    end

    # NOTE need to emulate this in another thread !
    #entry = Entry.create(:title => '1234')

    Entry.transaction(:isolation => :repeatable_read) do
      #entry.reload
      #Entry2.find(entry.id).update_attributes(:title => '567')

      #entry.reload
      #assert_equal '1234', entry.title
    end
    #entry.reload
    #assert_equal '567', entry.title
  end if Test::Unit::TestCase.ar_version('4.0')

  # @override
  def test_savepoint
    #omit 'savepoins not supported' unless @supports_savepoints
    Entry.create! :title => '1'
    assert_equal 1, Entry.count

    connection = ActiveRecord::Base.connection
    connection.transaction do
      begin
        connection.create_savepoint
        savepoint_created = true

        Entry.create! :title => '2'
        Entry.create! :title => '3'

        assert_equal 3, Entry.count

        connection.rollback_to_savepoint
        assert_equal 1, Entry.count
      ensure
        # NOTE: HSQLDB seems to not support release after rollback :
        # Invalid argument in JDBC call: 3B001 savepoint exception: invalid specification
        #connection.release_savepoint if savepoint_created
      end
    end
  end unless Test::Unit::TestCase.ar_version('4.1')

  # @override
  def test_using_named_savepoints
    #omit 'savepoins not supported' unless @supports_savepoints

    first = Entry.create! :title => '1'; first.reload

    Entry.transaction do
      first.content = 't'
      first.save!
      Entry.connection.create_savepoint("first")

      first.content = 'f'
      first.save!
      Entry.connection.rollback_to_savepoint("first")
      assert_equal 't', first.reload.content

      first.content = 'f'
      first.save!
      #Entry.connection.release_savepoint("first")
      #assert_equal 'f', first.reload.content
    end
  end if Test::Unit::TestCase.ar_version('4.1')

end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<wicket:extend>

[galleryHeading]

	<form wicket:id="galleryForm" class="gallery-form">

[noPicturesLabel]

[dataview navigator]

[galleryImageThumbnailRenderer]

	</form>

[addPictureHeading]

	<form wicket:id="form" class="profileForm">

[fileFeedback]

[invalidFileTypeMessage]

			[addPictureLabel]

			<input type="submit" wicket:id="submitPicture"
				value="Upload"></input>
			[galleryImageUploadToolTip]

			Files
			(file)

	</form>

</wicket:extend>


text:
all:
	go build

test:
	go test

doc:
	markdown-cli -i GoTemplate.md -o GoTemplate.html -c ../markdown-cfg.json

mkdocs:
	cat GoTemplate.md  >>../tmp2
	echo "GoTemplate/GoTemplate.md" >>../m.list


text:
from django.db import models
from django.template.defaultfilters import slugify
from django.urls import reverse
#from django.core.urlresolvers import reverse
from django.utils import timezone
from django.contrib.auth.models import User

# Create your models here.
class GameGroup(models.Model):
    name = models.CharField(max_length=255)
    game_type = models.CharField(max_length=255, blank=True, null=True)
    description = models.TextField(blank=True, null=True)
    active = models.BooleanField(default=True)
    created_date = models.DateTimeField('created date')
    last_played = models.DateTimeField('last played')
    status = models.CharField(max_length=100)
    slug = models.SlugField(blank=True, null=True)

    def save(self):
        if not self.id:
            self.slug = slugify(self.name)

        super(GameGroup, self).save()

    def __str__(self):
        return self.name

class GameType(models.Model):
    name = models.CharField(max_length=225)
    era = models.ForeignKey('GameEra',
                            on_delete=models.PROTECT,
                            blank=True,
                            null=True,
                            related_name='era')
    description = models.TextField(blank=True, null=True)
    active = models.BooleanField(default=False)
    created_date = models.DateTimeField('created date')
    modified_date = models.DateTimeField('modified date')
    slug = models.SlugField(blank=True, null=True)

    def save(self):
        if not self.id:
            self.slug = slugify(self.name)

        super(GameType, self).save()

    def __str__(self):
        return self.name

class GameEra(models.Model):
    name = models.CharField(max_length=255)
    slug = models.SlugField(blank=True, null=True)

    def save(self):
        if not self.id:
            self.slug = slugify(self.name)

        super(GameEra, self).save()

    def __str__(self):
        return self.name

class Game(models.Model):
    title = models.CharField(max_length=255)
    group = models.ForeignKey('GameGroup',
        on_delete=models.PROTECT,
        blank=True,
        null=True)
    game_type = models.ForeignKey('GameType',
                                  on_delete= models.PROTECT,
                                  blank=True,
                                  null=True,
                                  related_name='game_type')
    body = models.TextField(blank=True, null=True)
    description = models.TextField(blank=True, null=True)
    active = models.BooleanField(default=False)
    number_views = models.IntegerField(default=0)
    number_comments = models.IntegerField(default=0)
    slug = models.SlugField(blank=True, null=True)
    created_date = models.DateTimeField('created date')
    modified_date = models.DateTimeField()
    publish_date = models.DateTimeField(null=True, blank=True, default=None)
    thumbnail = models.ImageField(upload_to='actual_play/image/%Y/%m/%d',\
     blank=True, null=True)
    image = models.ImageField(upload_to='actual_play/image/%Y/%m/%d',\
     blank=True, null=True)
    audio_ogg = models.FileField(upload_to='actual_play/audio/%Y/%m/%d/',\
     blank=True, null=True)
    audio_mp3 = models.FileField(upload_to='actual_play/audio/%Y/%m/%d/',\
     blank=True, null=True)
    video_ogv = models.FileField(upload_to='actual_play/video/%Y/%m/%d/',\
     blank=True, null=True)
    video_mp4 = models.FileField(upload_to='actual_play/video/%Y/%m/%d/',\
     blank=True, null=True)
    audio_url_ogg = models.CharField(max_length=255, blank=True, null=True)
    audio_url_mp3 = models.CharField(max_length=255, blank=True, null=True)
    video_url_ogv = models.CharField(max_length=255, blank=True, null=True)
    video_url_mp4 = models.CharField(max_length=255, blank=True, null=True)

    @property
    def sidebar_icon_class(self):
        return 'sm_icon_class_actual_play'

    def get_group_name(self):
        if self.group:
            group = GameGroup.get(pk=self.group_id)

        return group.slug

    def get_game_type(self):
        if self.game_type:
            game_type = GameType.objects.get(pk=self.game_type_id)

        return game_type.slug

    def get_absolute_url(self):
        return reverse('game', kwargs={'game_type': self.get_game_type(),
            'slug': self.slug})

    def save(self):
        if not self.id:
            self.slug = slugify(self.title)

        super(Game, self).save()

    def __str__(self):
        return self.title

class GameComment(models.Model):
    game = models.ForeignKey(Game,
        on_delete=models.PROTECT,
        related_name='comments')
    comment = models.TextField(null=True, blank=True)
    user = models.ForeignKey(User,
        on_delete=models.PROTECT,
        related_name='actual_play_user',
        null=True,
        blank=True)
    name = models.CharField(max_length=30, null=True, blank=True)
    created_date = models.DateTimeField(auto_now=True)
    approved = models.BooleanField(default=False)

    def approve(self):
        self.approved = True
        self.save()

    def __str__(self):
        return self.game.title

class Player(models.Model):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    nickname = models.CharField(max_length=100)
    email = models.CharField(max_length=255)
    group = models.ManyToManyField(GameGroup)
    active = models.BooleanField(default=True)
    created_date = models.DateTimeField('created date')
    image = models.ImageField(upload_to='actual_play/player/%Y/%m/%d',\
     blank=True, null=True)

    def __str__(self):
        return self.nickname


text:
package org.sfs.vo;

import com.google.common.base.Optional;
import io.vertx.core.json.JsonObject;

import static com.google.common.base.Optional.fromNullable;

public abstract class XFileSystem<T extends XFileSystem> {

    private String partition;
    private String device;
    private String path;
    private Long totalSpace;
    private Long unallocatedSpace;
    private Long usableSpace;
    private String type;

    public Optional<String> getPath() {
        return fromNullable(path);
    }

    public T setPath(String path) {
        this.path = path;
        return (T) this;
    }

    public Optional<String> getDevice() {
        return fromNullable(device);
    }

    public T setDevice(String device) {
        this.device = device;
        return (T) this;
    }

    public Optional<Long> getTotalSpace() {
        return fromNullable(totalSpace);
    }

    public T setTotalSpace(Long totalSpace) {
        this.totalSpace = totalSpace;
        return (T) this;
    }

    public Optional<Long> getUnallocatedSpace() {
        return fromNullable(unallocatedSpace);
    }

    public T setUnallocatedSpace(Long unallocatedSpace) {
        this.unallocatedSpace = unallocatedSpace;
        return (T) this;
    }

    public Optional<String> getType() {
        return fromNullable(type);
    }

    public T setType(String type) {
        this.type = type;
        return (T) this;
    }

    public Optional<Long> getUsableSpace() {
        return fromNullable(usableSpace);
    }

    public T setUsableSpace(Long usableSpace) {
        this.usableSpace = usableSpace;
        return (T) this;
    }

    public Optional<String> getPartition() {
        return fromNullable(partition);
    }

    public T setPartition(String partition) {
        this.partition = partition;
        return (T) this;
    }

    public abstract T copy();

    protected T copyInternal(XFileSystem t) {
        setPath(t.path);
        setTotalSpace(t.totalSpace);
        setUnallocatedSpace(t.unallocatedSpace);
        setUsableSpace(t.usableSpace);
        setType(t.type);
        setDevice(t.device);
        setPartition(t.partition);
        return (T) this;
    }

    public T merge(XFileSystem<? extends XFileSystem> other) {
        this.path = other.path;
        this.totalSpace = other.totalSpace;
        this.unallocatedSpace = other.unallocatedSpace;
        this.usableSpace = other.usableSpace;
        this.type = other.type;
        this.device = other.device;
        this.partition = other.partition;
        return (T) this;
    }

    public T merge(JsonObject jsonObject) {
        this.path = jsonObject.getString("path");
        this.totalSpace = jsonObject.getLong("totalSpace");
        this.unallocatedSpace = jsonObject.getLong("unallocated_space");
        this.usableSpace = jsonObject.getLong("usable_space");
        this.type = jsonObject.getString("type");
        this.device = jsonObject.getString("device");
        this.partition = jsonObject.getString("partition");
        return (T) this;
    }

    public JsonObject toJsonObject() {
        return new JsonObject()
                .put("path", path)
                .put("total_space", totalSpace)
                .put("unallocated_space", unallocatedSpace)
                .put("usable_space", usableSpace)
                .put("type", type)
                .put("device", device)
                .put("partition", partition);
    }
}


text:
/**
 * @file
 *
 * 6LowPAN output for IPv6. Uses ND tables for link-layer addressing. Fragments packets to 6LowPAN units.
 *
 * This implementation aims to conform to IEEE 802.15.4(-2015), RFC 4944 and RFC 6282.
 * @todo: RFC 6775.
 */

/*
 * Copyright (c) 2015 Inico Technologies Ltd.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
 * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
 * OF SUCH DAMAGE.
 *
 * This file is part of the lwIP TCP/IP stack.
 *
 * Author: Ivan Delamer <delamer@inicotech.com>
 *
 *
 * Please coordinate changes and requests with Ivan Delamer
 * <delamer@inicotech.com>
 */

/**
 * @defgroup sixlowpan 6LoWPAN (RFC4944)
 * @ingroup netifs
 * 6LowPAN netif implementation
 */

#include "netif/lowpan6.h"

#if LWIP_IPV6

#include "lwip/ip.h"
#include "lwip/pbuf.h"
#include "lwip/ip_addr.h"
#include "lwip/netif.h"
#include "lwip/nd6.h"
#include "lwip/mem.h"
#include "lwip/udp.h"
#include "lwip/tcpip.h"
#include "lwip/snmp.h"
#include "netif/ieee802154.h"

#include <string.h>

#if LWIP_6LOWPAN_802154_HW_CRC
#define LWIP_6LOWPAN_DO_CALC_CRC(buf, len) 0
#else
#define LWIP_6LOWPAN_DO_CALC_CRC(buf, len) LWIP_6LOWPAN_CALC_CRC(buf, len)
#endif

/** This is a helper struct for reassembly of fragments
 * (IEEE 802.15.4 limits to 127 bytes)
 */
struct lowpan6_reass_helper {
  struct lowpan6_reass_helper *next_packet;
  struct pbuf *reass;
  struct pbuf *frags;
  u8_t timer;
  struct lowpan6_link_addr sender_addr;
  u16_t datagram_size;
  u16_t datagram_tag;
};

/** This struct keeps track of per-netif state */
struct lowpan6_ieee802154_data {
  /** fragment reassembly list */
  struct lowpan6_reass_helper *reass_list;
#if LWIP_6LOWPAN_NUM_CONTEXTS > 0
  /** address context for compression */
  ip6_addr_t lowpan6_context[LWIP_6LOWPAN_NUM_CONTEXTS];
#endif
  /** Datagram Tag for fragmentation */
  u16_t tx_datagram_tag;
  /** local PAN ID for IEEE 802.15.4 header */
  u16_t ieee_802154_pan_id;
  /** Sequence Number for IEEE 802.15.4 transmission */
  u8_t tx_frame_seq_num;
};

/* Maximum frame size is 127 bytes minus CRC size */
#define LOWPAN6_MAX_PAYLOAD (127 - 2)

/** Currently, this state is global, since there's only one 6LoWPAN netif */
static struct lowpan6_ieee802154_data lowpan6_data;

#if LWIP_6LOWPAN_NUM_CONTEXTS > 0
#define LWIP_6LOWPAN_CONTEXTS(netif) lowpan6_data.lowpan6_context
#else
#define LWIP_6LOWPAN_CONTEXTS(netif) NULL
#endif

static const struct lowpan6_link_addr ieee_802154_broadcast = {2, {0xff, 0xff}};

#if LWIP_6LOWPAN_INFER_SHORT_ADDRESS
static struct lowpan6_link_addr short_mac_addr = {2, {0, 0}};
#endif /* LWIP_6LOWPAN_INFER_SHORT_ADDRESS */

/* IEEE 802.15.4 specific functions: */

/** Write the IEEE 802.15.4 header that encapsulates the 6LoWPAN frame.
 * Src and dst PAN IDs are filled with the ID set by @ref lowpan6_set_pan_id.
 *
 * Since the length is variable:
 * @returns the header length
 */
static u8_t
lowpan6_write_iee802154_header(struct ieee_802154_hdr *hdr, const struct lowpan6_link_addr *src,
                               const struct lowpan6_link_addr *dst)
{
  u8_t ieee_header_len;
  u8_t *buffer;
  u8_t i;
  u16_t fc;

  fc = IEEE_802154_FC_FT_DATA; /* send data packet (2003 frame version) */
  fc |= IEEE_802154_FC_PANID_COMPR; /* set PAN ID compression, for now src and dst PANs are equal */
  if (dst != &ieee_802154_broadcast) {
    fc |= IEEE_802154_FC_ACK_REQ; /* data packet, no broadcast: ack required. */
  }
  if (dst->addr_len == 2) {
    fc |= IEEE_802154_FC_DST_ADDR_MODE_SHORT;
  } else {
    LWIP_ASSERT("invalid dst address length", dst->addr_len == 8);
    fc |= IEEE_802154_FC_DST_ADDR_MODE_EXT;
  }
  if (src->addr_len == 2) {
    fc |= IEEE_802154_FC_SRC_ADDR_MODE_SHORT;
  } else {
    LWIP_ASSERT("invalid src address length", src->addr_len == 8);
    fc |= IEEE_802154_FC_SRC_ADDR_MODE_EXT;
  }
  hdr->frame_control = fc;
  hdr->sequence_number = lowpan6_data.tx_frame_seq_num++;
  hdr->destination_pan_id = lowpan6_data.ieee_802154_pan_id; /* pan id */

  buffer = (u8_t *)hdr;
  ieee_header_len = 5;
  i = dst->addr_len;
  /* reverse memcpy of dst addr */
  while (i-- > 0) {
    buffer[ieee_header_len++] = dst->addr[i];
  }
  /* Source PAN ID skipped due to PAN ID Compression */
  i = src->addr_len;
  /* reverse memcpy of src addr */
  while (i-- > 0) {
    buffer[ieee_header_len++] = src->addr[i];
  }
  return ieee_header_len;
}

/** Parse the IEEE 802.15.4 header from a pbuf.
 * If successful, the header is hidden from the pbuf.
 *
 * PAN IDs and seuqence number are not checked
 *
 * @param p input pbuf, p->payload pointing at the IEEE 802.15.4 header
 * @param src pointer to source address filled from the header
 * @param dest pointer to destination address filled from the header
 * @returns ERR_OK if successful
 */
static err_t
lowpan6_parse_iee802154_header(struct pbuf *p, struct lowpan6_link_addr *src,
                               struct lowpan6_link_addr *dest)
{
  u8_t *puc;
  s8_t i;
  u16_t frame_control, addr_mode;
  u16_t datagram_offset;

  /* Parse IEEE 802.15.4 header */
  puc = (u8_t *)p->payload;
  frame_control = puc[0] | (puc[1] << 8);
  datagram_offset = 2;
  if (frame_control & IEEE_802154_FC_SEQNO_SUPPR) {
    if (IEEE_802154_FC_FRAME_VERSION_GET(frame_control) <= 1) {
      /* sequence number suppressed, this is not valid for versions 0/1 */
      return ERR_VAL;
    }
  } else {
    datagram_offset++;
  }
  datagram_offset += 2; /* Skip destination PAN ID */
  addr_mode = frame_control & IEEE_802154_FC_DST_ADDR_MODE_MASK;
  if (addr_mode == IEEE_802154_FC_DST_ADDR_MODE_EXT) {
    /* extended address (64 bit) */
    dest->addr_len = 8;
    /* reverse memcpy: */
    for (i = 0; i < 8; i++) {
      dest->addr[i] = puc[datagram_offset + 7 - i];
    }
    datagram_offset += 8;
  } else if (addr_mode == IEEE_802154_FC_DST_ADDR_MODE_SHORT) {
    /* short address (16 bit) */
    dest->addr_len = 2;
    /* reverse memcpy: */
    dest->addr[0] = puc[datagram_offset + 1];
    dest->addr[1] = puc[datagram_offset];
    datagram_offset += 2;
  } else {
    /* unsupported address mode (do we need "no address"?) */
    return ERR_VAL;
  }

  if (!(frame_control & IEEE_802154_FC_PANID_COMPR)) {
    /* No PAN ID compression, skip source PAN ID */
    datagram_offset += 2;
  }

  addr_mode = frame_control & IEEE_802154_FC_SRC_ADDR_MODE_MASK;
  if (addr_mode == IEEE_802154_FC_SRC_ADDR_MODE_EXT) {
    /* extended address (64 bit) */
    src->addr_len = 8;
    /* reverse memcpy: */
    for (i = 0; i < 8; i++) {
      src->addr[i] = puc[datagram_offset + 7 - i];
    }
    datagram_offset += 8;
  } else if (addr_mode == IEEE_802154_FC_DST_ADDR_MODE_SHORT) {
    /* short address (16 bit) */
    src->addr_len = 2;
    src->addr[0] = puc[datagram_offset + 1];
    src->addr[1] = puc[datagram_offset];
    datagram_offset += 2;
  } else {
    /* unsupported address mode (do we need "no address"?) */
    return ERR_VAL;
  }

  /* hide IEEE802.15.4 header. */
  if (pbuf_remove_header(p, datagram_offset)) {
    return ERR_VAL;
  }
  return ERR_OK;
}

/** Calculate the 16-bit CRC as required by IEEE 802.15.4 */
u16_t
lowpan6_calc_crc(const void* buf, u16_t len)
{
#define CCITT_POLY_16 0x8408U
  u16_t i;
  u8_t b;
  u16_t crc = 0;
  const u8_t* p = (const u8_t*)buf;

  for (i = 0; i < len; i++) {
    u8_t data = *p;
    for (b = 0U; b < 8U; b++) {
      if (((data ^ crc) & 1) != 0) {
        crc = (u16_t)((crc >> 1) ^ CCITT_POLY_16);
      } else {
        crc = (u16_t)(crc >> 1);
      }
      data = (u8_t)(data >> 1);
    }
    p++;
  }
  return crc;
}

/* Fragmentation specific functions: */

static void
free_reass_datagram(struct lowpan6_reass_helper *lrh)
{
  if (lrh->reass) {
    pbuf_free(lrh->reass);
  }
  if (lrh->frags) {
    pbuf_free(lrh->frags);
  }
  mem_free(lrh);
}

/**
 * Removes a datagram from the reassembly queue.
 **/
static void
dequeue_datagram(struct lowpan6_reass_helper *lrh, struct lowpan6_reass_helper *prev)
{
  if (lowpan6_data.reass_list == lrh) {
    lowpan6_data.reass_list = lowpan6_data.reass_list->next_packet;
  } else {
    /* it wasn't the first, so it must have a valid 'prev' */
    LWIP_ASSERT("sanity check linked list", prev != NULL);
    prev->next_packet = lrh->next_packet;
  }
}

/**
 * Periodic timer for 6LowPAN functions:
 *
 * - Remove incomplete/old packets
 */
void
lowpan6_tmr(void)
{
  struct lowpan6_reass_helper *lrh, *lrh_next, *lrh_prev = NULL;

  lrh = lowpan6_data.reass_list;
  while (lrh != NULL) {
    lrh_next = lrh->next_packet;
    if ((--lrh->timer) == 0) {
      dequeue_datagram(lrh, lrh_prev);
      free_reass_datagram(lrh);
    } else {
      lrh_prev = lrh;
    }
    lrh = lrh_next;
  }
}

/*
 * Encapsulates data into IEEE 802.15.4 frames.
 * Fragments an IPv6 datagram into 6LowPAN units, which fit into IEEE 802.15.4 frames.
 * If configured, will compress IPv6 and or UDP headers.
 * */
static err_t
lowpan6_frag(struct netif *netif, struct pbuf *p, const struct lowpan6_link_addr *src, const struct lowpan6_link_addr *dst)
{
  struct pbuf *p_frag;
  u16_t frag_len, remaining_len, max_data_len;
  u8_t *buffer;
  u8_t ieee_header_len;
  u8_t lowpan6_header_len;
  u8_t hidden_header_len;
  u16_t crc;
  u16_t datagram_offset;
  err_t err = ERR_IF;

  LWIP_ASSERT("lowpan6_frag: netif->linkoutput not set", netif->linkoutput != NULL);

  /* We'll use a dedicated pbuf for building 6LowPAN fragments. */
  p_frag = pbuf_alloc(PBUF_RAW, 127, PBUF_RAM);
  if (p_frag == NULL) {
    MIB2_STATS_NETIF_INC(netif, ifoutdiscards);
    return ERR_MEM;
  }
  LWIP_ASSERT("this needs a pbuf in one piece", p_frag->len == p_frag->tot_len);

  /* Write IEEE 802.15.4 header. */
  buffer = (u8_t *)p_frag->payload;
  ieee_header_len = lowpan6_write_iee802154_header((struct ieee_802154_hdr *)buffer, src, dst);
  LWIP_ASSERT("ieee_header_len < p_frag->len", ieee_header_len < p_frag->len);

#if LWIP_6LOWPAN_IPHC
  /* Perform 6LowPAN IPv6 header compression according to RFC 6282 */
  /* do the header compression (this does NOT copy any non-compressed data) */
  err = lowpan6_compress_headers(netif, (u8_t *)p->payload, p->len,
    &buffer[ieee_header_len], p_frag->len - ieee_header_len, &lowpan6_header_len,
    &hidden_header_len, LWIP_6LOWPAN_CONTEXTS(netif), src, dst);
  if (err != ERR_OK) {
    MIB2_STATS_NETIF_INC(netif, ifoutdiscards);
    pbuf_free(p_frag);
    return err;
  }
  pbuf_remove_header(p, hidden_header_len);

#else /* LWIP_6LOWPAN_IPHC */
  /* Send uncompressed IPv6 header with appropriate dispatch byte. */
  lowpan6_header_len = 1;
  buffer[ieee_header_len] = 0x41; /* IPv6 dispatch */
#endif /* LWIP_6LOWPAN_IPHC */

  /* Calculate remaining packet length */
  remaining_len = p->tot_len;

  if (remaining_len > 0x7FF) {
    MIB2_STATS_NETIF_INC(netif, ifoutdiscards);
    /* datagram_size must fit into 11 bit */
    pbuf_free(p_frag);
    return ERR_VAL;
  }

  /* Fragment, or 1 packet? */
  max_data_len = LOWPAN6_MAX_PAYLOAD - ieee_header_len - lowpan6_header_len;
  if (remaining_len > max_data_len) {
    u16_t data_len;
    /* We must move the 6LowPAN header to make room for the FRAG header. */
    memmove(&buffer[ieee_header_len + 4], &buffer[ieee_header_len], lowpan6_header_len);

    /* Now we need to fragment the packet. FRAG1 header first */
    buffer[ieee_header_len] = 0xc0 | (((p->tot_len + hidden_header_len) >> 8) & 0x7);
    buffer[ieee_header_len + 1] = (p->tot_len + hidden_header_len) & 0xff;

    lowpan6_data.tx_datagram_tag++;
    buffer[ieee_header_len + 2] = (lowpan6_data.tx_datagram_tag >> 8) & 0xff;
    buffer[ieee_header_len + 3] = lowpan6_data.tx_datagram_tag & 0xff;

    /* Fragment follows. */
    data_len = (max_data_len - 4) & 0xf8;
    frag_len = data_len + lowpan6_header_len;

    pbuf_copy_partial(p, buffer + ieee_header_len + lowpan6_header_len + 4, frag_len - lowpan6_header_len, 0);
    remaining_len -= frag_len - lowpan6_header_len;
    /* datagram offset holds the offset before compression */
    datagram_offset = frag_len - lowpan6_header_len + hidden_header_len;
    LWIP_ASSERT("datagram offset must be a multiple of 8", (datagram_offset & 7) == 0);

    /* Calculate frame length */
    p_frag->len = p_frag->tot_len = ieee_header_len + 4 + frag_len + 2; /* add 2 bytes for crc*/

    /* 2 bytes CRC */
    crc = LWIP_6LOWPAN_DO_CALC_CRC(p_frag->payload, p_frag->len - 2);
    pbuf_take_at(p_frag, &crc, 2, p_frag->len - 2);

    /* send the packet */
    MIB2_STATS_NETIF_ADD(netif, ifoutoctets, p_frag->tot_len);
    LWIP_DEBUGF(LWIP_LOWPAN6_DEBUG | LWIP_DBG_TRACE, ("lowpan6_send: sending packet %p\n", (void *)p));
    err = netif->linkoutput(netif, p_frag);

    while ((remaining_len > 0) && (err == ERR_OK)) {
      struct ieee_802154_hdr *hdr = (struct ieee_802154_hdr *)buffer;
      /* new frame, new seq num for ACK */
      hdr->sequence_number = lowpan6_data.tx_frame_seq_num++;

      buffer[ieee_header_len] |= 0x20; /* Change FRAG1 to FRAGN */

      LWIP_ASSERT("datagram offset must be a multiple of 8", (datagram_offset & 7) == 0);
      buffer[ieee_header_len + 4] = (u8_t)(datagram_offset >> 3); /* datagram offset in FRAGN header (datagram_offset is max. 11 bit) */

      frag_len = (127 - ieee_header_len - 5 - 2) & 0xf8;
      if (frag_len > remaining_len) {
        frag_len = remaining_len;
      }

      pbuf_copy_partial(p, buffer + ieee_header_len + 5, frag_len, p->tot_len - remaining_len);
      remaining_len -= frag_len;
      datagram_offset += frag_len;

      /* Calculate frame length */
      p_frag->len = p_frag->tot_len = frag_len + 5 + ieee_header_len + 2;

      /* 2 bytes CRC */
      crc = LWIP_6LOWPAN_DO_CALC_CRC(p_frag->payload, p_frag->len - 2);
      pbuf_take_at(p_frag, &crc, 2, p_frag->len - 2);

      /* send the packet */
      MIB2_STATS_NETIF_ADD(netif, ifoutoctets, p_frag->tot_len);
      LWIP_DEBUGF(LWIP_LOWPAN6_DEBUG | LWIP_DBG_TRACE, ("lowpan6_send: sending packet %p\n", (void *)p));
      err = netif->linkoutput(netif, p_frag);
    }
  } else {
    /* It fits in one frame. */
    frag_len = remaining_len;

    /* Copy IPv6 packet */
    pbuf_copy_partial(p, buffer + ieee_header_len + lowpan6_header_len, frag_len, 0);
    remaining_len = 0;

    /* Calculate frame length */
    p_frag->len = p_frag->tot_len = frag_len + lowpan6_header_len + ieee_header_len + 2;
    LWIP_ASSERT("", p_frag->len <= 127);

    /* 2 bytes CRC */
    crc = LWIP_6LOWPAN_DO_CALC_CRC(p_frag->payload, p_frag->len - 2);
    pbuf_take_at(p_frag, &crc, 2, p_frag->len - 2);

    /* send the packet */
    MIB2_STATS_NETIF_ADD(netif, ifoutoctets, p_frag->tot_len);
    LWIP_DEBUGF(LWIP_LOWPAN6_DEBUG | LWIP_DBG_TRACE, ("lowpan6_send: sending packet %p\n", (void *)p));
    err = netif->linkoutput(netif, p_frag);
  }

  pbuf_free(p_frag);

  return err;
}

/**
 * @ingroup sixlowpan
 * Set context
 */
err_t
lowpan6_set_context(u8_t idx, const ip6_addr_t *context)
{
#if LWIP_6LOWPAN_NUM_CONTEXTS > 0
  if (idx >= LWIP_6LOWPAN_NUM_CONTEXTS) {
    return ERR_ARG;
  }

  IP6_ADDR_ZONECHECK(context);

  ip6_addr_set(&lowpan6_data.lowpan6_context[idx], context);

  return ERR_OK;
#else
  LWIP_UNUSED_ARG(idx);
  LWIP_UNUSED_ARG(context);
  return ERR_ARG;
#endif
}

#if LWIP_6LOWPAN_INFER_SHORT_ADDRESS
/**
 * @ingroup sixlowpan
 * Set short address
 */
err_t
lowpan6_set_short_addr(u8_t addr_high, u8_t addr_low)
{
  short_mac_addr.addr[0] = addr_high;
  short_mac_addr.addr[1] = addr_low;

  return ERR_OK;
}
#endif /* LWIP_6LOWPAN_INFER_SHORT_ADDRESS */

/* Create IEEE 802.15.4 address from netif address */
static err_t
lowpan6_hwaddr_to_addr(struct netif *netif, struct lowpan6_link_addr *addr)
{
  addr->addr_len = 8;
  if (netif->hwaddr_len == 8) {
    LWIP_ERROR("NETIF_MAX_HWADDR_LEN >= 8 required", sizeof(netif->hwaddr) >= 8, return ERR_VAL;);
    SMEMCPY(addr->addr, netif->hwaddr, 8);
  } else if (netif->hwaddr_len == 6) {
    /* Copy from MAC-48 */
    SMEMCPY(addr->addr, netif->hwaddr, 3);
    addr->addr[3] = addr->addr[4] = 0xff;
    SMEMCPY(&addr->addr[5], &netif->hwaddr[3], 3);
  } else {
    /* Invalid address length, don't know how to convert this */
    return ERR_VAL;
  }
  return ERR_OK;
}

/**
 * @ingroup sixlowpan
 * Resolve and fill-in IEEE 802.15.4 address header for outgoing IPv6 packet.
 *
 * Perform Header Compression and fragment if necessary.
 *
 * @param netif The lwIP network interface which the IP packet will be sent on.
 * @param q The pbuf(s) containing the IP packet to be sent.
 * @param ip6addr The IP address of the packet destination.
 *
 * @return err_t
 */
err_t
lowpan6_output(struct netif *netif, struct pbuf *q, const ip6_addr_t *ip6addr)
{
  err_t result;
  const u8_t *hwaddr;
  struct lowpan6_link_addr src, dest;
#if LWIP_6LOWPAN_INFER_SHORT_ADDRESS
  ip6_addr_t ip6_src;
  struct ip6_hdr *ip6_hdr;
#endif /* LWIP_6LOWPAN_INFER_SHORT_ADDRESS */

#if LWIP_6LOWPAN_INFER_SHORT_ADDRESS
  /* Check if we can compress source address (use aligned copy) */
  ip6_hdr = (struct ip6_hdr *)q->payload;
  ip6_addr_copy_from_packed(ip6_src, ip6_hdr->src);
  ip6_addr_assign_zone(&ip6_src, IP6_UNICAST, netif);
  if (lowpan6_get_address_mode(&ip6_src, &short_mac_addr) == 3) {
    src.addr_len = 2;
    src.addr[0] = short_mac_addr.addr[0];
    src.addr[1] = short_mac_addr.addr[1];
  } else
#endif /* LWIP_6LOWPAN_INFER_SHORT_ADDRESS */
  {
    result = lowpan6_hwaddr_to_addr(netif, &src);
    if (result != ERR_OK) {
      MIB2_STATS_NETIF_INC(netif, ifoutdiscards);
      return result;
    }
  }

  /* multicast destination IP address? */
  if (ip6_addr_ismulticast(ip6addr)) {
    MIB2_STATS_NETIF_INC(netif, ifoutnucastpkts);
    /* We need to send to the broadcast address.*/
    return lowpan6_frag(netif, q, &src, &ieee_802154_broadcast);
  }

  /* We have a unicast destination IP address */
  /* @todo anycast? */

#if LWIP_6LOWPAN_INFER_SHORT_ADDRESS
  if (src.addr_len == 2) {
    /* If source address was compressable to short_mac_addr, and dest has same subnet and
     * is also compressable to 2-bytes, assume we can infer dest as a short address too. */
    dest.addr_len = 2;
    dest.addr[0] = ((u8_t *)q->payload)[38];
    dest.addr[1] = ((u8_t *)q->payload)[39];
    if ((src.addr_len == 2) && (ip6_addr_netcmp_zoneless(&ip6_hdr->src, &ip6_hdr->dest)) &&
        (lowpan6_get_address_mode(ip6addr, &dest) == 3)) {
      MIB2_STATS_NETIF_INC(netif, ifoutucastpkts);
      return lowpan6_frag(netif, q, &src, &dest);
    }
  }
#endif /* LWIP_6LOWPAN_INFER_SHORT_ADDRESS */

  /* Ask ND6 what to do with the packet. */
  result = nd6_get_next_hop_addr_or_queue(netif, q, ip6addr, &hwaddr);
  if (result != ERR_OK) {
    MIB2_STATS_NETIF_INC(netif, ifoutdiscards);
    return result;
  }

  /* If no hardware address is returned, nd6 has queued the packet for later. */
  if (hwaddr == NULL) {
    return ERR_OK;
  }

  /* Send out the packet using the returned hardware address. */
  result = lowpan6_hwaddr_to_addr(netif, &dest);
  if (result != ERR_OK) {
    MIB2_STATS_NETIF_INC(netif, ifoutdiscards);
    return result;
  }
  MIB2_STATS_NETIF_INC(netif, ifoutucastpkts);
  return lowpan6_frag(netif, q, &src, &dest);
}
/**
 * @ingroup sixlowpan
 * NETIF input function: don't free the input pbuf when returning != ERR_OK!
 */
err_t
lowpan6_input(struct pbuf *p, struct netif *netif)
{
  u8_t *puc, b;
  s8_t i;
  struct lowpan6_link_addr src, dest;
  u16_t datagram_size = 0;
  u16_t datagram_offset, datagram_tag;
  struct lowpan6_reass_helper *lrh, *lrh_next, *lrh_prev = NULL;

  if (p == NULL) {
    return ERR_OK;
  }

  MIB2_STATS_NETIF_ADD(netif, ifinoctets, p->tot_len);

  if (p->len != p->tot_len) {
    /* for now, this needs a pbuf in one piece */
    goto lowpan6_input_discard;
  }

  if (lowpan6_parse_iee802154_header(p, &src, &dest) != ERR_OK) {
    goto lowpan6_input_discard;
  }

  /* Check dispatch. */
  puc = (u8_t *)p->payload;

  b = *puc;
  if ((b & 0xf8) == 0xc0) {
    /* FRAG1 dispatch. add this packet to reassembly list. */
    datagram_size = ((u16_t)(puc[0] & 0x07) << 8) | (u16_t)puc[1];
    datagram_tag = ((u16_t)puc[2] << 8) | (u16_t)puc[3];

    /* check for duplicate */
    lrh = lowpan6_data.reass_list;
    while (lrh != NULL) {
      uint8_t discard = 0;
      lrh_next = lrh->next_packet;
      if ((lrh->sender_addr.addr_len == src.addr_len) &&
          (memcmp(lrh->sender_addr.addr, src.addr, src.addr_len) == 0)) {
        /* address match with packet in reassembly. */
        if ((datagram_tag == lrh->datagram_tag) && (datagram_size == lrh->datagram_size)) {
          /* duplicate fragment. */
          goto lowpan6_input_discard;
        } else {
          /* We are receiving the start of a new datagram. Discard old one (incomplete). */
          discard = 1;
        }
      }
      if (discard) {
        dequeue_datagram(lrh, lrh_prev);
        free_reass_datagram(lrh);
      } else {
        lrh_prev = lrh;
      }
      /* Check next datagram in queue. */
      lrh = lrh_next;
    }

    pbuf_remove_header(p, 4); /* hide frag1 dispatch */

    lrh = (struct lowpan6_reass_helper *) mem_malloc(sizeof(struct lowpan6_reass_helper));
    if (lrh == NULL) {
      goto lowpan6_input_discard;
    }

    lrh->sender_addr.addr_len = src.addr_len;
    for (i = 0; i < src.addr_len; i++) {
      lrh->sender_addr.addr[i] = src.addr[i];
    }
    lrh->datagram_size = datagram_size;
    lrh->datagram_tag = datagram_tag;
    lrh->frags = NULL;
    if (*(u8_t *)p->payload == 0x41) {
      /* This is a complete IPv6 packet, just skip dispatch byte. */
      pbuf_remove_header(p, 1); /* hide dispatch byte. */
      lrh->reass = p;
    } else if ((*(u8_t *)p->payload & 0xe0 ) == 0x60) {
      lrh->reass = lowpan6_decompress(p, datagram_size, LWIP_6LOWPAN_CONTEXTS(netif), &src, &dest);
      if (lrh->reass == NULL) {
        /* decompression failed */
        mem_free(lrh);
        goto lowpan6_input_discard;
      }
    }
    /* TODO: handle the case where we already have FRAGN received */
    lrh->next_packet = lowpan6_data.reass_list;
    lrh->timer = 2;
    lowpan6_data.reass_list = lrh;

    return ERR_OK;
  } else if ((b & 0xf8) == 0xe0) {
    /* FRAGN dispatch, find packet being reassembled. */
    datagram_size = ((u16_t)(puc[0] & 0x07) << 8) | (u16_t)puc[1];
    datagram_tag = ((u16_t)puc[2] << 8) | (u16_t)puc[3];
    datagram_offset = (u16_t)puc[4] << 3;
    pbuf_remove_header(p, 4); /* hide frag1 dispatch but keep datagram offset for reassembly */

    for (lrh = lowpan6_data.reass_list; lrh != NULL; lrh_prev = lrh, lrh = lrh->next_packet) {
      if ((lrh->sender_addr.addr_len == src.addr_len) &&
          (memcmp(lrh->sender_addr.addr, src.addr, src.addr_len) == 0) &&
          (datagram_tag == lrh->datagram_tag) &&
          (datagram_size == lrh->datagram_size)) {
        break;
      }
    }
    if (lrh == NULL) {
      /* rogue fragment */
      goto lowpan6_input_discard;
    }
    /* Insert new pbuf into list of fragments. Each fragment is a pbuf,
       this only works for unchained pbufs. */
    LWIP_ASSERT("p->next == NULL", p->next == NULL);
    if (lrh->reass != NULL) {
      /* FRAG1 already received, check this offset against first len */
      if (datagram_offset < lrh->reass->len) {
        /* fragment overlap, discard old fragments */
        dequeue_datagram(lrh, lrh_prev);
        free_reass_datagram(lrh);
        goto lowpan6_input_discard;
      }
    }
    if (lrh->frags == NULL) {
      /* first FRAGN */
      lrh->frags = p;
    } else {
      /* find the correct place to insert */
      struct pbuf *q, *last;
      u16_t new_frag_len = p->len - 1; /* p->len includes datagram_offset byte */
      for (q = lrh->frags, last = NULL; q != NULL; last = q, q = q->next) {
        u16_t q_datagram_offset = ((u8_t *)q->payload)[0] << 3;
        u16_t q_frag_len = q->len - 1;
        if (datagram_offset < q_datagram_offset) {
          if (datagram_offset + new_frag_len > q_datagram_offset) {
            /* overlap, discard old fragments */
            dequeue_datagram(lrh, lrh_prev);
            free_reass_datagram(lrh);
            goto lowpan6_input_discard;
          }
          /* insert here */
          break;
        } else if (datagram_offset == q_datagram_offset) {
          if (q_frag_len != new_frag_len) {
            /* fragment mismatch, discard old fragments */
            dequeue_datagram(lrh, lrh_prev);
            free_reass_datagram(lrh);
            goto lowpan6_input_discard;
          }
          /* duplicate, ignore */
          pbuf_free(p);
          return ERR_OK;
        }
      }
      /* insert fragment */
      if (last == NULL) {
        lrh->frags = p;
      } else {
        last->next = p;
        p->next = q;
      }
    }
    /* check if all fragments were received */
    if (lrh->reass) {
      u16_t offset = lrh->reass->len;
      struct pbuf *q;
      for (q = lrh->frags; q != NULL; q = q->next) {
        u16_t q_datagram_offset = ((u8_t *)q->payload)[0] << 3;
        if (q_datagram_offset != offset) {
          /* not complete, wait for more fragments */
          return ERR_OK;
        }
        offset += q->len - 1;
      }
      if (offset == datagram_size) {
        /* all fragments received, combine pbufs */
        u16_t datagram_left = datagram_size - lrh->reass->len;
        for (q = lrh->frags; q != NULL; q = q->next) {
          /* hide datagram_offset byte now */
          pbuf_remove_header(q, 1);
          q->tot_len = datagram_left;
          datagram_left -= q->len;
        }
        LWIP_ASSERT("datagram_left == 0", datagram_left == 0);
        q = lrh->reass;
        q->tot_len = datagram_size;
        q->next = lrh->frags;
        lrh->frags = NULL;
        lrh->reass = NULL;
        dequeue_datagram(lrh, lrh_prev);
        mem_free(lrh);

        /* @todo: distinguish unicast/multicast */
        MIB2_STATS_NETIF_INC(netif, ifinucastpkts);
        return ip6_input(q, netif);
      }
    }
    /* pbuf enqueued, waiting for more fragments */
    return ERR_OK;
  } else {
    if (b == 0x41) {
      /* This is a complete IPv6 packet, just skip dispatch byte. */
      pbuf_remove_header(p, 1); /* hide dispatch byte. */
    } else if ((b & 0xe0 ) == 0x60) {
      /* IPv6 headers are compressed using IPHC. */
      p = lowpan6_decompress(p, datagram_size, LWIP_6LOWPAN_CONTEXTS(netif), &src, &dest);
      if (p == NULL) {
        MIB2_STATS_NETIF_INC(netif, ifindiscards);
        return ERR_OK;
      }
    } else {
      goto lowpan6_input_discard;
    }

    /* @todo: distinguish unicast/multicast */
    MIB2_STATS_NETIF_INC(netif, ifinucastpkts);

    return ip6_input(p, netif);
  }
lowpan6_input_discard:
  MIB2_STATS_NETIF_INC(netif, ifindiscards);
  pbuf_free(p);
  /* always return ERR_OK here to prevent the caller freeing the pbuf */
  return ERR_OK;
}

/**
 * @ingroup sixlowpan
 */
err_t
lowpan6_if_init(struct netif *netif)
{
  netif->name[0] = 'L';
  netif->name[1] = '6';
  netif->output_ip6 = lowpan6_output;

  MIB2_INIT_NETIF(netif, snmp_ifType_other, 0);

  /* maximum transfer unit */
  netif->mtu = 1280;

  /* broadcast capability */
  netif->flags = NETIF_FLAG_BROADCAST /* | NETIF_FLAG_LOWPAN6 */;

  return ERR_OK;
}

/**
 * @ingroup sixlowpan
 * Set PAN ID
 */
err_t
lowpan6_set_pan_id(u16_t pan_id)
{
  lowpan6_data.ieee_802154_pan_id = pan_id;

  return ERR_OK;
}

#if !NO_SYS
/**
 * @ingroup sixlowpan
 * Pass a received packet to tcpip_thread for input processing
 *
 * @param p the received packet, p->payload pointing to the
 *          IEEE 802.15.4 header.
 * @param inp the network interface on which the packet was received
 */
err_t
tcpip_6lowpan_input(struct pbuf *p, struct netif *inp)
{
  return tcpip_inpkt(p, inp, lowpan6_input);
}
#endif /* !NO_SYS */

#endif /* LWIP_IPV6 */


text:
import unittest
from helper import properties
from base_page import BasePage

class TestCase(unittest.TestCase):

    def setUp(self):
        self.driver = BasePage().get_driver( )
        self.driver.get( properties.get_settings()['DEFAULT-BASE-URL'] )

    def tearDown(self):
        self.driver.quit()

if __name__ == "__main__":
    unittest.main()


text:
var win = Ti.UI.currentWindow;

Ti.include('/includes/lib/json.i18n.js');

var ServerHandler = require('/includes/ServerHandler'),
	Utils = require('/includes/Utils'),

tableView = require('/includes/PullToRefresh')({
	style: Ti.UI.iPhone.TableViewStyle.PLAIN,
	scrollIndicatorStyle: Ti.UI.iPhone.ScrollIndicatorStyle.WHITE,
	editable: true,
	separatorColor: '#4b4b4b',
	backgroundColor: Utils.getBackgroundColor()
});

win.add(tableView);

function updateList() {
	//opening the database containing the servers that we will display
	var db = Ti.Database.open('servers'),
		servers = db.execute('SELECT * FROM servers'),
		i = 0; //this index corresponds to the tableviewrow id

	//erase the existing tableview entries
	tableView.setData([]);

	if(servers.rowCount < 1) {
		tableView.appendRow(ServerHandler.getEmptyPlaceholderRow());
	} else {
		//loop through the servers
		while(servers.isValidRow()) {
			//getting all the data corresponding to the row, it will be useful later
			var data = {
				name: servers.fieldByName('name'),
				host: servers.fieldByName('host'),
				port: servers.fieldByName('port'),
				sqlid: servers.fieldByName('id'),
				id: i
			};

			try {
				//create temporary row, that will say "polling server..."
				ServerHandler.getRow(data, i, function(e) {
					e.row.data = e.data;
					tableView.appendRow(e.row);
				}, ServerHandler.state.POLLING);

				//get real info
				ServerHandler.getServerInfo(data, i, function(e) {
					e.row.data = e.data;
					e.row.addEventListener('click', rowClickHandler);

					//update the existing temporary row and update it in consequence
					tableView.updateRow(e.index, e.row);
				});
			} catch(e) {
				alert("Uh oh, I think something went terribly wrong. :(\nFor now you can refresh or try to restart the app.");
			}

			//next server, next row
			servers.next();
			i++;
		}
	}

	//we're done with the database
	servers.close();
}

Ti.App.addEventListener('reload', updateList);

tableView.addEventListener('delete', function(e) {
	if(e.rowData.data != null) {
		var db = Ti.Database.open('servers');
		db.execute('DELETE FROM servers WHERE id=?', e.rowData.data.sqlid);
		db.close();
	}
});

function rowClickHandler(e) {
	//if we click on a row, we want to edit it
	var win_add = Ti.UI.createWindow({
		url: 'server-info.js',
		title: I('addServer.titleEdit'),
		barColor: Utils.getNavBarColor(),
		tintColor: Utils.getTintColor(),
		backgroundColor: Utils.getBackgroundColor(),
		serverIDToEdit: e.rowData.data.sqlid,
		translucent: false
	});

	container = Ti.UI.createWindow({
		navBarHidden: true
	}),

	navGroup = Ti.UI.iPhone.createNavigationGroup({
		window: win_add,
		tintColor: Utils.getTintColor()
	});

	container.add(navGroup);

	container.addEventListener('close', function() {
		container = null;
		navGroup = null;
		win_add = null;

		updateList();
	});

	win_add.container = container;

	container.open({
		modal: true
	});
}

var b_add = Ti.UI.createButton({
	systemButton: Ti.UI.iPhone.SystemButton.ADD
});

b_add.addEventListener('click', function(e) {
	//open the server creation window
	var win_add = Ti.UI.createWindow({
		url: 'server-info.js',
		title: I('addServer.title'),
		barColor: Utils.getNavBarColor(),
		navTintColor: Utils.getTintColor(),
		backgroundColor: Utils.getBackgroundColor(),
		translucent: false
	});

	container = Ti.UI.createWindow({
		navBarHidden: true
	}),

	navGroup = Ti.UI.iPhone.createNavigationGroup({
		window: win_add,
		tintColor: Utils.getTintColor()
	});

	container.add(navGroup);

	container.addEventListener('close', function() {
		container = null;
		navGroup = null;
		win_add = null;

		updateList();
	});

	win_add.container = container;

	container.open({
		modal: true
	});
});

var b_info = Ti.UI.createButton({
	style: Ti.UI.iPhone.SystemButton.INFO_LIGHT,
	left: 10
});

var view_info = Ti.UI.createView();
view_info.add(b_info);

b_info.addEventListener('click', function(e) {
	var win_info = Ti.UI.createWindow({
		url: 'credits.js',
		title: I('credits.title'),
		barColor: Utils.getNavBarColor(),
		backgroundColor: Utils.getBackgroundColor(),
		translucent: false
	});

	container = Ti.UI.createWindow({
		navBarHidden: true
	}),

	navGroup = Ti.UI.iPhone.createNavigationGroup({
		window: win_info,
		tintColor: Utils.getTintColor()
	});

	container.add(navGroup);

	container.addEventListener('close', function() {
		container = null;
		navGroup = null;
		win_info = null;
	});

	win_info.container = container;

	container.open({
		modal: true
	});
});

win.setRightNavButton(b_add);
win.setLeftNavButton(view_info);

var adView = Ti.UI.iOS.createAdView({
	adSize: Ti.UI.iOS.AD_SIZE_PORTRAIT,
	height: Ti.UI.SIZE,
	width: Ti.UI.FILL,
	bottom: 0,
	backgroundColor: 'transparent'
});

adView.addEventListener('load', function(e) {
	if(tableView != null) {
		tableView.animate({
			bottom: 50,
			duration: 200
		});
	}
});

adView.addEventListener('error', function(e) {
	if(tableView != null) {
		tableView.animate({
			bottom: 0,
			duration: 200
		});
	}
});

win.add(adView);
updateList();


text:
<html>
<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.14/angular.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-strap/2.1.6/angular-strap.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-strap/2.1.6/angular-strap.tpl.js"></script>
  <script type="text/javascript">
    angular.module('failure', ['mgcrea.ngStrap.datepicker'])
  </script>
</head>
<body>
  <div ng-app="failure">
    <input type='text' id="foo" bs-datepicker="" ng-model="data">
  </div>
</body>
</html>


text:
module Workers
  module Groups
    class ClassLevel
      include Sidekiq::Worker

      CLASS_LEVELS = {
        Freshman:   'FR',
        Sophomore:  'SO',
        Junior:     'JR',
        Senior:     'SR'
      }

      def perform
        CLASS_LEVELS.each do |group, col_value|
          GroupSynchronizer.new(group, "SELECT pidm FROM bsv_lum_registered_students WHERE class_level = '#{col_value}'").call
        end
      end
    end
  end
end


text:
package org.broadinstitute.hellbender.utils;

import org.apache.commons.math3.linear.EigenDecomposition;
import org.apache.commons.math3.linear.LUDecomposition;
import org.apache.commons.math3.linear.RealMatrix;
import org.apache.commons.math3.special.Gamma;
import org.broadinstitute.hellbender.exceptions.GATKException;

import java.util.Arrays;
import java.util.List;

/**
 * MathUtils is a static class (no instantiation allowed!) with some useful math methods.
 */
public final class MathUtils {

    /**
     * The smallest log10 value we'll emit from normalizeFromLog10 and other functions
     * where the real-space value is 0.0.
     */
    public static final double LOG10_P_OF_ZERO = -1000000.0;

    /**
     * Log10 of the e constant.
     */
    public static final double LOG10_OF_E = Math.log10(Math.E);

    /**
     * Private constructor.  No instantiating this class!
     */
    private MathUtils() {
    }

    /**
     * A helper class to maintain a cache of log10 values
     */
    public static final class Log10Cache {
        /**
         * Get the value of log10(n), expanding the cache as necessary
         * @param n operand
         * @return log10(n)
         */
        public static double get(final int n) {
            if (n < 0)
                throw new GATKException(String.format("Can't take the log of a negative number: %d", n));
            if (n >= cache.length)
                ensureCacheContains(Math.max(n+10, 2*cache.length));
            /*
               Array lookups are not atomic.  It's possible that the reference to cache could be
               changed between the time the reference is loaded and the data is fetched from the correct
               offset.  However, the value retrieved can't change, and it's guaranteed to be present in the
               old reference by the conditional above.
             */
            return cache[n];
        }

        /**
         * Ensures that the cache contains a value for n.  After completion of ensureCacheContains(n),
         * #get(n) is guaranteed to return without causing a cache expansion
         * @param n desired value to be precomputed
         */
        public static void ensureCacheContains(final int n) {
            if (n < cache.length)
                return;
            final double[] newCache = new double[n + 1];
            System.arraycopy(cache, 0, newCache, 0, cache.length);
            for (int i=cache.length; i < newCache.length; i++)
                newCache[i] = Math.log10(i);
            cache = newCache;
        }

        //initialize with the special case: log10(0) = NEGATIVE_INFINITY
        private static double[] cache = new double[] { Double.NEGATIVE_INFINITY };
    }

    /**
     * Encapsulates the second term of Jacobian log identity for differences up to MAX_TOLERANCE
     */
    private static final class JacobianLogTable {

        public static final double MAX_TOLERANCE = 8.0;

        public static double get(final double difference) {
            if (cache == null) {
                initialize();
            }
            final int index = fastRound(difference * INV_STEP);
            return cache[index];
        }

        private static void initialize() {
            if (cache == null) {
                final int tableSize = (int) (MAX_TOLERANCE / TABLE_STEP) + 1;
                cache = new double[tableSize];
                for (int k = 0; k < cache.length; k++) {
                    cache[k] = Math.log10(1.0 + Math.pow(10.0, -((double) k) * TABLE_STEP));
                }
            }
        }

        private static final double TABLE_STEP = 0.0001;
        private static final double INV_STEP = 1.0 / TABLE_STEP;
        private static double[] cache = null;
    }

    // A fast implementation of the Math.round() method.  This method does not perform
    // under/overflow checking, so this shouldn't be used in the general case (but is fine
    // if one is already make those checks before calling in to the rounding).
    public static int fastRound(final double d) {
        return (d > 0.0) ? (int) (d + 0.5d) : (int) (d - 0.5d);
    }

    public static double approximateLog10SumLog10(final double[] vals) {
        return approximateLog10SumLog10(vals, vals.length);
    }

    public static double approximateLog10SumLog10(final double[] vals, final int endIndex) {

        final int maxElementIndex = MathUtils.maxElementIndex(vals, endIndex);
        double approxSum = vals[maxElementIndex];

        for (int i = 0; i < endIndex; i++) {
            if (i == maxElementIndex || vals[i] == Double.NEGATIVE_INFINITY) {
                continue;
            }

            final double diff = approxSum - vals[i];
            if (diff < JacobianLogTable.MAX_TOLERANCE) {
                // See notes from the 2-inout implementation below
                approxSum += JacobianLogTable.get(diff);
            }
        }

        return approxSum;
    }

    public static double approximateLog10SumLog10(final double a, final double b, final double c) {
        return approximateLog10SumLog10(a, approximateLog10SumLog10(b, c));
    }

    public static double approximateLog10SumLog10(final double a, final double b) {
        // this code works only when a <= b so we flip them if the order is opposite
        if (a > b) {
            return approximateLog10SumLog10(b, a);
        }

        if (a == Double.NEGATIVE_INFINITY) {
            return b;
        }

        final double diff = b - a;
        if (diff >= JacobianLogTable.MAX_TOLERANCE) {
            return b;
        }

        // OK, so |y-x| < tol: we use the following identity then:
        // we need to compute log10(10^x + 10^y)
        // By Jacobian logarithm identity, this is equal to
        // max(x,y) + log10(1+10^-abs(x-y))
        // we compute the second term as a table lookup with integer quantization
        // we have pre-stored correction for 0,0.1,0.2,... 10.0
        return b + JacobianLogTable.get(diff);
    }

    public static double sum(final double[] values) {
        double s = 0.0;
        for (double v : values)
            s += v;
        return s;
    }

    public static long sum(final int[] x) {
        long total = 0;
        for (int v : x)
            total += v;
        return total;
    }

    public static int sum(final byte[] x) {
        int total = 0;
        for (byte v : x)
            total += (int)v;
        return total;
    }

    public static long sum(final long[] x) {
        int total = 0;
        for (long v : x)
            total += v;
        return total;
    }

    /** Returns the sum of the elements in the array starting with start and ending before stop. */
    public static long sum(final long[] arr, final int start, final int stop) {
        return sum(Arrays.copyOfRange(arr, start, stop));
    }

    /**
     * Compares double values for equality (within 1e-6), or inequality.
     *
     * @param a the first double value
     * @param b the second double value
     * @return -1 if a is greater than b, 0 if a is equal to be within 1e-6, 1 if b is greater than a.
     */
    public static byte compareDoubles(final double a, final double b) {
        return compareDoubles(a, b, 1e-6);
    }

    /**
     * Compares double values for equality (within epsilon), or inequality.
     *
     * @param a       the first double value
     * @param b       the second double value
     * @param epsilon the precision within which two double values will be considered equal
     * @return -1 if a is greater than b, 0 if a is equal to be within epsilon, 1 if b is greater than a.
     */
    public static byte compareDoubles(final double a, final double b, final double epsilon) {
        if (Math.abs(a - b) < epsilon) {
            return 0;
        }
        if (a > b) {
            return -1;
        }
        return 1;
    }

    /**
     */
    public static double log10BinomialCoefficient(final int n, final int k) {
        if ( n < 0 ) {
            throw new IllegalArgumentException("n: Must have non-negative number of trials");
        }
        if ( k > n || k < 0 ) {
            throw new IllegalArgumentException("k: Must have non-negative number of successes, and no more successes than number of trials");
        }

        return log10Factorial(n) - log10Factorial(k) - log10Factorial(n - k);
    }

    /**
     * Computes a binomial probability.  This is computed using the formula
     *

     * B(k; n; p) = [ n! / ( k! (n - k)! ) ] (p^k)( (1-p)^k )
     *

     * where n is the number of trials, k is the number of successes, and p is the probability of success
     *
     * @param n number of Bernoulli trials
     * @param k number of successes
     * @param p probability of success
     * @return the binomial probability of the specified configuration.  Computes values down to about 1e-237.
     */
    public static double binomialProbability(final int n, final int k, final double p) {
        return Math.pow(10, log10BinomialProbability(n, k, Math.log10(p)));
    }

    /**
     * binomial Probability(int, int, double) with log10 applied to result
     */
    public static double log10BinomialProbability(final int n, final int k, final double log10p) {
        if ( log10p > 1e-18 )
            throw new IllegalArgumentException("log10p: Log-probability must be 0 or less");
        double log10OneMinusP = Math.log10(1 - Math.pow(10, log10p));
        return log10BinomialCoefficient(n, k) + log10p * k + log10OneMinusP * (n - k);
    }

    public static double log10sumLog10(final double[] log10p, final int start) {
        return log10sumLog10(log10p, start, log10p.length);
    }

    public static double log10sumLog10(final double[] log10values) {
        return log10sumLog10(log10values, 0);
    }

    public static double log10sumLog10(final double[] log10p, final int start, final int finish) {
        if (start >= finish) {
            return Double.NEGATIVE_INFINITY;
        }
        final int maxElementIndex = maxElementIndex(log10p, start, finish);
        final double maxValue = log10p[maxElementIndex];
        if(maxValue == Double.NEGATIVE_INFINITY) {
            return maxValue;
        }
        double sum = 1.0;
        for (int i = start; i < finish; i++) {
            double curVal = log10p[i];
            double scaled_val = curVal - maxValue;
            if (i == maxElementIndex || curVal == Double.NEGATIVE_INFINITY) {
                continue;
            } else {
                sum += Math.pow(10.0, scaled_val);
            }
        }
        if ( Double.isNaN(sum) || sum == Double.POSITIVE_INFINITY ) {
            throw new IllegalArgumentException("log10p: Values must be non-infinite and non-NAN");
        }
        return maxValue + (sum != 1.0 ? Math.log10(sum) : 0.0);
    }

    /**
     * normalizes the log10-based array.  ASSUMES THAT ALL ARRAY ENTRIES ARE <= 0 (<= 1 IN REAL-SPACE).
     *
     * @param array the array to be normalized
     * @return a newly allocated array corresponding the normalized values in array
     */
    public static double[] normalizeFromLog10(final double[] array) {
        return normalizeFromLog10(array, false);
    }

    /**
     * normalizes the log10-based array.  ASSUMES THAT ALL ARRAY ENTRIES ARE <= 0 (<= 1 IN REAL-SPACE).
     *
     * @param array             the array to be normalized
     * @param takeLog10OfOutput if true, the output will be transformed back into log10 units
     * @return a newly allocated array corresponding the normalized values in array, maybe log10 transformed
     */
    public static double[] normalizeFromLog10(final double[] array, final boolean takeLog10OfOutput) {
        return normalizeFromLog10(array, takeLog10OfOutput, false);
    }

    /**
     * See #normalizeFromLog10 but with the additional option to use an approximation that keeps the calculation always in log-space
     *
     * @param array
     * @param takeLog10OfOutput
     * @param keepInLogSpace
     *
     * @return
     */
    public static double[] normalizeFromLog10(final double[] array, final boolean takeLog10OfOutput, final boolean keepInLogSpace) {
        // for precision purposes, we need to add (or really subtract, since they're
        // all negative) the largest value; also, we need to convert to normal-space.
        double maxValue = arrayMax(array);

        // we may decide to just normalize in log space without converting to linear space
        if (keepInLogSpace) {
            for (int i = 0; i < array.length; i++) {
                array[i] -= maxValue;
            }
            return array;
        }

        // default case: go to linear space
        double[] normalized = new double[array.length];

        for (int i = 0; i < array.length; i++)
            normalized[i] = Math.pow(10, array[i] - maxValue);

        // normalize
        double sum = 0.0;
        for (int i = 0; i < array.length; i++)
            sum += normalized[i];
        for (int i = 0; i < array.length; i++) {
            double x = normalized[i] / sum;
            if (takeLog10OfOutput) {
                x = Math.log10(x);
                if ( x < LOG10_P_OF_ZERO || Double.isInfinite(x) )
                    x = array[i] - maxValue;
            }

            normalized[i] = x;
        }

        return normalized;
    }

    /**
     * normalizes the real-space probability array.
     *
     * Does not assume anything about the values in the array, beyond that no elements are below 0.  It's ok
     * to have values in the array of > 1, or have the sum go above 0.
     *
     * @param array the array to be normalized
     * @return a newly allocated array corresponding the normalized values in array
     */
    public static double[] normalizeFromRealSpace(final double[] array) {
        if ( array.length == 0 )
            return array;

        final double sum = sum(array);
        final double[] normalized = new double[array.length];
        if ( sum < 0.0 ) throw new IllegalArgumentException("Values in probability array sum to a negative number " + sum);
        for ( int i = 0; i < array.length; i++ ) {
            normalized[i] = array[i] / sum;
        }
        return normalized;
    }

    public static int maxElementIndex(final double[] array) {
        return maxElementIndex(array, array.length);
    }

    public static int maxElementIndex(final double[] array, final int start, final int endIndex) {
        if (array == null || array.length == 0)
            throw new IllegalArgumentException("Array cannot be null!");

        if (start > endIndex) {
            throw new IllegalArgumentException("Start cannot be after end.");
        }

        int maxI = start;
        for (int i = (start+1); i < endIndex; i++) {
            if (array[i] > array[maxI])
                maxI = i;
        }
        return maxI;
    }

    public static int maxElementIndex(final double[] array, final int endIndex) {
        return maxElementIndex(array, 0, endIndex);
    }

    public static double arrayMax(final double[] array) {
        return array[maxElementIndex(array)];
    }

    /**
     * Checks that the result is a well-formed log10 probability
     *
     * @param result a supposedly well-formed log10 probability value.  By default allows
     *               -Infinity values, as log10(0.0) == -Infinity.
     * @return true if result is really well formed
     */
    public static boolean goodLog10Probability(final double result) {
        return goodLog10Probability(result, true);
    }

    /**
     * Checks that the result is a well-formed log10 probability
     *
     * @param result a supposedly well-formed log10 probability value
     * @param allowNegativeInfinity should we consider a -Infinity value ok?
     * @return true if result is really well formed
     */
    public static boolean goodLog10Probability(final double result, final boolean allowNegativeInfinity) {
        return result <= 0.0 && result != Double.POSITIVE_INFINITY && (allowNegativeInfinity || result != Double.NEGATIVE_INFINITY) && ! Double.isNaN(result);
    }

    /**
     * Checks that the result is a well-formed probability
     *
     * @param result a supposedly well-formed probability value
     * @return true if result is really well formed
     */
    public static boolean goodProbability(final double result) {
        return result >= 0.0 && result <= 1.0 && ! Double.isInfinite(result) && ! Double.isNaN(result);
    }

    //
    // useful common utility routines
    //

    /**
     * Converts LN to LOG10
     *
     * @param ln log(x)
     * @return log10(x)
     */
    public static double lnToLog10(final double ln) {
        return ln * LOG10_OF_E;
    }

    /**
     * Calculates the log10 of the gamma function for x.
     *
     * @param x the x parameter
     * @return the log10 of the gamma function at x.
     */
    public static double log10Gamma(final double x) {
        return lnToLog10(Gamma.logGamma(x));
    }

    public static double log10Factorial(final int x) {
        if (x >= Log10FactorialCache.size() || x < 0)
            return log10Gamma(x + 1);
        else
            return Log10FactorialCache.get(x);
    }

    /**
     * Wrapper class so that the log10Factorial array is only calculated if it's used
     */
    private static class Log10FactorialCache {

        /**
         * The size of the precomputed cache.  Must be a positive number!
         */
        private static final int CACHE_SIZE = 10_000;

        public static int size() { return CACHE_SIZE; }

        public static double get(final int n) {
            if (cache == null)
                initialize();
            return cache[n];
        }

        private static void initialize() {
            if (cache == null) {
                Log10Cache.ensureCacheContains(CACHE_SIZE);
                cache = new double[CACHE_SIZE];
                cache[0] = 0.0;
                for (int k = 1; k < cache.length; k++)
                    cache[k] = cache[k-1] + Log10Cache.get(k);
            }
        }

        private static double[] cache = null;
    }

    /**
     * Compute in a numerical correct way the quantity log10(1-x)
     *
     * Uses the approximation log10(1-x) = log10(1/x - 1) + log10(x) to avoid very quick underflow
     * in 1-x when x is very small
     *
     * @param x a positive double value between 0.0 and 1.0
     * @return an estimate of log10(1-x)
     */
    public static double log10OneMinusX(final double x) {
        if ( x == 1.0 )
            return Double.NEGATIVE_INFINITY;
        else if ( x == 0.0 )
            return 0.0;
        else {
            final double d = Math.log10(1 / x - 1) + Math.log10(x);
            return Double.isInfinite(d) || d > 0.0 ? 0.0 : d;
        }
    }

    /**
     * Now for some matrix methods
     */

    /**
     *
     * @param m a real-valued matrix
     * @return whether m is symmetric
     */
    public static boolean isSymmetric(RealMatrix m) {
        return m.equals(m.transpose());
    }

    /**
     *
     * @param m a real-valued matrix
     * @return whether m is positive semi-definite i.e. has no negative eigenvalues
     */
    public static boolean isPositiveSemiDefinite(RealMatrix m) {
        EigenDecomposition ed = new EigenDecomposition(m);
        for (final double eigval : ed.getRealEigenvalues()) {
            if (eigval < 0) return false;
        }
        return true;
    }

    /**
     * Compute the logarithm of a square matrix.  Unfortunately, Aoache Commons does not have this method.
     *
     * We compute the matrix logarithm by diagonalizing, taking logarithms of the diagonal entries, and
     * reversing the diagonalizing change of basis
     *
     * @param M
     * @return the matrix logarithm of M
     */
    public static RealMatrix matrixLog(RealMatrix M) {
        EigenDecomposition ed = new EigenDecomposition(M);
        RealMatrix D = ed.getD();   //D is diagonal
        RealMatrix V = ed.getV();   //M = V*D*V^T; V is the diagonalizing change of basis

        //replace D (in-place) by its logarithm
        for (int i = 0; i < M.getColumnDimension(); i++) {
            D.setEntry(i, i, Math.log(D.getEntry(i, i)));
        }

        return V.multiply(D).multiply(V.transpose());   //reverse the change of basis
    }

    /**
     * Measure the difference between two covariance matrices in terms of the Kullback-Leibler
     * divergence between associated Gaussians.
     *
     * If d is the dimension of these matrices, the KL divergence between zero-centered Gaussians
     * with covariances A and B is (1/2){tr[A^(-1)B] + ln(det(A) - ln(det(B)) - d}.  Note: the KL
     * divergence is not symmetric.  Switching A <--> B and averaging gives (1/2){tr[A^(-1)B] + tr[B^(-1)A] - d}
     *
     * @param cov1 a matrix covariance
     * @param cov2 a matrix covariance
     * @return the average of KL divergences, (KL(p|q) + KL(q|p))/2, where p and q are probability densities
     * of zero-centered Gaussians with the give covariance
     */
    public static double covarianceKLDivergence(RealMatrix cov1, RealMatrix cov2) {
        if (!isSymmetric(cov1) || !isSymmetric(cov2)) {
            throw new GATKException("Covariance matrices must be symmetric.");
        }

        if (!isPositiveSemiDefinite(cov1) || !isPositiveSemiDefinite(cov2)) {
            throw new GATKException("Covariance matrices must be positive semidefinite.");
        }

        int d = cov1.getRowDimension();

        if (cov1.getRowDimension() != cov2.getRowDimension()) {
            throw new GATKException("Can only compare covariance matrices of equal dimension.");
        }

        LUDecomposition LU1 = new LUDecomposition(cov1);
        LUDecomposition LU2 = new LUDecomposition(cov2);

        return (LU1.getSolver().solve(cov2).getTrace() + LU2.getSolver().solve(cov1).getTrace() - d)/2;
    }

    /**
     * Measure the geodesic distance between the two covariances within the manifold of symmetric,
     * positive-definite matrices.  This is also called the affine-invariant metric.
     *
     * The formula is ||log(A^(-1/2)*B*A^(-1/2)||_F, where ||    ||_F is the Frobenius norm.  This formula
     * is symmetric despite its appearance.
     *
     * For positive semidefinite matrices with eigendecomposition M = V*D*V^(-1), where D is diagonal
     * the matrix inverse square root is M^(-1/2) = V*D^(-1/2)*V^(-1)
     *
     * @param cov1 a covariance matrix
     * @param cov2 a covariance matrix
     * @return the geodesic distance between cov1 and cov2 in the manifold of positive semi-definite
     * symmetric matrices, which is more natural than the Euclidean distance inherited from the embedding
     * in R^(d^2)
     */
    public static double covarianceGeodesicDistance(RealMatrix cov1, RealMatrix cov2) {
        if (!isSymmetric(cov1) || !isSymmetric(cov2)) {
            throw new GATKException("Covariance matrices must be symmetric.");
        }

        if (!isPositiveSemiDefinite(cov1) || !isPositiveSemiDefinite(cov2)) {
            throw new GATKException("Covariance matrices must be positive semidefinite.");
        }

        if (cov1.getRowDimension() != cov2.getRowDimension()) {
            throw new GATKException("Can only compare covariance matrices of equal dimension.");
        }

        RealMatrix sqrt = (new EigenDecomposition(cov1)).getSquareRoot();
        RealMatrix inverseSqrt = (new LUDecomposition(sqrt)).getSolver().getInverse();

        //the thing inside the matrix logarithm
        RealMatrix mat = inverseSqrt.multiply(cov2).multiply(inverseSqrt);
        return matrixLog(mat).getFrobeniusNorm();

    }

    /** Calculate the mean of an array of doubles. */
    public static double mean(final double[] in, final int start, final int stop) {
        if ((stop - start) <= 0 ) return Double.NaN;

        double total = 0;
        for (int i = start; i < stop; ++i) {
            total += in[i];
        }

        return total / (stop - start);
    }

    /** Calculate the (population) standard deviation of an array of doubles. */
    public static double stddev(final double[] in, final int start, final int length) {
        return stddev(in, start, length, mean(in, start, length));
    }

    /** Calculate the (population) standard deviation of an array of doubles. */
    public static double stddev(final double[] in, final int start, final int stop, final double mean) {
        if ((stop - start) <= 0) return Double.NaN;

        double total = 0;
        for (int i = start; i < stop; ++i) {
            total += (in[i] * in[i]);
        }

        return Math.sqrt((total / (stop - start)) - (mean * mean));
    }

    /** "Promotes" an int[] into a double array with the same values (or as close as precision allows). */
    public static double[] promote(final int[] is) {
        final double[] ds = new double[is.length];
        for (int i = 0; i < is.length; ++i) ds[i] = is[i];
        return ds;
    }
}


text:
AmazingEvents::App.controllers :events do
  before(except: :show) { authenticate }

  get :new do
    @event = current_user.created_events.build
    @event.start_time = DateTime.now
    @event.end_time = DateTime.now
    render :new
  end

  post :create, '/events' do
    @event = current_user.created_events.build(params[:event])
    if @event.save
      redirect url(:events, :show, @event.id), notice: '作成しました'
    else
      render :new
    end
  end

  get :show, '/events/:id' do
    @event = Event.find(params[:id])
    @tickets = @event.tickets.includes(:user).order(:created_at)
    @ticket = current_user && current_user.tickets.find_by(event_id: params[:id])
    render :show
  end

  get :edit, with: :id do
    @event = current_user.created_events.find(params[:id])
    render :edit
  end

  patch :update, '/events/:id' do
    @event = current_user.created_events.find(params[:id])
    if @event.update(params[:event])
      redirect url(:events, :show, @event.id), notice: '更新しました'
    else
      render :edit
    end
  end

  delete :destroy, '/events/:id' do
    @event = current_user.created_events.find(params[:id])
    @event.destroy!
    redirect url(:welcome, :index), notice: '削除しました'
  end

end


text:
using System;
using System.Data.SQLite;
using System.Reflection;
using NHibernate;
using NHibernate.Cfg;

namespace pwiz.Common.Database.NHibernate
{
    public static class SessionFactoryFactory
    {
        private const string DEFAULT_SCHEMA_FILENAME = "mapping.xml"; // Not L10N

        public static ISessionFactory CreateSessionFactory(String path, Type typeDb, bool createSchema)
        {
            return CreateSessionFactory(path, typeDb, DEFAULT_SCHEMA_FILENAME, createSchema);
        }

        public static ISessionFactory CreateSessionFactory(String path, Type typeDb, string schemaFilename, bool createSchema)
        {
            Configuration configuration = new Configuration()
                //.SetProperty("show_sql", "true")
                //.SetProperty("generate_statistics", "true")
                .SetProperty("dialect", typeof(global::NHibernate.Dialect.SQLiteDialect).AssemblyQualifiedName) // Not L10N
                .SetProperty("connection.connection_string", SQLiteConnectionStringBuilderFromFilePath(path).ToString()) // Not L10N
                .SetProperty("connection.driver_class", // Not L10N
                typeof(global::NHibernate.Driver.SQLite20Driver).AssemblyQualifiedName);
            if (createSchema)
            {
                configuration.SetProperty("hbm2ddl.auto", "create"); // Not L10N
            }
            configuration.SetProperty("connection.provider", // Not L10N
                typeof(global::NHibernate.Connection.DriverConnectionProvider).AssemblyQualifiedName);
            ConfigureMappings(configuration, typeDb, schemaFilename);
            ISessionFactory sessionFactory = configuration.BuildSessionFactory();
            return sessionFactory;
        }

        /// <summary>
        /// Returns a ConnectionStringBuilder with the datasource set to the specified path.  This method takes
        /// care of the special settings needed to work with UNC paths.
        /// </summary>
        public static SQLiteConnectionStringBuilder SQLiteConnectionStringBuilderFromFilePath(string path)
        {
            // when SQLite parses the connection string, it treats backslash as an escape character
            // This is not normally an issue, because backslashes followed by a non-reserved character
            // are not treated specially.

            // Also, in order to prevent a drive letter being prepended to UNC paths, we specify ToFullPath=false
            return new SQLiteConnectionStringBuilder
            {
                DataSource = path.Replace("\\", "\\\\"), // Not L10N
                ToFullPath = false,
            };
        }

        public static Configuration ConfigureMappings(Configuration configuration, Type typeDb, string schemaFilename = DEFAULT_SCHEMA_FILENAME)
        {
            Assembly assembly = typeDb.Assembly;
            configuration.SetDefaultAssembly(assembly.FullName);
            configuration.SetDefaultNamespace(typeDb.Namespace);
            return configuration.AddInputStream(
                assembly.GetManifestResourceStream(typeDb.Namespace + "." + schemaFilename)); // Not L10N
        }
    }
}


text:
desc_pl=FirewallD
<<<<<<< HEAD
longdesc_pl=Konfiguracja Firewalla Linuksa u¿ywaj±c FirewallD, poprzez edytowanie dozwolonych us³ug i portów.
=======
longdesc_pl=Konfiguracja Firewalla Linuksa używając FirewallD, poprzez edytowanie dozwolonych usług i portów.
>>>>>>> upstream/master


text:
require 'spec_helper'

describe EventInstancesHelper, type: :helper do
  let(:uuid) { '82c2b3b8-42f7-442b-be64-86c2f407b2ed' }

  before do
    expect(SecureRandom).to receive(:uuid).and_return(uuid)
  end

  it 'generates a unique id for a hangout event' do
    user = FactoryGirl.build_stubbed(:user, id: '45')

    expect(generate_event_instance_id(user, '85')).to eq("4585-#{uuid}")
  end

  it 'generates an id if project is nil' do
    user = FactoryGirl.build_stubbed(:user, id: '45')

    expect(generate_event_instance_id(user)).to eq("4500-#{uuid}")
  end
end


text:
<?php

namespace Todstoychev\Icr\Exception;

/**
 * Handles image not set error
 *
 * @package Todstoychev\Icr\Exception
 * @author Todor Todorov <todstoychev@gmail.com>
 */
class ImageNotSetException extends \RuntimeException
{

}


text:
ACCEPTED

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

#### Published in
Philos. Trans. 77(2):308, t. 12. 1787

#### Original name
null

### Remarks
null


text:
            <?php $this->load->view('site/common/admin_menu'); ?>

                <?php
                    if($this->session->has_userdata('suc_msg')){
                        echo message_alert($this->session->userdata('suc_msg'), 2);
                        $this->session->unset_userdata('suc_msg');
                    }
                    if($this->session->has_userdata('err_msg')){
                        echo message_alert($this->session->userdata('err_msg'), 4);
                        $this->session->unset_userdata('err_msg');
                    }
                ?>

Manage Reports

                        <form action="<?php echo base_url(); ?>manage-report/search-report" name="report_filter" method="POST" id="report_filter" class="form-inline">
                            <?php if(isset($locations)): ?>

                            <select name="location" class="form-control">
                                <option value="">All Locations</option>
                                <?php foreach($locations as $location): if($location == ''){continue;}?>
                                <option value="<?php echo $location; ?>"><?php echo $location; ?></option>
                                <?php endforeach; ?>
                            </select>

                            <?php endif; ?>
                            <?php if(isset($ages)): ?>

                            <select name="ages" class="form-control">
                                <option value="">All Ages</option>
                                <?php foreach($ages as $age): if($age == ''){continue;}?>
                                <option value="<?php echo $age; ?>"><?php echo $age; ?></option>
                                <?php endforeach; ?>
                            </select>

                            <?php endif; ?>
                            <?php if(isset($genders)): ?>

                            <select name="genders" class="form-control">
                                <option value="">All Genders</option>
                                <?php foreach($genders as $gender): if($gender == ''){continue;}?>
                                <option value="<?php echo $gender; ?>"><?php echo $gender; ?></option>
                                <?php endforeach; ?>
                            </select>

                            <?php endif; ?>
                            <?php if(isset($departments)): ?>

                            <select name="departments" class="form-control">
                                <option value="">All Departments</option>
                                <?php foreach($departments as $department): if($department == ''){continue;}?>
                                <option value="<?php echo $department; ?>"><?php echo $department; ?></option>
                                <?php endforeach; ?>
                            </select>

                            <?php endif; ?>
                            <?php if(isset($levels)): ?>

                            <select name="levels" class="form-control">
                                <option value="">All Levels</option>
                                <?php foreach($levels as $level): if($level == ''){continue;}?>
                                <option value="<?php echo $level; ?>"><?php echo $level; ?></option>
                                <?php endforeach; ?>
                            </select>

                            <?php endif; ?>
                            <button type="submit" name="filter_report" value="Filter"  class="btn btn-danger btn-filter"> Filter</button>

                            <button type="button" onclick="tableToExcel('tbExport', 'Report Table', 'report.xls')" value="Export to Excel" class="btn btn-danger btn-filter"> Export to Excel</button>
                        </form>

                                    User
                                    <?php if(isset($dimentions)) :?>
                                    <?php foreach($dimentions as $dimention): ?>
                                    <?php echo $dimention->question; ?>
                                    <?php endforeach; ?>
                                    <?php endif; ?>

                                    <?php echo $surveys; ?>


text:
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

namespace UnityEditor.VFX.Block
{
    abstract class PositionBase : VFXBlock
    {
        public enum PositionMode
        {
            Surface,
            Volume,
            ThicknessAbsolute,
            ThicknessRelative
        }

        public enum SpawnMode
        {
            Randomized,
            Custom
        }

        public class ThicknessProperties
        {
            [Min(0), Tooltip("Controls whether particles are spawned on the surface of the shape, or inside the volume.")]
            public float Thickness = 0.1f;
        }

        [VFXSetting, Tooltip("Controls whether particles are spawned on the surface of the shape, or inside the volume.")]
        public PositionMode positionMode;
        [VFXSetting, Tooltip("Controls whether particles are spawned randomly, or can be controlled by a deterministic input.")]
        public SpawnMode spawnMode;

        public override VFXContextType compatibleContexts { get { return VFXContextType.kInitAndUpdateAndOutput; } }
        public override VFXDataType compatibleData { get { return VFXDataType.kParticle; } }

        protected virtual bool needDirectionWrite { get { return false; } }

        public override IEnumerable<VFXAttributeInfo> attributes
        {
            get
            {
                yield return new VFXAttributeInfo(VFXAttribute.Position, VFXAttributeMode.ReadWrite);
                yield return new VFXAttributeInfo(VFXAttribute.Seed, VFXAttributeMode.ReadWrite);
                if (needDirectionWrite)
                    yield return new VFXAttributeInfo(new VFXAttribute("direction", VFXValue.Constant(new Vector3(0.0f, 0.0f, 1.0f))), VFXAttributeMode.Write);
            }
        }

        public override IEnumerable<VFXNamedExpression> parameters
        {
            get
            {
                foreach (var p in GetExpressionsFromSlots(this).Where(e => e.name != "Thickness"))
                    yield return p;

                yield return new VFXNamedExpression(CalculateVolumeFactor(positionMode, 0, 1), "volumeFactor");
            }
        }

        protected override IEnumerable<VFXPropertyWithValue> inputProperties
        {
            get
            {
                var properties = PropertiesFromType(GetInputPropertiesTypeName());
                if (positionMode == PositionMode.ThicknessAbsolute || positionMode == PositionMode.ThicknessRelative)
                    properties = properties.Concat(PropertiesFromType("ThicknessProperties"));
                if (spawnMode == SpawnMode.Custom)
                    properties = properties.Concat(PropertiesFromType("CustomProperties"));
                return properties;
            }
        }

        protected virtual float thicknessDimensions { get { return 3.0f; } }

        protected VFXExpression CalculateVolumeFactor(PositionMode positionMode, int radiusIndex, int thicknessIndex)
        {
            VFXExpression factor = VFXValue.Constant(0.0f);

            switch (positionMode)
            {
                case PositionMode.Surface:
                    factor = VFXValue.Constant(0.0f);
                    break;
                case PositionMode.Volume:
                    factor = VFXValue.Constant(1.0f);
                    break;
                case PositionMode.ThicknessAbsolute:
                case PositionMode.ThicknessRelative:
                {
                    var thickness = inputSlots[thicknessIndex].GetExpression();
                    if (positionMode == PositionMode.ThicknessAbsolute)
                    {
                        var radius = inputSlots[radiusIndex][1].GetExpression();
                        thickness = thickness / radius;
                    }

                    factor = VFXOperatorUtility.Saturate(thickness);
                    break;
                }
            }

            return new VFXExpressionPow(VFXValue.Constant(1.0f) - factor, VFXValue.Constant(thicknessDimensions));
        }
    }
}


text:
using System;
using NakedFramework.Architecture.Adapter;
using NakedFramework.Architecture.Framework;
using NakedFramework.Architecture.Spec;

namespace NakedFramework.Metamodel.Facet;

[Serializable]
public sealed class ActionDefaultsFacetAnnotation : ActionDefaultsFacetAbstract {
    private readonly bool isDateTime;
    private readonly object value;

    public ActionDefaultsFacetAnnotation(object value, bool isDateTime) {
        this.value = value;
        this.isDateTime = isDateTime;
    }

    public override bool CanAlwaysReplace => false;

    private object GetDefaultValue() => isDateTime && value is int i ? DateTime.UtcNow.AddDays(i) : value;

    public override (object value, TypeOfDefaultValue type) GetDefault(INakedObjectAdapter nakedObjectAdapter, INakedFramework framework) => (GetDefaultValue(), TypeOfDefaultValue.Explicit);
}

// Copyright (c) Naked Objects Group Ltd.


text:
package org.apache.ignite.internal.processors.igfs.client;

import org.apache.ignite.binary.BinaryObjectException;
import org.apache.ignite.binary.BinaryRawReader;
import org.apache.ignite.binary.BinaryRawWriter;
import org.apache.ignite.igfs.IgfsPath;
import org.apache.ignite.internal.processors.igfs.IgfsContext;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.jetbrains.annotations.Nullable;

/**
 * IGFS client set times callable.
 */
public class IgfsClientSetTimesCallable extends IgfsClientAbstractCallable<Void> {
    /** */
    private static final long serialVersionUID = 0L;

    /** Access time. */
    private long accessTime;

    /** Modification time. */
    private long modificationTime;

    /**
     * Default constructor.
     */
    public IgfsClientSetTimesCallable() {
        // NO-op.
    }

    /**
     * Constructor.
     *
     * @param igfsName IGFS name.
     * @param path Path.
     * @param accessTime Access time.
     * @param modificationTime Modification time.
     */
    public IgfsClientSetTimesCallable(@Nullable String igfsName, IgfsPath path, long accessTime,
        long modificationTime) {
        super(igfsName, path);

        this.accessTime = accessTime;
        this.modificationTime = modificationTime;
    }

    /** {@inheritDoc} */
    @Override protected Void call0(IgfsContext ctx) throws Exception {
        ctx.igfs().setTimes(path, accessTime, modificationTime);

        return null;
    }

    /** {@inheritDoc} */
    @Override public void writeBinary0(BinaryRawWriter writer) throws BinaryObjectException {
        writer.writeLong(accessTime);
        writer.writeLong(modificationTime);
    }

    /** {@inheritDoc} */
    @Override public void readBinary0(BinaryRawReader reader) throws BinaryObjectException {
        accessTime = reader.readLong();
        modificationTime = reader.readLong();
    }

    /** {@inheritDoc} */
    @Override public String toString() {
        return S.toString(IgfsClientSetTimesCallable.class, this);
    }
}


text:
FILE(REMOVE_RECURSE
  "CMakeFiles/sparse_extra_2.dir/sparse_extra.cpp.o"
  "sparse_extra_2.pdb"
  "sparse_extra_2"
)

# Per-language clean rules from dependency scanning.
FOREACH(lang CXX)
  INCLUDE(CMakeFiles/sparse_extra_2.dir/cmake_clean_${lang}.cmake OPTIONAL)
ENDFOREACH(lang)


text:
The files in this directory are not strictly necessary for running SynthNotes, but may be helpful or interesting to users.

## Helper Scripts

The script ``csv_to_parquet.py`` takes a CSV file, such as ``NOTE_EVENTS.csv``, and converts it to a parquet file using the encoding of your choice (default gzip). This may be helpful for converting the MIMIC-III table output to something that can be read by SynthNotes.

## Jupyter Notebooks

These notebooks do not directly interface with the operation of SynthNotes, but may be interesting for users looking for insights into how it functions.

* ``preprocessing.ipynb`` graphically demonstrates how the preprocessing stage works.
* ``clustering.ipynb`` graphically demonstrates how the clustering stage works.


text:
'use strict';

// Declare app level module which depends on views, and components
angular.module('myApp', [
    'ngRoute',
    'myApp.users',
    'pascalprecht.translate']);


text:
@class NSString;
BOOL applyBinaryDelta(NSString *source, NSString *destination, NSString *patchFile, BOOL verbose, NSError * __autoreleasing *error);

#endif