text:
<!-- README.md is generated from README.Rmd. Please edit that file -->

# novaMobenzi

<!-- badges: start -->
<!-- badges: end -->

The goal of novaMobenzi is to …

## Installation

You can install the released version of novaMobenzi from
[CRAN](https://CRAN.R-project.org) with:

``` r
# install.packages("devtools")
devtools::install_github("NovaInstitute/Rpackages", subdir = "novaMobenzi")
```

## Example

This is a basic example which shows you how to solve a common problem:

``` r
library(novaMobenzi)
## basic example code
```

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Diagnostics;
using System.IO;
using System.Windows;

namespace MS.Internal.IO.Zip
{
    /// <summary>
    /// This class is used to represent and parse the Padding Extra Field
    ///
    /// The Padding Extra Field is defined as:
    /// Header ID               UInt16 (2 bytes)    0xA220
    /// Length of the field     UInt16 (2 bytes)
    /// Signature               UInt16 (2 bytes)    0xA028 (for verification)
    /// Padding Initial Value   UInt16 (2 bytes)    Padding size originally requested by the caller
    /// Padding                 ? bytes             Padding respresented by null characters
    /// </summary>
    internal class ZipIOExtraFieldPaddingElement  : ZipIOExtraFieldElement
    {
        // creates a brand new empty Padding extra field element
        internal static ZipIOExtraFieldPaddingElement CreateNew()
        {
            ZipIOExtraFieldPaddingElement newElement = new ZipIOExtraFieldPaddingElement();

            return newElement;
        }

        // parse Padding extra field element
        internal override void ParseDataField(BinaryReader reader, UInt16 size)
        {
            // The signature is already read and validated
            Debug.Assert(size >= MinimumSize);

            // It is guaranteed that there is enough bytes to read in UInt16
            //  since it is already checked from ZipIOExtraFieldElement.Parse()
            _initialRequestedPaddingSize = reader.ReadUInt16();

            // need to subtract the size of the signature and size fields
            // We don't need to use checked{} since size is guaranteed to be bigger than
            //  MinimumFieldDataSize by the called (ZipIOExtraFieldElement.Parse)
            size -= _minimumFieldDataSize;

            _paddingSize = size;

            // Skip the padding
            if (_paddingSize != 0)
            {
                reader.BaseStream.Seek(size, SeekOrigin.Current);
            }
        }

        internal static bool MatchesPaddingSignature(byte[] sniffiedBytes)
        {
            if (sniffiedBytes.Length < _signatureSize)
            {
                return false;
            }

            Debug.Assert(sniffiedBytes.Length == _signatureSize);

            if (BitConverter.ToUInt16(sniffiedBytes, 0) != _signature)
            {
                return false;
            }

            return true;
        }

        internal override void Save(BinaryWriter writer)
        {
            writer.Write(_constantFieldId);
            writer.Write(SizeField);
            writer.Write(_signature);
            writer.Write(_initialRequestedPaddingSize);

            for (int i = 0; i < _paddingSize; ++i)
            {
                writer.Write((byte) 0);
            }
        }

        // This property calculates size of the field on disk (how many bytes need to be allocated on the disk)
        //  id + size field + data field (SizeField)
        internal override UInt16 Size
        {
            get
            {
                return checked((UInt16) (SizeField + MinimumSize));
            }
        }

        // This property calculates the value of the size record whch holds the size without the Id and without the size itself.
        // we are always guranteed that Size == SizeField + 2 * sizeof(UInt16))
        internal override UInt16 SizeField
        {
            get
            {
                return checked((UInt16) (_minimumFieldDataSize + _paddingSize));
            }
        }

        static internal UInt16 ConstantFieldId
        {
            get
            {
                return _constantFieldId;
            }
        }

        static internal UInt16 MinimumFieldDataSize
        {
            get
            {
                return _minimumFieldDataSize;
            }
        }

        static internal UInt16 SignatureSize
        {
            get
            {
                return _signatureSize;
            }
        }

        internal UInt16 PaddingSize
        {
            get
            {
                return _paddingSize;
            }
            set
            {
                _paddingSize = value;
            }
        }

        //------------------------------------------------------
        //
        //  Private Constructor
        //
        //------------------------------------------------------
        internal ZipIOExtraFieldPaddingElement() : base(_constantFieldId)
        {
            _initialRequestedPaddingSize = _newInitialPaddingSize;
            _paddingSize = _initialRequestedPaddingSize;
        }

        //------------------------------------------------------
        //
        //  Private Methods
        //
        //------------------------------------------------------

        //------------------------------------------------------
        //
        //  Private fields
        //
        //------------------------------------------------------
        private const UInt16 _constantFieldId = 0xA220;
        private const UInt16 _signature = 0xA028;
        // 20 is the maximum size of Zip64 Extra Field element we can use for Local File Header
        //  (Id, Size, Compressed and UnCompressed Sizes; 2 + 2 + 8 + 8 = 20)
        //  DiskNumber and Relative Offset of Local File Header is not counted since we don't use
        //  it in Local File Header
        private const UInt16 _newInitialPaddingSize = 20;

        // UInt16 signature
        // UInt16 initial requested padding size
        private static readonly UInt16 _minimumFieldDataSize = 2 * sizeof(UInt16);
        private static readonly UInt16 _signatureSize = sizeof(UInt16);

        private UInt16 _paddingSize;
        private UInt16 _initialRequestedPaddingSize;
    }
}


text:
<?php

declare(strict_types=1);

namespace Doctrine\ODM\MongoDB\Tests\Functional\Ticket;

use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use Doctrine\ODM\MongoDB\Tests\BaseTest;

class GH1107Test extends BaseTest
{
    public function testOverrideIdStrategy(): void
    {
        $childObj       = new GH1107ChildClass();
        $childObj->name = 'ChildObject';
        $this->dm->persist($childObj);
        $this->dm->flush();
        self::assertNotNull($childObj->id);
    }
}

/**
 * @ODM\Document
 * @ODM\InheritanceType("SINGLE_COLLECTION")
 */
class GH1107ParentClass
{
    /**
     * @ODM\Id(strategy="NONE")
     *
     * @var string|null
     */
    public $id;

    /**
     * @ODM\Field(type="string")
     *
     * @var string|null
     */
    public $name;
}

/** @ODM\Document */
class GH1107ChildClass extends GH1107ParentClass
{
    /**
     * @ODM\Id(strategy="AUTO")
     *
     * @var string|null
     */
    public $id;
}


text:
BasicUtil
=========

Nothing special at the moment just messing around with bukkit plugins


text:
import zstackwoodpecker.test_state as ts_header
import os
TestAction = ts_header.TestAction
def path():

    return dict(initial_formation="template5", checking_point=8, path_list=[
		[TestAction.create_vm, 'vm1', ],
		[TestAction.create_volume, 'volume1', 'flag=scsi'],
		[TestAction.attach_volume, 'vm1', 'volume1'],
		[TestAction.create_volume, 'volume2', 'flag=scsi'],
		[TestAction.attach_volume, 'vm1', 'volume2'],
		[TestAction.create_volume, 'volume3', 'flag=scsi'],
		[TestAction.attach_volume, 'vm1', 'volume3'],
		[TestAction.create_vm_snapshot, 'vm1', 'vm1-snapshot1'],
		[TestAction.clone_vm, 'vm1', 'vm2'],
		[TestAction.create_volume_backup, 'volume3', 'volume3-backup1'],
		[TestAction.stop_vm, 'vm1'],
		[TestAction.use_volume_backup, 'volume3-backup1'],
		[TestAction.start_vm, 'vm1'],
		[TestAction.create_vm_snapshot, 'vm2', 'vm2-snapshot5'],
		[TestAction.delete_vm_snapshot, 'vm1-snapshot1'],
		[TestAction.create_vm_snapshot, 'vm2', 'vm2-snapshot6'],
		[TestAction.clone_vm, 'vm2', 'vm3', 'full'],
		[TestAction.delete_volume_snapshot, 'vm2-snapshot5'],
		[TestAction.stop_vm, 'vm2'],
		[TestAction.change_vm_image, 'vm2'],
		[TestAction.create_vm_snapshot, 'vm1', 'vm1-snapshot7'],
		[TestAction.delete_vm_snapshot, 'vm1-snapshot7'],
])

'''
The final status:
Running:['vm1', 'vm3']
Stopped:['vm2']
Enadbled:['vm2-snapshot6', 'volume3-backup1']
attached:['volume1', 'volume2', 'volume3']
Detached:[]
Deleted:['vm1-snapshot1', 'volume1-snapshot1', 'volume2-snapshot1', 'volume3-snapshot1', 'vm2-snapshot5', 'vm1-snapshot7', 'volume1-snapshot7', 'volume2-snapshot7', 'volume3-snapshot7']
Expunged:[]
Ha:[]
Group:
'''


text:
<?php
$this->load->view('template_admin/head');
?>
<?php
$this->load->view('template_admin/topbar');
$this->load->view('template_admin/sidebar');
?>
 <link href="<?php echo base_url('assets/tags/jquery.tagsinput.css') ?>" rel="stylesheet" type="text/css" />

        List Tryout

 Home

Tryout

List Tryout

                            No
                            Nama Peserta
                            Bidang
                            Waktu
                            Nilai

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

Person Form

                <form action="#" id="form" class="form-horizontal">
                    <input type="text" value="" name="kode_soal"/>

                            Kategori

                                <select name="id_katTO" class="form-control">
                                    <?php
                                        foreach ($kategori as $key) {?>
                                        <option value="<?php echo $key->id_katTO; ?>"><?php echo $key->nama; ?></option>
                                    <?php
                                        }
                                    ?>
                                </select>

                      Deskripsi Soal

                         <form>
                            <textarea name="soal_des" id="editor1"  required>

                            </textarea>

                        </form>

                            Bobot

                                <input name="bobot" placeholder="Nama Kategori TO" class="form-control" type="text">

                            Opsi A

                                <input name="opsi_a" placeholder="Pilihan A" class="form-control" type="text">

                            Opsi A

                                <input name="opsi_a" placeholder="Pilihan A" class="form-control" type="text">

                            Opsi B

                                <input name="opsi_b" placeholder="Pilihan B" class="form-control" type="text">

                            Opsi C

                                <input name="opsi_c" placeholder="Pilihan C" class="form-control" type="text">

                            Opsi D

                                <input name="opsi_d" placeholder="Pilihan D" class="form-control" type="text">

                            Opsi E

                                <input name="opsi_e" placeholder="Pilihan E" class="form-control" type="text">

                      Uraian

                         <form>
                            <textarea name="uraian" id="editor2"  required>

                            </textarea>

                        </form>

                            Kunci

                                <input name="kunci" placeholder="Masukkan kunci jawaban" class="form-control" type="text">

                      Pembahasan

                         <form>
                            <textarea name="uraian" id="editor3"  required>

                            </textarea>

                        </form>

                            Status

                                <select name="status" class="form-control" >
                                    <option value="active">Aktif</option>
                                    <option value="not_active">Tidak</option>
                                </select>

                </form>

                <button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
                <button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>

<?php
$this->load->view('template_admin/js_tables');
?>

<?php
$this->load->view('template_admin/foot');
?>


text:
//---------------------------------------------------------------------
// <copyright file="IDataTypeToCodeTypeReferenceResolver.cs" company="Microsoft">
//      Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------

namespace Microsoft.Test.Taupo.Contracts.Types
{
    using System.CodeDom;

    /// <summary>
    /// Resolves DataTypes into their CodeTypeReferences
    /// </summary>
    public interface IDataTypeToCodeTypeReferenceResolver
    {
        /// <summary>
        /// Resolves the specified type into its type reference.
        /// </summary>
        /// <param name="dataType">The data type.</param>
        /// <returns>CodeTypeReference that should be used in code to refer to the type.</returns>
        CodeTypeReference Resolve(DataType dataType);
    }
}


text:
typedef void (^TKPromiseKeptBlock)();
typedef void (^TKPromiseFailedBlock)();
typedef void (^TKPromiseResolvedBlock)();
typedef void (^TKCommitmentKeptBlock)(NSString *commitment);

#define kTKPromiseCommitmentAlreadyKeptError @"kTKPromiseCommitmentAlreadyKeptError"
#define kTKPromiseCommitmentAlreadyFailedError @"kTKPromiseCommitmentAlreadyFailedError"
#define kTKPromiseNoSuchCommitmentError @"kTKPromiseNoSuchCommitmentError"
#define kTKPromiseAlreadyResolvedError @"kTKPromiseAlreadyResolvedError"

@class TKPromise;

@protocol TKPromiseDelegate <NSObject>
@optional
- (void) promise:(TKPromise *)promise didKeepCommitment:(NSString *)commitment;
- (void) promise:(TKPromise *)promise didFailCommitment:(NSString *)commitment;
- (void) promiseKept:(TKPromise *)promise;
- (void) promiseDidFail:(TKPromise *)promise;
- (void) promiseDidResolve:(TKPromise *)promise;
@end

@interface TKPromise : NSObject {
    TKPromiseKeptBlock promiseKeptBlock;
    TKPromiseFailedBlock promiseFailedBlock;
    TKPromiseResolvedBlock resolveBlock;
    NSMutableSet *commitments;
    NSMutableSet *keptCommitments;
    NSMutableSet *failedCommitments;
}

- (id) initWithPromiseKeptBlock:(TKPromiseKeptBlock)promiseKeptBlock
             promiseFailedBlock:(TKPromiseFailedBlock)promiseFailedBlock
           promiseResolvedBlock:(TKPromiseResolvedBlock)resolveBlock
                    commitments:(NSString *)aCommitment, ... NS_REQUIRES_NIL_TERMINATION;

@property(nonatomic, weak) id<TKPromiseDelegate> delegate;
@property(nonatomic, copy) TKCommitmentKeptBlock commitmentKeptBlock;

- (BOOL) isCommittedTo:(NSString *)commitment;
- (BOOL) isCommitmentKept:(NSString *)commitment;
- (BOOL) isCommitmentFailed:(NSString *)commitment;
- (BOOL) isKept;
- (BOOL) isFailed;
- (BOOL) isResolved;
- (NSInteger) countOfCommitmentsKept;
- (NSInteger) countOfCommitmentsFailed;
- (NSInteger) countOfCommitmentsToKeep;
- (void) keepCommitment:(NSString *)commitment;
- (void) failCommitment:(NSString *)commitment;
- (void) addCommitment:(NSString *)commitment;
- (void) addCommitments:(NSSet *)commitments;
- (void) failAllCommitments;

@end


text:
namespace dda_simulator {

/// Edge of a network.
struct Edge {
	/// Index of the destination vertex.
	std::size_t dest;

	/// Index of this edge in the adjacency list in vertex 'dest'.
	std::size_t back_index;
};

/// Networks are given as vectors containing the adjacency list as vector
/// for each vertex.
typedef std::vector<std::vector<Edge>> Network;

/// Add edge (a, b) to 'network'. Assumes that the network has large enough size
/// for both parameters.
void addEdge(Network& network, std::size_t a, std::size_t b) {
	std::size_t a_ind = network[a].size();
	network[a].emplace_back();
	std::size_t b_ind = network[b].size();
	network[b].emplace_back();

	network[a][a_ind].dest = b;
	network[a][a_ind].back_index = b_ind;

	network[b][b_ind].dest = a;
	network[b][b_ind].back_index = a_ind;
}

/// Read a simple network by asking the adjacency lists from standard input.
Network readNetwork() {
	Network ret;

	std::cout << "Number of nodes: ";
	std::size_t n;
	std::cin >> n;
	while(std::cin.get() != '\n') { }
	ret.resize(n);

	std::cout << "The nodes are numbered 0.." << n - 1 << "\nGive the adjacency lists as space separated lists of numbers.\n";
	for(std::size_t i = 0; i < n; ++i) {
		std::cout << i << ": ";
		std::string line;
		std::getline(std::cin, line);
		line.push_back('\n');
		std::stringstream ss(line);

		while(true) {
			std::size_t j;
			ss >> j;
			if(!ss.good()) break;
			if(j >= n) {
				throw std::runtime_error("readNetwork: Node index out of bounds.");
			}
			if(i == j) {
				throw std::runtime_error("readNetwork: Loop created.");
			}

			ret[i].push_back(Edge{j, 0});
		}
	}

	for(std::size_t i = 0; i < n; ++i) {
		for(Edge& e : ret[i]) {
			bool found = false;
			for(std::size_t k = 0; k < ret[e.dest].size(); ++k) {
				if(ret[e.dest][k].dest == i) {
					if(found) {
						std::stringstream err;
						err << "readNetwork: Multiple edges " << i << " - " << e.dest << ".";
						throw std::runtime_error(err.str());
					}
					found = true;
					e.back_index = k;
				}
			}
			if(!found) {
				std::stringstream err;
				err << "readNetwork: No backward edge for " << i << " - " << e.dest << ".";
				throw std::runtime_error(err.str());
			}
		}
	}

	return ret;
}

}


text:
package org.fest.util;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

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

import static org.fest.util.Preconditions.checkNotNull;

/**
 * Utility methods related to arrays.
 *
 * @author Alex Ruiz
 * @author Joel Costigliola
 */
public class Arrays {
  private static final ArrayFormatter FORMATTER = new ArrayFormatter();

  private Arrays() {
  }

  /**
   * Indicates whether the given object is not {@code null} and is an array.
   *
   * @param o the given object.
   * @return {@code true} if the given object is not {@code null} and is an array, otherwise {@code false}.
   */
  public static boolean isArray(@Nullable Object o) {
    return o != null && o.getClass().isArray();
  }

  /**
   * Indicates whether the given array is {@code null} or empty.
   *
   * @param <T>   the type of elements of the array.
   * @param array the array to check.
   * @return {@code true} if the given array is {@code null} or empty, otherwise {@code false}.
   */
  public static <T> boolean isNullOrEmpty(@Nullable T[] array) {
    return array == null || !hasElements(array);
  }

  /**
   * Returns an array containing the given arguments.
   *
   * @param <T>    the type of the array to return.
   * @param values the values to store in the array.
   * @return an array containing the given arguments.
   */
  public static @NotNull <T> T[] array(@NotNull T... values) {
    return checkNotNull(values);
  }

  /**
   * Returns the {@code String} representation of the given array, or {@code null} if the given object is either {@code
   * null} or not an array. This method supports arrays having other arrays as elements.
   *
   * @param array the object that is expected to be an array.
   * @return the {@code String} representation of the given array.
   */
  public static @Nullable String format(@Nullable Object array) {
    return FORMATTER.format(array);
  }

  /**
   * Returns all the non-{@code null} elements in the given array.
   *
   * @param <T>   the type of elements of the array.
   * @param array the given array.
   * @return all the non-{@code null} elements in the given array.
   * @throws NullPointerException if the given array is {@code null}.
   * @since 1.1.3
   */
  public static <T> List<T> nonNullElementsIn(@NotNull T[] array) {
    checkNotNull(array);
    List<T> nonNullElements = new ArrayList<T>();
    for (T o : array) {
      if (o != null) {
        nonNullElements.add(o);
      }
    }
    return nonNullElements;
  }

  /**
   * Returns {@code true} if the given array has only {@code null} elements, {@code false} otherwise. If given array is
   * empty, this method returns {@code true}.
   *
   * @param <T>   the type of elements of the array.
   * @param array the given array. <b>It must not be null</b>.
   * @return {@code true} if the given array has only {@code null} elements or is empty, {@code false} otherwise.
   * @throws NullPointerException if the given array is {@code null}.
   * @since 1.1.3
   */
  public static <T> boolean hasOnlyNullElements(@NotNull T[] array) {
    checkNotNull(array);
    if (!hasElements(array)) {
      return false;
    }
    for (T o : array) {
      if (o != null) {
        return false;
      }
    }
    return true;
  }

  private static <T> boolean hasElements(@NotNull T[] array) {
    return array.length > 0;
  }
}


text:
import { View } from "react-native"
import LinearGradient from "react-native-linear-gradient"

import OpaqueImageView from "app/Components/OpaqueImageView/OpaqueImageView"
import { useTheme } from "palette/Theme"
import { Spacer } from "../../atoms/Spacer"
import { Flex } from "../Flex"
import { Text } from "../Text"
import { CardTag, CardTagProps } from "./CardTag"

export interface LargeCardProps {
  image: string
  title: string
  subtitle?: string
  tag?: CardTagProps
}

/**
 * `Large` is a card with one image one tall image, and text for title and subtitle
 * at the bottom.
 */
export const LargeCard: React.FC<LargeCardProps> = ({ image, title, subtitle, tag }) => {
  const { color, space } = useTheme()
  return (
    <View style={{ width: "100%", aspectRatio: 1.0 / 1.33, flexDirection: "row" }}>
      <Flex flex={2} background={color("black10")}>
        <OpaqueImageView imageURL={image} style={{ flex: 1 }} />
      </Flex>
      <LinearGradient
        colors={["rgba(0, 0, 0, 0)", "rgba(0, 0, 0, 1)"]}
        style={{
          position: "absolute",
          width: "100%",
          height: "100%",
          opacity: 0.15,
        }}
      />
      <Flex
        style={{
          position: "absolute",
          bottom: 0,
          left: space(2),
          right: space(6),
        }}
      >
        <Text variant="sm-display" color={color("white100")}>
          {title}
        </Text>
        {!!subtitle && (
          <Text variant="sm" color={color("white100")}>
            {subtitle}
          </Text>
        )}
        <Spacer mt={2} />
      </Flex>
      {!!tag && (
        <CardTag {...tag} style={{ position: "absolute", top: space(2), left: space(2) }} />
      )}
    </View>
  )
}


text:
<?php

/**
 * Retorna os nutrientes de um alimentos em formato JSON
 *
 * @param $nutrienteAlimento
 * @return string
 */
function grafoComposicao($nutrienteAlimento)
{

    $totalNutrientes = 0;
    $percentNutr = [];

    foreach ($nutrienteAlimento as $nutrieAlm) {
        if ($nutrieAlm->nutriente->nomeNutriente != "Energia(J)" &&
            $nutrieAlm->nutriente->nomeNutriente != "Energia" &&
            $nutrieAlm->qtde != 0
        ) {

            if ($nutrieAlm->nutriente->unidadeMedida->siglaUnidade == 'mg'
                && $nutrieAlm->qtde != 'NA' && $nutrieAlm->qte != 'Tr'
            ) {
                $totalNutrientes += ($nutrieAlm->qtde / 1000);
                array_push($percentNutr, ['label' => $nutrieAlm->nutriente->nomeNutriente, 'value' => $nutrieAlm->qtde / 1000]);
            } elseif ($nutrieAlm->qtde != 'NA' && $nutrieAlm->qte != 'Tr') {
                $totalNutrientes += $nutrieAlm->qtde;
                array_push($percentNutr, ['label' => $nutrieAlm->nutriente->nomeNutriente, 'value' => $nutrieAlm->qtde]);
            }
        }
    }

    $vlrs = [];
    $toJson = [];
    foreach ($percentNutr as $nutriente) {
        $porcentagemAtual = ($nutriente['value'] * 100) / $totalNutrientes;
        $porcentagemAtual = number_format($porcentagemAtual, 0);
        if ($porcentagemAtual > 0) {
            array_push($toJson, ['label' => $nutriente['label'],
                'value' => $porcentagemAtual]);
        }
    }
    return json_encode($toJson);
}


text:
from __future__ import division
from builtins import range
import sys

sys.path.insert(1, "../../../")
import h2o
from tests import pyunit_utils, assert_equals
from h2o.estimators.gbm import H2OGradientBoostingEstimator

def gbm_predict_contributions_sorting_large():
    fr = h2o.import_file(path=pyunit_utils.locate("bigdata/laptop/creditcardfraud/creditcardfraud.csv"))

    m = H2OGradientBoostingEstimator(ntrees=10, seed=1234)
    m.train(x=list(range(0, fr.ncol)), y=30, training_frame=fr)

    contributions = m.predict_contributions(fr, top_n=-1, bottom_n=0, compare_abs=False)
    assert_equals(61, contributions.shape[1], "Wrong number of columns")
    assert_equals(284807, contributions.shape[0], "Wrong number of rows")

if __name__ == "__main__":
    pyunit_utils.standalone_test(gbm_predict_contributions_sorting_large)
else:
    gbm_predict_contributions_sorting_large()


text:
package org.apache.openwhisk.core.controller

import java.util.Base64

import scala.concurrent.Future
import scala.util.{Failure, Success, Try}
import akka.http.scaladsl.model.HttpEntity.Empty
import akka.http.scaladsl.server.Directives
import akka.http.scaladsl.model.HttpMethod
import akka.http.scaladsl.model.HttpHeader
import akka.http.scaladsl.model.MediaType
import akka.http.scaladsl.model.MediaTypes
import akka.http.scaladsl.model.MediaTypes._
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.model.StatusCode
import akka.http.scaladsl.model.headers.RawHeader
import akka.http.scaladsl.model.headers._
import akka.http.scaladsl.model.Uri.Query
import akka.http.scaladsl.model.HttpEntity
import akka.http.scaladsl.server.Route
import akka.http.scaladsl.model.headers.`Content-Type`
import akka.http.scaladsl.model.headers.`Timeout-Access`
import akka.http.scaladsl.model.ContentType
import akka.http.scaladsl.model.ContentTypes
import akka.http.scaladsl.model.FormData
import akka.http.scaladsl.model.HttpMethods.{OPTIONS}
import akka.http.scaladsl.model.HttpCharsets
import akka.http.scaladsl.model.HttpResponse
import spray.json._
import spray.json.DefaultJsonProtocol._
import WhiskWebActionsApi.MediaExtension
import RestApiCommons.{jsonPrettyResponsePrinter => jsonPrettyPrinter}
import org.apache.openwhisk.common.TransactionId
import org.apache.openwhisk.core.controller.actions.PostActionActivation
import org.apache.openwhisk.core.database._
import org.apache.openwhisk.core.entitlement.{Collection, Privilege, Resource}
import org.apache.openwhisk.core.entity._
import org.apache.openwhisk.core.entity.types._
import org.apache.openwhisk.core.loadBalancer.LoadBalancerException
import org.apache.openwhisk.http.ErrorResponse.terminate
import org.apache.openwhisk.http.Messages
import org.apache.openwhisk.http.LenientSprayJsonSupport._
import org.apache.openwhisk.spi.SpiLoader
import org.apache.openwhisk.utils.JsHelpers._
import org.apache.openwhisk.core.entity.Exec

protected[controller] sealed class WebApiDirectives(prefix: String = "__ow_") {
  // enforce the presence of an extension (e.g., .http) in the URI path
  val enforceExtension = false

  // the field name that represents the status code for an http action response
  val statusCode = "statusCode"

  // parameters that are added to an action input to pass HTTP request context values
  val method: String = fields("method")
  val headers: String = fields("headers")
  val path: String = fields("path")
  val namespace: String = fields("user")
  val query: String = fields("query")
  val body: String = fields("body")

  lazy val reservedProperties: Set[String] = Set(method, headers, path, namespace, query, body)

  protected final def fields(f: String) = s"$prefix$f"
}

private case class Context(propertyMap: WebApiDirectives,
                           method: HttpMethod,
                           headers: Seq[HttpHeader],
                           path: String,
                           query: Query,
                           body: Option[JsValue] = None) {
  val queryAsMap = query.toMap

  // returns true iff the attached query and body parameters contain a property
  // that conflicts with the given reserved parameters
  def overrides(reservedParams: Set[String]): Boolean = {
    val queryParams = queryAsMap.keySet
    val bodyParams = body
      .map {
        case JsObject(fields) => fields.keySet
        case _                => Set.empty
      }
      .getOrElse(Set.empty)

    (queryParams ++ bodyParams).forall(key => !reservedParams.contains(key))
  }

  // attach the body to the Context
  def withBody(b: Option[JsValue]) = Context(propertyMap, method, headers, path, query, b)

  def metadata(user: Option[Identity]): Map[String, JsValue] = {
    Map(
      propertyMap.method -> method.value.toLowerCase.toJson,
      propertyMap.headers -> headers
        .collect {
          case h if h.name != `Timeout-Access`.name => h.lowercaseName -> h.value
        }
        .toMap
        .toJson,
      propertyMap.path -> path.toJson) ++
      user.map(u => propertyMap.namespace -> u.namespace.name.asString.toJson)
  }

  def toActionArgument(user: Option[Identity], boxQueryAndBody: Boolean): Map[String, JsValue] = {
    val queryParams = if (boxQueryAndBody) {
      Map(propertyMap.query -> JsString(query.toString))
    } else {
      queryAsMap.map(kv => kv._1 -> JsString(kv._2))
    }

    // if the body is a json object, merge with query parameters
    // otherwise, this is an opaque body that will be nested under
    // __ow_body in the parameters sent to the action as an argument
    val bodyParams: Map[String, JsValue] = body match {
      case Some(JsObject(fields)) if !boxQueryAndBody => fields
      case Some(v)                                    => Map(propertyMap.body -> v)
      case None if !boxQueryAndBody                   => Map.empty
      case _                                          => Map(propertyMap.body -> JsString.empty)
    }

    // precedence order is: query params -> body (last wins)
    metadata(user) ++ queryParams ++ bodyParams
  }
}

protected[core] object WhiskWebActionsApi extends Directives {

  private val mediaTranscoders = {
    // extensions are expected to contain only [a-z]
    Seq(
      MediaExtension(".http", resultAsHttp _),
      MediaExtension(".json", resultAsJson _),
      MediaExtension(".html", resultAsHtml _),
      MediaExtension(".svg", resultAsSvg _),
      MediaExtension(".text", resultAsText _))
  }

  private val defaultMediaTranscoder: MediaExtension = mediaTranscoders.find(_.extension == ".http").get

  val allowedExtensions: Set[String] = mediaTranscoders.map(_.extension).toSet

  /**
   * Splits string into a base name plus optional extension.
   * If name ends with ".xxxx" which matches a known extension, accept it as the extension.
   * Otherwise, the extension is ".http" by definition unless enforcing the presence of an extension.
   */
  def mediaTranscoderForName(name: String, enforceExtension: Boolean): (String, Option[MediaExtension]) = {
    mediaTranscoders
      .find(mt => name.endsWith(mt.extension))
      .map { mt =>
        val base = name.dropRight(mt.extensionLength)
        (base, Some(mt))
      }
      .getOrElse {
        (name, if (enforceExtension) None else Some(defaultMediaTranscoder))
      }
  }

  /**
   * Supported extensions, their default projection and transcoder to complete a request.
   *
   * @param extension  the supported media types for action response
   * @param transcoder the HTTP decoder and terminator for the extension
   */
  protected case class MediaExtension(extension: String,
                                      transcoder: (JsValue, TransactionId, WebApiDirectives) => Route) {
    val extensionLength = extension.length
  }

  private def resultAsHtml(result: JsValue, transid: TransactionId, rp: WebApiDirectives) = {
    val htmlResult = result match {
      case JsObject(fields) => fields.get("body").orElse(fields.get("html")).getOrElse(JsNull)
      case _                => result
    }

    htmlResult match {
      case JsString(html) => complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, html))
      case _              => terminate(BadRequest, Messages.invalidMedia(`text/html`))(transid, jsonPrettyPrinter)
    }
  }

  private def resultAsSvg(result: JsValue, transid: TransactionId, rp: WebApiDirectives) = {
    val svgResult = result match {
      case JsObject(fields) => fields.get("body").orElse(fields.get("svg")).getOrElse(JsNull)
      case _                => result
    }

    svgResult match {
      case JsString(svg) => complete(HttpEntity(`image/svg+xml`, svg.getBytes))
      case _             => terminate(BadRequest, Messages.invalidMedia(`image/svg+xml`))(transid, jsonPrettyPrinter)
    }
  }

  private def resultAsText(result: JsValue, transid: TransactionId, rp: WebApiDirectives) = {
    val txtResult = result match {
      case JsObject(fields) => fields.get("body").orElse(fields.get("text"))
      case _                => Some(result)
    }

    txtResult match {
      case Some(r: JsObject)  => complete(OK, r.prettyPrint)
      case Some(r: JsArray)   => complete(OK, r.prettyPrint)
      case Some(JsString(s))  => complete(OK, s)
      case Some(JsBoolean(b)) => complete(OK, b.toString)
      case Some(JsNumber(n))  => complete(OK, n.toString)
      case Some(JsNull)       => complete(OK, JsNull.toString)
      case _                  => terminate(NotFound, Messages.propertyNotFound)(transid, jsonPrettyPrinter)
    }
  }

  private def resultAsJson(result: JsValue, transid: TransactionId, rp: WebApiDirectives) = {
    result match {
      case r: JsObject => complete(OK, r)
      case r: JsArray  => complete(OK, r)
      case _           => terminate(BadRequest, Messages.invalidMedia(`application/json`))(transid, jsonPrettyPrinter)
    }
  }

  private def resultAsHttp(result: JsValue, transid: TransactionId, rp: WebApiDirectives) = {
    Try {
      val JsObject(fields) = result
      val headers = fields.get("headers").map {
        case JsObject(hs) =>
          hs.flatMap {
            case (k, v) => headersFromJson(k, v)
          }.toList

        case _ => throw new Throwable("Invalid header")
      } getOrElse List.empty

      val body = fields.get("body")

      val code = fields.get(rp.statusCode).map {
        case JsNumber(c) =>
          // the following throws an exception if the code is not a whole number or a valid code
          StatusCode.int2StatusCode(c.toIntExact)
        case JsString(c) =>
          // parse the string to an Int (not a BigInt) matching JsNumber case match above
          // c.toInt could throw an exception if the string isn't an integer
          StatusCode.int2StatusCode(c.toInt)

        case _ => throw new Throwable("Illegal status code")
      }

      body.collect {
        case JsString(str) if str.nonEmpty   => interpretHttpResponse(code.getOrElse(OK), headers, str, transid)
        case JsString(str) /* str.isEmpty */ => respondWithEmptyEntity(code.getOrElse(NoContent), headers)
        case js if js != JsNull              => interpretHttpResponseAsJson(code.getOrElse(OK), headers, js, transid)
      } getOrElse respondWithEmptyEntity(code.getOrElse(NoContent), headers)

    } getOrElse {
      // either the result was not a JsObject or there was an exception validating the
      // response as an http result
      terminate(BadRequest, Messages.invalidMedia(`message/http`))(transid, jsonPrettyPrinter)
    }
  }

  private def respondWithEmptyEntity(code: StatusCode, headers: List[RawHeader]) = {
    respondWithHeaders(removeContentTypeHeader(headers)) {
      // note that if header defined a content-type, it will be ignored
      // since the type must be compatible with the data response
      complete(HttpResponse(code, entity = HttpEntity.Empty))
    }
  }

  private def headersFromJson(k: String, v: JsValue): Seq[RawHeader] = v match {
    case JsString(v)  => Seq(RawHeader(k, v))
    case JsBoolean(v) => Seq(RawHeader(k, v.toString))
    case JsNumber(v)  => Seq(RawHeader(k, v.toString))
    case JsArray(v)   => v.flatMap(inner => headersFromJson(k, inner))
    case _            => throw new Throwable("Invalid header")
  }

  /**
   * Finds the content-type in the header list and ensures that it is a valid format. If it is not
   * valid, construct a failure with appropriate message.
   * If the content-type header is missing, then return the supplied defaultType
   */
  private def findContentTypeInHeader(headers: List[RawHeader],
                                      transid: TransactionId,
                                      defaultType: MediaType): Try[MediaType] = {
    headers.find(_.lowercaseName == `Content-Type`.lowercaseName) match {
      case Some(header) =>
        MediaType.parse(header.value) match {
          case Right(mediaType: MediaType) => Success(mediaType)
          case _                           => Failure(RejectRequest(BadRequest, Messages.httpUnknownContentType)(transid))
        }
      case None => Success(defaultType)
    }
  }

  def isJsonFamily(mt: MediaType): Boolean = {
    mt == `application/json` || mt.value.endsWith("+json")
  }

  private def interpretHttpResponseAsJson(code: StatusCode,
                                          headers: List[RawHeader],
                                          js: JsValue,
                                          transid: TransactionId) = {
    findContentTypeInHeader(headers, transid, `application/json`) match {
      // use the default akka-http response marshaler for standard application/json
      case Success(mediaType) if mediaType == `application/json` =>
        respondWithHeaders(removeContentTypeHeader(headers)) {
          complete(code, js)
        }

      // for all other json-family content-type, explicitly marshal the response;
      // the order of the case statement matters; isJsonFamily returns true for application/json
      case Success(mediaType) if isJsonFamily(mediaType) =>
        respondWithHeaders(removeContentTypeHeader(headers)) {
          complete(
            code,
            HttpEntity(
              ContentType(
                MediaType.customWithFixedCharset(mediaType.mainType, mediaType.subType, HttpCharsets.`UTF-8`)),
              js.prettyPrint))
        }

      case _ =>
        terminate(BadRequest, Messages.httpContentTypeError)(transid, jsonPrettyPrinter)
    }
  }

  private def interpretHttpResponse(code: StatusCode, headers: List[RawHeader], str: String, transid: TransactionId) = {
    findContentTypeInHeader(headers, transid, `text/html`).flatMap { mediaType =>
      val ct = ContentType(mediaType, () => HttpCharsets.`UTF-8`)
      ct match {
        // TODO: remove this extract check for base64 on json response
        // this is here for legacy reasons to not brake old webactions returning base64 json that have not migrated yet
        case nonbinary: ContentType.NonBinary if (isJsonFamily(mediaType) && Exec.isBinaryCode(str)) =>
          Try(Base64.getDecoder().decode(str)).map(HttpEntity(ct, _))
        case nonbinary: ContentType.NonBinary => Success(HttpEntity(nonbinary, str))

        // because of the default charset provided to the content type constructor
        // the remaining content types to match against are binary at this point
        case _ /* ContentType.Binary */ => Try(Base64.getDecoder().decode(str)).map(HttpEntity(ct, _))
      }
    } match {
      case Success(entity) =>
        respondWithHeaders(removeContentTypeHeader(headers)) {
          complete(code, entity)
        }

      case Failure(RejectRequest(code, message)) =>
        terminate(code, message)(transid, jsonPrettyPrinter)

      case _ =>
        terminate(BadRequest, Messages.httpContentTypeError)(transid, jsonPrettyPrinter)
    }
  }

  private def removeContentTypeHeader(headers: List[RawHeader]) =
    headers.filter(_.lowercaseName != `Content-Type`.lowercaseName)
}

