text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>SyncRequest.Builder</title>
<meta name="date" content="2018-10-24">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.fitpay.android.paymentdevice.models

Class SyncRequest.Builder

java.lang.Object

com.fitpay.android.paymentdevice.models.SyncRequest.Builder

Enclosing class:

SyncRequest

public static final class SyncRequest.Builder
extends java.lang.Object

Constructor Summary

Constructors

Constructor and Description

Builder()

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

SyncRequest
build()

SyncRequest.Builder
setConnector(PaymentDeviceConnectable connector)

Set current connector PaymentDeviceConnectable

SyncRequest.Builder
setDevice(Device device)

Set current device

SyncRequest.Builder
setSyncId(java.lang.String syncId)

Set sync id

SyncRequest.Builder
setSyncInfo(SyncInfo syncInfo)

Set sync links

SyncRequest.Builder
setUseLastAckCommit(boolean useLastAckCommit)

Use last ack commit

SyncRequest.Builder
setUser(User user)

Set current user

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

Builder

public Builder()

Method Detail

setSyncId

public SyncRequest.Builder setSyncId(java.lang.String syncId)

Set sync id

Parameters:

syncId - sync id

Returns:

this

setUser

public SyncRequest.Builder setUser(@NonNull
                                   User user)

Set current user

Parameters:

user - current user

Returns:

this

setDevice

public SyncRequest.Builder setDevice(@NonNull
                                     Device device)

Set current device

Parameters:

device - current device

Returns:

this

setUseLastAckCommit

public SyncRequest.Builder setUseLastAckCommit(boolean useLastAckCommit)

Use last ack commit

Parameters:

useLastAckCommit - true/false

Returns:

this

setConnector

public SyncRequest.Builder setConnector(@NonNull
                                        PaymentDeviceConnectable connector)

Set current connector PaymentDeviceConnectable

Parameters:

connector - payment device connector

Returns:

this

setSyncInfo

public SyncRequest.Builder setSyncInfo(SyncInfo syncInfo)

Set sync links

Parameters:

syncInfo - sync links

Returns:

this

build