trait WhiskWebActionsApi
    extends Directives
    with ValidateRequestSize
    with PostActionActivation
    with CustomHeaders
    with CorsSettings.WebActions {
  services: WhiskServices =>

  /** API path invocation path for posting activations directly through the host. */
  protected val webInvokePathSegments: Seq[String]

  /** Mapping of HTTP request fields to action parameter names. */
  protected val webApiDirectives: WebApiDirectives

  /** Store for identities. */
  protected val authStore: AuthStore

  /** Configured authentication provider. */
  protected val authenticationProvider = SpiLoader.get[AuthenticationDirectiveProvider]

  /** The collection type for this trait. */
  protected val collection = Collection(Collection.ACTIONS)

  /** The prefix for web invokes e.g., /web. */
  private lazy val webRoutePrefix = {
    pathPrefix(webInvokePathSegments.map(_segmentStringToPathMatcher(_)).reduceLeft(_ / _))
  }

  /** Allowed verbs. */
  private lazy val allowedOperations = get | delete | post | put | head | options | patch

  private lazy val validNameSegment = pathPrefix(EntityName.REGEX.r)
  private lazy val packagePrefix = pathPrefix("default".r | EntityName.REGEX.r)

  private val defaultCorsBaseResponse =
    List(allowOrigin, allowMethods)

  private val defaultCorsWithAllowHeader = {
    defaultCorsBaseResponse :+ allowHeaders
  }

  private def defaultCorsResponse(headers: Seq[HttpHeader]): List[HttpHeader] = {
    headers.find(_.name == `Access-Control-Request-Headers`.name).map { h =>
      defaultCorsBaseResponse :+ `Access-Control-Allow-Headers`(h.value)
    } getOrElse defaultCorsWithAllowHeader
  }

  private def contentTypeFromEntity(entity: HttpEntity) = entity.contentType match {
    case ct if ct == ContentTypes.NoContentType => None
    case ct                                     => Some(RawHeader(`Content-Type`.lowercaseName, ct.toString))
  }

  /** Extracts the HTTP method, headers, query params and unmatched (remaining) path. */
  private val requestMethodParamsAndPath = {
    extract { ctx =>
      val method = ctx.request.method
      val query = ctx.request.uri.query()
      val path = ctx.unmatchedPath.toString
      val headers = ctx.request.headers ++ contentTypeFromEntity(ctx.request.entity)
      Context(webApiDirectives, method, headers, path, query)
    }
  }

  def routes(user: Identity)(implicit transid: TransactionId): Route = routes(Some(user))

  def routes()(implicit transid: TransactionId): Route = routes(None)

  private val maxWaitForWebActionResult = Some(controllerActivationConfig.maxWaitForBlockingActivation)

  /**
   * Adds route to web based activations. Actions invoked this way are anonymous in that the
   * caller is not authenticated. The intended action must be named in the path as a fully qualified
   * name as in /web/some-namespace/some-package/some-action. The package is optional
   * in that the action may be in the default package, in which case, the string "default" must be used.
   * If the action doesn't exist (or the namespace is not valid) NotFound is generated. Following the
   * action name, an "extension" is required to specify the desired content type for the response. This
   * extension is one of supported media types. An example is ".json" for a JSON response or ".html" for
   * an text/html response.
   *
   * Optionally, the result form the action may be projected based on a named property. As in
   * /web/some-namespace/some-package/some-action/some-property. If the property
   * does not exist in the result then a NotFound error is generated. A path of properties may
   * be supplied to project nested properties.
   *
   * Actions may be exposed to this web proxy by adding an annotation ("export" -> true).
   */
  def routes(user: Option[Identity])(implicit transid: TransactionId): Route = {
    (allowedOperations & webRoutePrefix) {
      validNameSegment { namespace =>
        packagePrefix { pkg =>
          validNameSegment { seg =>
            handleMatch(namespace, pkg, seg, user)
          }
        }
      }
    }
  }

  /**
   * Gets identity from datastore.
   * This method is factored out to allow mock testing.
   */
  protected def getIdentity(namespace: EntityName)(implicit transid: TransactionId): Future[Identity] = {
    // ask auth provider to create an identity for the given namespace
    authenticationProvider.identityByNamespace(namespace)(transid, actorSystem, authStore)
  }

  private def handleMatch(namespaceSegment: String,
                          pkgSegment: String,
                          actionNameWithExtension: String,
                          onBehalfOf: Option[Identity])(implicit transid: TransactionId) = {

    def fullyQualifiedActionName(actionName: String) = {
      val namespace = EntityName(namespaceSegment)
      val pkgName = if (pkgSegment == "default") None else Some(EntityName(pkgSegment))
      namespace.addPath(pkgName).addPath(EntityName(actionName)).toFullyQualifiedEntityName
    }

    provide(WhiskWebActionsApi.mediaTranscoderForName(actionNameWithExtension, webApiDirectives.enforceExtension)) {
      case (actionName, Some(extension)) =>
        // extract request context, checks for overrides of reserved properties, and constructs action arguments
        // as the context body which may be the incoming request when the content type is JSON or formdata, or
        // the raw body as __ow_body (and query parameters as __ow_query) otherwise
        extract(_.request.entity) { e =>
          validateSize(isWhithinRange(e.contentLengthOption.getOrElse(0)))(transid, jsonPrettyPrinter) {
            requestMethodParamsAndPath { context =>
              provide(fullyQualifiedActionName(actionName)) { fullActionName =>
                onComplete(verifyWebAction(fullActionName, onBehalfOf.isDefined)) {
                  case Success((actionOwnerIdentity, action)) =>
                    val requiredAuthOk =
                      requiredWhiskAuthSuccessful(action.annotations, context.headers).getOrElse(true)
                    if (!requiredAuthOk) {
                      logging.debug(
                        this,
                        "web action with require-whisk-auth was invoked without a matching x-require-whisk-auth header value")
                      terminate(Unauthorized)
                    } else if (!action.annotations
                                 .getAs[Boolean](Annotations.WebCustomOptionsAnnotationName)
                                 .getOrElse(false)) {
                      respondWithHeaders(defaultCorsResponse(context.headers)) {
                        if (context.method == OPTIONS) {
                          complete(OK, HttpEntity.Empty)
                        } else {
                          extractEntityAndProcessRequest(actionOwnerIdentity, action, extension, onBehalfOf, context, e)
                        }
                      }
                    } else {
                      extractEntityAndProcessRequest(actionOwnerIdentity, action, extension, onBehalfOf, context, e)
                    }

                  case Failure(t: RejectRequest) =>
                    terminate(t.code, t.message)

                  case Failure(t) =>
                    logging.error(this, s"exception in handleMatch: $t")
                    terminate(InternalServerError)
                }
              }
            }
          }
        }

      case (_, None) =>
        terminate(NotAcceptable, Messages.contentTypeExtensionNotSupported(WhiskWebActionsApi.allowedExtensions))
    }
  }

  /**
   * Checks that subject has right to post an activation and fetch the action
   * followed by the package and merge parameters. The action is fetched first since
   * it will not succeed for references relative to a binding, and the export bit is
   * confirmed before fetching the package and merging parameters.
   *
   * @return Future that completes with the action and action-owner-identity on success otherwise
   *         a failed future with a request rejection error which may be one of the following:
   *         not entitled (throttled), package/action not found, action not web enabled,
   *         or request overrides final parameters
   */
  private def verifyWebAction(actionName: FullyQualifiedEntityName, authenticated: Boolean)(
    implicit transid: TransactionId) = {

    // lookup the identity for the action namespace
    identityLookup(actionName.path.root) flatMap { actionOwnerIdentity =>
      confirmExportedAction(actionLookup(actionName), authenticated) flatMap { a =>
        checkEntitlement(actionOwnerIdentity, a) map { _ =>
          (actionOwnerIdentity, a)
        }
      }
    }
  }

  private def extractEntityAndProcessRequest(actionOwnerIdentity: Identity,
                                             action: WhiskActionMetaData,
                                             extension: MediaExtension,
                                             onBehalfOf: Option[Identity],
                                             context: Context,
                                             httpEntity: HttpEntity)(implicit transid: TransactionId) = {

    def process(body: Option[JsValue], isRawHttpAction: Boolean) = {
      processRequest(actionOwnerIdentity, action, extension, onBehalfOf, context.withBody(body), isRawHttpAction)
    }

    provide(action.annotations.getAs[Boolean](Annotations.RawHttpAnnotationName).getOrElse(false)) { isRawHttpAction =>
      httpEntity match {
        case Empty =>
          process(None, isRawHttpAction)

        case HttpEntity.Strict(ct, json) if WhiskWebActionsApi.isJsonFamily(ct.mediaType) && !isRawHttpAction =>
          if (json.nonEmpty) {
            entity(as[JsValue]) { body =>
              process(Some(body), isRawHttpAction)
            }
          } else {
            process(None, isRawHttpAction)
          }

        case HttpEntity.Strict(ContentType(MediaTypes.`application/x-www-form-urlencoded`, _), _) if !isRawHttpAction =>
          entity(as[FormData]) { form =>
            val body = form.fields.toMap.toJson.asJsObject
            process(Some(body), isRawHttpAction)
          }

        case HttpEntity.Strict(contentType, data) =>
          // for legacy, we are encoding application/json still
          if (contentType.mediaType.binary || contentType.mediaType == `application/json`) {
            Try(JsString(Base64.getEncoder.encodeToString(data.toArray))) match {
              case Success(bytes) => process(Some(bytes), isRawHttpAction)
              case Failure(t)     => terminate(BadRequest, Messages.unsupportedContentType(contentType.mediaType))
            }
          } else {
            val str = JsString(data.utf8String)
            process(Some(str), isRawHttpAction)
          }

        case _ => terminate(BadRequest, Messages.unsupportedContentType)
      }
    }
  }

  private def processRequest(actionOwnerIdentity: Identity,
                             action: WhiskActionMetaData,
                             responseType: MediaExtension,
                             onBehalfOf: Option[Identity],
                             context: Context,
                             isRawHttpAction: Boolean)(implicit transid: TransactionId) = {

    def queuedActivation = {
      // checks (1) if any of the query or body parameters override final action parameters
      // computes overrides if any relative to the reserved __ow_* properties, and (2) if
      // action is a raw http handler
      //
      // NOTE: it is assumed the action parameters do not intersect with the reserved properties
      // since these are system properties, the action should not define them, and if it does,
      // they will be overwritten
      if (isRawHttpAction || context
            .overrides(webApiDirectives.reservedProperties ++ action.immutableParameters)) {
        val content = context.toActionArgument(onBehalfOf, isRawHttpAction)
        invokeAction(actionOwnerIdentity, action, Some(JsObject(content)), maxWaitForWebActionResult, cause = None)
      } else {
        Future.failed(RejectRequest(BadRequest, Messages.parametersNotAllowed))
      }
    }

    completeRequest(queuedActivation, responseType)
  }

  private def completeRequest(queuedActivation: Future[Either[ActivationId, WhiskActivation]],
                              responseType: MediaExtension)(implicit transid: TransactionId) = {
    onComplete(queuedActivation) {
      case Success(Right(activation)) =>
        respondWithActivationIdHeader(activation.activationId) {
          val result = activation.resultAsJson

          if (activation.response.isSuccess || activation.response.isApplicationError) {
            val resultPath = if (activation.response.isSuccess) {
              List.empty
            } else {
              // the activation produced an error response: therefore ignore
              // the requested projection and unwrap the error instead
              // and attempt to handle it per the desired response type (extension)
              List(ActivationResponse.ERROR_FIELD)
            }

            val result = getFieldPath(activation.resultAsJson, resultPath)
            result match {
              case Some(projection) =>
                val marshaler = Future(responseType.transcoder(projection, transid, webApiDirectives))
                onComplete(marshaler) {
                  case Success(done) => done // all transcoders terminate the connection
                  case Failure(t)    => terminate(InternalServerError)
                }
              case _ => terminate(NotFound, Messages.propertyNotFound)
            }
          } else {
            terminate(BadRequest, Messages.errorProcessingRequest)
          }
        }

      case Success(Left(activationId)) =>
        // blocking invoke which got queued instead
        // this should not happen, instead it should be a blocking invoke timeout
        logging.debug(this, "activation waiting period expired")
        respondWithActivationIdHeader(activationId) {
          terminate(Accepted, Messages.responseNotReady)
        }

      case Failure(t: RejectRequest) => terminate(t.code, t.message)

      case Failure(t: LoadBalancerException) =>
        logging.error(this, s"failed in loadbalancer: $t")
        terminate(ServiceUnavailable)

      case Failure(t) =>
        logging.error(this, s"exception in completeRequest: $t")
        terminate(InternalServerError)
    }
  }

  /**
   * Gets the action if it exists and fail future with RejectRequest if it does not.
   *
   * @return future action document or NotFound rejection
   */
  private def actionLookup(actionName: FullyQualifiedEntityName)(
    implicit transid: TransactionId): Future[WhiskActionMetaData] = {
    WhiskActionMetaData.resolveActionAndMergeParameters(entityStore, actionName) recoverWith {
      case _: ArtifactStoreException | DeserializationException(_, _, _) =>
        Future.failed(RejectRequest(NotFound))
    }
  }

  /**
   * Gets the identity for the namespace.
   */
  private def identityLookup(namespace: EntityName)(implicit transid: TransactionId): Future[Identity] = {
    getIdentity(namespace) recoverWith {
      case _: ArtifactStoreException | DeserializationException(_, _, _) =>
        Future.failed(RejectRequest(NotFound))
      case t =>
        // leak nothing no matter what, failure is already logged so skip here
        Future.failed(RejectRequest(NotFound))
    }
  }

  /**
   * Checks if an action is exported (i.e., carries the required annotation).
   */
  private def confirmExportedAction(actionLookup: Future[WhiskActionMetaData], authenticated: Boolean)(
    implicit transid: TransactionId): Future[WhiskActionMetaData] = {
    actionLookup flatMap { action =>
      val requiresAuthenticatedUser =
        action.annotations.getAs[Boolean](Annotations.RequireWhiskAuthAnnotation).getOrElse(false)
      val isExported = action.annotations.getAs[Boolean](Annotations.WebActionAnnotationName).getOrElse(false)

      if ((isExported && requiresAuthenticatedUser && authenticated) ||
          (isExported && !requiresAuthenticatedUser)) {
        logging.debug(this, s"${action.fullyQualifiedName(true)} is exported")
        Future.successful(action)
      } else if (!isExported) {
        logging.debug(this, s"${action.fullyQualifiedName(true)} not exported")
        Future.failed(RejectRequest(NotFound))
      } else {
        logging.debug(this, s"${action.fullyQualifiedName(true)} requires authentication")
        Future.failed(RejectRequest(Unauthorized))
      }
    }
  }

  /**
   * Checks if an action is executable.
   */
  private def checkEntitlement(identity: Identity, action: WhiskActionMetaData)(
    implicit transid: TransactionId): Future[Unit] = {

    val fqn = action.fullyQualifiedName(false)
    val resource = Resource(fqn.path, collection, Some(fqn.name.asString))
    entitlementProvider.check(identity, Privilege.ACTIVATE, resource)
  }

  /**
   * Check if "require-whisk-auth" authentication is needed, and if so, authenticate the request
   * NOTE: Only number or string JSON "require-whisk-auth" annotation values are supported
   *
   * @param annotations - web action annotations
   * @param reqHeaders  - web action invocation request headers
   * @return Option[Boolean]
   *         None if annotations does not include require-whisk-auth (i.e. auth test not needed)
   *         Some(true) if annotations includes require-whisk-auth and it's value matches the request header `X-Require-Whisk-Auth` value
   *         Some(false) if annotations includes require-whisk-auth and the request does not include the header `X-Require-Whisk-Auth`
   *         Some(false) if annotations includes require-whisk-auth and it's value deos not match the request header `X-Require-Whisk-Auth` value
   */
  private def requiredWhiskAuthSuccessful(annotations: Parameters, reqHeaders: Seq[HttpHeader]): Option[Boolean] = {
    annotations
      .get(Annotations.RequireWhiskAuthAnnotation)
      .flatMap {
        case JsString(authStr) => Some(authStr)
        case JsNumber(authNum) => Some(authNum.toString)
        case _                 => None
      }
      .map { reqWhiskAuthAnnotationStr =>
        reqHeaders
          .find(_.is(WhiskAction.requireWhiskAuthHeader))
          .map(_.value == reqWhiskAuthAnnotationStr)
          .getOrElse(false) // false => when no x-require-whisk-auth header is present
      }
  }
}


text:
const http = require("http");

const options = {
  "method": "POST",
  "hostname": "mockbin.com",
  "port": null,
  "path": "/har",
  "headers": {
    "content-type": "text/plain"
  }
};

const req = http.request(options, function (res) {
  const chunks = [];

  res.on("data", function (chunk) {
    chunks.push(chunk);
  });

  res.on("end", function () {
    const body = Buffer.concat(chunks);
    console.log(body.toString());
  });
});

req.write("Hello World");
req.end();


text:
\documentclass{article}
\usepackage{graphicx}
\usepackage[utf8]{inputenc}
\usepackage[linesnumbered]{algorithm2e}
\usepackage[margin=.75in]{geometry}
\newenvironment{algorithmic}{%
\renewenvironment{algocf}[1][h]{}{}% pass over the floating stuff
\algorithm
}{%
\endalgorithm
}
\begin{document}
%
\title{Assignment 2 \\ Advanced Algorithms \& Data Structures PS}%
\author{Christian Müller 1123410 \\ Daniel Kocher, 0926293}%
\maketitle%
\clearpage%
%
{\noindent\bfseries Aufgabe 4}%

\medskip%

{\noindent\LARGE VORSCHLAG KOCHER}%

\medskip%
\noindent
F{\"u}r den Divide-\&-Conquer Algorithmus zur Berechnung von Segmentschnittpunkten
werden zuerst zwei Datenstrukturen definiert, welche verwendet werden um die
Elemente der Liste $S$ darzustellen.

\paragraph{Endpunkt}
Stellt einen Endpunkt eines horizontalen Segments dar.
Jeder Endpunkt besitzt mindestens drei Felder:
\begin{itemize}
  \item[-] $x$ \ldots repr{\"a}sentiert die x-Koordinate des Endpunktes.
  \item[-] $y$ \ldots repr{\"a}sentiert die y-Koordinate des Endpunktes.
  \item[-] $ass$ \ldots Pointer zum zugeh{\"o}rigen Partner-Endpunkt.
\end{itemize}

\emph{Beispiel}: Das horizontale Segment mit den Endpunkten $(1, 2)$ und $(4, 2)$ wird
durch zwei {\bfseries Endpunkte} $e_{1, 2}$ repr{\"a}sentiert. Die Felder von
$e_{1, 2}$ sind wie folgt belegt:

\begin{center}
\begin{tabular}{l||l|l|l|}
  \hline
  $e_1$ & $.x = 1$ & $.y = 2$ & $.ass = e_2$ \tabularnewline
  \hline
  $e_2$ & $.x = 4$ & $.y = 2$ & $.ass = e_1$ \tabularnewline
  \hline
\end{tabular}
\end{center}

\paragraph{VertSegment}
Stellt ein vertikales Segment dar. Jedes vertikale Segment besitzt mindestens
drei Felder:
\begin{itemize}
  \item[-] $x$ \ldots repr{\"a}sentiert die x-Koordinate des vertikalen Segments.
  \item[-] $y_{unten}$ \ldots repr{\"a}sentiert die untere y-Koordinate des
    vertikalen Segments.
  \item[-] $y_{oben}$ \ldots repr{\"a}sentiert die obere y-Koordinate des
    vertikalen Segments.
\end{itemize}

\emph{Beispiel}: Das vertikale Segment mit den Endpunkten $(1, 6)$ und $(1, 1)$
wird durch ein {\bfseries VertSegment} $v$ repr{\"a}sentiert. Die Felder von $v$
sind wie folgt belegt:

\begin{center}
\begin{tabular}{l||l|l|l|}
  \hline
  $v$ & $.x = 1$ & $.y_{unten} = 1$ & $.y_{oben} = 6$ \tabularnewline
  \hline
\end{tabular}
\end{center}

%
Desweiteren werden f{\"u}r jede Liste $S_i$ jeweils drei Listen $L(S_i)$, $R(S_i)$
und $V(S_i)$ global verwaltet. Dies k{\"o}nnten auch lokale Listen sein,
allerdings geht nachfolgender Algorithmus von global verwalteten Listen aus.

$L(S_i)$ enth{\"a}lt die y-Koordinaten aller linken Endpunkte in $S_i$, deren
rechter Partner ($ass$) nicht in $S_i$ enthalten ist. Analog beinhaltet $R(S_i)$
die y-Koordinaten aller rechten Endpunkte in $S_i$, deren linker Partner ($ass$)
nicht in $S_i$ liegt. $V(S_i$) hingegen enth{\"a}lt die y-Intervalle ($y_{unten}$
bis $y_{oben}$) der vertikalen Segmente in $S_i$.

$L(S_i)$ und $R(S_i)$ sind nach steigenden y-Koordinaten sortierte, einfach
verkettete Listen. $V(S_i)$ sind nach steigenden unteren Endpunkten ($y_{unten}$)
sortierte, einfach verkettete Listen.

Seien $l$, $l_i$ einfach verkettete Listen und $d$ ein Wert gespeichert in einer
einfach verketteten Liste. Solche Listen haben mindestens folgende Felder:
\begin{itemize}
  \item[-] $head$ \ldots Erster Knoten einer Liste.
\end{itemize}

\noindent
Weiters stellen sie folgende Funktionen zur Verf{\"u}gung:
\begin{itemize}
  \item[-] $l_1$.insertAll($l_2$) \ldots F{\"u}gt alle Element von Liste $l_2$ zu
    Liste $l_1$ hinzu.
  %\item[-] $l$.getHead() \ldots Gibt den ersten Knoten der Liste $l$ zur{\"u}ck.
  \item[-] $l$.search($d$) \ldots Durchsucht die Liste $l$ nach einem Element $d$
    und gibt dessen Knoten zur{\"u}ck (falls gefunden).
  \item[-] $l$.insert($d$) \ldots F{\"u}gt das Element $d$ zu Liste $l$ hinzu.
  \item[-] $l$.delete($d$) \ldots Entfernt das Element $d$ aus Liste $l$.
\end{itemize}
%
Knoten einer solchen Liste stellen mindestens die folgenden Felder bereit:
\begin{itemize}
  \item[-] $next$ \ldots N{\"a}chster Knoten.
  %\item[-] $data$ \ldots Korrespondierender Datensatz.
\end{itemize}
%
\begin{algorithm}
\begin{algorithmic}[1]
  \SetKwProg{Fn}{Function}{}{}%
  \SetKwInOut{Input}{Input}%
  \SetKwInOut{Output}{Output}%
%
  \Input{
    Liste $S$ bestehend aus vertikalen Segmenten ({\bfseries VertSegment}) und
    Endpunkten ({\bfseries Endpunkt}) von horizontalen Segmenten. \newline%
    $S$ sei nach horizontalen Koordinaten sortiert (Algorithmus ist leicht zu
    adaptieren falls nicht).
  }%
  \Output{
    Alle Schnittpunkte von vertikalen Segmenten mit horizontalen Segmenten
  }%
  \Fn{ReportCuts($S$)}{%
    \lIf{$|S| \leq 0$}{\Return}%
    \If{$|S| = 1$}{
      \tcp{Initialisierung von $L(S)$, $R(S)$ und $V(S)$}
      Sei $s$ das einzige Element in $S$\;
      \BlankLine%
      \lIf{$s$ ist linker Endpunkt}{$L(S) \leftarrow \{s\}$, $R(S) \leftarrow \emptyset$, $V(S) \leftarrow \emptyset$}%
      \BlankLine%
      \lElseIf{$s$ ist rechter Endpunkt}{$L(S) \leftarrow \emptyset$, $R(S) \leftarrow \{s\}$, $V(S) \leftarrow \emptyset$}%
      \BlankLine%
      \lElseIf{$s$ ist vertikales Segment}{$L(S) \leftarrow \emptyset$, $R(S) \leftarrow \emptyset$, $V(S) \leftarrow \{s\}$}%
      \BlankLine%
      \Return \tcp*{Rekursionsende}%
    }%
    \BlankLine%
    \lIf{$S$ ist nicht bez{\"u}glich x-Koordinaten sortiert}{Sortiere $S$ bez{\"u}glich x-Koordinaten}%
    \BlankLine%
    \tcc{
      Divide Schritt. \newline
      $m$ sei ein Integer (repr{\"a}sentiert die Mitte der Liste $S$). \newline
      $S_1$ und $S_2$ seien Listen von vertikalen Segmenten und Endpunkten von
      horizontalen Segmenten, sortiert bezüglich ihrer x-Koordinaten.
    }%
    \lIf{$|S|$ ist gerade}{$m \leftarrow |S| / 2$}%
    \lElse{$m \leftarrow \lceil |S| / 2 \rceil$}%
    $S_1 \leftarrow $ Liste der ersten $m$ Elemente aus $S$\;
    $S_2 \leftarrow $ Liste der letzten $\left( |S| - m \right)$ Elemente aus $S$\;
    \BlankLine%
    \tcp{Conquer Schritt}%
    ReportCuts($S_1$)\;%
    ReportCuts($S_2$)\;%
    \BlankLine%
    \tcc{
      $L(S_i)$, $R(S_i)$, $V(S_i)$ f{\"u}r $i = 1, 2$ bekannt $\Rightarrow$ Merge
      Schritt \newline%
      Berichte Segmentschnittpunkte (Paare $(h, v)$)%
    }%
    $h_1 \leftarrow R(S_2)$\;
    DeletePartnersOf($h_1$, $L(S_1)$) \tcp*{$h_1$ wird f{\"u}r Aktualisierung von $R(S)$ wiederverwendet (*1)}
    $v_1 \leftarrow V(S_1)$\;
    IntersectAndReport($h_1$, $v_1$)\;
    \BlankLine%
    $h_2 \leftarrow L(S_1)$\;
    DeletePartnersOf($h_2$, $R(S_2)$) \tcp*{$h_2$ wird f{\"u}r Aktualisierung von $L(S)$ wiederverwendet (*2)}
    $v_2 \leftarrow V(S_2)$\;
    IntersectAndReport($h_2$, $v_2$)\;

    \BlankLine%
    \tcp{Aktualisiere $L(S)$, $R(S)$ und $V(S)$ f{\"u}r $S = S_1 \cup S_2$}
    $L(S) \leftarrow h_2$ \tcp*{$h_2$ ist bereits $L(S_1) \setminus R(S_2)$, siehe (*2)}
    $L(S)$.InsertAll($L(S_2)$)\;
    \BlankLine%
    $R(S) \leftarrow h_1$ \tcp*{$h_1$ ist bereits $R(S_2) \setminus L(S_1)$, siehe (*1)}
    $R(S)$.InsertAll($R(S_1)$)\;
    \BlankLine%
    $V(S) \leftarrow V(S_1)$\;
    $V(S)$.InsertAll($V(S_2)$)\;
  }%
\end{algorithmic}
\end{algorithm}
%
\begin{algorithm}
\begin{algorithmic} [1]
  \SetKwProg{Fn}{Function}{}{}%                 % enter the algorithmic environment
  \SetKwInOut{Input}{Input}%
  \SetKwInOut{Output}{Output}%
%
  \Input{
    Zwei einfach verkettete Listen $l_1$ und $l_2$. \newline%
    $l_{1,2}$ beinhalten nur Endpunkte von horizontalen Segmenten.
  }%
  \Output{
    Eine Liste, welche alle Elemente aus $l_1$ beinhaltet, die keinen Partner in
    $l_2$ besitzen.
  }%

  \Fn{DeletePartnersOf($l_1$, $l_2$)}{
    \lIf{$l_2$ ist leer}{\Return $l_1$}

    $current \leftarrow l_2.head$\;
    \While{$current \neq null$}{
      \lIf{$l_1.search(current.ass)$ hat einen Partner gefunden}{
        $l_1.delete(current)$
      }
      $current \leftarrow current.next$\;
    }

    \Return $l_1$\;
  }
\end{algorithmic}
\end{algorithm}
%
\begin{algorithm}
\begin{algorithmic} [1]
  \SetKwProg{Fn}{Function}{}{}%                 % enter the algorithmic environment
  \SetKwInOut{Input}{Input}%
  \SetKwInOut{Output}{Output}%
%
  \Input{
    Zwei einfach verkettete Listen $h$ und $v$. \newline%
    $h$ enth{\"a}lt Endpunkte von horizontalen Segmenten. \newline%
    $v$ enth{\"a}lt vertikale Segmente. \newline%
    $h$ und $v$ sind aufsteigend gem{\"a}{\ss} $y$ bzw. $y_{unten}$ sortiert.%
  }%
  \Output{
    Berichtet alle Schnittpunkte zwischen Elementen aus $v$ und Elementen aus $h$.
  }%
  \Fn{IntersectAndReport($h$, $v$)}{
    \tcp{Keine Schnittpunkte m{\"o}glich}%
    \lIf{$h$ ist leer \textbf{oder} $v$ ist leer}{\Return}%
    \BlankLine%
    $currHor \leftarrow h$.head\;
    $currVert \leftarrow v$.head\;
    \While{$currHor \neq null$ und $currVert \neq null$}{
      \lIf{$currHor.y > currVert.y_{oben}$}{$currVert = currVert.next$}%
      \BlankLine%
      \eIf{$currHor.y \geq currVert.y_{unten}$}{
		    print($currVert.x$, $currHor.y$)\;
		    \BlankLine%
        $tmpHor \leftarrow currHor.next$\;
        \While{$tmpHor$ $\neq$ $null$ \textbf{und} $tmpHor.y < currVert.y_{oben}$}
        {
			    print($currVert.x$, $tmpHor.y$)\;
			    $tmpHor \leftarrow tmpHor.next$\;
		    }
		    $currVert \leftarrow currVer.next$\;
      }{
        \lIf{$currVert \neq null$}{$currHor \leftarrow currHor.next$}
      }
	  }
  }
\end{algorithmic}
\end{algorithm}

\end{document}


text:
define([
		'jquery',
		'backbone',
		'underscore',
		'chromecast',
		'../uiconfig',
		'text!templates/Playing.html'],
function($, Backbone, _, chromecastWeb, config, template) {
	var chromecast;
	if (window.cordova) {
		chromecast = ChromecastPlugin;
	} else {
		chromecast = chromecastWeb;
	}
	var View = Backbone.View.extend({
		events: {
			"click #playPause" : function() {
				if (this.state === "play") {
					this.state = "pause";
					$("#playPause .ui-btn-text").html("Play");
					$("#playPause").buttonMarkup({icon : "playIcon" });
					chromecast.pause();
				} else if (this.state === "pause") {
					this.state = "play";
					$("#playPause .ui-btn-text").html("Pause");
					$("#playPause").buttonMarkup({icon : "pauseIcon" });
					chromecast.play();
				} else {
					this.state = "play";
					$("#playPause .ui-btn-text").html("Pause");
					$("#playPause").buttonMarkup({icon : "pauseIcon" });
					var url = this.playing.get("url");
					if (window.cordova) {
						url = config.baseUrl+"/"+url;
					} else {
						url = "http://"+window.location.host+"/"+url;
					}
					chromecast.cast(url);
				}
			},
			"click #stop" : function() {
				this.state = "stopped";
				$("#playPause .ui-btn-text").html("Play");
				$("#playPause").buttonMarkup({icon : "playIcon" });
				chromecast.stopCast();
				$("#currentpos").text("0 mins : 00 secs of [0 mins : 00 secs]");
				$("#position").val(0);
			},
			"change #position" : function() {
				var position = $("#position").val();
				if (position != this.currentPosition) {
					this.currentPosition = position;
					console.log("position set to "+position);
					chromecast.play(position);
				}
			}
		},
		initialize: function(options) {
			this.state = "stopped";
			this.currentPosition = 0;
			this.playing = options.playing;
			this.template = _.template( template, { playing: this.playing.toJSON() } );
			chromecast.addStatusListener(this.statusListener);
		},
		render: function() {
			$(this.el).html( this.template );
			chromecast.addReceiverListener(function() {
				setTimeout(function() {
					$("#statusMessage").text("Receiver available");
					$("#playPause").removeClass( "ui-disabled" );
					$("#stop").removeClass( "ui-disabled" );
				}, 1000);
			}.bind(this));
		},
		statusListener: function(status) {
			var duration = Math.floor(status.duration);
			var durmins = Math.floor(duration / 60);
			var dursecs = duration - durmins * 60;
			dursecs = (dursecs < 10 ? '0' : '') + dursecs;

			var position = Math.floor(status.position);
			var minutes = Math.floor(position / 60);
			var seconds = position - minutes * 60;
			seconds = (seconds < 10 ? '0' : '') + seconds;
			$("#currentpos").text(minutes+" mins : "+seconds + " secs of ["+durmins+" mins : "+dursecs+" secs]");
			var currentDuration = $("#position").attr("max");

			if (duration > 0 && parseInt(currentDuration) !== duration) {
				console.log("position: "+position+" currentDuration:"+currentDuration+ " "+minutes+" mins : "+seconds + " secs of ["+durmins+" mins : "+dursecs+" secs]");
				$("#position").attr("max", duration);
				$("#position").slider('refresh');
			}
			if (status.statusMessage) {
				$("#statusMessage").text(status.statusMessage);
			}
			if (status.state === "PLAYING") {
				this.state = "play";
				$("#playPause .ui-btn-text").html("Pause");
				$("#playPause").buttonMarkup({icon : "pauseIcon" });
			}
		}
	});

	return View;
});


text:
using System;
using System.Collections.Generic;
using System.IO;

class SortwordsToAnotherFile
{
    static void Main()
    {
        StreamReader reader = new StreamReader("..\\..\\MyFile.txt");
        StreamWriter writer = new StreamWriter("..\\..\\MyNewFile.txt");
        using(reader)
        {
            using (writer)
            {
                string word = reader.ReadLine().Trim();
                List<string> words = new List<string>();

                while (word != null)
                {
                    words.Add(word.Trim());
                    word = reader.ReadLine();
                }

                words.Sort((a, b) => a.CompareTo(b));

                foreach (string name in words)
                {
                    writer.WriteLine(name);
                }
            }
        }
    }
}


text: webpack --progress --colors --watch


text:
{% load i18n %}
{% csrf_token %}
{% for error in form.non_field_errors %}

 {{ error }}

{% endfor %}

{% if not nodc %}{% include "gui/dc/dc_form_field.html" with prefix="_adm" %}{% endif %}
{% include "gui/form_field_checkbox.html" with field=form.dc_bound %}
{% include "gui/form_field.html" with field=form.name %}
{% include "gui/form_field.html" with field=form.alias %}
{% include "gui/form_field.html" with field=form.owner %}
{% include "gui/form_field.html" with field=form.access %}
{% include "gui/form_field.html" with field=form.ip_network %}
{% include "gui/form_field.html" with field=form.gateway %}
{% include "gui/form_field.html" with field=form.vlan_id %}
{% include "gui/form_field.html" with field=form.nic_tag %}
{% include "gui/form_field.html" with field=form.vxlan_id %}
{% include "gui/form_field.html" with field=form.desc %}

{% include "gui/form_field.html" with field=form.resolvers %}
{# {% include "gui/form_field.html" with field=form.dns_domain %} #}
{% include "gui/form_field.html" with field=form.ptr_domain %}
{% include "gui/form_field.html" with field=form.mtu %}
{% include "gui/form_field_checkbox.html" with field=form.dhcp_passthrough %}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.spincast</groupId>
        <artifactId>spincast-parent</artifactId>
        <version>{{ spincastVersion }}</version> <!-- 1.4.0 -->
    </parent>
    <artifactId>spincast-test</artifactId>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <app.mainClass>org.spincast.test.App</app.mainClass>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.spincast</groupId>
            <artifactId>spincast-default</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>org.spincast</groupId>
            <artifactId>spincast-plugins-config</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>org.spincast</groupId>
            <artifactId>spincast-quickstart</artifactId>
            <version>${project.version}</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.25</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.1.0</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <createDependencyReducedPom>false</createDependencyReducedPom>
                            <filters>
                                <!--===================================
                                see : http://stackoverflow.com/a/6743609/843699
                                ====================================-->
                                <filter>
                                    <artifact>*:*</artifact>
                                    <excludes>
                                        <exclude>META-INF/*.SF</exclude>
                                        <exclude>META-INF/*.DSA</exclude>
                                        <exclude>META-INF/*.RSA</exclude>
                                    </excludes>
                                </filter>
                            </filters>
                            <transformers>
                                <transformer
                                    implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <manifestEntries>
                                        <Main-Class>${app.mainClass}</Main-Class>
                                    </manifestEntries>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>


text:
<?php
namespace Controller;

use Model\Dao\ChaineDAO;
use Model\Dao\ProgrammationDAO;
use Model\Dao\ProgrammeDAO;
use Model\Dto\ProgrammationDTO;
use View\View;

class ProgrammationController {
    public function createAction($parameters) {
        $programmationDAO = new ProgrammationDAO();
        $chaineDAO = new ChaineDAO();
        $programmeDAO = new ProgrammeDAO();

        $programmationDTO = new ProgrammationDTO();
        if (!empty($parameters['by']) && !empty($parameters['id'])) {
            if ($parameters['by'] === 'chaine') {
                $chaineDTO = $chaineDAO->find($parameters['id']);
                if ($chaineDTO !== null) {
                    $programmationDTO->setChaineDTO($chaineDTO);
                }
            } elseif ($parameters['by'] === 'programme') {
                $programmeDTO = $programmeDAO->find($parameters['id']);
                if ($programmeDTO !== null) {
                    $programmationDTO->setProgrammeDTO($programmeDTO);
                }
            }
        }

        if (!empty($_POST)) {
            $programmationDTO->hydrate($_POST);
            $programmationDAO->insert($programmationDTO);
            if ($programmationDTO->getChaineDTO() !== null) {
                // The one we selected
                header('location: /chaine/' . $programmationDTO->getChaineId());
            } elseif ($programmationDTO->getProgrammeDTO() !== null) {
                // The one we selected
                header('location: /programme/' . $programmationDTO->getProgrammeId());
            } else {
                header('location: /');
            }
            exit();
        }
        echo (new View('programmation', 'form'))->create([
            'programmationDTO' => $programmationDTO,
            'availableChaines' => $chaineDAO->findAll(),
            'availableProgrammes' => $programmeDAO->findAll(),
        ]);
    }

    public function deleteAction($parameters) {
        $programmationDTO = new ProgrammationDTO();
        $programmationDTO->hydrate($parameters);
        $programmationDAO = new ProgrammationDAO();
        $programmationDAO->delete($programmationDTO);
        if (!empty($parameters['by'])) {
            if ($parameters['by'] === 'chaine') {
                header('location: /chaine/' . $programmationDTO->getChaineId());
                exit();
            } elseif ($parameters['by'] === 'programme') {
                header('location: /programme/' . $programmationDTO->getProgrammeId());
                exit();
            }
        }
        header('location: /');
    }
}


text:
<component refname="U" compname="FT231X-SSOP" package="DIP">
	DTRn,O
</component>


text:
package visualization;

import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BuildDataSets
{
	String file;

	public BuildDataSets(String file)
	{
		this.file = file;
	}

	public String[] readData(String regex)
	{
		RandomAccessFile raf;
		int counter = 400000;
		Pattern regexPtr = Pattern.compile(regex);
		Matcher matcher = null;
		String data[] = null;

		try
		{
			raf = new RandomAccessFile(this.file, "r");
	    	raf.seek(counter);
			String dataIns[] = raf.readUTF().split("\n");

			for(int i = 0; i < dataIns.length; i ++)
    		{
				matcher = regexPtr.matcher(dataIns[i]);
				if(matcher.find())
    			{
					data = matcher.group(1).split(",");
					i = dataIns.length;
    			}
    		}
			raf.close();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return data;
	}

	public ArrayList<String> parseData(String[] data)
	{
		ArrayList<String> temp = new ArrayList<String>();
		String test = "(.*)=(.*)";
		Pattern ptrTest = Pattern.compile(test);
		Matcher mTest = null;

		for(int i = 0; i < data.length; i ++)
		{
			data[i] = data[i].trim();
			mTest = ptrTest.matcher(data[i]);
			if(mTest.find())
			{
				temp.add(mTest.group(1));
			}
		}

		return temp;
	}

	public static void main(String[] args)
	{
		BuildDataSets bds = new BuildDataSets("");
		String d[] = bds.readData("\\[node\\] (.*)");
		ArrayList<String> s = bds.parseData(d);
		for(int i = 0; i < s.size(); i ++)
		{
			System.out.println(s.get(i));
		}
	}
}


text:
package io.digdag.core.agent;

import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import io.digdag.client.config.Config;
import io.digdag.client.config.ConfigException;
import io.digdag.client.config.ConfigFactory;
import io.digdag.spi.TaskRequest;
import static java.util.Locale.ENGLISH;

public class RuntimeParams
{
    public static Config buildRuntimeParams(ConfigFactory cf, TaskRequest request)
    {
        Config params = cf.create();

        ZoneId timeZone = request.getTimeZone();
        params.set("timezone", timeZone);

        // session_*
        params.set("session_uuid", request.getSessionUuid().toString());
        params.set("session_time", formatSessionTime(request.getSessionTime(), timeZone));
        setTimeParameters(params, "session_", timeZone, request.getSessionTime());

        // last_session_*
        try {
            // last_session_time is set by AttemptBuilder
            String st = request.getConfig().get("last_session_time", String.class, null);
            if (st != null) {
                Instant instant = Instant.from(TIME_FORMAT.parse(st));
                setTimeParameters(params, "last_session_", timeZone, instant);
            }
        }
        catch (ConfigException | DateTimeParseException ex) {
            // skip last_session_time
        }

        // next_session_*
        try {
            // next_session_time is set by AttemptBuilder
            String st = request.getConfig().get("next_session_time", String.class, null);
            if (st != null) {
                Instant instant = Instant.from(TIME_FORMAT.parse(st));
                setTimeParameters(params, "next_session_", timeZone, instant);
            }
        }
        catch (ConfigException | DateTimeParseException ex) {
            // skip next_session_time
        }

        // project_*
        params.set("project_id", request.getProjectId());

        params.set("retry_attempt_name", request.getRetryAttemptName().orNull());

        return params;
    }

    private static final DateTimeFormatter TIME_FORMAT =
        DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssxxx", ENGLISH);

    private static final DateTimeFormatter DATE_FORMAT =
        DateTimeFormatter.ofPattern("yyyy-MM-dd", ENGLISH);

    private static final DateTimeFormatter DATE_COMPACT_FORMAT =
        DateTimeFormatter.ofPattern("yyyyMMdd", ENGLISH);

    private static final DateTimeFormatter DATETIME_FORMAT =
        DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", ENGLISH);

    private static final DateTimeFormatter DATETIME_COMPACT_FORMAT =
        DateTimeFormatter.ofPattern("yyyyMMddHHmmss", ENGLISH);

    private static final DateTimeFormatter TZ_OFFSET_FORMAT =
        DateTimeFormatter.ofPattern("xx", ENGLISH);

    private static void setTimeParameters(Config params, String prefix, ZoneId timeZone, Instant instant)
    {
        params.set(prefix + "date", DATE_FORMAT.withZone(timeZone).format(instant));
        params.set(prefix + "date_compact", DATE_COMPACT_FORMAT.withZone(timeZone).format(instant));
        params.set(prefix + "local_time", DATETIME_FORMAT.withZone(timeZone).format(instant));
        //params.set(prefix + "local_time_compact", DATETIME_COMPACT_FORMAT.withZone(timeZone).format(instant));
        params.set(prefix + "tz_offset", TZ_OFFSET_FORMAT.withZone(timeZone).format(instant));
        params.set(prefix + "unixtime", instant.getEpochSecond());
    }

    // also used by AttemptBuilder to set last_session_time and next_session_time
    public static String formatSessionTime(Instant instant, ZoneId timeZone)
    {
        return TIME_FORMAT.withZone(timeZone).format(instant);
    }
}


text:
/**
* Controller for the Add Contributor modal.
*/
'use strict';

var $ = require('jquery');
var ko = require('knockout');
var moment = require('moment');
require('knockout-mapping');
require('knockout-punches');
require('jquery-autosize');
ko.punches.enableAll();

var osfHelpers = require('./osf-helpers.js');
var CommentPane = require('./commentpane.js');

var nodeApiUrl = window.contextVars.node.urls.api;

// Maximum length for comments, in characters
var MAXLENGTH = 500;

var ABUSE_CATEGORIES = {
    spam: 'Spam or advertising',
    hate: 'Hate speech',
    violence: 'Violence or harmful behavior'
};

/*
    * Format UTC datetime relative to current datetime, ensuring that time
    * is in the past.
    */
var relativeDate = function(datetime) {
    var now = moment.utc();
    var then = moment.utc(datetime);
    then = then > now ? now : then;
    return then.fromNow();
};

var notEmpty = function(value) {
    return !!$.trim(value);
};

var exclusify = function(subscriber, subscribees) {
    subscriber.subscribe(function(value) {
        if (value) {
            for (var i=0; i<subscribees.length; i++) {
                subscribees[i](false);
            }
        }
    });
};

var exclusifyGroup = function() {
    var observables = Array.prototype.slice.call(arguments);
    for (var i=0; i<observables.length; i++) {
        var subscriber = observables[i];
        var subscribees = observables.slice();
        subscribees.splice(i, 1);
        exclusify(subscriber, subscribees);
    }
};

/*
    *
    */
var BaseComment = function() {

    var self = this;

    self.abuseOptions = Object.keys(ABUSE_CATEGORIES);

    self._loaded = false;
    self.id = ko.observable();

    self.errorMessage = ko.observable();
    self.editErrorMessage = ko.observable();
    self.replyErrorMessage = ko.observable();

    self.replying = ko.observable(false);
    self.replyContent = ko.observable('');

    self.submittingReply = ko.observable(false);

    self.comments = ko.observableArray();
    self.unreadComments = ko.observable(0);

    self.displayCount = ko.computed(function() {
        if (self.unreadComments() !== 0) {
            return self.unreadComments().toString();
        } else {
            return ' ';
        }
    });

    /* Removes number of unread comments from tab when comments pane is opened  */
    self.removeCount = function() {
        self.unreadComments(0);
    };

    self.replyNotEmpty = ko.computed(function() {
        return notEmpty(self.replyContent());
    });
    self.saveButtonText = ko.computed(function() {
        return self.submittingReply() ? 'Saving' : 'Save';
    });

};

BaseComment.prototype.abuseLabel = function(item) {
    return ABUSE_CATEGORIES[item];
};

BaseComment.prototype.showReply = function() {
    this.replying(true);
};

BaseComment.prototype.cancelReply = function() {
    this.replyContent('');
    this.replying(false);
    this.submittingReply(false);
    this.replyErrorMessage('');
};

BaseComment.prototype.setupToolTips = function(elm) {
    $(elm).each(function(idx, item) {
        var $item = $(item);
        if ($item.attr('data-toggle') === 'tooltip') {
            $item.tooltip();
        } else {
            $item.find('[data-toggle="tooltip"]').tooltip();
        }
    });
};

BaseComment.prototype.fetch = function() {
    var self = this;
    var deferred = $.Deferred();
    if (self._loaded) {
        deferred.resolve(self.comments());
    }
    $.getJSON(
        nodeApiUrl + 'comments/',
        {target: self.id()},
        function(response) {
            self.comments(
                ko.utils.arrayMap(response.comments.reverse(), function(comment) {
                    return new CommentModel(comment, self, self.$root);
                })
            );
            self.unreadComments(response.nUnread);
            deferred.resolve(self.comments());
            self._loaded = true;
        }
    );
    return deferred;
};

BaseComment.prototype.submitReply = function() {
    var self = this;
    if (!self.replyContent()) {
        self.replyErrorMessage('Please enter a comment');
        return;
    }
    // Quit if already submitting reply
    if (self.submittingReply()) {
        return;
    }
    self.submittingReply(true);
    osfHelpers.postJSON(
        nodeApiUrl + 'comment/',
        {
            target: self.id(),
            content: self.replyContent(),
        }
    ).done(function(response) {
        self.cancelReply();
        self.replyContent(null);
        self.comments.unshift(new CommentModel(response.comment, self, self.$root));
        if (!self.hasChildren()) {
            self.hasChildren(true);
        }
        self.replyErrorMessage('');
        // Update discussion in case we aren't already in it
        // TODO: This can lead to unnecessary API calls; fix this
        if (!self.$root.commented()) {
            self.$root.fetchDiscussion();
            self.$root.commented(true);
        }
        self.onSubmitSuccess(response);
    }).fail(function() {
        self.cancelReply();
        self.errorMessage('Could not submit comment');
    });
};

/*
    *
    */
var CommentModel = function(data, $parent, $root) {

    BaseComment.prototype.constructor.call(this);

    var self = this;

    self.$parent = $parent;
    self.$root = $root;

    $.extend(self, ko.mapping.fromJS(data));
    self.dateCreated(data.dateCreated);
    self.dateModified(data.dateModified);

    self.prettyDateCreated = ko.computed(function() {
        return relativeDate(self.dateCreated());
    });
    self.prettyDateModified = ko.computed(function() {
        return 'Modified ' + relativeDate(self.dateModified());
    });

    self.showChildren = ko.observable(false);

    self.hoverContent = ko.observable(false);

    self.reporting = ko.observable(false);
    self.deleting = ko.observable(false);
    self.unreporting = ko.observable(false);
    self.undeleting = ko.observable(false);

    self.abuseCategory = ko.observable('spam');
    self.abuseText = ko.observable();

    self.editing = ko.observable(false);
    self.editVerb = self.modified ? 'edited' : 'posted';

    exclusifyGroup(
        self.editing, self.replying, self.reporting, self.deleting,
        self.unreporting, self.undeleting
    );

    self.isVisible = ko.computed(function() {
        return !self.isDeleted() && !self.isAbuse();
    });

    self.editNotEmpty = ko.computed(function() {
        return notEmpty(self.content());
    });

    self.toggleIcon = ko.computed(function() {
        return self.showChildren() ? 'icon-collapse-alt' : 'icon-expand-alt';
    });
    self.editHighlight = ko.computed(function() {
        return self.canEdit() && self.hoverContent();
    });
    self.canReport = ko.computed(function() {
        return self.$root.canComment() && !self.canEdit();
    });

    self.shouldShow = ko.computed(function() {
        return !self.isDeleted() || self.hasChildren() || self.canEdit();
    });

};

CommentModel.prototype = new BaseComment();

CommentModel.prototype.edit = function() {
    if (this.canEdit()) {
        this._content = this.content();
        this.editing(true);
        this.$root.editors += 1;
    }
};

CommentModel.prototype.autosizeText = function(elm) {
    $(elm).find('textarea').autosize().focus();
};

CommentModel.prototype.cancelEdit = function() {
    this.editing(false);
    this.$root.editors -= 1;
    this.editErrorMessage('');
    this.hoverContent(false);
    this.content(this._content);
};

CommentModel.prototype.submitEdit = function(data, event) {
    var self = this;
    var $tips = $(event.target)
        .closest('.comment-container')
        .find('[data-toggle="tooltip"]');
    if (!self.content()) {
        self.errorMessage('Please enter a comment');
        return;
    }
    osfHelpers.putJSON(
        nodeApiUrl + 'comment/' + self.id() + '/',
        {content: self.content()}
    ).done(function(response) {
        self.content(response.content);
        self.dateModified(response.dateModified);
        self.editing(false);
        self.modified(true);
        self.editErrorMessage('');
        self.$root.editors -= 1;
        // Refresh tooltip on date modified, if present
        $tips.tooltip('destroy').tooltip();
    }).fail(function() {
        self.cancelEdit();
        self.errorMessage('Could not submit comment');
    });
};

CommentModel.prototype.reportAbuse = function() {
    this.reporting(true);
};

CommentModel.prototype.cancelAbuse = function() {
    this.abuseCategory(null);
    this.abuseText(null);
    this.reporting(false);
};

CommentModel.prototype.submitAbuse = function() {
    var self = this;
    osfHelpers.postJSON(
        nodeApiUrl + 'comment/' + self.id() + '/report/',
        {
            category: self.abuseCategory(),
            text: self.abuseText()
        }
    ).done(function() {
        self.isAbuse(true);
    }).fail(function() {
        self.errorMessage('Could not report abuse.');
    });
};

CommentModel.prototype.startDelete = function() {
    this.deleting(true);
};

CommentModel.prototype.submitDelete = function() {
    var self = this;
    $.ajax({
        type: 'DELETE',
        url: nodeApiUrl + 'comment/' + self.id() + '/',
    }).done(function() {
        self.isDeleted(true);
        self.deleting(false);
    }).fail(function() {
        self.deleting(false);
    });
};

CommentModel.prototype.cancelDelete = function() {
    this.deleting(false);
};

CommentModel.prototype.startUndelete = function() {
    this.undeleting(true);
};

CommentModel.prototype.submitUndelete = function() {
    var self = this;
    osfHelpers.putJSON(
        nodeApiUrl + 'comment/' + self.id() + '/undelete/',
        {}
    ).done(function() {
        self.isDeleted(false);
    }).fail(function() {
        self.undeleting(false);
    });
};

CommentModel.prototype.cancelUndelete = function() {
    this.undeleting(false);
};

CommentModel.prototype.startUnreportAbuse = function() {
    this.unreporting(true);
};

CommentModel.prototype.submitUnreportAbuse = function() {
    var self = this;
    osfHelpers.postJSON(
        nodeApiUrl + 'comment/' + self.id() + '/unreport/',
        {}
    ).done(function() {
        self.isAbuse(false);
    }).fail(function() {
        self.unreporting(false);
    });
};

CommentModel.prototype.cancelUnreportAbuse = function() {
    this.unreporting(false);
};

CommentModel.prototype.startHoverContent = function() {
    this.hoverContent(true);
};

CommentModel.prototype.stopHoverContent = function() {
    this.hoverContent(false);
};

CommentModel.prototype.toggle = function () {
    this.fetch();
    this.showChildren(!this.showChildren());
};

CommentModel.prototype.onSubmitSuccess = function() {
    this.showChildren(true);
};

/*
    *
    */
var CommentListModel = function(userName, canComment, hasChildren) {

    BaseComment.prototype.constructor.call(this);

    var self = this;

    self.$root = self;
    self.MAXLENGTH = MAXLENGTH;

    self.editors = 0;
    self.commented = ko.observable(false);
    self.userName = ko.observable(userName);
    self.canComment = ko.observable(canComment);
    self.hasChildren = ko.observable(hasChildren);
    self.discussion = ko.observableArray();

    self.fetch();
    self.fetchDiscussion();

};

CommentListModel.prototype = new BaseComment();

CommentListModel.prototype.onSubmitSuccess = function() {};

CommentListModel.prototype.fetchDiscussion = function() {
    var self = this;
    $.getJSON(
        nodeApiUrl + 'comments/discussion/',
        function(response) {
            self.discussion(response.discussion);
        }
    );
};

CommentListModel.prototype.initListeners = function() {
    var self = this;
    $(window).on('beforeunload', function() {
        if (self.editors) {
            return 'Your comments have unsaved changes. Are you sure ' +
                'you want to leave this page?';
        }
    });
};

var timestampUrl = nodeApiUrl + 'comments/timestamps/';
var onOpen = function() {
    var request = osfHelpers.putJSON(timestampUrl);
    request.fail(function(xhr, textStatus, errorThrown) {
        Raven.captureMessage('Could not update comment timestamp', {
            url: timestampUrl,
            textStatus: textStatus,
            errorThrown: errorThrown
        });
    });
};

var init = function(selector, userName, canComment, hasChildren) {
    new CommentPane(selector, {onOpen: onOpen});
    var viewModel = new CommentListModel(userName, canComment, hasChildren);
    var $elm = $(selector);
    if (!$elm.length) {
        throw('No results found for selector');
    }
    ko.applyBindings(viewModel, $elm[0]);
    viewModel.initListeners();

    return viewModel;
};

module.exports = {
    init: init
};


text:
package client.controllers;

import common.connection.RemoteCallback;
import client.UpdateLongpollingCallbackRegistrar;

import javafx.application.Platform;
import javafx.stage.Stage;

public interface SelfUpdating {

  void update();

  Stage getCurrentStage();

  default void subscribeForUpdates() {
    RemoteCallback rc = () -> Platform.runLater(SelfUpdating.this::update);
    UpdateLongpollingCallbackRegistrar.registerCallbackOnServer(rc);
    getCurrentStage().setOnCloseRequest(event ->
        UpdateLongpollingCallbackRegistrar.deregisterMostRecentCallback());
  }
}