public SyncRequest build()

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
CREATE TABLE IF NOT EXISTS `ci_sessions` (
  `id` varchar(40) NOT NULL,
  `ip_address` varchar(45) NOT NULL,
  `timestamp` int(10) unsigned NOT NULL DEFAULT '0',
  `data` blob NOT NULL,
  PRIMARY KEY (`id`),
  KEY `ci_sessions_timestamp` (`timestamp`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

-- --------------------------------------------------------

--
-- Table structure for table `auth_sessions`
--
-- The IP address and user agent are only
-- included so that sessions can be identified.
-- This can be helpful if you want to show the
-- user their sessions, and allow them to terminate
-- selected sessions.
--

CREATE TABLE IF NOT EXISTS `auth_sessions` (
  `id` varchar(40) NOT NULL,
  `user_id` int(10) unsigned NOT NULL,
  `login_time` datetime DEFAULT NULL,
  `modified_at` timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `ip_address` varchar(45) NOT NULL,
  `user_agent` varchar(60) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

-- --------------------------------------------------------

--
-- Table structure for table `ips_on_hold`
--

CREATE TABLE IF NOT EXISTS `ips_on_hold` (
  `ai` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `ip_address` varchar(45) NOT NULL,
  `time` datetime NOT NULL,
  PRIMARY KEY (`ai`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

-- --------------------------------------------------------

--
-- Table structure for table `login_errors`
--

CREATE TABLE IF NOT EXISTS `login_errors` (
  `ai` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `username_or_email` varchar(255) NOT NULL,
  `ip_address` varchar(45) NOT NULL,
  `time` datetime NOT NULL,
  PRIMARY KEY (`ai`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

-- --------------------------------------------------------

--
-- Table structure for table `denied_access`
--

CREATE TABLE IF NOT EXISTS `denied_access` (
  `ai` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `ip_address` varchar(45) NOT NULL,
  `time` datetime NOT NULL,
  `reason_code` tinyint(2) DEFAULT 0,
  PRIMARY KEY (`ai`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

-- --------------------------------------------------------

--
-- Table structure for table `username_or_email_on_hold`
--

CREATE TABLE IF NOT EXISTS `username_or_email_on_hold` (
  `ai` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `username_or_email` varchar(255) NOT NULL,
  `time` datetime NOT NULL,
  PRIMARY KEY (`ai`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

-- --------------------------------------------------------

--
-- Table structure for table `users`
--

CREATE TABLE IF NOT EXISTS `users` (
  `user_id` int(10) unsigned NOT NULL,
  `username` varchar(12) DEFAULT NULL,
  `email` varchar(255) NOT NULL,
  `auth_level` tinyint(2) unsigned NOT NULL,
  `banned` enum('0','1') NOT NULL DEFAULT '0',
  `passwd` varchar(60) NOT NULL,
  `passwd_recovery_code` varchar(60) DEFAULT NULL,
  `passwd_recovery_date` datetime DEFAULT NULL,
  `passwd_modified_at` datetime DEFAULT NULL,
  `last_login` datetime DEFAULT NULL,
  `created_at` datetime NOT NULL,
  `modified_at` timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`user_id`),
  UNIQUE KEY `username` (`username`),
  UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- --------------------------------------------------------

--
-- Trigger updates passwd_modified_at field if passwd modified
--

delimiter $$
DROP TRIGGER IF EXISTS ca_passwd_trigger ;
$$
CREATE TRIGGER ca_passwd_trigger BEFORE UPDATE ON users
FOR EACH ROW
BEGIN
    IF ((NEW.passwd <=> OLD.passwd) = 0) THEN
        SET NEW.passwd_modified_at = NOW();
    END IF;
END;$$
delimiter ;

-- --------------------------------------------------------

redpajama_set_name: RedPajamaGithub


text:
// Define block signatures

typedef void (^socialActionSuccess)();
typedef void (^socialActionFail)(NSString* message);
typedef void (^contactsActionSuccess)(NSArray* userProfiles, bool hasMore);
typedef void (^contactsActionFail)(NSString* message);
typedef void (^feedsActionSuccess)(NSArray* feeds, bool hasMore);
typedef void (^feedsActionFail)(NSString* message);
typedef void (^inviteSuccess)(NSString * requestId, NSArray *invitedIds);
typedef void (^inviteFail)(NSString *message);
typedef void (^inviteCancel)();


text:
package org.opencb.opencga.catalog.stats.solr;

import org.apache.solr.client.solrj.beans.Field;

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

/**
 * Created by wasim on 27/06/18.
 */
public class FamilySolrModel extends CatalogSolrModel {

    @Field
    private List<String> phenotypes;

    @Field
    private List<String> disorders;

    @Field
    private int numMembers;

    @Field
    private int expectedSize;

    @Field
    private int version;

    @Field
    private List<String> annotationSets;

    @Field("annotations__*")
    private Map<String, Object> annotations;

    public FamilySolrModel() {
        this.annotationSets = new ArrayList<>();
        this.annotations = new HashMap<>();
        this.phenotypes = new ArrayList<>();
        this.disorders = new ArrayList<>();
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("FamilySolrModel{");
        sb.append("id='").append(id).append('\'');
        sb.append(", uid=").append(uid);
        sb.append(", studyId='").append(studyId).append('\'');
        sb.append(", creationYear=").append(creationYear);
        sb.append(", creationMonth='").append(creationMonth).append('\'');
        sb.append(", creationDay=").append(creationDay);
        sb.append(", creationDayOfWeek='").append(creationDayOfWeek).append('\'');
        sb.append(", status='").append(status).append('\'');
        sb.append(", phenotypes=").append(phenotypes);
        sb.append(", disorders=").append(disorders);
        sb.append(", numMembers=").append(numMembers);
        sb.append(", expectedSize=").append(expectedSize);
        sb.append(", release=").append(release);
        sb.append(", version=").append(version);
        sb.append(", acl=").append(acl);
        sb.append(", annotationSets=").append(annotationSets);
        sb.append(", annotations=").append(annotations);
        sb.append('}');
        return sb.toString();
    }

    public List<String> getPhenotypes() {
        return phenotypes;
    }

    public FamilySolrModel setPhenotypes(List<String> phenotypes) {
        this.phenotypes = phenotypes;
        return this;
    }

    public List<String> getDisorders() {
        return disorders;
    }

    public FamilySolrModel setDisorders(List<String> disorders) {
        this.disorders = disorders;
        return this;
    }

    public int getNumMembers() {
        return numMembers;
    }

    public FamilySolrModel setNumMembers(int numMembers) {
        this.numMembers = numMembers;
        return this;
    }

    public int getExpectedSize() {
        return expectedSize;
    }

    public FamilySolrModel setExpectedSize(int expectedSize) {
        this.expectedSize = expectedSize;
        return this;
    }

    public int getVersion() {
        return version;
    }

    public FamilySolrModel setVersion(int version) {
        this.version = version;
        return this;
    }

    public List<String> getAnnotationSets() {
        return annotationSets;
    }

    public FamilySolrModel setAnnotationSets(List<String> annotationSets) {
        this.annotationSets = annotationSets;
        return this;
    }

    public Map<String, Object> getAnnotations() {
        return annotations;
    }

    public FamilySolrModel setAnnotations(Map<String, Object> annotations) {
        this.annotations = annotations;
        return this;
    }
}


text:
layout: post
title: "Object::Pad and Types? A Learning Experience"
author: "Dave Jacoby"
date: "2021-09-27 18:28:54 -0400"
categories: ""
---

[Previously in my investigation of Object::Pad](https://jacoby.github.io/2021/09/23/objectpad-again-this-time-with-subclassing.html), I created an implementation of a Point object, which I was able to extend to allow it to become a Point in 3D space by adding a z axis.

The next step? Do something with a Line consisting of two points.

Honestly, so far, just using arrayrefs has been easy enough for me:

```perl
#!/usr/bin/env perl

use strict;
use warnings;
use feature qw{ say signatures state };
no warnings qw{ experimental };

my $i = [ 0, 0 ];
my $j = [ 3, 2 ];

my $distance = distance( $i, $j );
say $distance;

# 3.60555127546399

# As seen in
# https://jacoby.github.io/2021/07/27/ugly-and-square-perl-weekly-challenge-123.html
sub distance ( $p1, $p2 ) {
    return
        sqrt(
        ( ( $p1->[0] - $p2->[0] )**2 ) + ( ( $p1->[1] - $p2->[1] )**2 ) );
}
```

The point **J** is microscopically past 3.605 from point **I**, which is the origin. I personally think that rounding the result to the third decimal place is sufficient for nearly anything I'd want to do with it, and I do it rarely enough that an arrayref is sufficient to contain everything I would need.

Previously, I had a `CorPoint` class that contained thing I didn't need, because I wanted to learn how to use attributes. I wiped them, leaving only `x` and `y`.

```perl
use Object::Pad;

use strict;
use warnings;
use feature qw{ say postderef signatures };
no warnings qw{ experimental };

package CorPoint 0.01;

class CorPoint {
    has $x :param :mutator = 0;
    has $y :param :mutator = 0;

    method xy () {
        return join ', ',$x,$y;
    }
}
```

And now I need a **Line** object that takes two Point objects. I need to be able to say that they _must_ be Point objects, and we get that from [Object::Pad::SlotAttr::Isa](https://metacpan.org/pod/Object::Pad::SlotAttr::Isa) (which doesn't install on Strawberry Perl with `cpanm` but I was too far down this rabbit hole to shave that yak). I get to say `:Isa(CorPoint)`. I've tried to feed it non-CorPoint values and it silently drops to defaults. I'm not currently sure whether I'd want it to silently handle it or `croak` and complain. I think it depends on where I am in development.

```perl
use strict;
use warnings;
use feature qw{ say postderef signatures };
no warnings qw{ experimental };

use Carp;
use Object::Pad;
use Object::Pad::SlotAttr::Isa;

use lib '.';
use CorPoint;

package CorLine 0.01;

class CorLine {
    has $i :param :reader :Isa(CorPoint) = CorPoint->new();
    has $j :param :reader :Isa(CorPoint) = CorPoint->new();

    method distance {
        return
            sqrt( ( ( $self->i->x - $self->j->x )**2 ) +
                ( ( $self->i->y - $self->j->y )**2 ) );
    }

    method dist {
        return sprintf '%0.3f', $self->distance;
    }
}
```

(I made the `dist` method because of my earlier _third-decimal place_ comment.)

So, now I can make an object where the values are objects of the specified class.

And, in place?

```perl
#!/usr/bin/env perl

use strict;
use warnings;
use feature qw{ say signatures state };
no warnings qw{ experimental };

use Cwd qw( abs_path );
use File::Basename qw( dirname );
use lib dirname( abs_path($0) );
use CorLine;
use CorPoint;

my $i = CorPoint->new( x => 5, y => 7 );
my $j = CorPoint->new( x => 3, y => 2 );
my $k = CorPoint->new();

my $l = CorPoint->new( 1, 4 ); # defaults to x=>0, y=>0
$l->x = 1;
$l->y = 4;

for my $p1 ( $i, $j, $k, $l ) {
    for my $p2 ( $i, $j, $k, $l ) {
        my $line = CorLine->new( i => $p1, j => $p2 );
        say join "\t",
            $line->i->xy,
            $line->j->xy,
            $line->dist,
            $line->distance,
            ;
    }
    say '';
}
```

And the output:

```text
5, 7    5, 7    0.000   0
5, 7    3, 2    5.385   5.3851648071345
5, 7    0, 0    8.602   8.60232526704263
5, 7    1, 4    5.000   5

3, 2    5, 7    5.385   5.3851648071345
3, 2    3, 2    0.000   0
3, 2    0, 0    3.606   3.60555127546399
3, 2    1, 4    2.828   2.82842712474619

0, 0    5, 7    8.602   8.60232526704263
0, 0    3, 2    3.606   3.60555127546399
0, 0    0, 0    0.000   0
0, 0    1, 4    4.123   4.12310562561766

1, 4    5, 7    5.000   5
1, 4    3, 2    2.828   2.82842712474619
1, 4    0, 0    4.123   4.12310562561766
1, 4    1, 4    0.000   0
```

As I mentioned previously, Paul Evans talked to Purdue Perl Mongers about this, and to get my understanding to the point where the code worked, I had to go back to the **See Also** at the end of his slides and do some searching to get to `SlotAttr::Isa`, but I'm now very happy with it.

There was [a recent Weekly Challenge](https://jacoby.github.io/2021/07/27/ugly-and-square-perl-weekly-challenge-123.html) where we're given four points and are to determine if they're squares. In the review, it was mentioned that mine failed because it assumed an order. I'm thinking that I can resolve that using these Points and Lines. My thought is that you take points **A**, **B**, **C** and **D**, make lines between all of them (you _can_ do **A->A**, sure, but why?), sort the pairs by length, and determine if the longest four lines have the same length. If they don't, it's not a square.

But that's a task for another night.

#### If you have any questions or comments, I would be glad to hear it. Ask me on [Twitter](https://twitter.com/jacobydave) or [make an issue on my blog repo.](https://github.com/jacoby/jacoby.github.io)


text:
using System;
using System.Runtime.Serialization;

namespace Orleans.Runtime
{
    /// <summary>
    /// Signifies that a gateway silo is currently in overloaded / load shedding state
    /// and is unable to currently accept this message being sent.
    /// </summary>
    /// <remarks>
    /// This situation is usually a transient condition.
    /// The message is likely to be accepted by this or another gateway if it is retransmitted at a later time.
    /// </remarks>
    [Serializable]
    [GenerateSerializer]
    public class GatewayTooBusyException : OrleansException
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="GatewayTooBusyException"/> class.
        /// </summary>
        public GatewayTooBusyException()
            : base("Gateway too busy")
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="GatewayTooBusyException"/> class.
        /// </summary>
        /// <param name="message">
        /// The message.
        /// </param>
        public GatewayTooBusyException(string message)
            : base(message)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="GatewayTooBusyException"/> class.
        /// </summary>
        /// <param name="message">
        /// The message.
        /// </param>
        /// <param name="innerException">
        /// The inner exception.
        /// </param>
        public GatewayTooBusyException(string message, Exception innerException)
            : base(message, innerException)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="GatewayTooBusyException"/> class.
        /// </summary>
        /// <param name="info">
        /// The serialization info.
        /// </param>
        /// <param name="context">
        /// The context.
        /// </param>
        protected GatewayTooBusyException(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
        }
    }
}


text:
/* Include file for the R2 point class */

/* Initialization functions */

int R2InitPoint();
void R2StopPoint();

/* Class definition */

class R2Point {
    public:
        // Constructor/destructor functions
	R2Point(void);
	R2Point(const R2Point& point);
	R2Point(RNCoord x, RNCoord y);
	R2Point(const RNCoord array[2]);

        // Property functions/operators
	const RNCoord X(void) const;
	const RNCoord Y(void) const;
	const RNCoord Coord(RNDimension dim) const;
	const RNCoord operator[](RNDimension dim) const;
	const RNCoord *Coords(void) const;
	const RNBoolean IsZero(void) const;
	const RNBoolean IsFinite(void) const;
	const R2Vector Vector(void) const;

	// Relationship functions/operators
	const RNBoolean Collinear(const R2Point& point1, const R2Point& point2) const;
	const RNBoolean operator==(const R2Point& point) const;
	const RNBoolean operator!=(const R2Point& point) const;

        // Manipulation functions/operators
	void X(RNCoord x);
	void Y(RNCoord y);
	void SetCoord(RNDimension dim, RNCoord coord);
        void Translate(const R2Vector& vector);
	void Project(const R2Line& line);
	void Mirror(const R2Line& line);
	void Rotate(const R2Point& origin, RNAngle theta);
	void Transform(const R2Transformation& transformation);
	void InverseTransform(const R2Transformation& transformation);
	void Reset(RNCoord x, RNCoord y);

        // Draw functions/operators
        void Draw(void) const;

	// Assignment operators
	R2Point& operator=(const R2Point& point);
	R2Point& operator+=(const R2Point& point);
	R2Point& operator+=(const R2Vector& vector);
	R2Point& operator-=(const R2Vector& vector);
	R2Point& operator*=(const RNScalar a);
	R2Point& operator*=(const R3Matrix& m);
	R2Point& operator/=(const RNScalar a);

        // Arithmetic operators
	friend R2Point operator+(const R2Point& point);
	friend R2Point operator-(const R2Point& point);
	friend R2Point operator+(const R2Point& point1, const R2Point& point2) ;
	friend R2Point operator+(const R2Point& point, const R2Vector& vector) ;
	friend R2Point operator+(const R2Vector& vector, const R2Point& point) ;
	friend R2Vector operator-(const R2Point& point1, const R2Point& point2);
	friend R2Point operator-(const R2Point& point, const R2Vector& vector);
	friend R2Point operator*(const R2Point& point, const RNScalar a);
	friend R2Point operator*(const RNScalar a, const R2Point& point);
	friend R2Point operator*(const R2Point& point, const R3Matrix& m);
	friend R2Point operator/(const R2Point& point, const RNScalar a);

        // Undocumented functions/operators
  	RNCoord& operator[](RNDimension dim);

    private:
	RNCoord v[2];
};

/* Public variables */

extern const R2Point R2null_point;
extern const R2Point R2ones_point;
extern const R2Point R2posx_point;
extern const R2Point R2posy_point;
extern const R2Point R2negx_point;
extern const R2Point R2negy_point;
extern const R2Point R2infinite_point;
extern const R2Point R2unknown_point;
#define R2zero_point R2null_point

/* Inline functions */

inline const RNCoord R2Point::
X (void) const
{
    return(v[0]);
}

inline const RNCoord R2Point::
Y (void) const
{
    return(v[1]);
}

inline const RNCoord R2Point::
Coord (RNDimension dim) const
{
    assert ((dim>=RN_X)&&(dim<=RN_Y));
    return(v[dim]);
}

inline const RNCoord R2Point::
operator[](RNDimension dim) const
{
    assert((dim>=RN_X) && (dim<=RN_Y));
    return(v[dim]);
}

inline const RNCoord *R2Point::
Coords(void) const
{
    // Return coords array
    return v;
}

inline const RNBoolean R2Point::
IsZero(void) const
{
    // Return whether point is zero
    return ((v[0] == 0.0) && (v[1] == 0.0));
}

inline const R2Vector R2Point::
Vector(void) const
{
    // Return vector to point from origin
    return R2Vector(v[0], v[1]);
}

inline void R2Point::
X (RNCoord x)
{
    // Set X coord
    v[0] = x;
}

inline void R2Point::
Y (RNCoord y)
{
    // Set Y coord
    v[1] = y;
}

inline void R2Point::
SetCoord (RNDimension dim, RNCoord coord)
{
    // Set coord
    assert ((dim>=RN_X)&&(dim<=RN_Y));
    v[dim] = coord;
}

inline void R2Point::
Reset(RNCoord x, RNCoord y)
{
    // Set all coords
    v[0] = x;
    v[1] = y;
}

inline void R2Point::
Translate (const R2Vector& vector)
{
    // Move point by vector
    *this += vector;
}

inline R2Point
operator+(const R2Vector& vector, const R2Point& point)
{
    // Commute addition
    return (point + vector);
}

inline R2Point
operator*(const RNScalar a, const R2Point& point)
{
    // Commute scale
    return (point * a);
}

inline RNCoord& R2Point::
operator[] (RNDimension dim)
{
    assert((dim>=RN_X) && (dim<=RN_Y));
    return(v[dim]);
}


text:
#include <iostream>
#include <array>
#include <vector>
#include <algorithm>

#include "algo/Graph.hpp"
#include "algo/GraphSearch.hpp"

const constexpr unsigned POD_COST = 20;

struct Assignment
{
    int priority = -1;
    std::vector<unsigned> path;
    unsigned neededPods = 0;

    bool operator==(const Assignment& other) const
    {
        if (!path.empty() && !other.path.empty())
            return path.back() == other.path.back();
        return true;
    }

    bool operator<(const Assignment& other) const { return priority < other.priority; }
    bool operator>(const Assignment& other) const { return priority > other.priority; }
};

class AssignmentsManager
{
public:
    bool hasAssignmentFor(unsigned zoneId) const
    {
        return moves_.find(zoneId) != moves_.end();
    }

    void addMoveCommand(const Assignment& assignment)
    {
        if (assignment.path.size() < 1)
            return;

        unsigned srcZone = assignment.path[0];
        auto& assignments = moves_[srcZone];
        auto it = std::find(assignments.begin(), assignments.end(), assignment);
        if (it != assignments.end())
        {
            Assignment concated = concatAssignments(*it, assignment);
            assignments.erase(it);
            assignments.push_back(concated);
        }
        else
        {
            assignments.push_back(assignment);
        }
    }

    template<typename GraphType>
    void performMoves(const GraphType& graph, unsigned playerNo)
    {
        if (moves_.empty())
        {
            std::cerr << "No moves planned" << std::endl;
            std::cout << "WAIT" << std::endl;
            return;
        }

        bool commandGiven = false;

        for (auto& val : moves_)
        {
            auto zoneId = val.first;
            auto& assignments = val.second;
            std::sort(assignments.begin(), assignments.end(), std::greater<Assignment>());
            auto playerPods = graph.data(zoneId).pods[playerNo];

            auto assignmentId = 0;

            while (playerPods > 0 && assignments.size() > assignmentId)
            {
                auto& a = assignments[assignmentId];
                unsigned usedPods = std::min(playerPods, a.neededPods);
                // if there's a path - it's a move command
                // otherwise it's a defence command
                if (a.path.size() > 1)
                {
                    commandGiven = true;
                    std::cout << usedPods << " " << a.path.at(0) << " " << a.path.at(1) << " ";
                }
                playerPods -= usedPods;
                ++assignmentId;
            }

        }

        if (commandGiven)
        {
            std::cout << std::endl;
        }
        else
        {
            std::cerr << "Only defence commands this turn." << std::endl;
            std::cout << "WAIT" << std::endl;
        }

        moves_.clear();
    }

    void addBuyCommand(const Assignment& assignment)
    {
        if (assignment.path.empty())
            return;

        unsigned srcZone = assignment.path[0];
        auto it = std::find_if(buys_.begin(), buys_.end(),
            [srcZone](const Assignment& a){ return a.path[0] == srcZone; });
        if (it != buys_.end() && it->neededPods >= assignment.neededPods)
            return;
        buys_.push_back(assignment);
    }

    void performBuys(unsigned availablePlatinum)
    {
        if (buys_.empty())
        {
            std::cerr << "No buy commands." << std::endl;
            std::cout << "WAIT" << std::endl;;
            return;
        }

        std::sort(buys_.begin(), buys_.end(), std::greater<Assignment>());

        const unsigned podCost = 20;
        auto buyId = 0;
        bool boughtSth = false;

        while (availablePlatinum >= podCost && buys_.size() > buyId)
        {
            auto& buy = buys_[buyId];
            unsigned neededPlat = buy.neededPods * podCost;
            if (neededPlat <= availablePlatinum)
            {
                std::cout << buy.neededPods << " " << buy.path[0] << " ";
                availablePlatinum -= (buy.neededPods * podCost);
                boughtSth = true;
            }
            ++buyId;
        }

        if (boughtSth) // any buy command was given
        {
            std::cout << std::endl;
        }
        else
        {
            std::cerr << "Not enough platinum to perform any buy." << std::endl;
            std::cout << "WAIT" << std::endl;;
        }

        buys_.clear();
    }

private:
    Assignment concatAssignments(const Assignment& lhs, const Assignment& rhs)
    {
        Assignment ret;
        ret.neededPods = lhs.neededPods + rhs.neededPods;
        if (lhs < rhs)
        {
            ret.priority = rhs.priority;
            ret.path = rhs.path;
        }
        else
        {
            ret.priority = lhs.priority;
            ret.path = lhs.path;
        }
        return ret;
    }

private:
    std::unordered_map<int, std::vector<Assignment>> moves_;
    std::vector<Assignment> buys_;
};

struct Zone
{
    unsigned id;
    int owner = -1;
    int platinum = 0;
    int neighbourhoodValue = 0;
    std::array<unsigned, 4> pods = {{0, 0, 0, 0}}; // single brace works in clang, not in g++...
    std::vector<Assignment> assignments;

    unsigned maxEnemyCount(unsigned playerNo) const
    {
        auto podsCopy = pods;
        podsCopy[playerNo] = 0;
        return *std::max_element(podsCopy.begin(), podsCopy.end());
    }

    bool hasPlayerPods(unsigned playerNo) const
    {
        return pods[playerNo] > 0;
    }
};

struct Player
{
    unsigned id = 0;
    unsigned platinum = 200;
};

class AssignmentGenerator
{
    using GraphType = algo::Graph<unsigned, Zone>;
    using NodeType = GraphType::NodeType;

public:
    AssignmentGenerator(unsigned playerNo, unsigned totalPlayers, GraphType& graph) :
        playerNo_(playerNo), totalPlayers_(totalPlayers), graph_(graph)
    {
        for (auto& kv : graph_)
            addPlatinumNode(&kv.second);
    }

    void generateAssignments(unsigned availablePlatinum)
    {
        auto zonesWithMyPods = getZonesWithMyPods();

        conquerZones();
        defendZones();
        freeRoamAll(zonesWithMyPods);
        buyPods();

        assMan.performMoves(graph_, playerNo_);
        assMan.performBuys(availablePlatinum);
    }

private:
    void addPlatinumNode(NodeType* node)
    {
        // fill neighbourhoodValue for all nodes
        auto neighbours = node->neighbours();
        auto neighboursCount = neighbours.size();
        unsigned totalPlatinumInNeighbourhood = std::accumulate(
            neighbours.begin(), neighbours.end(), 0,
            [neighboursCount](unsigned acc, const NodeType* n){ return acc + n->data().platinum; } );

        node->data().neighbourhoodValue = node->data().platinum;// +  totalPlatinumInNeighbourhood / neighboursCount;

        if (node->data().platinum > 0)
        {
            platinumNodes_.push_back(node);
            ++platinumNodesCount_[node->data().platinum - 1];
        }
    }

    bool tryNinjaAttack(NodeType* platinumNode)
    {
        unsigned maxEnemiesOnPlat = platinumNode->data().maxEnemyCount(playerNo_);
        unsigned platinumAvailable = platinumNode->data().neighbourhoodValue;
        unsigned pno = playerNo_;

        // Ninja attack
        if (maxEnemiesOnPlat <= 3)
        {
            auto neighbours = platinumNode->neighbours();
            auto neededPodsToAttack = maxEnemiesOnPlat + 1;

            std::sort(neighbours.begin(), neighbours.end(),
                [pno](NodeType* lhs, NodeType* rhs)
                { return lhs->data().pods[pno] > rhs->data().pods[pno]; });

            std::vector<Assignment> tempAsses;

            for (auto* neighbour : neighbours)
            {
                Assignment a;
                a.priority = platinumAvailable;
                a.neededPods = std::min(neededPodsToAttack, neighbour->data().pods[pno]);
                a.path = {neighbour->data().id, platinumNode->data().id};

                neededPodsToAttack -= a.neededPods;

                if (a.neededPods > 0)
                    tempAsses.push_back(a);

                if (neededPodsToAttack == 0)
                    break;
            }

            if (neededPodsToAttack == 0 && tempAsses.size() > 1)
            {
                for (auto& a : tempAsses)
                {
                    assMan.addMoveCommand(a);
                    std::cerr << "Becoming a ninja: " << a.path[0]  << "->" << a.path[1] << std::endl;
                }
                return true;
            }
        }
        return false;
    }

    void conquerZones()
    {
        for (auto* platinumNode : platinumNodes_)
        {
            if (platinumNode->data().owner == playerNo_)
                continue;

            if (tryNinjaAttack(platinumNode))
                continue;

            unsigned maxEnemiesOnPlat = platinumNode->data().maxEnemyCount(playerNo_);
            unsigned platinumAvailable = platinumNode->data().neighbourhoodValue;
            unsigned pno = playerNo_;

            auto pathToClosestZoneWithEnoughPods  = algo::findShortestPathBfs(
                graph_, platinumNode->data().id,
                [pno, maxEnemiesOnPlat](const NodeType& n)
                    { return n.data().pods[pno] > maxEnemiesOnPlat;  },
                [pno, maxEnemiesOnPlat](const NodeType& frontier)
                    {
                        auto mec = frontier.data().maxEnemyCount(pno);
                        return (mec == 0 || mec < maxEnemiesOnPlat);
                    },
                algo::GraphPred<GraphType>::nodeFalse);

            if (!pathToClosestZoneWithEnoughPods.empty())
            {
                unsigned pathSize = pathToClosestZoneWithEnoughPods.size();
                unsigned distance = pathSize - std::min(2u, pathSize);

                Assignment a;
                a.priority = platinumAvailable - std::min(platinumAvailable, distance);
                a.neededPods = maxEnemiesOnPlat + 1;  // let's hope it won't overflow ;)

                // we searched starting from platinum node, but assignment is set starting from node
                // with pod (from found path end)
                std::vector<unsigned> path;
                std::transform(
                    pathToClosestZoneWithEnoughPods.rbegin(),
                    pathToClosestZoneWithEnoughPods.rend(),
                    std::back_inserter(a.path), [](Zone& z) { return z.id; });
                assMan.addMoveCommand(a);
            }
        }
    }

    void defendZones()
    {
        for (auto* platinumNode : platinumNodes_)
        {
            if (platinumNode->data().owner != playerNo_)
                continue;

            std::array<unsigned, 4> enemyCount = {{0, 0, 0, 0}};

            for (auto* neighbour : platinumNode->neighbours())
            {
                enemyCount[0] += neighbour->data().pods[0];
                enemyCount[1] += neighbour->data().pods[1];
                enemyCount[2] += neighbour->data().pods[2];
                enemyCount[3] += neighbour->data().pods[3];
            }

            enemyCount[playerNo_] = 0;

            unsigned maxEnemies = *std::max_element(enemyCount.begin(), enemyCount.end());

            if (maxEnemies > 0)
            {
                bool enoughExistingPods = false;
                Assignment a;
                a.priority = platinumNode->data().neighbourhoodValue + 1; // defensive assignments have higher priority
                a.neededPods = maxEnemies;

                for (auto* neighbour : platinumNode->neighbours())
                {
                    if (neighbour->data().pods[playerNo_] >= maxEnemies)
                    {
                        a.path = {neighbour->data().id, platinumNode->data().id};
                        assMan.addMoveCommand(a);
                        enoughExistingPods = true;
                        break;
                    }
                }

                if (!enoughExistingPods)
                {
                    a.path.push_back(platinumNode->data().id);
                    assMan.addBuyCommand(a);
                }

            }
        }
    }

    void freeRoamAll(const std::vector<std::reference_wrapper<Zone>>& zonesWithMyPods)
    {

        for (Zone& zone : zonesWithMyPods)
        {
            std::vector<unsigned> takenDestinations;
            std::vector<unsigned> firstFound;
            for (unsigned i = 0; i < zone.pods[playerNo_]; ++i)
            {
                auto closestUntakenPath = algo::findShortestPathBfs(graph_, zone.id,
                    [&takenDestinations, this](const NodeType& n)
                        { return n.data().owner != playerNo_ && !zoneFound(n.data().id, takenDestinations); },
                    algo::GraphPred<GraphType>::nodeTrue,
                    algo::GraphPred<GraphType>::nodeFalse);

                Assignment a;
                a.priority = 0;

                if (!closestUntakenPath.empty())
                {
                    std::vector<unsigned> path;
                    std::transform(closestUntakenPath.begin(), closestUntakenPath.end(),
                        std::back_inserter(a.path), [](Zone& z) { return z.id; });
                    if (firstFound.empty())
                        firstFound = a.path;

                    a.neededPods = 1;

                    takenDestinations.push_back(a.path.back());
                }
                else if (!firstFound.empty())
                {
                    a.path = firstFound;
                    a.neededPods = zone.pods[playerNo_]; // assignment manager will correctly move remaining pods
                    continue;
                }

                assMan.addMoveCommand(a);
            }
        }
    }

    std::vector<std::reference_wrapper<Zone>> getZonesWithMyPods()
    {
        std::vector<std::reference_wrapper<Zone>> ret;
        for (auto& kv : graph_)
        {
            Zone& z = kv.second.data();
            if (z.hasPlayerPods(playerNo_))
                ret.push_back(z);
        }
        return ret;
    }

    void buyPods()
    {
        for (auto* pn : platinumNodes_)
        {
            if (pn->data().owner != playerNo_)
            {
                unsigned neighbourhoodValue = pn->data().neighbourhoodValue;
                unsigned platinum = pn->data().platinum;

                // usually optimal placement during the first turn when there are more than 2
                // players ends with disaster...
                if (firstBuyEver_ && totalPlayers_ > 2 && platinum >= 5)
                    continue;

                auto nearbyPods = findMatchingNodesBfs(graph_, pn->data().id,
                    [this](const NodeType& n) { return n.data().pods[playerNo_] > 0; },
                    algo::GraphPred<GraphType>::nodeTrue,
                    [](const NodeType& n) { return n.distance > 1; }); // FIXME: empirical test what radius of check is the best

                decltype(nearbyPods) path;

                if (!nearbyPods.empty())
                {
                    auto it = std::max_element(nearbyPods.begin(), nearbyPods.end(),
                        [this](const Zone& lhs, const Zone& rhs)
                            { return lhs.pods[playerNo_] < rhs.pods[playerNo_]; });
                    path = findShortestPathBfs(graph_, pn->data().id,
                        [&it](const NodeType& n) { return n.data().id == it->get().id; },
                        [this](const NodeType& n) { return n.data().maxEnemyCount(playerNo_) == 0; },
                        algo::GraphPred<GraphType>::nodeFalse);
                }

                if (path.empty())
                {
                    path = findShortestPathBfs(graph_, pn->data().id,
                        [this](const NodeType& n)
                            { auto owner = n.data().owner; return (owner == -1 || owner == playerNo_); },
                        algo::GraphPred<GraphType>::nodeTrue,
                        algo::GraphPred<GraphType>::nodeFalse);
                }

                if (path.empty())
                    continue;

                unsigned podsToBuy = pn->data().maxEnemyCount(playerNo_) + 1;
                unsigned alreadyAvailablePods = path.back().get().pods[playerNo_];
                if (alreadyAvailablePods > podsToBuy)
                    continue;
                podsToBuy -= alreadyAvailablePods;

                Assignment a;
                a.priority = static_cast<int>(neighbourhoodValue);
                a.path.push_back(path.back().get().id);
                a.neededPods = podsToBuy;

                if (path.size() > 1)
                    a.priority = 1;

                if (firstBuyEver_ && neighbourhoodValue > 5 && platinum > 3)
                    a.neededPods += 1;

                assMan.addBuyCommand(a);
            }
        }

        for (auto kv : graph_)
        {
            const auto& node = kv.second;
            if (node.data().owner == -1)
            {
                Assignment a;
                a.priority = 0;
                a.neededPods = 1;
                a.path.push_back(node.data().id);
                assMan.addBuyCommand(a);
            }
        }

        firstBuyEver_ = false;
    }

    bool zoneFound(unsigned zoneId, const std::vector<unsigned>& foundZones) const
    {
        return std::find(foundZones.begin(), foundZones.end(), zoneId) != foundZones.end();
    }

private:
    unsigned playerNo_;
    unsigned totalPlayers_;
    GraphType& graph_;
    std::vector<NodeType*> platinumNodes_;
    AssignmentsManager assMan;
    bool firstBuyEver_ = true;
    std::array<int, 6> platinumNodesCount_ = {{0,0,0,0,0,0}};
};

class Game
{
    using GraphType = algo::Graph<unsigned, Zone>;

public:
    void run()
    {
        init();
        AssignmentGenerator assGen(me_.id, playersNo_,  graph_);

        while (true)
        {
            parseRoundInput();
            assGen.generateAssignments(me_.platinum);
        }
    }

private:
    void init()
    {
        unsigned linksNo;

        std::cin >> playersNo_ >> me_.id >> zoneNo_ >> linksNo;

        for (unsigned i = 0; i < zoneNo_; ++i)
        {
            Zone z;
            std::cin >> z.id >> z.platinum;
            auto* node = graph_.addNode(z.id, z);
        }

        for (unsigned i = 0; i < linksNo; ++i)
        {
            unsigned zid1, zid2;
            std::cin >> zid1 >> zid2;
            graph_.addConnection(zid1, zid2);
        }
    }

    void parseRoundInput()
    {
        std::cin >> me_.platinum;
        for (unsigned i = 0; i < zoneNo_; ++i)
        {
            unsigned zid;
            std::cin >> zid;
            auto& z = graph_.data(zid);
            std::cin >> z.owner >> z.pods[0] >> z.pods[1] >> z.pods[2] >> z.pods[3];
        }
    }

private:
    unsigned playersNo_;
    unsigned zoneNo_;
    Player me_;

    GraphType graph_;
};

int main()
{
    try
    {
        Game g;
        g.run();
    }
    catch (const std::exception& e)
    {
        std::cerr << "Uncaught exception. Program will now terminate." << std::endl;
        std::cerr << "what(): " << e.what() << std::endl;
        return 1;
    }
}


text:
<?php

use yii\db\Migration;

class m160305_100403_splatoon_version extends Migration
{
    public function up()
    {
        $this->createTable('splatoon_version', [
            'id'            => $this->primaryKey(),
            'tag'           => $this->string(32)->notNull()->unique(),
            'name'          => $this->string(32)->notNull(),
            'released_at'   => 'TIMESTAMP(0) WITH TIME ZONE NOT NULL',
        ]);
        $this->createIndex('ix_splatoon_version_1', 'splatoon_version', 'released_at');

        $this->execute('ALTER TABLE {{battle}} ' . implode(', ', [
            'ADD COLUMN [[version_id]] INTEGER REFERENCES {{splatoon_version}} ( [[id]] )',
        ]));
    }

    public function down()
    {
        $this->execute('ALTER TABLE {{battle}} DROP COLUMN [[version_id]]');
        $this->dropTable('splatoon_version');
    }
}


text:
'''
ABOUT: How Python can be used to execute IRAF/PyRAF tasks
DEPENDS: Python 2.7.3
AUTHOR: S N Bright for STScI, 2013
HISTORY: 2013: Test program
USE: python pyraf_example.py
'''

#Load the packages we need
import pyraf, os, glob
from pyraf import iraf
from iraf import noao, digiphot, daophot

#Generate a list of all the fits files
file_list = glob.glob('*_ima.fits')
print file_list

#Loops though all the .fits files
for file in file_list:
    #Test for old files, and remove them if they exist
    file_query = os.access(file + '1.coo.1', os.R_OK)
    if file_query == True:
        os.remove(file + '1.coo.1')
    #Run daofind on one image
    iraf.daofind(
        image = file + '[1]',
        interactive = 'no',
        verify = 'no')


text:
package de.uni_hildesheim.sse.qmApp.editors;

import org.eclipse.jface.viewers.DialogCellEditor;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;

import de.uni_hildesheim.sse.ConstraintSyntaxException;
import de.uni_hildesheim.sse.ModelUtility;
import net.ssehub.easy.producer.ui.productline_editor.ConfigurationTableEditorFactory.UIConfiguration;
import net.ssehub.easy.producer.ui.productline_editor.IUpdateListener;
import net.ssehub.easy.producer.ui.productline_editor.IUpdateProvider;
import net.ssehub.easy.varModel.confModel.AssignmentState;
import net.ssehub.easy.varModel.confModel.ConfigurationException;
import net.ssehub.easy.varModel.confModel.ContainerVariable;
import net.ssehub.easy.varModel.confModel.IDecisionVariable;
import net.ssehub.easy.varModel.cst.CSTSemanticException;
import net.ssehub.easy.varModel.cst.ConstraintSyntaxTree;
import net.ssehub.easy.varModel.model.datatypes.Compound;
import net.ssehub.easy.varModel.model.datatypes.ConstraintType;
import net.ssehub.easy.varModel.model.values.ContainerValue;
import net.ssehub.easy.varModel.model.values.Value;
import net.ssehub.easy.varModel.model.values.ValueDoesNotMatchTypeException;
import net.ssehub.easy.varModel.model.values.ValueFactory;
import net.ssehub.easy.varModel.persistency.StringProvider;
import qualimasterapplication.Activator;

/**
 * Implements a cell editor for constraints.
 *
 * @author Holger Eichelberger
 * @author El-Sharkawy
 * @see
 * http://stackoverflow.com/questions/14464611/jface-dialogcelleditor-how-to-make-buttons-always-appear
 */
class ConstraintsCellEditor extends DialogCellEditor implements IUpdateProvider {

    private IDecisionVariable context;
    private IUpdateListener listener;
    private Button button;

    /**
     * Creates a constraint cell editor.
     *
     * @param config the configuration
     * @param variable the decision variable
     * @param parent the parent composite
     */
    ConstraintsCellEditor(UIConfiguration config, IDecisionVariable variable, Composite parent) {
        super(parent);

        if (null != parent && parent instanceof Tree && variable instanceof ContainerVariable
            && ((ContainerValue) variable.getValue()).getElementSize() == 0) {

            Tree propertiesTree = (Tree) parent;
            ContainerVariable conVar = (ContainerVariable) variable;

            String constraintValues = null;
            for (int i = 0, end = propertiesTree.getItems().length; i < end && null == constraintValues; i++) {
                TreeItem tmpItem = propertiesTree.getItems()[i];
                if (tmpItem.getText().contains("constraints")) {
                    constraintValues = tmpItem.getText(1);
                    if (constraintValues != null && !constraintValues.isEmpty()) {
                        String[] tmpArray = constraintValues.split(ConstraintsEditorDialog.SEPARATOR);
                        for (int j = 0; j < tmpArray.length; j++) {
                            try {
                                ConstraintSyntaxTree cst = ModelUtility.INSTANCE.createExpression(tmpArray[j],
                                    variable.getDeclaration().getParent());
                                Value constraintValue = ValueFactory.createValue(ConstraintType.TYPE, cst);
                                conVar.addNestedElement().setValue(constraintValue, AssignmentState.ASSIGNED);
                            } catch (ValueDoesNotMatchTypeException e) {
                                Activator.getLogger(ConstraintsCellEditor.class).exception(e);
                            } catch (ConfigurationException e) {
                                Activator.getLogger(ConstraintsCellEditor.class).exception(e);
                            } catch (CSTSemanticException e) {
                                Activator.getLogger(ConstraintsCellEditor.class).exception(e);
                            } catch (ConstraintSyntaxException e) {
                                Activator.getLogger(ConstraintsCellEditor.class).exception(e);
                            }
                        }
                    }
                }
            }
        }

        this.context = variable;
    }

    @Override
    protected Button createButton(Composite parent) {
        button = super.createButton(parent);
        button.setText("...");
        return button;
    }

    @Override
    protected Object openDialogBox(Control cellEditorWindow) {
        // null means that dialog was canceled or no selectionw as made in dialog
        Object returnValue = null;
        ConstraintsEditorDialog dlg = new ConstraintsEditorDialog(cellEditorWindow.getShell(), context, valueToStr());
        if (Window.OK == dlg.open()) {
            setValue(dlg.getConstraintsText());
            returnValue = getValue();
        }
        return returnValue;
    }

    /**
     * Converts a (ContainerValue full of Constraints) value into a string representation as needed by the
     * {@link ConstraintsEditorDialog}.
     * @return A String representation of the current value, maybe an empty string, but not <tt>null</tt>.
     */
    private String valueToStr() {
        StringBuffer sb = new StringBuffer();
        Value value = context.getValue();
        if (null != value && value instanceof ContainerValue) {
            ContainerValue conValue = (ContainerValue) value;
            int nConstraints = conValue.getElementSize();
            if (nConstraints > 0) {
                ConstraintSyntaxTree cst = (ConstraintSyntaxTree) conValue.getElement(0).getValue();
                sb.append(StringProvider.toIvmlString(cst, (Compound) context.getDeclaration().getParent()));
            }
            for (int i = 1; i < nConstraints; i++) {
                sb.append(ConstraintsEditorDialog.SEPARATOR);
                ConstraintSyntaxTree cst = (ConstraintSyntaxTree) conValue.getElement(i).getValue();
                sb.append(StringProvider.toIvmlString(cst, (Compound) context.getDeclaration().getParent()));
            }
        }
        return sb.toString();
    }

    @Override
    protected void doSetValue(Object value) {
        super.doSetValue(value);
        notifyValueChanged();
    }

    @Override
    public IDecisionVariable getVariable() {
        return context;
    }

    @Override
    public void setUpdateListener(IUpdateListener listener) {
        this.listener = listener;
    }

    /**
     * Called to notify about a value change.
     */
    protected void notifyValueChanged() {
        if (null != listener) {
            listener.valueChanged(this);
        }
    }

    @Override
    public void refresh() {
        // TODO Auto-generated method stub

    }

}


text:
// This is a copy of the JsHelpers as a trait to allow
// catalog tests to still work until they are migrated
package common

import spray.json.JsObject
import spray.json.JsValue

/**
 * @deprecated Use {@link whisk.common.JsHelpers} instead.
 */
@Deprecated
trait JsHelpers {
    implicit class JsObjectHelper(js: JsObject) {
        def getFieldPath(path: String*): Option[JsValue] = {
            whisk.utils.JsHelpers.getFieldPath(js, path.toList)
        }

        def fieldPathExists(path: String*): Boolean = {
            whisk.utils.JsHelpers.fieldPathExists(js, path.toList)
        }
    }
}


text:
module.exports = function initExpressApp (customApp) {
	if (this.app) return this;
	this.initDatabaseConfig();
	this.initExpressSession(this.mongoose);
	if (customApp) {
		this.app = customApp;
		require('../../server/createApp')(this);
	} else {
		this.app = require('../../server/createApp')(this);
	}
	return this;
};


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_height="fill_parent"
  android:layout_width="fill_parent"
  android:textColor="#ffffff">
  <GridView android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    android:id="@+id/gridShirtList"
    android:numColumns="auto_fit"
    android:columnWidth="60sp"
/>

</LinearLayout>


text:
package com.thinkgem.jeesite.modules.act.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.beanutils.Converter;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 日期转换类
 * @author ThinkGem
 * @version 2013-11-03
 */
public class DateConverter implements Converter {

	private static final Logger logger = LoggerFactory.getLogger(DateConverter.class);

	private static final String DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss";

	private static final String DATETIME_PATTERN_NO_SECOND = "yyyy-MM-dd HH:mm";

	private static final String DATE_PATTERN = "yyyy-MM-dd";

	private static final String MONTH_PATTERN = "yyyy-MM";

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Object convert(Class type, Object value) {
		Object result = null;
		if (type == Date.class) {
			try {
				result = doConvertToDate(value);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		} else if (type == String.class) {
			result = doConvertToString(value);
		}
		return result;
	}

	/**
	 * Convert String to Date
	 *
	 * @param value
	 * @return
	 * @throws ParseException
	 */
	private Date doConvertToDate(Object value) throws ParseException {
		Date result = null;

		if (value instanceof String) {
			result = DateUtils.parseDate((String) value, new String[] { DATE_PATTERN, DATETIME_PATTERN,
					DATETIME_PATTERN_NO_SECOND, MONTH_PATTERN });

			// all patterns failed, try a milliseconds constructor
			if (result == null && StringUtils.isNotEmpty((String) value)) {

				try {
					result = new Date(new Long((String) value).longValue());
				} catch (Exception e) {
					logger.error("Converting from milliseconds to Date fails!");
					e.printStackTrace();
				}

			}

		} else if (value instanceof Object[]) {
			// let's try to convert the first element only
			Object[] array = (Object[]) value;

			if (array.length >= 1) {
				value = array[0];
				result = doConvertToDate(value);
			}

		} else if (Date.class.isAssignableFrom(value.getClass())) {
			result = (Date) value;
		}
		return result;
	}

	/**
	 * Convert Date to String
	 *
	 * @param value
	 * @return
	 */
	private String doConvertToString(Object value) {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATETIME_PATTERN);
		String result = null;
		if (value instanceof Date) {
			result = simpleDateFormat.format(value);
		}
		return result;
	}

}


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

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Logging Configuration — ownCloud Server Administration Manual 8.1 documentation</title>

    <link rel="stylesheet" href="../_static/style.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="../_static/style.css" type="text/css" />
    <link rel="stylesheet" href="../_static/bootstrap-sphinx.css" type="text/css" />

    <link rel="top" title="ownCloud Server Administration Manual 8.1 documentation" href="../index.html" />
    <link rel="up" title="ownCloud Server Configuration" href="index.html" />
    <link rel="next" title="Hardening and Security Guidance" href="harden_server.html" />
    <link rel="prev" title="Language Configuration" href="language_configuration.html" />

ownCloud Server Administration Manual

Table of Contents

ownCloud 8.1 Server Administration Manual Introduction

ownCloud 8.1 Release Notes

What’s New for Admins in ownCloud 8

Installation

User Management

File Sharing and Management

ownCloud Server Configuration

Warnings on Admin Page

Using the occ Command

Configuring the Activity App

Configuring the ClamAV Antivirus Scanner

Automatic Configuration Setup

Defining Background Jobs

Config.php Parameters

Email Configuration

Linking External Sites

JavaScript and CSS Asset Management

Knowledge Base Configuration

Language Configuration

Logging Configuration

Parameters

Hardening and Security Guidance

Server Tuning & Performance Tips

Reverse Proxy Configuration

Enabling Full-Text Search

Using Third Party PHP Components

Database Configuration

Maintenance

Operations

Issues and Troubleshooting

ownCloud Videos

Enterprise Subscription Installation (ES Only)

Creating Branded ownCloud Clients (ES only)

External Storage (ES only)

User Management (ES only)

Enabling Anonymous Uploads with Files Drop (ES Only)

Logging Configuration¶

To get an idea of how the current status of an ownCloud system is or to
solve issues log information is a good point to start with. ownCloud allows
to configure the way how and which depth of information should be logged.

Parameters¶

First you need to decide in which way logging should be done. You can
choose between the two options owncloud and syslog. Then you need
to configure the log level which directly influences how much information
will be logged. You can choose between:

0: DEBUG

1: INFO

2: WARN

3: ERROR

4: FATAL

The most detailed information will be written if 0 (DEBUG) is set, the
least information will be written if 3 (ERROR) is set. Keep in mind that
it might slow down the whole system if a too detailed logging will has been
configured. By default the log level is set to 2 (WARN).

This parameters can be set in the <tt class="file docutils literal">config/config.php</tt>

ownCloud¶

All log information will be written to a separate log file which can be
viewed using the log menu in the admin menu of ownCloud. By default a log
file named owncloud.log will be created in the directory which has
been configured by the datadirectory parameter.

The desired date format can optionally be defined using the logdateformat.
By default the PHP date function parameter “c” is used and therefore the
date/time is written in the format “2013-01-10T15:20:25+02:00”. By using the
date format in the example the date/time format will be written in the format
“January 10, 2013 15:20:25”.

<?php

  "log_type" => "owncloud",
  "logfile" => "owncloud.log",
  "loglevel" => "3",
  "logdateformat" => "F d, Y H:i:s",

syslog¶

All log information will be send to the default syslog daemon of a system.

<?php

  "log_type" => "syslog",
  "logfile" => "",
  "loglevel" => "3",


text:
package com.nvim.proto;

import java.util.UUID;

import org.json.JSONException;
import org.json.JSONObject;

import com.nvim.config.ProtocolConstant;
import com.nvim.config.SysConstant;
import com.nvim.entity.MessageInfo;
import com.nvim.log.Logger;

public class MessageEntity {
	public int seqNo;
	public String fromId;
	public String toId;
	public String talkerId;// the guy which sends the message
	public int createTime;
	public byte type;
	public int msgLen;
	public byte[] msgData;
	public String attach;

	// non-meta members
	protected Logger logger = Logger.getLogger(MessageEntity.class);
	public String msgId;
	public String sessionId;
	public int sessionType = -1;
	public boolean multiLoginSelfMsg = false;

	// public boolean isMy() {
	// return fromId.equals(IMLoginManager.instance().getLoginId());
	// }

	public void copy(MessageEntity anotherEntity) {
		seqNo = anotherEntity.seqNo;
		fromId = anotherEntity.fromId;
		toId = anotherEntity.toId;
		talkerId = anotherEntity.talkerId;
		createTime = anotherEntity.createTime;
		type = anotherEntity.type;
		msgLen = anotherEntity.msgLen;
		msgData = anotherEntity.msgData;
		attach = anotherEntity.attach;
		generateMsgId();
		sessionId = anotherEntity.sessionId;
		sessionType = anotherEntity.sessionType;
		multiLoginSelfMsg = anotherEntity.multiLoginSelfMsg;
	}

	private String getMsgDataDescription() {
		if (type == ProtocolConstant.MSG_TYPE_P2P_TEXT) {
			return new String(msgData);
		} else {
			return "";
		}
	}

	public boolean isTextType() {
		// return (msgType == ProtocolConstant.MSG_TYPE_GROUP_TEXT || msgType ==
		// ProtocolConstant.MSG_TYPE_P2P_TEXT);
		return msgInfo.getDisplayType() == SysConstant.DISPLAY_TYPE_TEXT;
	}

	public boolean isAudioType() {
		// return (msgType == ProtocolConstant.MSG_TYPE_GROUP_AUDIO || msgType
		// == ProtocolConstant.MSG_TYPE_P2P_AUDIO);
		return msgInfo.getDisplayType() == SysConstant.DISPLAY_TYPE_AUDIO;
	}

	public boolean isImage() {
		// if (isTextType()) {
		// String msgContent = new String(msgData);
		// if (msgContent != null &&
		// msgContent.contains(SysConstant.MESSAGE_IMAGE_LINK_START)) {
		// return true;
		// }
		// }
		//
		// return false;
		return msgInfo.getDisplayType() == SysConstant.DISPLAY_TYPE_IMAGE;
	}

	public String getText() {
		if (isTextType()) {
			return new String(msgData);
		} else {
			return "";
		}
	}

	public void generateMsgId(/* boolean sending */) {
		// logger.d("chat#generateMessageId -> sending:%s", sending);
		//
		// // unique session, unique time, seqNo+fromId
		// msgId = String.format("%s_%d_%d_%s", getSessionId(sending),
		// createTime,
		// seqNo, fromId);
		msgId = UUID.randomUUID().toString();
	}

	public void generateMsgIdIfEmpty(/* boolean sending */) {
		if (msgId == null || (msgId.length() == 0)) {
			msgId = UUID.randomUUID().toString();
		}
	}

	public void generateSessionId(boolean sending) {
		logger.d("chat#generateSessionId sending:%s", sending);

		sessionId = getSessionId(sending);

		logger.d("chat#session id:%s", sessionId);
	}

	public void generateSessionType(int sessionType) {
		this.sessionType = sessionType;
	}

	public boolean isGroupMsg() {
		// todo eric consider flag &
		if (type == ProtocolConstant.MSG_TYPE_GROUP_AUDIO || type == ProtocolConstant.MSG_TYPE_GROUP_TEXT
				|| type == ProtocolConstant.MSG_TYPE_GROUP_TEXT_FOR_HISTORY_REASON_COMPATIBILITY) {
			return true;
		}

		return false;
	}

	public boolean isP2PMsg() {
		if (type == ProtocolConstant.MSG_TYPE_P2P_AUDIO || type == ProtocolConstant.MSG_TYPE_P2P_TEXT) {
			return true;
		}

		return false;
	}

	@Override
	public String toString() {
		// todo eric make createtime readble
		// todo eric if the content is text, should i logging here
		// todo eric fix all warnings, like locale param in String.format
		return String.format(
				"seqNo:%d,  fromId:%s, toId:%s, createTime:%d, msgType:%d, msgLen:%d, msgData:%s, attach:%s, msgId:%s",
				seqNo, fromId, toId, createTime, type, msgLen, getMsgDataDescription(), (attach == null) ? "" : attach,
				(msgId == null) ? "" : msgId);
	}

	public String getSessionId(boolean sending) {
		if (type == ProtocolConstant.MSG_TYPE_P2P_TEXT || type == ProtocolConstant.MSG_TYPE_P2P_AUDIO) {
			if (multiLoginSelfMsg) {
				return toId;
			}

			return sending ? toId : fromId;
		}

		if (type == ProtocolConstant.MSG_TYPE_GROUP_TEXT
				|| type == ProtocolConstant.MSG_TYPE_GROUP_TEXT_FOR_HISTORY_REASON_COMPATIBILITY
				|| type == ProtocolConstant.MSG_TYPE_GROUP_AUDIO) {
			return toId;
		}

		logger.e("chat#getSessionId failed");

		return null;
	}

	public static String createAudioInfo(MessageInfo msgInfo) {
		JSONObject jo = new JSONObject();
		try {
			jo.put("path", msgInfo.getSavePath());
			jo.put("length", msgInfo.getPlayTime());
			jo.put("readStatus", msgInfo.getMsgReadStatus());
			return jo.toString();
		} catch (JSONException e) {
			Logger logger = Logger.getLogger(MessageEntity.class);
			logger.e("audio#createAudioInfo failed");
		}

		return "";
	}

	public static String createPicInfo(MessageInfo msgInfo) {
		Logger logger = Logger.getLogger(MessageEntity.class);
		logger.d("pic#createPicInfo getSavePath:%s", msgInfo.getSavePath());
		JSONObject jo = new JSONObject();
		try {
			String savePath = msgInfo.getSavePath();
			if (savePath == null) {
				savePath = "";
			}

			jo.put("path", savePath);

			String url = msgInfo.getUrl();
			if (url == null) {
				url = "";
			}

			logger.d("pic#save pic to db, path:%s, url:%s", savePath, url);

			jo.put("url", url);

			return jo.toString();
		} catch (JSONException e) {

			logger.e("pic#createPicInfo failed");
		}

		return "";
	}

	public static class AudioInfo {
		private String path;
		private int length;
		private int readStatus;

		public int getReadStatus() {
			return readStatus;
		}

		public void setReadStatus(int readStatus) {
			this.readStatus = readStatus;
		}

		public String getPath() {
			return path;
		}

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

		public int getLength() {
			return length;
		}

		public void setLength(int length) {
			this.length = length;
		}

		public AudioInfo(String path, int length, int readStatus) {
			this.path = path;
			this.length = length;
			this.readStatus = readStatus;

			Logger.getLogger(MessageEntity.class).d("audio#path:%s, length:%d, readStatus", path, length, readStatus);
		}

		public static AudioInfo create(String info) {
			Logger logger = Logger.getLogger(AudioInfo.class);
			String path = "";
			int length = 0;
			int readStatus = SysConstant.MESSAGE_UNREAD;
			try {
				JSONObject jo = new JSONObject(info);

				path = jo.getString("path");
				length = jo.getInt("length");
				readStatus = jo.getInt("readStatus");

			} catch (JSONException e1) {
				// TODO Auto-generated catch block
				logger.w("audio#createAudioInfo failed");
			}

			logger.d("audio#read audio info from db -> path:%s, length:%d, readStatus:%d", path, length, readStatus);
			return new AudioInfo(path, length, readStatus);
		}
	}

	public static class PicInfo {
		public String getPath() {
			return path;
		}

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

		private String path = "";
		private String url = "";

		public String getUrl() {
			return url;
		}

		public void setUrl(String url) {
			this.url = url;
		}

		public PicInfo(String path, String url) {
			this.path = path;
			this.url = url;

			Logger.getLogger(PicInfo.class).d("pic#read picture content path:%s, url:%s", path, url);
		}

		public static PicInfo create(String info) {
			String path = "";
			String url = "";

			try {
				JSONObject jo = new JSONObject(info);

				url = (String) jo.get("url");
				path = (String) jo.get("path");
			} catch (JSONException e1) {
			}

			Logger.getLogger(PicInfo.class).d("pic#read pic info from db, url:%s, path:%s", url, path);
			return new PicInfo(path, url);
		}
	}

	// todo eric
	public MessageInfo msgInfo;

}


text:
class ValidationError(Exception):
    def __init__(self, errors, unset):
        self.errors = errors
        self.unset = unset
        super().__init__(str(errors), str(unset))

    def __str__(self):
        return "<ValidationError errors: {}; unset: {}".format(self.errors, self.unset)

    def __repr__(self):
        return self.__str__()


text:
Add Food item Details

<?php echo $this->session->flashdata('message');?>

                    <form action="<?php echo base_url(); ?>admin/fooditems/insert" method="post" enctype="multipart/form-data">

           <?php echo validation_errors(); ?>

        Food Item  Name

           <input type="text" id="food_name" name="food_name" class="form-control col-md-7 col-xs-12" required>

         Select type

         <select class="form-control" id="state_id" name="type" required>

        <option value="">-Select Type-</option>

        <option value="Veg">Veg</option>

         <option value="Non-Veg">Non-Veg</option>

                           </select>

         Status

           <select class="form-control" id="ststus" name="status" required>

             <option value="">-Select Availability-</option>

          <option value="1">Available</option>
         <option value="0">Unavailable</option>
         </select>

                     Image

                      <input type="file" name="picture" class="form-control col-md-7 col-xs-12" required>

                    Description

                      <textarea class="form-control" rows="3" id="discription" name="discription" required></textarea>

                    Food Item Charges

                      <input type="text" id="food_charges" name="food_charges" class="form-control col-md-7 col-xs-12" required>

                      <button type="submit" class="btn btn-primary" onclick="window.location='<?php echo base_url(); ?>admin/fooditems';return false;">Cancel</button>

                      <button type="submit" name="submit" class="btn btn-success">Submit</button>

                </form>


text:
import {SWRConfig, SWRConfiguration} from 'swr'

import {swrFetcher} from 'lib/utils/safe-fetch'

// Cypress runs tests quite fast and can run into the automatic deduping and throttling of requests.
const config: SWRConfiguration = {
  dedupingInterval: process.env.NEXT_PUBLIC_CYPRESS === 'true' ? 0 : 1_000, // default is 2_000 ms
  fetcher: swrFetcher,
  focusThrottleInterval: process.env.NEXT_PUBLIC_CYPRESS === 'true' ? 0 : 1_000 // default is 5_000 ms
}

// SWRConfig wrapper
export default function SWRWrapper({children}) {
  return <SWRConfig value={config}>{children}</SWRConfig>
}


text:
import tarfile
import paddle.fluid as fluid
import paddle
from paddle.fluid import core

URL = 'http://paddle-unittest-data.gz.bcebos.com/python_paddle_fluid_tests_demo_async-executor/train_data.tar.gz'
MD5 = '2a405a31508969b3ab823f42c0f522ca'

def bow_net(data,
            label,
            dict_dim=89528,
            emb_dim=128,
            hid_dim=128,
            hid_dim2=96,
            class_dim=2):
    """
    BOW net
    This model is from https://github.com/PaddlePaddle/models:
    models/fluid/PaddleNLP/text_classification/nets.py
    """
    # embedding
    emb = fluid.layers.embedding(
        input=data, size=[dict_dim, emb_dim], is_sparse=True)
    bow = fluid.layers.sequence_pool(input=emb, pool_type='sum')
    bowh = fluid.layers.tanh(bow)
    # fc layer after conv
    fc_1 = fluid.layers.fc(input=bowh, size=hid_dim, act="tanh")
    fc_2 = fluid.layers.fc(input=fc_1, size=hid_dim2, act="tanh")
    # probability of each class
    prediction = fluid.layers.fc(input=[fc_2], size=class_dim, act="softmax")
    # cross entropy loss
    cost = fluid.layers.cross_entropy(input=prediction, label=label)
    # mean loss
    avg_cost = fluid.layers.mean(x=cost)
    acc = fluid.layers.accuracy(input=prediction, label=label)
    return avg_cost, acc, prediction

def train():
    # Download data
    with tarfile.open(paddle.dataset.common.download(URL, "imdb", MD5)) as tarf:
        tarf.extractall(path='./')
        tarf.close()

    # Initialize dataset description
    dataset = fluid.DataFeedDesc('train_data/data.prototxt')
    dataset.set_batch_size(128)  # See API doc for how to change other fields
    print dataset.desc()  # Debug purpose: see what we get

    # define network
    # input text data
    data = fluid.layers.data(
        name="words", shape=[1], dtype="int64", lod_level=1)
    # label data
    label = fluid.layers.data(name="label", shape=[1], dtype="int64")

    avg_cost, acc, prediction = bow_net(data, label)
    sgd_optimizer = fluid.optimizer.Adagrad(learning_rate=0.002)
    opt_ops, weight_and_grad = sgd_optimizer.minimize(avg_cost)

    # Run startup program
    startup_program = fluid.default_startup_program()
    place = fluid.CPUPlace()
    executor = fluid.Executor(place)
    executor.run(startup_program)

    async_executor = fluid.AsyncExecutor(place)
    main_program = fluid.default_main_program()
    epochs = 10
    filelist = ["train_data/part-%d" % i for i in range(12)]
    for i in range(epochs):
        thread_num = 4
        async_executor.run(
            main_program,  # This can be changed during iteration
            dataset,  # This can be changed during iteration
            filelist,  # This can be changed during iteration
            thread_num,  # This can be changed during iteration
            [data, acc],  # Multiple fetch targets can be specified
            debug=False)
        fluid.io.save_inference_model('imdb/epoch%d.model' % i,
                                      [data.name, label.name], [acc], executor)

if __name__ == "__main__":
    train()


text:
package org.jboss.pnc.spi.builddriver;

import org.jboss.pnc.spi.builddriver.exception.BuildDriverException;
import org.jboss.pnc.spi.environment.RunningEnvironment;

/**
 * Created by Matej Lazar on 2014-12-23.
 */
public interface CompletedBuild {
    BuildDriverStatus getCompleteStatus();

    BuildDriverResult getBuildResult() throws BuildDriverException;

    RunningEnvironment getRunningEnvironment();
}


text:
require_relative '../../../spec_helper'

describe "GC::Profiler.report" do
  it "needs to be reviewed for spec completeness"
end


text:
package com.intel.analytics.zoo.pipeline.api.keras.layers

import com.intel.analytics.bigdl.nn.abstractnn.AbstractModule
import com.intel.analytics.bigdl.nn.keras.{Embedding => BEmbedding}
import com.intel.analytics.bigdl.optim.Regularizer
import com.intel.analytics.bigdl.tensor.TensorNumericMath.TensorNumeric
import com.intel.analytics.bigdl.utils.Shape
import com.intel.analytics.bigdl.nn.{AddConstant => TAddConstant, InitializationMethod, LookupTable, RandomUniform, Sequential => TSequential}
import com.intel.analytics.bigdl.tensor.Tensor
import com.intel.analytics.zoo.pipeline.api.Net
import com.intel.analytics.zoo.pipeline.api.keras.layers.utils.KerasUtils

import scala.reflect.ClassTag

/**
 * Turn non-negative integers (indices) into dense vectors of fixed size.
 * The input of this layer should be 2D.
 *
 * This layer can only be used as the first layer in a model, you need to provide the argument
 * inputShape (a Single Shape, does not include the batch dimension).
 *
 * @param inputDim Int > 0. Size of the vocabulary, ie. 1 + maximum integer
 *                 index occurring in the input data.
 *                 Each word index in the input should be within range [0, inputDim-1].
 * @param outputDim Int > 0. Dimension of the dense embedding.
 * @param init Initialization method for the weights of the layer. Default is RandomUniform.
 *             You can also pass in corresponding string representations such as 'uniform'
 *             or 'normal', etc. for simple init methods in the factory method.
 * @param initWeights Tensor. Initial weights set to this layer, which should be a Tensor of
 *                size (inputDim, outputDim). Default is null and in this case weights are
 *                initialized by the initialization method specified by 'init'.
 *                Otherwise, 'weights' will override 'init' to take effect.
 * @param trainable Whether this layer is trainable or not. Default is true.
 * @param wRegularizer An instance of [[Regularizer]], (eg. L1 or L2 regularization),
 *                     applied to the embedding matrix. Default is null.
 * @param inputShape A Single Shape, does not include the batch dimension.
 * @param maskZero: if maskZero is set to true, the input whose value equals `paddingValue`
 *                the output will be masked to zero vector.
 * @param paddingValue padding value, default 0
 * @param zeroBasedId default true and input should be 0 based. Otherwise need to be 1 base
 * @tparam T Numeric type of parameter(e.g. weight, bias). Only support float/double now.
 */
class Embedding[T: ClassTag](
                              override val inputDim: Int,
                              override val outputDim: Int,
                              override val init: InitializationMethod = RandomUniform,
                              val initWeights: Tensor[T] = null,
                              val trainable: Boolean = true,
                              wRegularizer: Regularizer[T] = null,
                              inputShape: Shape = null,
                              maskZero: Boolean = false,
                              paddingValue: Int = 0,
                              zeroBasedId: Boolean = true
                              )(implicit ev: TensorNumeric[T])
  extends BEmbedding[T] (
    inputDim, outputDim, init, wRegularizer, inputShape) with Net {

  require(inputDim > 0, s"inputDim of Embedding must be a positive integer, but got $inputDim")
  require(outputDim > 0, s"outputDim of Embedding must be a positive integer, but got $outputDim")

  if (initWeights != null) {
    require(initWeights.size().sameElements(Array(inputDim, outputDim)),
    "weights size should match (inputDim, outputDim)")
  }

  override def doBuild(inputShape: Shape): AbstractModule[Tensor[T], Tensor[T], T] = {
    val model = TSequential[T]()
    if (zeroBasedId) {
      model.add(TAddConstant(1.0))
    }
    val layer = LookupTable(
      nIndex = inputDim,
      nOutput = outputDim,
      wRegularizer = wRegularizer,
      maskZero = maskZero,
      paddingValue = paddingValue)
    if (initWeights != null) {
      layer.setWeightsBias(Array(initWeights))
    }
    else {
      layer.setInitMethod(weightInitMethod = init, biasInitMethod = init)
    }
    model.add(layer)
    if (! trainable) model.freeze()
    model.asInstanceOf[AbstractModule[Tensor[T], Tensor[T], T]]
  }

  override private[zoo] def toKeras2(): String = {
    val params = Net.inputShapeToString(inputShape) ++
      Net.param(getName()) ++
      Net.param(inputDim, "input_dim") ++
      Net.param(outputDim, "output_dim") ++
      Net.param(maskZero, "mask_zero")
    Net.kerasDef(this, params)
  }
}

object Embedding {
  def apply[@specialized(Float, Double) T: ClassTag](
    inputDim: Int,
    outputDim: Int,
    init: String = "uniform",
    weights: Tensor[T] = null,
    trainable: Boolean = true,
    wRegularizer: Regularizer[T] = null,
    inputLength: Int = -1,
    maskZero: Boolean = false,
    paddingValue: Int = 0,
    zeroBasedId: Boolean = true
      )(implicit ev: TensorNumeric[T]): Embedding[T] = {
    // Remark: It is possible that inputShape is specified in Input node or layer.
    val shape = if (inputLength > 0) Shape(inputLength) else null
    new Embedding[T](inputDim, outputDim, KerasUtils.getInitMethod(init),
      weights, trainable, wRegularizer, shape, maskZero, paddingValue, zeroBasedId)
  }
}


text:
"""Gram-Schmidt process for generating orthogonal polynomials."""
import logging

import numpy
import numpoly
import chaospy

def gram_schmidt(
    order,
    dist,
    normed=False,
    graded=True,
    reverse=True,
    retall=False,
    cross_truncation=1.0,
    **kws
):
    """
    Gram-Schmidt process for generating orthogonal polynomials.

    Args:
        order (int, numpoly.ndpoly):
            The upper polynomial order. Alternative a custom polynomial basis
            can be used.
        dist (Distribution):
            Weighting distribution(s) defining orthogonality.
        normed (bool):
            If True orthonormal polynomials will be used instead of monic.
        graded (bool):
            Graded sorting, meaning the indices are always sorted by the index
            sum. E.g. ``q0**2*q1**2*q2**2`` has an exponent sum of 6, and will
            therefore be consider larger than both ``q0**2*q1*q2``,
            ``q0*q1**2*q2`` and ``q0*q1*q2**2``, which all have exponent sum of
            5.
        reverse (bool):
            Reverse lexicographical sorting meaning that ``q0*q1**3`` is
            considered bigger than ``q0**3*q1``, instead of the opposite.
        retall (bool):
            If true return numerical stabilized norms as well. Roughly the same
            as ``cp.E(orth**2, dist)``.
        cross_truncation (float):
            Use hyperbolic cross truncation scheme to reduce the number of
            terms in expansion.

    Returns:
        (chapspy.poly.ndpoly):
            The orthogonal polynomial expansion.

    Examples:
        >>> distribution = chaospy.J(chaospy.Normal(), chaospy.Normal())
        >>> polynomials, norms = chaospy.expansion.gram_schmidt(2, distribution, retall=True)
        >>> polynomials.round(10)
        polynomial([1.0, q1, q0, q1**2-1.0, q0*q1, q0**2-1.0])
        >>> norms.round(10)
        array([1., 1., 1., 2., 1., 2.])
        >>> polynomials = chaospy.expansion.gram_schmidt(2, distribution, normed=True)
        >>> polynomials.round(3)
        polynomial([1.0, q1, q0, 0.707*q1**2-0.707, q0*q1, 0.707*q0**2-0.707])

    """
    logger = logging.getLogger(__name__)
    dim = len(dist)

    if isinstance(order, int):
        order = numpoly.monomial(
            0,
            order + 1,
            dimensions=numpoly.variable(2).names,
            graded=graded,
            reverse=reverse,
            cross_truncation=cross_truncation,
        )
    basis = list(order)
    polynomials = [basis[0]]

    norms = [1.0]
    for idx in range(1, len(basis)):

        # orthogonalize polynomial:
        for idy in range(idx):
            orth = chaospy.E(basis[idx] * polynomials[idy], dist, **kws)
            basis[idx] = basis[idx] - polynomials[idy] * orth / norms[idy]

        norms_ = chaospy.E(basis[idx] ** 2, dist, **kws)
        if norms_ <= 0:  # pragma: no cover
            logger.warning("Warning: Polynomial cutoff at term %d", idx)
            break

        norms.append(1.0 if normed else norms_)
        basis[idx] = basis[idx] / numpy.sqrt(norms_) if normed else basis[idx]
        polynomials.append(basis[idx])

    polynomials = chaospy.polynomial(polynomials).flatten()
    if retall:
        norms = numpy.array(norms)
        return polynomials, norms
    return polynomials